Repository navigation
bundler: no export table for a lifted CommonJS file that stays wrapped - #41334
Conversation
A lifted CommonJS file that require() reaches again prints its
exports.x = ... assignments inside a __commonJS wrapper. Step 5 still
built the namespace export part with getters for the lifted bindings.
A call of an own export (exports.x()) uses exports, which made that
part live, so __export(exports, {...}) was printed inside the wrapper.
The getters read bindings the wrapped file never declares.
Step 5 now skips the export aliases of such a file. Step 4 marks the
file as a user of exports, because the parser counted no use of it
once the assignments were lifted, and the wrapper needs the parameter.
Fixes #41333
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (3)
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review. WalkthroughThe bundler now preserves ChangesLifted CommonJS export handling
Suggested reviewers: Merge Risk: ⚪ Minimal · up to This fixes bundled lifted CommonJS modules so their CommonJS exports and wrapper semantics are preserved without generating invalid namespace export helpers. Targeted regression coverage confirms the affected output and runtime behavior, with no remaining merge-blocking risk identified. 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it changes what sorted_and_filtered_export_aliases holds for a class of files and that list feeds several downstream consumers (cross-chunk exports, entry-point export clauses, reserved names, metafile), a human look from someone familiar with the linker would still be worthwhile.
What was reviewed:
- Verified the
else ifrestructuring inscanImportsAndExports.rspreserves the original setter-param condition (lifted && wrap != Cjs && export_kind != Cjs). - Checked the new unsafe SoA reads in
doStep5.rsfollow the same per-row-before-write pattern as the movedis_lifted_commonjsread. - Confirmed the two
itBundledtests assert both output shape (no__export(, wrapper takesexports) and runtime stdout, covering colliding and distinct export names.
Extended reasoning...
Overview
This PR fixes a bundler linker bug where a CommonJS file lifted to ESM (COMMONJS_LIFTED_TO_ESM) but then re-wrapped as __commonJS (because something require()s it) still emitted an __export(...) getter table for the lifted bindings — bindings the wrapped body never declares, since the wrapper prints the original exports.x = ... form. Two files change: doStep5.rs now skips the resolved-exports alias loop entirely when is_lifted_commonjs && wrap == Cjs, so sorted_and_filtered_export_aliases becomes empty for such files; scanImportsAndExports.rs sets USES_EXPORTS_REF on those files so the wrapper closure receives exports, and restructures the existing setter-param branch into an else if that is semantically equivalent to the old condition. Two new itBundled tests reproduce the public-encrypt-style shape.
Security risks
None. This is bundler output-generation logic with no auth, crypto, network, or filesystem trust boundary in play. The unsafe blocks touched are the existing SoA per-row column reads already used throughout step 5; the new read of meta.flags[id].wrap follows the same "own row, before create_exports_for_file writes" pattern as the pre-existing ast.flags read that was merely hoisted.
Level of scrutiny
Moderate-to-high. The linker is a hot, subtle, parallelized subsystem, and this change alters an invariant — sorted_and_filtered_export_aliases is now empty for lifted-then-wrapped CJS files. The PR description asserts that downstream consumers (entry-point export clauses, cross-chunk exports, reserved-name computation, metafile) already special-case wrap == Cjs entry points as default-only, which is plausible and consistent with plain CJS files having no resolved exports, but it is exactly the kind of "every consumer already handles this" claim that benefits from a reviewer who knows the linker's downstream flow. The USES_EXPORTS_REF set is a small behavioral change whose only stated purpose is making the wrapper signature include exports; a linker-familiar reviewer can quickly confirm it has no other side effects.
Other factors
The bug hunt ran to a dry streak with no findings. No CODEOWNERS entry covers src/bundler/. The else if restructuring is behavior-preserving for the setter-param path (the else implies wrap != Cjs given is_lifted_commonjs is true in both arms). Tests are well-placed in the existing bundler_cjs2esm.test.ts, use itBundled, and assert exact output substrings plus runtime stdout — meeting the REVIEW.md bar of asserting the strongest invariant rather than just "it runs". The change is small and surgical, but the blast radius of a wrong assumption here is silently-broken bundle output for edge-case module graphs, which argues for a human sanity check rather than auto-approval.
Problem
require()reaches stays in a__commonJSwrapper. If it calls one of its own exports (exports.publicEncrypt(k)), the bundle prints__export(exports, { publicEncrypt: () => $publicEncrypt, ... })inside that wrapper.$publicEncryptis never declared there, so the getters returnundefinedor throwReferenceError: $publicEncrypt is not defined. Thecryptobrowser polyfill (public-encryptthroughcrypto-browserify) has this shape.exports, which makes the namespace export part live. Step 5 (src/bundler/linker_context/doStep5.rs) still built that part for a wrapped lifted file, with getters for the lifted bindings. Before bundler: keep this for a call of an export in its own lifted file #41273 the part existed but was dead.Fix
wrapisCjs. Its namespace is the realmodule.exports, so it gets no export getters. This matches a plain CommonJS file, which has no resolved exports.scanImportsAndExports.rs) setsUSES_EXPORTS_REFon such a file. The parser counts no use ofexportsafter it lifts the assignments, and the__exportpart used to set the flag as a side effect. The wrapper needs theexportsparameter to printexports.x = ....cryptopolyfill built with this branch loads in node andpublicEncryptis a function.test/bundler/bundler_cjs2esm.test.ts(2 new tests, both fail on main). Alsobundler_cjs,bundler_browser,bundler_splitting,bundler_edgecase,bundler_esbuild_default,esbuild/importstar,esbuild/default.Background
COMMONJS_LIFTED_TO_ESM) turnsexports.foo = xintovar $foo = xplus an ES module export, so importers bind to$foodirectly.require(), step 1 setswrap = Cjs. The printer then prints the originalexports.foo = xform inside a__commonJS(function(exports, module) { ... })wrapper.__export(exports, {...}): getters that expose a file's ES module bindings on a namespace object. Any part that uses the file'sexportssymbol pulls it in.Notes
bun build entry.js --outfile=out.js && node out.jsprintsundefined undefinedon main andfunction functionwith this branch.undefined), one with distinct names (the getter would throwReferenceError).wrap == Cjsis the same condition the printer uses forcommonjs_named_exports_deoptimized, so step 5 and the printer agree on which files printexports.x = ....sorted_and_filtered_export_aliasesis now empty, as for a plain CommonJS file. The consumers of that list (entry point export clauses, cross-chunk exports, reserved names, metafile) already treat awrap == Cjsentry point asdefaultonly.[human-review] gate passed · iteration 0 · 3 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 0 rejected · iteration 0
evidence per changed file