Repository navigation
Conversation
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 4 minutes. View limit details
No actionable comments were generated in the recent review. ℹ️ Recent review info
WalkthroughESM CommonJS wrappers conditionally receive a local ChangesCommonJS direct-eval require
Suggested reviewers: Priority: Severity of issue fixed: Medium Merge Risk:
|
|
Updated 12:46 AM PT - Oct 27th, 2026
✅ @robobun, your commit 6a7f94aae3f6dab1915ac7e04e6a53c9b1811bc5 passed in 🧪 To try this PR locally: bunx bun-pr 35581That installs a local version of the PR into your bun-35581 --bun |
|
Found 3 issues this PR may fix:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
src/bundler/LinkerContext.rs:3231-3243— This gate (output_format != Cjs && contains_direct_eval) is looser than the one ingenerateCodeForFileInChunkJS.rs, which additionally requiresmodule_scope.members["require"]to beKind::Unbound. When a wrapped CJS module has a user-levelvar require = …(orlet/const/function) plus direct eval, codegen setsneeds_require_arg = falseand emits a one-arg__commonJScall, but this block has already registered a use of__requireon the wrapper part, so tree-shaking keeps it live and the output carries a deadvar __require = import.meta.require(or, fortarget=node, an unusedcreateRequire(import.meta.url)call). Mirror theKind::Unboundcheck here — or better, hoist the decision into a single shared predicate — so the two sites agree.Extended reasoning...
What the bug is
The new require-binding feature is gated in two places, and the gates can diverge:
LinkerContext.rs:3231registers a use of the runtime__requiresymbol on the CJS wrapper part wheneveroutput_format != Cjs && module_scope.contains_direct_eval.generateCodeForFileInChunkJS.rs:539-551only emits the second__commonJSargument (and the third closure parameter) when, additionally,module_scope.members["require"]exists and its symbol kind isKind::Unbound. If it is notUnbound— the code even comments this: "User declared their ownvar require; it already shadows whatever we would pass" —require_arg_refbecomesNoneandneeds_require_arg = false.
When the second gate says "no" while the first has already said "yes", the wrapper part carries a recorded use of
__requirethat nothing in the printed output for that file consumes.The code path that triggers it
declare_common_js_symbol(p.rs:4443-4472) is called for"require"withKind::Unboundafterhoist_symbols. If the user wrotevar require = …at module scope,module_scope.members["require"]already holds the user'sHoistedsymbol. The merge branch at p.rs:4443-4450 requires both sides to beHoisted, but the incoming kind isUnbound, so it falls through and pushes the freshUnboundref ontomodule_scope.generated— leaving the user's non-Unboundsymbol inmembers["require"]. The codegen lookup then hits the_ => Nonearm.The same divergence occurs for
let require,const require, andfunction requiredeclarations — none of those produce anUnboundmember.Note that
runtime_require_ref.is_some()is equivalent tooutput_format != Cjs(set in generateCompileResultForJSChunk.rs:141 / postProcessJSChunk.rs:89), so that half of the two gates already agrees; the divergence is purely the missingKind::Unboundcheck on the LinkerContext side.Why existing code doesn't prevent it
Nothing in
LinkerContext.rsconsultsmodule_scope.members["require"]or the symbol table before callinggenerate_runtime_symbol_import_and_use. Tree-shaking runs after this registration and before codegen, so once the use is recorded the runtime__requirepart is kept live regardless of what codegen later decides to emit.Step-by-step proof
Bundle to ESM (
target: "bun"ortarget: "node", format: "esm"):// mod.cjs var require = globalThis.customRequire; // user declares their own require module.exports = eval("1 + 1"); // direct eval
output_format != Cjsandmodule_scope.contains_direct_eval == true→LinkerContext.rs:3231registers a use of__requireon the wrapper part.- Tree-shaking marks the runtime
__requirepart live. - Codegen looks up
module_scope.members["require"], finds the user'sHoistedsymbol, hits_ => None, soneeds_require_arg = false. - The wrapper is printed as
__commonJS(function(exports, module) { … })— one argument, no__requirepassed. - The chunk still contains
var __require = import.meta.require;(target=bun) orimport { createRequire } from "node:module"; var __require = createRequire(import.meta.url);(target=node) with no consumer from this call site.
Impact
No functional breakage — the bundle runs correctly. For
target=bunit is a handful of dead bytes; fortarget=nodeit also runscreateRequire(import.meta.url)at bundle load for nothing. The trigger (a top-level userrequirebinding plus direct eval in a wrapped CJS module bundled to non-CJS output) is extremely obscure. This is a code-quality / "one source of truth" concern rather than a correctness bug.How to fix
Mirror the
Kind::Unboundcheck inLinkerContext.rsso the predicate matches codegen exactly — or, given the comment-cop bot has already flagged both blocks, hoist "does this wrapped CJS file need the require arg?" into a single shared helper onLinkerGraph/BundledAstand call it from both sites. That satisfies REVIEW.md's "One source of truth" and "Every line you add must be demonstrably live" without duplicating the lookup.
There was a problem hiding this comment.
All three of my earlier findings are now addressed — including the predicate-divergence nit on LinkerContext.rs, which the current diff already mirrors with the same Unbound-require member check as the emit site (that inline comment is stale). Deferring only because this changes the __commonJS runtime signature and the linker's wrapper codegen, which is worth a human look.
What was reviewed:
__commonJSsignature change is additive; existing single-arg call sites keepreq/modundefined so the memoization slot still works, andcjs/NoRequireArgWithoutDirectEvalpins the two-arg wrapper shape.- Emit-side and tree-shake-side guards now agree (
contains_direct_eval+ Unboundrequirescope member); theast.require_ref-vs-polyfill hazard is covered by the new dynamic-require+eval tests, andruntime_require_ref.unwrap()is guarded byneeds_require_arg. - Snapshot / sourcemap / filesize bumps are the expected +9-byte shift from the longer
__commonJShelper text. - The other in-tree
__commonJShelpers (src/js/node/wasi.ts,querystring.ts,internal/fs/glob.ts) are independent local copies, not the bundler runtime — correctly left alone.
Extended reasoning...
Overview
The PR threads a working require binding into the __commonJS closure when the wrapped CJS body contains direct eval, so eval("require") (protobufjs's inquire probe) resolves. Touches: src/runtime.js (__commonJS gains a req parameter), src/bundler/LinkerContext.rs (records a use of the runtime __require for the wrapper part), src/bundler/linker_context/generateCodeForFileInChunkJS.rs (emits the third require closure param and passes __require as the second __commonJS arg), plus 8 new itBundled cases and mechanical sourcemap/filesize snapshot bumps.
Prior review status
I previously flagged three issues: (1) 🔴 the third parameter used ast.require_ref, which under auto_polyfill_require is the Kind::Other __require symbol rather than the Unbound require — fixed by looking up module_scope.members["require"] and filtering on Kind::Unbound, with new DirectEvalWithDynamicRequire{Bun,NodeESM} tests covering it; (2) 🟡 the node-target test wasn't actually running under Node — fixed with runtime: "node"; (3) 🟡 the tree-shake-side guard in LinkerContext.rs didn't mirror the emit-side Unbound check — the current diff already includes that check, so the inline comment I left at 10:07 is stale (it raced with commits 8b38851e/1dc8873f/d57c752f). All three are addressed in the code as it stands.
Security risks
None. This is bundler output-shape only; no untrusted input parsing, no filesystem/network paths change.
Level of scrutiny
High — src/runtime.js's __commonJS is inlined into every bundle that wraps a CJS module, and generateCodeForFileInChunkJS / LinkerContext are core linker paths. The signature change is small and backward-compatible (verified: single-arg callers leave req undefined; mod is still the memoization slot), but it does add ~9 bytes to every bundle carrying the helper regardless of whether direct eval is present. That's a design trade-off (per REVIEW.md "API design" / "Performance" — a shared runtime helper is user-facing surface) a maintainer should sign off on rather than me.
Other factors
Test coverage is solid across the variant matrix (bun / bun+minify / node-esm-run-under-node / compile / dynamic-require+eval / require.resolve identity / negative tree-shake check). The comment-cop bot's multi-line-comment flags were addressed by the "trim comments" commits. No outstanding human reviewer comments.
There was a problem hiding this comment.
All three earlier concerns are addressed: the wrapper parameter now uses the Unbound require scope member (not ast.require_ref), the tree-shaking guard in LinkerContext.rs mirrors the same Unbound check so the two sites can't diverge, and the node-target case runs under runtime: "node". Remaining inline comment is a test-hygiene nit only. Deferring to a human for final sign-off since this changes the __commonJS runtime signature and CJS-wrap codegen for every bundle.
Extended reasoning...
Overview
Threads a require binding into the __commonJS closure when the wrapped CJS body contains direct eval, so eval("require") (protobufjs's @protobufjs/inquire) resolves. Touches src/runtime.js (__commonJS gains a req parameter), generateCodeForFileInChunkJS.rs (emit third require param + second __commonJS arg), LinkerContext.rs (record __require use for tree-shaking), plus 8 new itBundled cases and mechanical sourcemap/filesize/snapshot updates.
Follow-up on prior review
The three issues I raised on earlier revisions are now fixed in the current diff:
- The 🔴
ast.require_ref-may-be-__require-polyfill bug: emit side now looks upmodule_scope.members["require"]and filters onKind::Unbound, andcjs/DirectEvalWithDynamicRequire{Bun,NodeESM}cover the dynamic-require + direct-eval combination with anonAfterBundleregex asserting the parameter is literallyrequire. - The 🟡 predicate divergence:
LinkerContext.rsnow applies the identicalcontains_direct_eval && members["require"].kind == Unboundguard before recording the__requireuse, so the tree-shaking side and the emit side cannot disagree. - The 🟡
runtime: "node"omission: both node-target tests now passruntime: "node".
The comment-cop warnings were also resolved (comments trimmed to single lines).
Security risks
None. No user-controlled input reaches new parsing/allocation; the change is codegen shape only.
Level of scrutiny
High — this is bundler linker/codegen on the path every wrapped CJS module takes, and it changes the __commonJS runtime helper signature (visible in the react-compiler snapshot and the +9-byte filesize delta). The mechanism relies on renamer semantics for Kind::Unbound symbols under minify, and on two sites (LinkerContext vs generateCodeForFileInChunkJS) computing the same predicate. A prior attempt (#28885) was rejected on approach grounds, so a maintainer should confirm this design.
Other factors
I verified the __commonJS signature change is backward-compatible: the second parameter was previously an unused memoization slot never passed by generated code, so shifting mod to position 3 and inserting req is safe for the existing single-arg call sites. The other __commonJS definitions in src/js/ are unrelated built-in-module locals. The one open inline comment is a nit about extracting a shared dynamicRequireFiles fixture — no correctness impact.
There was a problem hiding this comment.
All three rounds of my earlier feedback have been addressed and nothing new turned up this pass — the fix now looks correct and well-covered. Deferring to a human because this changes bundler codegen and the __commonJS runtime-helper signature (every CJS-wrapped bundle shifts, per the sourcemap/filesize snapshot updates), and it takes a different approach than the earlier #28885 attempt; a bundler maintainer should sign off on the shape.
What was reviewed:
__commonJSsignature change:modwas only ever a memoization slot with no external callers passing it, so insertingreqbefore it is safe.runtime_require_refprovenance: confirmed it is the runtime__requiresymbol (generateCompileResultForJSChunk.rs:141-148) and.unwrap()is guarded byneeds_require_arg.- The LinkerContext use-count guard and the emit-site guard now use the same Unbound-
require-member predicate; theast.require_ref-is-polyfill case is handled and tested (DirectEvalWithDynamicRequire*).
Extended reasoning...
Overview
Threads a working require binding into the __commonJS wrapper closure when the wrapped body contains direct eval, so that eval("require")(...) (the @protobufjs/inquire pattern pulled in by every gRPC / @google-cloud/* client) resolves instead of throwing ReferenceError. Touches src/runtime.js (__commonJS gains a req parameter), src/bundler/linker_context/generateCodeForFileInChunkJS.rs (adds the third closure param and second __commonJS call arg), src/bundler/LinkerContext.rs (records a use of __require so tree-shaking keeps it live), plus test additions in bundler_cjs.test.ts and mechanical snapshot/sourcemap-offset updates in bundler_edgecase.test.ts, bundler_npm.test.ts, and react-compiler.test.ts.snap.
Prior review status
I left three rounds of inline findings on earlier revisions (all now marked resolved), and each has been addressed in the current diff:
- The wrapper param now uses the parser's Unbound
requirescope member rather thanast.require_ref(which can be the file-local__requirepolyfill), with newDirectEvalWithDynamicRequire{Bun,NodeESM}tests covering the mixed direct-eval + dynamic-require case. - The Node-target ESM tests now set
runtime: "node"so they actually execute under Node. - The LinkerContext use-count predicate now mirrors the emit-site predicate (both check the Unbound scope member), so a user-shadowed
requireno longer leaves a dead__requireprelude. - The two dynamic-require test fixtures were deduplicated into
dynamicRequireFiles. - The comment-cop complaints about paragraph-length comments were resolved by trimming to single-line comments.
Security risks
None identified. This is bundler output-shape work; no auth/crypto/permissions/untrusted-input parsing is touched.
Level of scrutiny
High. src/runtime.js and the linker's CJS-wrapper codegen are on the hot path for every bundle that contains a CommonJS module — the 9-byte filesize delta and sourcemap column shifts in the snapshot updates show the blast radius. The approach (per-module parameter threading) also differs from the earlier #28885 attempt (setting globalThis.require), which is exactly the kind of design choice a maintainer should approve. The Unbound-symbol lookup is subtle enough that it took two revisions to get right.
Other factors
Test coverage is good: bun target, bun+minify, node ESM run under Node, --compile, require.resolve/identity via the eval'd handle, the dynamic-require + direct-eval mix, and a negative check that __require stays tree-shaken when there is no direct eval. I verified runtime_require_ref resolves to the runtime __require symbol and that the .unwrap() is guarded, and that no existing caller passes a second positional arg to __commonJS (the old mod was purely a memoization slot). Other in-tree __commonJS copies (src/js/internal/fs/glob.ts, src/js/node/wasi.ts, src/js/node/querystring.ts) are independent local helpers, not the bundler runtime, so they are correctly untouched.
|
Build #80748 ran
Ready for review. |
alii
left a comment
There was a problem hiding this comment.
The linker fix is right, the wrapper change is not the shape I'd land.
- --target=node --format=iife bundles with an eval-containing CJS dep go from loading to throwing at load (LinkerContext.rs:3226).
- Changing __commonJS touches every bundle with a wrapped CJS module;
var require = __require;in the wrapper prefix fixes only the modules that need it and drops the three snapshot updates. - Needs a rebase either way; bundler_npm.test.ts is the conflict and has to be re-measured against main, not delta-patched.
b77991f to
debe29c
Compare
debe29c to
2c1ba3e
Compare
|
Reworked per review and rebased onto main (2c1ba3e):
PR body updated to describe the current shape. |
alii
left a comment
There was a problem hiding this comment.
Looks ready to merge from this side. The new head is the inside_wrapper_prefix shape: runtime.js and the three snapshot files are untouched, both the liveness site and the emit site go through one esm-only predicate that reads the module scope's require member (always present, and replaced by the user's own symbol when the file declares one, so the Unbound check holds), the decl is a var appended after the directive, and CJS-wrapped files are always one contiguous part range so it is emitted once. Checked the three pin cases (node iife, shadowed require, typeof require) against main's binary; the seven remaining cases failing on main and passing here is per the PR's own run, not rebuilt here. One nit not worth a push: the body says 8 of 10 cases fail without the fix, it is 7 (NoRequireDeclWithoutDirectEval also passes both ways).
…s direct eval A direct eval in a bundled CommonJS file cannot see `require` in ESM output. The `__commonJS` closure has `exports` and `module` only. @protobufjs/inquire 1.1.0 hides its require this way, so protobufjs falls back to the plain Writer, serializers return Uint8Array, and grpc-js fails with "undefined undefined: undefined". When a wrapped CommonJS file contains a direct eval and does not declare its own require, prepend `var require = __require;` to the wrapper body (stmts.inside_wrapper_prefix) and mark the runtime __require part live. LinkerContext::direct_eval_require_ref is the one predicate for both sites. It reads the binding from the module scope, not ast.require_ref: the parser points ast.require_ref at the __require polyfill when the file also has a dynamic require(). The change applies to --format=esm only, the one format that emits the __require part. A bundle without such a file is byte for byte unchanged. Fixes #14891
A server build with an HTML import bundles the scripts of the page for
the browser, but the runtime `__require` is the server's. With the
previous commit, the browser copy of a CommonJS file with a direct eval
got `var require = __require;`. For --target=node that pulled
`import { createRequire } from "node:module"` into the browser chunk,
which a browser cannot load.
direct_eval_require_ref now returns None for a Target::Browser file when
the build target is server side. The server copy of the file keeps the
declaration. When only browser files contain the eval, the build output
is the same as on main.
Tests: the browser target (eval sees the `__require` shim), and two
HTML import builds.
2c1ba3e to
7dc8b83
Compare
|
Rebased onto main (6c1eb06). The branch conflicted only in
Reproduction: printf 'console.log(eval("typeof require"));' > index.cjs
bun build --target=bun index.cjs --outfile=out.js && bun out.jsbun 1.4.2 and main print |
There was a problem hiding this comment.
Beyond the inline findings, I also checked that the new var require = __require; prefix cannot print at chunk top level: it uses the same inside_wrapper_prefix slot as the existing "use strict" directive, and a __commonJS-wrapped file's wrapper part is live whenever any of its parts are. The --format=iife gap was also looked at — there is no __require part in that format, and the PR text names it as out of scope.
Extended reasoning...
The change adds a direct_eval_require_ref predicate in src/bundler/LinkerContext.rs, marks the runtime __require live for matching CJS-wrapped files, and prepends var require = __require; inside the wrapper in src/bundler/linker_context/generateCodeForFileInChunkJS.rs, with 13 new itBundled cases. It touches bundler output semantics (what a direct eval can reach) but no auth, crypto, or input-parsing surface. The approach changed since the last human review (closure parameter replaced by a prefix statement; src/runtime.js is no longer touched), and a CHANGES_REQUESTED review from a maintainer remains the latest human state, so approval is not appropriate; the inline findings cover the behavior tradeoffs a maintainer must weigh.
Findings marked 🟡 are optional suggestions and need no follow-up push.
Two cases from review: - A browser has no `require`. In a --target=browser build the eval'd `require` was the runtime shim, which throws `Dynamic require of "x" is not supported`. Code that hides `require` in an eval to detect Node then took the Node path. A browser file now gets no declaration, in a browser build and in a server build. Its output is the same as on main. - A --target=node build with an HTML import prints the runtime `__require` part in the browser chunk too, and that part imports `node:module`. Such a build now gets no declaration, as --format=iife already does. Tests: the browser target, --splitting, and two HTML import builds.
The previous commit excluded a --target=node build with an HTML import. An HTML file given as an entry point beside a server entry has the same browser chunk and no HTML import record, so that build still printed the node `__require` part (`import ... from "node:module"`) in the page script. The predicate now checks the entry points: a node build with a browser entry point gets no declaration. The check runs only for a file that already has a direct eval and no `require` of its own. Tests: a node build with an HTML entry point. The bun HTML import case now also checks that the browser chunk exists.
cc7e9fa to
672fe62
Compare
There was a problem hiding this comment.
I re-reviewed the latest push (672fe62) and found no bugs; since this changes linker codegen and an earlier human review requested changes on the previous approach, a bundler maintainer's look is still worthwhile.
What was reviewed:
- The new entry-point gate in
direct_eval_require_ref(src/bundler/LinkerContext.rs): both an HTML entry point (bundle_v2.rs:3578-3592) and an HTML import (bundle_v2.rs:7324-7328) push the HTML source as a Browser-target entry, so the node/browser-chunk case I raised on the prior push is now covered by one predicate. - The
__requireuse recorded at the wrapper part and thevar require = __require;prefix only fire together: both call the same predicate, andruntime_require_ts_refisSomefor every non-CJS output format. - cjs/DirectEvalInServerAndBrowserChunk now asserts the chunk count before the filter, so the browser-chunk negative check can no longer pass vacuously.
Extended reasoning...
The diff adds a predicate in src/bundler/LinkerContext.rs plus a var require = __require; prefix statement in src/bundler/linker_context/generateCodeForFileInChunkJS.rs for wrapped CommonJS files containing direct eval, and ~370 lines of itBundled tests. It touches no security-sensitive surface (no auth, injection, or data exposure), but it changes bundler output and runtime behaviour of eval'd require for bun and node targets. The latest commit addressed both inline findings from the previous run and the hunt ran dry, yet an outstanding CHANGES_REQUESTED review from a human maintainer on an earlier version of this PR has not been superseded by an approval, and the change is non-trivial linker code, so approval is not appropriate.
|
Merged main (8a0e49e) into this branch.
|
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-27. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Fixes #14891
Problem
evalin a bundled CommonJS file cannot seerequire:eval("require")(x)throwsReferenceError: require is not defined.@protobufjs/inquire@1.1.0does this, and grpc-js then fails withError: undefined undefined: undefined.function(exports, module)(src/bundler/linker_context/generateCodeForFileInChunkJS.rs:577).Fix
LinkerContext::direct_eval_require_refselects a file: ESM output, a bun or node file, a direct eval, no ownrequire. The linker then keeps the runtime__requireand starts the wrapper body withvar require = __require;.test/bundler/bundler_cjs.test.ts(15 new cases, 9 fail on main), all oftest/bundler/. Self-reviewed: 5 concerns raised, 5 addressed.Background
__commonJS.__requireis a runtime export, one definition per target, emitted only inesmoutput.requireparameter on the closure: it changes every bundle. The prefix statement changes only files with a direct eval.Downsides
requirenow loads modules at run time. A--compilebinary with inquire 1.1.0, started next tonode_modules/long, throws on int64 decode. Bun 1.4.2 does the same with inquire 1.1.2.--format=iife, ES module files, and a--target=nodebuild with an HTML page.__requireif absent (37 bytes bun, 109 node). Other bundles are byte-identical. Release binary:.text+1,024 bytes.Notes
Changes since the approved head 2c1ba3e
test/bundler/bundler_cjs.test.ts. Thesrc/hunks of the first commit are byte-identical to 2c1ba3e.src/bundler/LinkerContext.rs:3330). A browser file gets no declaration. A--target=nodebuild with a browser entry point (an HTML import or an HTML entry point) gets none. They add five test cases.Tests
bun bd test test/bundler/bundler_cjs.test.ts: 77 pass.iife, a user-declaredrequire, no direct eval, a browser build, and a node build with an HTML import or an HTML entry point.test/bundler/on release builds of main 6c1eb06 and of this branch: the 9 cases are the only difference. Two bytecode tests time out at 5 s on both builds in this container.bundler_cjs2esm,bundler_bun,bundler_edgecase,bundler_npm,bundler_minify,bundler_splitting,bundler_string,esbuild/default,esbuild/splitting,esbuild/dce,esbuild/extra,esbuild/lower,transpiler/react-compiler): no assertion failure. 11 cases exceed the 5 s default under ASAN and pass with a longer timeout.Behavior by output
Fixture: an ES module entry that imports a
.cjsfile witheval("typeof require")andeval("require")("buffer").--target=bun --format=esm"undefined",ReferenceError"function", the call works, +64 bytes--target=node --format=esm"undefined",ReferenceError"function", the call works, +136 bytes--target=browser,--format=iife,--format=cjs--splitting: a chunk that holds such a file imports__requirefrom the chunk that holds the runtime (cjs/DirectEvalSeesRequireSplitting).--minify: the name staysrequire. The parser keeps the symbolUnbound, and main pins module scope names of a CommonJS file with a direct eval.requiregets no declaration.Run-time require
Fixture:
protobufjs@7.2.5(protobufjs/minimal) with@protobufjs/inquire@1.1.0,--target=bun.finish()returnsUint8Array.util.Longis absent, so int64 decodes to a number.finish()returnsBuffer. protobufjs also callsinquire("long"). Whenlongresolves at run time, int64 decodes toLong, as it does unbundled. When it does not resolve, int64 decodes to a number. Bun can auto-installlongat run time when nonode_modulesdirectory exists.bun build --compile, binary started in the project directory:require("long")returns the ES module namespace ({ default }), and int64 decode throwsModule is not a constructor (evaluating 'new util.Long(...)'). bun 1.4.2 with inquire 1.1.2 does the same. The binary works in a directory with nonode_modules/long.--compile-autoload-package-jsonmakes it work in both.HTML import builds
import page from "./index.html"bundles the scripts of the page for the browser. The runtime module is the server's, and each chunk prints every live part of it.--target=bun: a server file with the eval gets the declaration, and the browser copy of the file gets none (cjs/DirectEvalInServerAndBrowserChunk). The browser chunk gainsvar __require = import.meta.require;(+37 bytes), which is inert in a browser.--target=node: the runtime__requirepart starts withimport { createRequire } from "node:module";, which a browser cannot load. Main prints it in the browser chunk when a server file has a dynamicrequire(name). This PR does not add a second way to reach that defect: a node build with a browser entry point gets no declaration, and its output is the same as on main. That covers an HTML import (cjs/DirectEvalNodeBuildWithHtmlImport) and an HTML file given as an entry point (cjs/DirectEvalNodeBuildWithHtmlEntryPoint).Not covered
--target=browser: a browser has norequire. The runtime__requirethere is a shim that throwsDynamic require of "x" is not supported. Code that hidesrequirein an eval to detect Node would take the Node path with it. The output is the same as on main (cjs/DirectEvalBrowserTargetHasNoRequire).--format=iifehas no__requirepart. Node loads such a file as CommonJS, sorequireexists there. In Bun,eval("typeof require")is still"undefined".__commonJS. A direct eval there still has norequirein the bundle. Unbundled Bun gives such a file arequirewhen the file references the name:const r = require("node:path"); export const t = eval("typeof require"); console.log(t)printsfunctionunbundled andundefinedbundled.__dirnameand__filenamein a direct eval are a separate parser change. Related to @prisma/internals fails when running a build #13194 and bundler: inject __dirname/__filename into CJS wrappers that use direct eval #35651.@prisma/internals@7.10.0haseval(`require('path').join(__dirname, '..')`). With this PR its error changes fromrequire is not definedto__dirname is not defined. One combined test case is wanted when both changes are merged.Workarounds on bun 1.4.2
bun update @protobufjs/inquiremoves 1.1.0 to 1.1.2, which has no eval.--banner 'var require = import.meta.require;'for--target=bun.--banner 'import { createRequire as __cr } from "node:module"; var require = __cr(import.meta.url);'for--target=node --format=esm.globalThis.require ??= require;as the first line of a CommonJS entry.--format=cjs.The linker still declares
requireby default for two reasons. The failure is silent and far from its cause: inquire catches the error and returnsnull, and the symptom appears in grpc-js. The declaration is local to the one wrapped file, and a banner applies to the whole chunk.Upstream
@protobufjs/inquire1.1.0 (2017-01-25) uses the eval. 1.1.1 (2026-04-27) and 1.1.2 (2026-05-17) callrequire(moduleName)directly.protobufjs@7.2.5resolves inquire 1.1.2 and bundles correctly on bun 1.4.2. A lockfile that pins 1.1.0 keeps it onbun install.bun buildandfirebase-admin: firestore not able to fetch a document when called inside an bundled executable. #19601 (duplicates of Issue with@protobufjs/inquirewhen bundled with Bun #14891).Measurements
size: text 89,151,860 to 89,152,884 bytes (+1,024),.text65,818,853 to 65,819,877 bytes (+1,024). The stripped file is 89,318,984 bytes in both.__requiredefinition is 37 bytes (bun) or 109 bytes (node), once per bundle, and only when the bundle did not have it.--minify) are byte-identical between the two release builds. So are thebrowser,iifeandcjsbuilds of a fixture with an affected file.contains_direct_evalcheck. The entry point scan runs only for a file with a direct eval and norequireof its own. It allocates nothing. Instruction counts are not measured:valgrindandperfare not installed in this container.Self-review
Five concerns were raised.
__require. Addressed: a browser file gets no declaration.cjs/DirectEvalBrowserTargetHasNoRequire.The review also asked for three follow-up issues. They are not filed:
require("long")from a compiled executable returns the ES module namespace,requirefor a direct eval in an ES module file, and the runtime__requirepart in the browser chunk of a server build.The automated review of the rebased head raised six points in two rounds. The later commits handle five: a node build with an HTML import, a node build with an HTML entry point, the browser target, a
--splittingtest, and a chunk count check. The sixth is the--compilecase under Downsides.Earlier revision
The first version of this PR added a third
requireparameter to the closure and areqargument to__commonJS. That changed the runtime helper in every bundle with a wrapped CommonJS file, and it made the__requirepart live iniifeoutput, where it does not exist. Review asked for the prefix statement, which changes only the files that need it.[review] gate passed · iteration 1 · 3 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 0 rejected · iteration 1
evidence per changed file