Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
51 changes: 51 additions & 0 deletions src/bundler/linker_context/renameSymbolsInChunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
use crate::bun_renamer as renamer;
use crate::bun_renamer::{ChunkRenamer, MinifyRenamer, NumberRenamer, StableSymbolCount};
use crate::chunk::Content;
use crate::defines_table;
use crate::js_meta;
use crate::options;
use crate::{Chunk, LinkerContext, StableRef, WrapKind};

/// TODO: investigate if we need to parallelize this function
Expand Down Expand Up @@ -135,6 +137,55 @@
);
}

// Scope hoisting rewrites module-scope `const`/`let` to `var` so the
// declaration can be split from its initializer when a module is wrapped.
// For `--format=esm --target=browser` the chunk has no wrapper, so those
// `var`s sit at the true top level. Loaded as a module that is fine, but
// loaded as a classic `<script>` a top-level `var`/`function` becomes a
// property of `globalThis`. When the original name collides with a host
// global that the code reads back through `window`/`defaultView`, the
// bundle silently overwrites it (Chart.js's `const getComputedStyle = …`
// recurses into itself via `defaultView.getComputedStyle`; #14110).

Check warning on line 148 in src/bundler/linker_context/renameSymbolsInChunk.rs

View check run for this annotation

Claude / Claude Code Review

Bug history embedded in code comment

