Skip to content

bundler: no export table for a lifted CommonJS file that stays wrapped - #41334

Merged
Jarred-Sumner merged 4 commits into
mainfrom
robobun/ae9d7a86/wrapped-lifted-cjs-exports
Sep 4, 2026
Merged

Jarred-Sumner merged 4 commits into
mainfrom
robobun/ae9d7a86/wrapped-lifted-cjs-exports

Conversation

@robobun

@robobun robobun commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • A lifted CommonJS file that require() reaches stays in a __commonJS wrapper. If it calls one of its own exports (exports.publicEncrypt(k)), the bundle prints __export(exports, { publicEncrypt: () => $publicEncrypt, ... }) inside that wrapper. $publicEncrypt is never declared there, so the getters return undefined or throw ReferenceError: $publicEncrypt is not defined. The crypto browser polyfill (public-encrypt through crypto-browserify) has this shape.
  • Cause: bundler: keep this for a call of an export in its own lifted file #41273 records the call as a use of 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

  • Step 5 skips the export aliases of a lifted file whose wrap is Cjs. Its namespace is the real module.exports, so it gets no export getters. This matches a plain CommonJS file, which has no resolved exports.
  • Step 4 (scanImportsAndExports.rs) sets USES_EXPORTS_REF on such a file. The parser counts no use of exports after it lifts the assignments, and the __export part used to set the flag as a side effect. The wrapper needs the exports parameter to print exports.x = ....
  • Self-reviewed. The crypto polyfill built with this branch loads in node and publicEncrypt is a function.
  • Verified: test/bundler/bundler_cjs2esm.test.ts (2 new tests, both fail on main). Also bundler_cjs, bundler_browser, bundler_splitting, bundler_edgecase, bundler_esbuild_default, esbuild/importstar, esbuild/default.

Background

  • Lifting (COMMONJS_LIFTED_TO_ESM) turns exports.foo = x into var $foo = x plus an ES module export, so importers bind to $foo directly.
  • The linker can undo that choice per file. When another file reaches the lifted file through require(), step 1 sets wrap = Cjs. The printer then prints the original exports.foo = x form inside a __commonJS(function(exports, module) { ... }) wrapper.
  • The namespace export part (part index 0) holds __export(exports, {...}): getters that expose a file's ES module bindings on a namespace object. Any part that uses the file's exports symbol pulls it in.
Notes
  • Repro from the issue: bun build entry.js --outfile=out.js && node out.js prints undefined undefined on main and function function with this branch.
  • The two new tests: one with names that collide with the importer's lifted bindings (the issue's shape, values become undefined), one with distinct names (the getter would throw ReferenceError).
  • wrap == Cjs is the same condition the printer uses for commonjs_named_exports_deoptimized, so step 5 and the printer agree on which files print exports.x = ....
  • For a wrapped lifted file, sorted_and_filtered_export_aliases is 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 a wrap == Cjs entry point as default only.

[human-review] gate passed · iteration 0 · 3 files touched

fails on main (without fix)
ASAN without fix: 2 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" "test/bundler/bundler_cjs2esm.test.ts"
bun test v1.4.1 (e0a2b82fd)

