Skip to content

Commit

Permalink
feat: resolve promise
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed Jun 6, 2023
1 parent fe3b0f0 commit e629a4d
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,13 @@ export async function transformMacros(

let scope = attachScopes(program, 'scope')
const macros: {
node: CallExpression
node: Node
fn: string[]
args: any[]
isAwait: boolean
}[] = []
walkAST<WithScope<Node>>(program, {
enter(node) {
enter(node, parent) {
if (node.scope) scope = node.scope

if (
Expand All @@ -51,10 +52,13 @@ export async function transformMacros(
if (isLiteralType(arg)) return resolveLiteral(arg)
throw new Error('Macro arguments must be literals.')
})
const isAwait = parent?.type === 'AwaitExpression'

macros.push({
node,
node: isAwait ? parent : node,
fn,
args,
isAwait,
})
}
},
Expand All @@ -73,6 +77,7 @@ export async function transformMacros(
node,
fn: [local, ...keys],
args,
isAwait,
} of macros) {
const binding = imports[local]
const [, resolved] = await runner.resolveUrl(binding.source, id)
Expand All @@ -90,7 +95,11 @@ export async function transformMacros(
throw new Error(`Macro ${local} is not existed.`)
}

const ret = fn(...args)
let ret = fn(...args)
if (isAwait) {
ret = await ret
}

s.overwriteNode(node, ret === undefined ? 'undefined' : JSON.stringify(ret))

deps[id].add(resolved)
Expand Down
7 changes: 7 additions & 0 deletions tests/__snapshots__/fixtures.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,10 @@ exports[`fixture > tests/fixtures/nested-object.js 1`] = `
"\\"foo\\" === 'foo';
"
`;

exports[`fixture > tests/fixtures/promise.js 1`] = `
"var promise = \\"ok\\";
export { promise as default };
"
`;
3 changes: 3 additions & 0 deletions tests/fixtures/macros/promise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function promise() {
return Promise.resolve('ok')
}
3 changes: 3 additions & 0 deletions tests/fixtures/promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { promise } from './macros/promise' assert { type: 'macro' }

export default await promise()

0 comments on commit e629a4d

Please sign in to comment.