Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
7 changes: 7 additions & 0 deletions src/bundler/Chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,13 @@ impl Chunk {
self.entry_point.is_entry_point()
}

/// Whether `source_index` is the entry point of this chunk. Without code
/// splitting, the files of other entry points can print in this chunk too.
Comment on lines +278 to +279

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

#[inline]
pub(crate) fn is_entry_point_file(&self, source_index: u32) -> bool {
self.entry_point.is_entry_point() && self.entry_point.source_index() == source_index
}

/// Stable short name for this chunk in generated code: its final content hash, as `[hash]` prints it.
pub(crate) fn id(&self) -> [u8; CHUNK_ID_LEN] {
bun_core::fmt::truncated_hash32_bytes(
Expand Down
43 changes: 15 additions & 28 deletions src/bundler/LinkerGraph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -687,39 +687,26 @@ impl<'a> LinkerGraph<'a> {
+ server_component_boundaries.list.len()
+ dynamic_import_entry_points.len(),
)?;
// SAFETY: capacity reserved; columns initialized below.
unsafe { self.entry_points.set_len(entry_points.len()) };

// Note: `source_indices` / `path_strings` are disjoint columns of
// the same `MultiArrayList`. `split_mut()` hands out both at once;
// `self.entry_points` is not
// reallocated until after `path_strings`/`source_indices` are done
// with (the next `append_assume_capacity` is within the
// pre-reserved capacity, so no realloc).
let mut ep_slice = self.entry_points.slice();
let ep_cols = ep_slice.split_mut();
let source_indices: &mut [index::Int] = ep_cols.source_index;
let path_strings: &mut [RawSlice<u8>] = ep_cols.output_path;

debug_assert_eq!(entry_points.len(), path_strings.len());
debug_assert_eq!(entry_points.len(), source_indices.len());
for ((i, path_string), source_index) in entry_points
.iter()
.zip(path_strings.iter_mut())
.zip(source_indices.iter_mut())
{
for i in entry_points {
let source = &sources[i.get() as usize];
debug_assert!(source.index.0 == i.get());
entry_point_kinds[source.index.0 as usize] = entry_point::Kind::UserSpecified;

// Check if this entry point has an original name (from virtual entry resolution)
if let Some(original_name) = entry_point_original_names.get(i.get()) {
*path_string = RawSlice::new(original_name);
} else {
*path_string = RawSlice::new(source.path.text);
// Two entry points can name one file, e.g. when an onResolve plugin
// maps two names to it. The file gets one entry point and one output.
Comment on lines +694 to +695

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

if entry_point_kinds[source.index.0 as usize] != entry_point::Kind::None {
continue;
}
entry_point_kinds[source.index.0 as usize] = entry_point::Kind::UserSpecified;

*source_index = source.index.0;
// Check if this entry point has an original name (from virtual entry resolution)
let output_path = match entry_point_original_names.get(i.get()) {
Some(original_name) => RawSlice::new(original_name),
None => RawSlice::new(source.path.text),
};
self.entry_points.append_assume_capacity(EntryPoint {
source_index: source.index.0,
output_path,
});
}

for &id in dynamic_import_entry_points {
Expand Down
30 changes: 8 additions & 22 deletions src/bundler/linker_context/computeChunks.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::mal_prelude::*;
use bun_alloc::ArenaVecExt as _;
use core::sync::atomic::AtomicUsize;

use bun_alloc::Arena; // bumpalo::Bump re-export
Expand Down Expand Up @@ -109,28 +108,16 @@ pub(crate) fn compute_chunks(

let has_html_chunk = loaders[source_index as usize] == Loader::Html;

// For code splitting, entry point chunks should be keyed by ONLY the entry point's
// own bit, not the full entry_bits. This ensures that if an entry point file is
// reachable from other entry points (e.g., via re-exports), its content goes into
// a shared chunk rather than staying in the entry point's chunk.
// Entry point chunks are keyed by ONLY the entry point's own bit, not the full
// entry_bits. Entry points that reach each other have the same entry_bits, and
// each one still needs its own chunk. With code splitting, an entry point file
// that other entry points reach (e.g., via re-exports) goes into a shared chunk.
Comment on lines +111 to +114

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

// https://github.com/evanw/esbuild/blob/cd832972927f1f67b6d2cc895c06a8759c1cf309/internal/linker/linker.go#L3882
let mut entry_point_chunk_bits = AutoBitSet::init_empty(this.graph.entry_points.len())?;
entry_point_chunk_bits.set(entry_bit as usize);

let js_chunk_key: &[u8] = 'brk: {
if code_splitting {
break 'brk temp
.alloc_slice_copy(entry_point_chunk_bits.bytes(this.graph.entry_points.len()));
} else {
// Force HTML chunks to always be generated, even if there's an identical JS file.
// Build the byte key directly since
// entry_bits is arbitrary bytes (not UTF-8) and cannot go through fmt::Display.
let mut v = bun_alloc::ArenaVec::new_in(temp);
v.push((!has_html_chunk) as u8);
v.extend_from_slice(entry_bits.bytes(this.graph.entry_points.len()));
break 'brk v.into_bump_slice();
}
};
let js_chunk_key: &[u8] =
temp.alloc_slice_copy(entry_point_chunk_bits.bytes(this.graph.entry_points.len()));

// Put this early on in this loop so that CSS-only entry points work.
if has_html_chunk {
Expand Down Expand Up @@ -162,9 +149,7 @@ pub(crate) fn compute_chunks(
// Create a chunk for the entry point here to ensure that the chunk is
// always generated even if the resulting file is empty
let hash_to_use = if !this.options.css_chunking {
bun_wyhash::hash(
temp.alloc_slice_copy(entry_bits.bytes(this.graph.entry_points.len())),
)
bun_wyhash::hash(entry_point_chunk_bits.bytes(this.graph.entry_points.len()))
} else {
let mut hasher = Wyhash::init(5);
bun_core::write_any_to_hasher(&mut hasher, order.len());
Expand Down Expand Up @@ -203,6 +188,7 @@ pub(crate) fn compute_chunks(
// Create a chunk for the entry point here to ensure that the chunk is
// always generated even if the resulting file is empty
let js_chunk_entry = js_chunks.get_or_put(js_chunk_key)?;
debug_assert!(!js_chunk_entry.found_existing);
entry_point_to_js_chunk_idx[entry_id_] =
u32::try_from(js_chunk_entry.index).expect("int cast");
*js_chunk_entry.value_ptr = Chunk {
Expand Down
6 changes: 3 additions & 3 deletions src/bundler/linker_context/convertStmtsForChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,15 @@ pub(crate) fn convert_stmts_for_chunk(

let output_format = c.options.output_format;

// If this file is a CommonJS entry point, double-write re-exports to the
// external CommonJS "module.exports" object in addition to our internal ESM
// If this file is the CommonJS entry point of this chunk, double-write re-exports
// to the external CommonJS "module.exports" object in addition to our internal ESM
Comment on lines +65 to +66

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

// export namespace object. The difference between these two objects is that
// our internal one must not have the "__esModule" marker while the external
// one must have the "__esModule" marker. This is done because an ES module
// importing itself should not see the "__esModule" marker but a CommonJS module
// importing us should see the "__esModule" marker.
let mut module_exports_for_export: Option<Expr> = None;
if output_format == Format::Cjs && chunk.is_entry_point() {
if output_format == Format::Cjs && chunk.is_entry_point_file(source_index) {
module_exports_for_export = Some(Expr::allocate(
bump,
E::Dot {
Expand Down
2 changes: 2 additions & 0 deletions src/bundler/linker_context/doStep5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,8 @@ impl LinkerContext<'_> {
// instead of by mutating the exports object because other modules in the
// bundle (including the entry point module) may do "import * as" to get
// access to the exports object and should NOT see the "__esModule" flag.
// This stays the last statement of the part: `generate_code_for_file_in_chunk_js`
// drops it when another entry point's chunk prints this file.
Comment on lines +761 to +762

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

if force_include_exports_for_entry_point {
let to_common_js_ref = self.runtime_function(b"__toCommonJS");
emit_export_stmt!(Stmt::assign(
Expand Down
14 changes: 14 additions & 0 deletions src/bundler/linker_context/findAllImportedPartsInJSOrder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,20 @@ pub(crate) fn find_imported_parts_in_js_order(

Order::sort(&mut chunk_order_array);

// Without code splitting, a chunk holds every file that its entry point reaches.
// Distances are the minimum over all entry points, so other entry points in this
// chunk also sort at distance 0. Visit this chunk's own entry point first, so the
// files print in the order that this entry point imports them.
Comment on lines +109 to +112

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

if !this.graph.code_splitting && chunk.entry_point.is_entry_point() {
let entry_point = chunk.entry_point.source_index();
if let Some(i) = chunk_order_array
.iter()
.position(|order| order.source_index == entry_point)
{
chunk_order_array[..=i].rotate_right(1);
}
}

part_ranges_shared.clear();
parts_prefix_shared.clear();

Expand Down
11 changes: 10 additions & 1 deletion src/bundler/linker_context/generateCodeForFileInChunkJS.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,17 @@ pub fn generate_code_for_file_in_chunk_js<'r, 'src>(
&& parts_live.is_set(namespace_export_part_index as usize)
{
// SAFETY: see `parts` raw-pointer note above; index bounded by the range check just above.
let ns_part_stmts: &[Stmt] =
let mut ns_part_stmts: &[Stmt] =
unsafe { (*parts)[namespace_export_part_index as usize].stmts }.slice();
// Step 5 ends this part of a CommonJS entry point with
// `module.exports = __toCommonJS(exports)`. Only the chunk of that entry point runs it.
Comment on lines +291 to +292

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

if output_format == OutputFormat::Cjs
&& flags.force_include_exports_for_entry_point
&& !chunk.is_entry_point_file(source_index as u32)
&& let Some((_module_exports, rest)) = ns_part_stmts.split_last()
{
ns_part_stmts = rest;
}
if let Err(err) = convert_stmts_for_chunk(
c,
source_index as u32,
Expand Down
22 changes: 21 additions & 1 deletion test/bundler/bundler_compile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ describe("bundler", () => {
process.exitCode = 1;
process.versions.bun = "bun!";
if (process.versions.bun === "bun!") throw new Error("fail");
if (require("./${process.platform}-${process.arch}.js") === "${Bun.version.replaceAll("-debug", "")}") {
if (require("./${process.platform}-${process.arch}.js").replaceAll("-debug", "") === "${Bun.version.replaceAll("-debug", "")}") {
process.exitCode = 0;
}
`,
Expand Down Expand Up @@ -401,6 +401,26 @@ describe("bundler", () => {
},
});
}
// Two entry points that import() each other: the executable runs the first one.
itBundled("compile/EntryPointsImportEachOther", {
compile: true,
files: {
"/main.ts": /* js */ `
import("./plugin.ts").then(plugin => console.log("main loaded", plugin.name));
`,
"/plugin.ts": /* js */ `
export const name = "plugin";
export const loadMain = () => import("./main.ts");
`,
},
entryPointsRaw: ["./main.ts", "./plugin.ts"],
outfile: "dist/out",
run: {
stdout: "main loaded plugin",
file: "dist/out",
setCwd: true,
},
});
// https://github.com/oven-sh/bun/issues/8697
itBundled("compile/EmbeddedFileOutfile", {
compile: true,
Expand Down
82 changes: 82 additions & 0 deletions test/bundler/bundler_edgecase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3611,6 +3611,88 @@ describe("bundler", () => {
api.expectFile("/out.js").toContain("var arguments = 1;");
},
});

// Without code splitting, each entry point gets its own output file, even when
// entry points import each other. Each file runs its modules in the order that
// its own entry point imports them, so it prints what the unbundled entry prints.
itBundled("edgecase/EntryPointsImportEachOther", {
files: {
"/a.ts": /* ts */ `
import { b } from "./b.ts";
export function a() { return "a"; }
console.log("a runs, b() is", b());
`,
"/b.ts": /* ts */ `
import { a } from "./a.ts";
export function b() { return "b"; }
console.log("b runs, a() is", a());
`,
},
entryPoints: ["/a.ts", "/b.ts"],
outdir: "/out",
run: [
{ file: "/out/a.js", stdout: "b runs, a() is a\na runs, b() is b" },
{ file: "/out/b.js", stdout: "a runs, b() is b\nb runs, a() is a" },
],
});
itBundled("edgecase/EntryPointImportsEntryPointModuleOrder", {
files: {
"/a.ts": `import "./c.ts"; import "./b.ts"; console.log("a");`,
"/b.ts": `import "./d.ts"; console.log("b");`,
"/c.ts": `console.log("c");`,
"/d.ts": `console.log("d");`,
},
entryPoints: ["/a.ts", "/b.ts"],
outdir: "/out",
run: [
{ file: "/out/a.js", stdout: "c\nd\nb\na" },
{ file: "/out/b.js", stdout: "d\nb" },
],
});
itBundled("edgecase/CSSEntryPointsImportEachOther", {
files: {
"/a.css": `@import "./b.css"; .a { color: red }`,
"/b.css": `@import "./a.css"; .b { color: blue }`,
},
entryPoints: ["/a.css", "/b.css"],
outdir: "/out",
minifyWhitespace: true,
onAfterBundle(api) {
api.expectFile("/out/a.css").toEqualIgnoringWhitespace(".b{color:#00f}.a{color:red}");
api.expectFile("/out/b.css").toEqualIgnoringWhitespace(".a{color:red}.b{color:#00f}");
},
});
// With --format=cjs, the module.exports of each output holds the exports of its
// own entry point, also when the file of another entry point prints in it.
itBundled("edgecase/EntryPointsImportEachOtherCommonJS", {
files: {
"/a.ts": `import { b } from "./b.ts"; export function a() { return b(); }`,
"/b.ts": `import { a } from "./a.ts"; export function b() { return "b"; } export const useA = () => a;`,
},
runtimeFiles: {
"/check.js": `console.log(JSON.stringify([require("./out/a.js"), require("./out/b.js")].map(Object.keys)));`,
},
entryPoints: ["/a.ts", "/b.ts"],
outdir: "/out",
format: "cjs",
run: { file: "/check.js", stdout: `[["a"],["b","useA"]]` },
});
itBundled("edgecase/EntryPointImportsEntryPointCommonJS", {
files: {
"/index.ts": `import { x } from "./lib.ts"; export const y = x + 1;`,
"/lib.ts": `export * from "ext"; export const x = 1;`,
},
runtimeFiles: {
"/node_modules/ext/index.js": `module.exports = { fromExt: true };`,
"/check.js": `console.log(JSON.stringify([require("./out/index.js"), require("./out/lib.js")]));`,
},
entryPoints: ["/index.ts", "/lib.ts"],
outdir: "/out",
external: ["ext"],
target: "node",
format: "cjs",
run: { file: "/check.js", stdout: `[{"y":2},{"x":1,"fromExt":true}]` },
});
});

for (const backend of ["api", "cli"] as const) {
Expand Down
23 changes: 23 additions & 0 deletions test/bundler/bundler_html.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,29 @@ export const padZero = (num) => String(num).padStart(2, '0');`,
},
});

// A script that is also an entry point still runs in its place on the page.
itBundled("html/script-that-is-also-an-entry-point", {
outdir: "out/",
files: {
"/index.html": `
<!DOCTYPE html>
<html>
<head>
<script type="module" src="./first.js"></script>
<script type="module" src="./second.js"></script>
</head>
</html>`,
"/first.js": `console.log("first");`,
"/second.js": `console.log("second");`,
},
entryPoints: ["/index.html", "/second.js"],
onAfterBundle(api) {
const jsMatch = api.readFile("out/index.html").match(/src="(.*\.js)"/);
expect(api.readFile("out/" + jsMatch![1])).toMatch(/"first"[\s\S]*"second"/);
api.expectFile("out/second.js").toContain('console.log("second")');
},
});

// Test CSS imports
itBundled("html/css-imports", {
outdir: "out/",
Expand Down
28 changes: 28 additions & 0 deletions test/bundler/bundler_plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1865,4 +1865,32 @@ describe("bundler", () => {
});
expect(exitCode).toBe(0);
});

// Two entry point names that onResolve maps to one file make one output file.
for (const splitting of [false, true]) {
test.concurrent(`plugin/two entry points that resolve to one file (splitting: ${splitting})`, async () => {
using dir = tempDir("plugin-two-entry-points-one-file", {
"entry.ts": `console.log("entry");`,
});
const result = await Bun.build({
entrypoints: ["first-name", "second-name"],
outdir: join(String(dir), "out"),
splitting,
throw: false,
plugins: [
{
name: "alias",
setup(build) {
build.onResolve({ filter: /-name$/ }, () => ({ path: join(String(dir), "entry.ts") }));
},
},
],
});
expect({
success: result.success,
logs: result.logs.map(log => log.message),
outputs: result.outputs.map(output => path.basename(output.path)),
}).toEqual({ success: true, logs: [], outputs: ["second-name.js"] });
});
}
});
2 changes: 1 addition & 1 deletion test/bundler/esbuild/importstar.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1434,7 +1434,7 @@ describe.concurrent("bundler", () => {
},
run: {
file: "/test.js",
stdout: '{"inner":{"b":456},"a":123,"b":456}',
stdout: '{"inner":{"b":456},"a":123}',
},
});
itBundled("importstar/ReExportStarEntryPointAndInnerFile", {
Expand Down
Loading