Skip to content

Commit

Permalink
[fix] support top-level await for module #104
Browse files Browse the repository at this point in the history
  • Loading branch information
Siubaak committed Jan 10, 2025
1 parent b2399b3 commit afec42b
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/evaluate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import * as identifier from './identifier'
import * as statement from './statement'
import * as literal from './literal'
import * as pattern from './pattern'
/*<add>*//*import * as program from './program'*//*</add>*/
import * as program from './program'

let evaluateOps: any

Expand All @@ -25,7 +25,7 @@ export default function* evaluate(node: Node, scope: Scope) {
statement,
literal,
pattern,
/*<add>*//*program*//*</add>*/
program
)
}

Expand Down
21 changes: 18 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { EXPORTS, IMPORT } from './share/const'
import { version } from '../package.json'
import Scope from './scope'

import { runAsync } from './share/async'
import { hoist as hoistAsync } from './evaluate/helper'
import { hoist } from './evaluate_n/helper'
import evaluateAsync from './evaluate'
import evaluate from './evaluate_n'

export interface SvalOptions {
Expand Down Expand Up @@ -76,9 +79,21 @@ class Sval {
}

run(code: string | Node) {
const ast = typeof code === 'string' ? parse(code, this.options) as Node : code
hoist(ast as Program, this.scope)
evaluate(ast, this.scope)
const ast = typeof code === 'string' ? this.parse(code) : code
const scope = this.scope
// check if top-level await supports
if (this.options.sourceType === 'module' && (
this.options.ecmaVersion === 'latest'
|| this.options.ecmaVersion >= 13
)) {
runAsync((function* () {
yield* hoistAsync(ast as Program, scope)
yield* evaluateAsync(ast, scope)
})())
} else {
hoist(ast as Program, scope)
evaluate(ast, scope)
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions tests/expression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,4 +414,19 @@ describe('testing src/expression.ts', () => {
})
`)
})

it('should support top-level await', done => {
const interpreter = new Sval({ sourceType: 'module' })
interpreter.import('done', { default: done })
interpreter.import('expect', { default: expect })
interpreter.import('module', () => ({ default: 1 }))
interpreter.run(`
import done from 'done'
import expect from 'expect'
expect(await new Promise((resolve) => {
setTimeout(() => resolve(1), 50)
})).toBe(1)
done()
`)
})
})

0 comments on commit afec42b

Please sign in to comment.