(code: string)
| 80 | } |
| 81 | |
| 82 | export function rewriteTopLevelAwait(code: string): string | undefined { |
| 83 | let program: Program; |
| 84 | try { |
| 85 | // todo: strict needed due to https://github.com/acornjs/acorn/issues/988 |
| 86 | program = parseProgram(code); |
| 87 | } catch (e) { |
| 88 | return undefined; |
| 89 | } |
| 90 | |
| 91 | const makeAssignment = (id: Identifier, rhs: Expression): ExpressionStatement => ({ |
| 92 | type: 'ExpressionStatement', |
| 93 | expression: { |
| 94 | type: 'AssignmentExpression', |
| 95 | operator: '=', |
| 96 | left: id, |
| 97 | right: rhs, |
| 98 | }, |
| 99 | }); |
| 100 | |
| 101 | let containsAwait = false; |
| 102 | let containsReturn = false; |
| 103 | |
| 104 | const replaced = replace(program, { |
| 105 | enter(node, parent) { |
| 106 | switch (node.type) { |
| 107 | case 'ClassDeclaration': |
| 108 | return { |
| 109 | replace: makeAssignment(node.id || { type: 'Identifier', name: '_default' }, { |
| 110 | ...node, |
| 111 | type: 'ClassExpression', |
| 112 | }), |
| 113 | }; |
| 114 | case 'FunctionDeclaration': |
| 115 | return { |
| 116 | replace: makeAssignment(node.id || { type: 'Identifier', name: '_default' }, { |
| 117 | ...node, |
| 118 | type: 'FunctionExpression', |
| 119 | }), |
| 120 | }; |
| 121 | case 'FunctionExpression': |
| 122 | case 'ArrowFunctionExpression': |
| 123 | case 'MethodDefinition': |
| 124 | return VisitorOption.Skip; |
| 125 | case 'AwaitExpression': |
| 126 | containsAwait = true; |
| 127 | return; |
| 128 | case 'ForOfStatement': |
| 129 | if (node.await) { |
| 130 | containsAwait = true; |
| 131 | } |
| 132 | return; |
| 133 | case 'ReturnStatement': |
| 134 | containsReturn = true; |
| 135 | return; |
| 136 | case 'VariableDeclaration': |
| 137 | if (!parent || !('body' in parent) || !(parent.body instanceof Array)) { |
| 138 | return; |
| 139 | } |
no test coverage detected