Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 25 additions & 13 deletions src/bundler/linker_context/convertStmtsForChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,23 +274,35 @@ pub(crate) fn convert_stmts_for_chunk(
let flag = c.graph.meta.items_flags()[other_source_index];
let wrapper_ref = c.graph.ast.items_wrapper_ref()[other_source_index];
if flag.wrap == WrapKind::Esm && wrapper_ref.is_valid() {
let init_call = Expr::init(
E::Call {
target: Expr::init(
E::Identifier {
ref_: wrapper_ref,
..Default::default()
},
stmt.loc,
),
..Default::default()
},
stmt.loc,
);
// Await an async init only where this file's own
// wrapper is async (never in `__commonJS`).
Comment thread
robobun marked this conversation as resolved.
Resolved
let value = if flag.is_async_or_has_async_dependency
&& wrap != WrapKind::Cjs
&& c.graph.meta.items_flags()[source_index as usize]
.is_async_or_has_async_dependency
{
Comment thread
robobun marked this conversation as resolved.
Resolved
Expr::init(E::Await { value: init_call }, stmt.loc)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else {
init_call
};
stmts
.inside_wrapper_prefix
.append_non_dependency(Stmt::alloc(
S::SExpr {
value: Expr::init(
E::Call {
target: Expr::init(
E::Identifier {
ref_: wrapper_ref,
..Default::default()
},
stmt.loc,
),
..Default::default()
},
stmt.loc,
),
value,
..Default::default()
},
stmt.loc,
Comment thread
robobun marked this conversation as resolved.
Resolved
Expand Down
4 changes: 3 additions & 1 deletion src/bundler/linker_context/postProcessJSChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,8 @@ pub(crate) fn post_process_js_chunk(
// bytecode-compiled module that contains TLA gets evaluated on the sync path
// and the suspended generator is dropped — the entry promise resolves
// immediately and the process exits before the awaited value lands.
// A printed `await init_x()` has no `await` keyword in the source, so the
// async flag counts too.
Comment thread
robobun marked this conversation as resolved.
Resolved
if let Some(mi) = module_info.as_deref_mut() {
let tla_keywords = c.parse_graph().ast.items_top_level_await_keyword();
let wraps = c.graph.meta.items_flags();
Expand All @@ -327,7 +329,7 @@ pub(crate) fn post_process_js_chunk(
if wraps[idx].wrap != crate::WrapKind::None {
continue;
}
if !tla_keywords[idx].is_empty() {
if !tla_keywords[idx].is_empty() || wraps[idx].is_async_or_has_async_dependency {
Comment thread
robobun marked this conversation as resolved.
Resolved
mi.flags.has_tla = true;
break;
Comment thread
robobun marked this conversation as resolved.
Resolved
}
Expand Down
221 changes: 221 additions & 0 deletions test/bundler/bundler_barrel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2195,6 +2195,227 @@ describe("bundler", () => {
},
});

// `import()` of the barrel wraps it in a lazy `__esm` init. The barrel's
// `export *` target transitively has a top-level await, so the init of that
// target returns a promise and the barrel's init must await it, the same as
// for `import` / `export {} from`.
// https://github.com/oven-sh/bun/issues/47572
itBundled("barrel/ExportStarAwaitsAsyncTarget", {
files: {
"/main.js": /* js */ `
import { thing } from './consumer.js'
import { load } from './lazy.js'
console.log('ok', thing.ok, typeof (await load()).Thing)
`,
"/consumer.js": /* js */ `
import { Thing } from './barrel.js'
export const thing = new Thing()
`,
"/lazy.js": /* js */ `
export async function load() {
return import('./barrel.js')
}
`,
"/barrel.js": /* js */ `export * from './reexport.js'`,
"/reexport.js": /* js */ `export { Thing } from './facade.js'`,
"/facade.js": /* js */ `
import { client } from './tla.js'
export const Thing = client && class { constructor() { this.ok = true } }
`,
"/tla.js": /* js */ `
export const client = await new Promise(r => setTimeout(() => r('client'), 10))
`,
},
format: "esm",
target: "bun",
outdir: "/out",
run: {
stdout: "ok true function",
},
onAfterBundle(api) {
const out = api.readFile("/out/main.js");
expect(out).toMatch(/var init_barrel = __esm\(async \(\) => \{\s*await init_reexport\(\);\s*\}\);/);
},
});

// Two async `export *` targets are awaited one after the other, in source
// order.
itBundled("barrel/TwoExportStarsAwaitInOrder", {
files: {
"/main.js": /* js */ `
import { a, b } from './barrel.js'
import { load } from './lazy.js'
console.log(a, b, typeof (await load()).a)
`,
"/lazy.js": /* js */ `
export async function load() {
return import('./barrel.js')
}
`,
"/barrel.js": /* js */ `
export * from './a.js'
export * from './b.js'
`,
"/a.js": /* js */ `export const a = await Promise.resolve('A')`,
"/b.js": /* js */ `export const b = await Promise.resolve('B')`,
},
format: "esm",
target: "bun",
outdir: "/out",
run: {
stdout: "A B string",
},
onAfterBundle(api) {
const out = api.readFile("/out/main.js");
expect(out).toMatch(/var init_barrel = __esm\(async \(\) => \{\s*await init_a\(\);\s*await init_b\(\);\s*\}\);/);
},
});
Comment thread
robobun marked this conversation as resolved.
Resolved

// An `export *` target with its own sync `__esm` wrapper (it is lazily
// loaded too) keeps a plain init call.
itBundled("barrel/ExportStarSyncTargetIsNotAwaited", {
files: {
"/main.js": /* js */ `
import { a } from './barrel.js'
import { load } from './lazy.js'
console.log(a, typeof (await load()).a)
`,
"/lazy.js": /* js */ `
export async function load() {
await import('./a.js')
return import('./barrel.js')
}
`,
"/barrel.js": /* js */ `export * from './a.js'`,
"/a.js": /* js */ `export const a = String('A')`,
},
format: "esm",
target: "bun",
outdir: "/out",
run: {
stdout: "A string",
},
onAfterBundle(api) {
const out = api.readFile("/out/main.js");
expect(out).toMatch(/var init_barrel = __esm\(\(\) => \{\s*init_a\(\);\s*\}\);/);
expect(out).not.toContain("await init_a");
},
});

// An async `export *` init stays in source order after a CommonJS import
// too: the polyfill still runs before the library.
itBundled("barrel/ExportStarAsyncTargetKeepsSourceOrderAfterCommonJSImport", {
files: {
"/main.js": /* js */ `
import { load } from './lazy.js'
console.log(typeof (await load()).x)
`,
"/lazy.js": /* js */ `
export async function load() {
return import('./barrel.js')
}
`,
"/barrel.js": /* js */ `
import './polyfill.cjs'
export * from './container.js'
`,
"/container.js": /* js */ `
import './lib.cjs'
export const x = await Promise.resolve('x')
`,
"/lib.cjs": /* js */ `
if (!globalThis.__polyfill) throw new Error('lib needs the polyfill')
console.log('lib ok')
`,
"/polyfill.cjs": /* js */ `globalThis.__polyfill = 'ready'`,
},
format: "esm",
target: "bun",
outdir: "/out",
run: {
stdout: "lib ok\nstring",
},
onAfterBundle(api) {
const out = api.readFile("/out/main.js");
expect(out).toMatch(
/var init_barrel = __esm\(async \(\) => \{\s*import_polyfill = __toESM\(require_polyfill\(\)\);\s*await init_container\(\);\s*\}\);/,
);
},
});

// A sync `export *` init stays in source order after a CommonJS import
// (the polyfill-before-library pattern).
itBundled("barrel/ExportStarSyncTargetKeepsSourceOrderAfterCommonJSImport", {
files: {
"/main.js": /* js */ `
import { load } from './lazy.js'
console.log(typeof (await load()).x)
`,
"/lazy.js": /* js */ `
export async function load() {
return import('./barrel.js')
}
`,
"/barrel.js": /* js */ `
import './polyfill.cjs'
export * from './container.js'
`,
"/container.js": /* js */ `
import './lib.cjs'
export const x = String('x')
`,
"/lib.cjs": /* js */ `
if (!globalThis.__polyfill) throw new Error('lib needs the polyfill')
console.log('lib ok')
`,
"/polyfill.cjs": /* js */ `globalThis.__polyfill = 'ready'`,
},
format: "esm",
target: "bun",
outdir: "/out",
run: {
stdout: "lib ok\nstring",
},
onAfterBundle(api) {
const out = api.readFile("/out/main.js");
expect(out).toMatch(
/var init_barrel = __esm\(\(\) => \{\s*import_polyfill = __toESM\(require_polyfill\(\)\);\s*init_container\(\);\s*\}\);/,
);
},
});

// A `__commonJS` wrapper cannot contain `await`, so a file bundled as
// CommonJS (it writes `exports`) keeps the bare init call for an async
// `export *` target.
itBundled("barrel/ExportStarAsyncTargetInCommonJSWrapperIsNotAwaited", {
files: {
"/main.js": /* js */ `
import c from './c.js'
console.log(c.a)
`,
"/c.js": /* js */ `
export * from './tla.js'
exports.a = 1
Object.keys(exports)
`,
"/tla.js": /* js */ `
await 0
export const t = 1
`,
},
format: "esm",
target: "bun",
outdir: "/out",
run: {
stdout: "1",
},
onAfterBundle(api) {
const out = api.readFile("/out/main.js");
expect(out).toMatch(/var require_c = __commonJS\(function\(exports\) \{[^]*?init_tla\(\);\s*exports\.a = 1;/);
expect(out).not.toContain("await init_tla");
},
});

// The barrel deferral must produce the same output no matter in which order
// the parse tasks finish. When a request un-defers a barrel record, every
// alias the barrel imports through that record has to propagate to the next
Expand Down
18 changes: 18 additions & 0 deletions test/bundler/bundler_compile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,24 @@ describe("bundler", () => {
},
stdout: "function",
},
{
// No file in the main chunk has an `await` keyword of its own. The
// `import()` in lazy.ts wraps tla.ts in an async `__esm` init, and the
// entry prints `await init_tla()` at its top level. The module record
// has to carry hasTLA, or the process exits before the value lands.
name: "AwaitedAsyncWrapperWithoutOwnAwait",
files: {
"/entry.ts": `
import { value } from "./tla.ts";
import { load } from "./lazy.ts";
console.log("value:", value);
load().then(m => console.log("lazy:", typeof m.value));
`,
"/lazy.ts": `export function load() { return import("./tla.ts"); }`,
"/tla.ts": `export const value = await Promise.resolve(7);`,
},
stdout: "value: 7\nlazy: number",
},
];

for (const scenario of esmBytecodeScenarios) {
Expand Down
Loading