(text, func)
| 862 | // function, to which we pass the parsed-out arguments, body, and possible |
| 863 | // "async" prefix of the input function. Returns the output of that function. |
| 864 | export function modifyJSFunction(text, func) { |
| 865 | // Match a function with a name. |
| 866 | let async_; |
| 867 | let args; |
| 868 | let rest; |
| 869 | let oneliner = false; |
| 870 | let match = text.match(/^\s*(async\s+)?function\s+([^(]*)?\s*\(([^)]*)\)/); |
| 871 | if (match) { |
| 872 | async_ = match[1] ?? ''; |
| 873 | args = match[3]; |
| 874 | rest = text.slice(match[0].length); |
| 875 | } else { |
| 876 | // Match an arrow function |
| 877 | let match = text.match(/^\s*(var (\w+) = )?(async\s+)?\(([^)]*)\)\s+=>\s+/); |
| 878 | if (match) { |
| 879 | async_ = match[3] ?? ''; |
| 880 | args = match[4]; |
| 881 | rest = text.slice(match[0].length); |
| 882 | rest = rest.trim(); |
| 883 | oneliner = rest[0] != '{'; |
| 884 | } else { |
| 885 | // Match a function without a name (we could probably use a single regex |
| 886 | // for both, but it would be more complex). |
| 887 | match = text.match(/^\s*(async\s+)?function\(([^)]*)\)/); |
| 888 | assert(match, `could not match function:\n${text}\n`); |
| 889 | async_ = match[1] ?? ''; |
| 890 | args = match[2]; |
| 891 | rest = text.slice(match[0].length); |
| 892 | } |
| 893 | } |
| 894 | let body = rest; |
| 895 | if (!oneliner) { |
| 896 | const bodyStart = rest.indexOf('{'); |
| 897 | const bodyEnd = rest.lastIndexOf('}'); |
| 898 | assert(bodyEnd > 0); |
| 899 | body = rest.substring(bodyStart + 1, bodyEnd); |
| 900 | } |
| 901 | return func(args, body, async_, oneliner); |
| 902 | } |
| 903 | |
| 904 | export function runIfMainThread(text) { |
| 905 | if (WASM_WORKERS || PTHREADS) { |
no test coverage detected