The parenthetical "(Chart.js's `const getComputedStyle = …` recurses into itself via `defaultView.getComputedStyle`; #14110)" is bug history that already lives verbatim in the PR description — REVIEW.md's comment rule says bug history belongs there, not in code. The gating rationale (why `target=browser`, why skip `WrapKind::Cjs`, which symbol kinds) is durable design content and should stay; only the Chart.js/#14110 sentence needs trimming.
Comment thread
robobun marked this conversation as resolved.
Resolved
// Reserve any declared top-level name that is in the pure-global table so
// the number renamer suffixes the binding while unbound references to the
// real global keep the name.
//
// Gated to `target=browser` because Bun/Node load ESM output in module
// scope, where `var` never reaches `globalThis`. `WrapKind::Cjs` modules
// keep their declarations inside the `__commonJS` closure, so skip those
// too. Only symbol kinds that print as a VarScoped declaration at the
// chunk top level (`var`/`function`/`async function`/`function*`) are
// considered; `class` and `import` stay lexical and cannot clobber
// `globalThis`.
Comment thread
robobun marked this conversation as resolved.
Resolved
if c.options.output_format == options::OutputFormat::Esm
&& c.options.target == options::Target::Browser
{
for &source_index in files_in_order {
if all_flags[source_index as usize].wrap == WrapKind::Cjs {
continue;
}
let scope = &all_module_scopes[source_index as usize];
for member in scope.members.values() {
// SAFETY: `symbols` points to the live `c.graph.symbols`; read-only here.
let symbol = unsafe { &*symbols }.get_const(member.ref_).unwrap();
if matches!(
symbol.kind,
symbol::Kind::Hoisted
| symbol::Kind::HoistedFunction
| symbol::Kind::GeneratorOrAsyncFunction
| symbol::Kind::Constant
| symbol::Kind::Other
) && !symbol.must_not_be_renamed()

Check warning on line 178 in src/bundler/linker_context/renameSymbolsInChunk.rs

View check run for this annotation

Claude / Claude Code Review

Reservation matches! misses TsEnum/TsNamespace and ESM-hoisted Class kinds

The `matches!` misses two symbol kinds that also print as chunk-top-level `var`: (1) `TsEnum`/`TsNamespace` — a top-level `enum Event {…}` or `namespace URL {…}` emits `var Event;` via `generate_closure_for_type_script_namespace_or_enum` (p.rs:6108) while keeping kind `TsEnum`/`TsNamespace`; (2) `Class` in `WrapKind::Esm` modules — a non-movable class (`extends`, decorators, static block, computed key; `G::Class::can_be_moved`, g.rs:85) is hoisted to `var ClassName;` at `OutsideWrapperPrefix` (g
Comment thread
robobun marked this conversation as resolved.
Resolved
&& defines_table::is_pure_global_identifier(symbol.original_name.slice())
{
reserved_names
.put(symbol.original_name.slice(), 1)
.expect("unreachable");
}
}
}
}

let sorted_imports_from_other_chunks: Vec<StableRef> = {
let imports_from_other_chunks = match &chunk.content {
Content::Javascript(js) => js.imports_from_other_chunks.values(),
Expand Down
9 changes: 9 additions & 0 deletions src/js_parser/defines_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,15 @@ mod identifiers {
}
}

/// True when `name` is one of the pure global identifiers in
/// `defines_table.string-map.ts` (the ~640 well-known host/browser globals).
/// The bundler's renamer uses this to avoid emitting a chunk-top-level `var`
/// that would overwrite the global when an ESM bundle is loaded as a classic
/// script.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn is_pure_global_identifier(name: &[u8]) -> bool {
lookup_pure_global_identifier(name).is_some()
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub(crate) enum PureGlobalIdentifierValue {
NaN,
Expand Down
150 changes: 150 additions & 0 deletions test/bundler/bundler_edgecase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2831,6 +2831,156 @@ describe("bundler", () => {
},
120_000,
);
// https://github.com/oven-sh/bun/issues/14110
itBundled("edgecase/EsmTopLevelVarShadowsHostGlobal", {
files: {
"/entry.js": /* js */ `
import { getComputedStyle, requestAnimationFrame } from "./helpers.js";
const el = { ownerDocument: { defaultView: globalThis } };
console.log(getComputedStyle(el));
requestAnimationFrame(v => console.log(v));
`,
"/helpers.js": /* js */ `
export const getComputedStyle = el => el.ownerDocument.defaultView.getComputedStyle(el, null);
export const requestAnimationFrame = cb => cb("raf");
`,
},
format: "esm",
target: "browser",
runtimeFiles: {
"/run.cjs": /* js */ `
let calls = 0;
globalThis.getComputedStyle = function native() {
if (++calls > 1000) throw new RangeError("Maximum call stack size exceeded");
return "native";
};
globalThis.requestAnimationFrame = cb => cb("native-raf");
const src = require("fs").readFileSync(__dirname + "/out.js", "utf8");
// Indirect eval runs in the global scope so top-level "var" becomes a
// globalThis property, matching a classic <script> tag.
(0, eval)(src);
console.log("calls=" + calls);
`,
},
onAfterBundle(api) {
const out = api.readFile("/out.js");
expect(out).not.toMatch(/\bvar getComputedStyle\b/);
expect(out).not.toMatch(/\bvar requestAnimationFrame\b/);
expect(out).toContain("defaultView.getComputedStyle(");
},
run: {
file: "/run.cjs",
stdout: "native\nraf\ncalls=1",
},
});
itBundled("edgecase/EsmTopLevelVarShadowsHostGlobalUnboundReference", {
files: {
"/entry.js": /* js */ `
import { fetch as moduleFetch } from "./helpers.js";
console.log(moduleFetch());
console.log(typeof fetch);
`,
"/helpers.js": /* js */ `
export const fetch = () => "module fetch";
`,
},
format: "esm",
target: "browser",
onAfterBundle(api) {
const out = api.readFile("/out.js");
expect(out).not.toMatch(/\bvar fetch\b/);
expect(out).toMatch(/typeof fetch\b/);
},
run: { stdout: "module fetch\nfunction" },
});
itBundled("edgecase/EsmTopLevelVarShadowsHostGlobalScoping", {
files: {
"/entry.js": /* js */ `
import { Response as ModResponse } from "external-pkg";
import cjs from "./cjs.cjs";
export class Response { body = "mine"; }
console.log(new Response().constructor.name, cjs.URL, typeof ModResponse);
`,
"/cjs.cjs": /* js */ `
const URL = "cjs-url";
const fetch = () => "cjs-fetch";
module.exports = { URL, fetch };
`,
},
format: "esm",
target: "browser",
external: ["external-pkg"],
runtimeFiles: {
"/node_modules/external-pkg/index.js": `export const Response = 1;`,
},
onAfterBundle(api) {
const out = api.readFile("/out.js");
expect(out).toMatch(/\bclass Response\b/);
expect(out).not.toMatch(/\bclass Response2\b/);
expect(out).toMatch(/\bimport { Response\b/);
expect(out).toContain("{ URL, fetch }");
expect(out).not.toMatch(/\bURL2\b/);
},
run: { stdout: "Response cjs-url number" },
});
for (const target of ["bun", "node"] as const) {
itBundled(`edgecase/EsmTopLevelVarShadowsHostGlobalTarget_${target}`, {
files: {
"/entry.js": /* js */ `
import { getComputedStyle } from "./helpers.js";
const name = "app";
const status = "ok";
console.log(name, status, typeof getComputedStyle);
`,
"/helpers.js": /* js */ `
export const getComputedStyle = () => 0;
`,
},
format: "esm",
target,
onAfterBundle(api) {
const out = api.readFile("/out.js");
expect(out).toMatch(/\bvar getComputedStyle\b/);
expect(out).toMatch(/\bvar name\b/);
expect(out).toMatch(/\bvar status\b/);
},
run: { stdout: "app ok function" },
});
}
itBundled("edgecase/IifeTopLevelVarShadowsHostGlobal", {
files: {
"/entry.js": /* js */ `
import { getComputedStyle } from "./helpers.js";
globalThis.gcs = getComputedStyle;
`,
"/helpers.js": /* js */ `
export const getComputedStyle = el => el.ownerDocument.defaultView.getComputedStyle(el, null);
`,
},
format: "iife",
target: "browser",
runtimeFiles: {
"/run.cjs": /* js */ `
let calls = 0;
globalThis.getComputedStyle = function native() {
if (++calls > 1000) throw new RangeError("Maximum call stack size exceeded");
return "native";
};
const src = require("fs").readFileSync(__dirname + "/out.js", "utf8");
(0, eval)(src);
console.log(globalThis.gcs({ ownerDocument: { defaultView: globalThis } }));
console.log("calls=" + calls);
`,
},
onAfterBundle(api) {
const out = api.readFile("/out.js");
expect(out).toMatch(/\bvar getComputedStyle\b/);
},
run: {
file: "/run.cjs",
stdout: "native\ncalls=1",
},
});
itBundled("edgecase/NonAsciiPathDerivedWrapperName", {
files: {
"/entry.ts": /* js */ `
Expand Down
Loading