test/bundler/bundler_cjs2esm.test.ts:
(pass) bundler > cjs2esm/ModuleExportsFunction [795.05ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJSModuleRef [344.08ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJS [335.57ms]
(pass) bundler > cjs2esm/BadNamedImportNamedReExportedFromCommonJS [318.47ms]
(pass) bundler > cjs2esm/ExportsFunction [320.54ms]
(pass) bundler > cjs2esm/ModuleExportsFunctionTreeShaking [392.07ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequire [387.86ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPoint [429.30ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPoint [374.92ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPointSplitting [378.07ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireTwoEntryPoints [410.52ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvProduction [515.96ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvDevelopment [434
... (truncated)

release without fix: 4 FAILED
bun test v1.4.1-canary.1 (e0a2b82fd)

test/bundler/bundler_cjs2esm.test.ts:
(pass) bundler > cjs2esm/ModuleExportsFunction [20.81ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJSModuleRef [8.72ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJS [7.45ms]
(pass) bundler > cjs2esm/BadNamedImportNamedReExportedFromCommonJS [7.19ms]
(pass) bundler > cjs2esm/ExportsFunction [8.91ms]
(pass) bundler > cjs2esm/ModuleExportsFunctionTreeShaking [7.83ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequire [7.49ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPoint [8.83ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPoint [8.44ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPointSplitting [9.70ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireTwoEntryPoints [7.64ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvProduction [9.05ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvDevelopment [8.86ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRuntimeCondition [9.79ms]
(pass) bundler > cjs2esm/UnwrappedModuleRequireAssigned [7.93ms]
(pass) bundler > cjs2esm/UnwrappedModuleRequi
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" "test/bundler/bundler_cjs2esm.test.ts"
bun test v1.4.1 (e0a2b82fd)

test/bundler/bundler_cjs2esm.test.ts:
(pass) bundler > cjs2esm/ModuleExportsFunction [719.04ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJSModuleRef [332.80ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJS [402.09ms]
(pass) bundler > cjs2esm/BadNamedImportNamedReExportedFromCommonJS [388.61ms]
(pass) bundler > cjs2esm/ExportsFunction [387.06ms]
(pass) bundler > cjs2esm/ModuleExportsFunctionTreeShaking [390.34ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequire [383.98ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPoint [358.33ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPoint [378.05ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireEntryPointImportedByEntryPointSplitting [447.54ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequireTwoEntryPoints [349.82ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvProduction [578.04ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvDevelopment [495
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 607ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/141] gen JS modules (bundle-modules)
Preprocess modules (7326ms)
Bundle modules (673ms)
Postprocesss modules (999ms)
Bundle Functions (725ms)
Generate Code (36ms)

[9.78s] Bundled "src/js" for production
  2595 kb
  197 internal modules
  13 native modules
  50 internal functions across 16 files
[1/141] cargo bun_runtime → libbun_runtime.a
�[1m�[92m   Compiling�[0m bun_output_tags v0.0.0 (/workspace/bun/src/bun_output_tags)
�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_opaque v0.0.0 (/workspace/bun/src/opaque)
�[1m�[92m   Compiling�[0m bun_wyhash v0.0.0 (/workspace/bun/src/wyhash)
�[1m�[92m   Compiling�[0m bun_highway v0.0.0 (/workspace/bun/src/highway)
�[1m�[92m   Compiling�[0m bun_dispatch v0.0.0 (/workspace/bun/src/dispatch)
�[1m�[92m   Compiling�[0m bun_simdutf_sys v0.0.0 (/workspace/bun/src/simdutf_sys)
�[1m�[92m   Compiling�[0m bun_mimalloc_sys v0.0.0 (/workspace/bun/src/mimalloc_sys)
�[1m�[92m   Compiling�[0m bun_core_macros v0.0.0 (/works
... (truncated)
diff hotspot
src/bundler/linker_context/doStep5.rs              | 22 +++++---
 .../linker_context/scanImportsAndExports.rs        | 21 ++++----
 test/bundler/bundler_cjs2esm.test.ts               | 62 ++++++++++++++++++++++
 3 files changed, 90 insertions(+), 15 deletions(-)

gate history · 1 passed · 0 rejected · iteration 0

evidence per changed file
file                                                 reads  edits  tests
src/bundler/linker_context/doStep5.rs                    1      4      5
src/bundler/linker_context/scanImportsAndExports.rs      1      1      5
test/bundler/bundler_cjs2esm.test.ts                     1      1      5

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
@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 6735ce17-841f-45c8-a3c3-6cdf9193f6f9

📥 Commits

Reviewing files that changed from the base of the PR and between b1f7b8e and 5ec07a9.

📒 Files selected for processing (3)
  • src/bundler/linker_context/doStep5.rs
  • src/bundler/linker_context/scanImportsAndExports.rs
  • test/bundler/bundler_cjs2esm.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


Walkthrough

The bundler now preserves exports references for lifted CommonJS modules wrapped as CommonJS and skips unnecessary namespace export aliases. Regression tests cover self-method calls, this behavior, wrapper retention, and omitted export helpers.

Changes

Lifted CommonJS export handling

Layer / File(s) Summary
Preserve CommonJS export references
src/bundler/linker_context/scanImportsAndExports.rs
Lifted CommonJS modules wrapped as CommonJS now set USES_EXPORTS_REF. Non-CommonJS lifted modules continue to receive a generated setter parameter.
Skip redundant aliases and validate output
src/bundler/linker_context/doStep5.rs, test/bundler/bundler_cjs2esm.test.ts
Namespace export getter generation is skipped for wrapped lifted CommonJS files. Regression tests verify self-method calls, this behavior, retained __commonJS wrappers, and omitted __export helpers.

Suggested reviewers: jarred-sumner

Merge Risk: ⚪ Minimal · up to 79ae2

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)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main fix: preventing an export table for a lifted CommonJS file that remains wrapped.
Description check ✅ Passed The description explains the problem, cause, fix, affected files, tests, and verification results. It does not use the exact template headings, but it provides the required information and is mostly c…

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

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.

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 if restructuring in scanImportsAndExports.rs preserves the original setter-param condition (lifted && wrap != Cjs && export_kind != Cjs).
  • Checked the new unsafe SoA reads in doStep5.rs follow the same per-row-before-write pattern as the moved is_lifted_commonjs read.
  • Confirmed the two itBundled tests assert both output shape (no __export(, wrapper takes exports) 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.

@robobun

robobun commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:01 PM PT - Sep 3rd, 2026

@robobun, your commit fdbf0cc is building: #110058

@Jarred-Sumner
Jarred-Sumner merged commit aad89da into main Sep 4, 2026
8 of 9 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the robobun/ae9d7a86/wrapped-lifted-cjs-exports branch September 4, 2026 06:01

@claude claude Bot left a comment

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.

Code review found no issues

No high-confidence issues detected in this change.

This review covers commit 9325b00, which is no longer the latest commit on this pull request; later commits are not covered by it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants