Repository navigation
Conversation
|
Updated 4:14 AM PT - Oct 24th, 2026
✅ @robobun, your commit 450309b15979432a9bd75bbfd1e7bcbcad8d741e passed in 🧪 To try this PR locally: bunx bun-pr 34112That installs a local version of the PR into your bun-34112 --bun |
|
Found 3 issues this PR may fix:
🤖 Generated with Claude Code |
|
Verified all three against this change (the |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
CommonJS result handling src/jsc/bindings/ModuleLoader.cpp, src/jsc/bindings/ModuleLoader.h, src/jsc/bindings/ZigSourceProvider.cpp |
The result handler evaluates a supplied CommonJS module or creates one when needed. Pending results retain the module graph, which the async callback passes back with the original specifier. A source-provider assertion checks that CommonJS status matches sourceType == Program. |
CommonJS exports and plugin interoperability test/js/bun/plugin/module-plugins.ts, test/js/bun/plugin/plugins.test.ts |
Plugin fixtures and tests cover module.exports, exports.*, onLoad, import and require behavior, export mapping, side effects, errors, and pass-through loading. |
Async resolution, runtime state, and coverage test/js/bun/plugin/module-plugins.ts, test/js/bun/plugin/plugins.test.ts, test/cli/test/coverage.test.ts |
Tests cover execution and retry behavior, module-graph state, cache behavior, wrapper overrides, isolation, strict code-generation restrictions, and coverage for a plugin-loaded CommonJS module. |
Suggested reviewers: jarred-sumner
Priority:
Severity of issue fixed: Medium
Merge Risk: 
Minimal · up to ff514
-
No actionable merge-blocking issue is identified; the change is mergeable after normal checks.
Pre-merge checks: 
4
-
Full details: Linked Issues check
-
Explanation
Directly linked issue
#19279requires that a plugin onLoad result with loader 'js' and CommonJS contents (module.exports.foo = "foo";) provides named imports to the importer, including under bun test. The whole-PR diff of src/jsc/bindings/ModuleLoader.cpp adds an arm in handleVirtualModuleResult that checks res->result.value.isCommonJSModule. When no CommonJS module exists yet, the arm calls Bun::createCommonJSModule with a source provider built from the plugin text, so module.exports keys become named exports. When a CommonJS module exists (require path), the arm calls commonJSModule->evaluate. The PR description reports test/js/bun/plugin/plugins.test.ts and test/cli/test/coverage.test.ts as 197 passing on this PR and 42 failing on main. The PR description also states that the plugin test file could not run on the author's machine and defers to CI. Residual uncertainty: this assessment did not read every new test body. The conclusion relies on the implementation hunk, the PR description, and the test names in the summary.
Full details: Out of Scope Changes check
-
Explanation
All changed areas connect to the CommonJS plugin result path required by
#19279. (1) The isCommonJSModule arm in handleVirtualModuleResult is the core fix. (2) The hasOverriddenModuleWrapper branch selects the wrapper-aware evaluation path inside that same arm. It does not alter file-on-disk handling. (3) The early return for a pending promise, guarded by commonJSModule and !wasModuleMock, changes only require() of a pending plugin promise. The PR description states that this still throws. (4) The ModuleGraph field in PendingVirtualModuleResult and its forwarding through fetchESMSourceCode and jsFunctionOnLoadObjectResultResolve supports the require.cache placement of the same plugin CommonJS modules. (5) The debug-only ASSERT in ZigSourceProvider.cpp checks the CommonJS flag against the Program source type for the new arm. (6) Test and fixture changes in plugins.test.ts, module-plugins.ts, and coverage.test.ts exercise this path. The PR description discloses the resulting behavior changes, including files that previously reported 0 tests now running. No change was found that is unrelated to plugin CommonJS handling. Residual uncertainty: the full test file bodies were not read in this review.
Full details: Description check
-
Explanation
The description provides a detailed explanation of the problem, fix, scope, limitations, and verification results. It does not use the template headings exactly, but it includes the required information under equivalent sections such as Problem, Fix, and Tests.
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands.
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
…uator
A runtime Bun.plugin onLoad/module() callback returning contents that the
transpiler detects as CommonJS (module.exports, exports.x, bare require())
produced a silent empty module: the body never evaluated, side effects never
ran, import() succeeded with zero exports, and require() returned {}.
handleVirtualModuleResult's OnLoadResultTypeCode arm called
Bun__transpileVirtualModule and then unconditionally wrapped the result in an
ESM Zig::SourceProvider, never checking res->result.value.isCommonJSModule.
The transpiler had printed the source as a CJS wrapper function that nothing
ever invoked. Every other consumer of a transpile result (Bun__onFulfillAsyncModule,
fetchESMSourceCode, fetchCommonJSModuleNonBuiltin) already branches on
isCommonJSModule; this one did not.
Route the CJS case through commonJSModule->evaluate() (require path) or
Bun::createCommonJSModule() (import path), matching the on-disk code path.
Co-authored-by: isaacs <i@izs.me>
9bc93d5 to
a8bb4a4
Compare
|
Re: duplicate detection. #31770 (@isaacs, June 3) does make the same source change. It currently has merge conflicts against |
runVirtualModule runs before the IsolatedModuleCache lookup in both fetchCommonJSModule and fetchESMSourceCode, so routing virtual CJS through evaluate()/createCommonJSModule() inserted without a prior lookup. Under bun test --isolate, loading the same virtual CJS specifier from two files tripped ASSERT_WITH_MESSAGE(result.isNewEntry) in debug. Plugin output is not the on-disk file at the cache key anyway, so pass isBuiltIn=true to suppress the insert.
… isBuiltIn isBuiltIn=true also skips code coverage, changes SourceOrigin to builtin://, and on the require() path with an overridden Module.wrap skips the original source_code deref before the pointer is overwritten at :1383. Thread a dedicated skipIsolationCache bool that gates only the IsolatedModuleCache insert so plugin-sourced CJS keeps isBuiltIn=false for SourceProvider::create.
|
CI on 2d80dbf (build 93749, rebased onto current Remaining CI failures on 93749 are 9 lanes all tagged Ready for a maintainer to merge (or to close in favor of #31770). |
…ed async plugin result require() of an async virtual module throws 'async module unsupported' and removes its requireMap entry, but the then-reaction wired onto the plugin's promise still fires later. For CJS contents that reaction now reaches createCommonJSModule, which would re-insert a fresh unevaluated entry into require.cache. Record wasRequire on PendingVirtualModuleResult and have the resolve handler bail when the specifier is no longer in requireMap (i.e. the originating require() already threw and cleaned up). The already-fulfilled-promise require path is unaffected since its requireMap entry is still present when the reaction runs.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/jsc/bindings/ModuleLoader.cpp`:
- Around line 395-416: Update the async virtual-CJS completion path around
createCommonJSModule to pass false, true so it also skips the isolation cache,
matching the synchronous branch shown here. Add isolate regression coverage for
both async module() and import() virtual-CJS flows.
In `@test/js/bun/plugin/plugins.test.ts`:
- Around line 332-342: Replace the timing-based Bun.sleep(5) wait in the async
CommonJS module test with a fixture-controlled settlement promise that resolves
when the plugin’s continuation has completed. Await that signal before the
second require.cache assertion, preserving the existing side-effect and error
expectations without relying on timing.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: d0d82829-45db-4c26-adfa-a9f03a7bb187
📒 Files selected for processing (6)
src/jsc/bindings/JSCommonJSModule.cppsrc/jsc/bindings/JSCommonJSModule.hsrc/jsc/bindings/ModuleLoader.cppsrc/jsc/bindings/ModuleLoader.htest/js/bun/plugin/module-plugins.tstest/js/bun/plugin/plugins.test.ts
…olate coverage to async import()
…plugin-cjs-virtual-module
…he CommonJS evaluator The merge of main left the earlier fix uncompilable. createCommonJSModule takes a JSModuleGraph since #42590. This reworks the fix on main. handleVirtualModuleResult reads isCommonJSModule after it transpiles a plugin's contents. The arm builds the Program provider and calls the overloads of JSCommonJSModule::evaluate and createCommonJSModule that take a provider. Those overloads never insert into the IsolatedModuleCache, so the skipIsolationCache parameter is removed. With an overridden Module.wrapper the arm calls the ResolvedSource overloads. They apply the override and do not cache in that state. fetchESMSourceCode forwards its graph and key. PendingVirtualModuleResult carries the graph in a 4th internal field. An import from a Bun.ModuleGraph puts the module in the require cache of that graph. require() of a pending plugin promise returns before a pending cell exists. fetchCommonJSModule throws as before, and nothing loads the text later. The wasRequire flag is removed. Zig::SourceProvider::create asserts that a CommonJS source is a Program and that no other source is. Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
… file The subprocess cases move into a describe block of their own. New cases: - A table of CommonJS texts. Each is loaded by import(), require(), import.meta.require() and an import statement, from a sync and a pending callback, and compared with the same text on disk. - The body runs once for import then require, and for require then import. - A body that throws on require() runs again on the next require(). - A plugin-served entry point, and a plugin-served test file under bun test. - A module of a Bun.ModuleGraph, from a sync and a pending callback. - An overridden Module.wrapper. - --disallow-code-generation-from-strings=strict. - The repro of #39786. Under --isolate, the next test file must get the file from disk, not the plugin's text. The case for require() of a pending promise now also loads the module by import() afterwards.
….wrapper override An import under an override does not run the module body, for a file and for a plugin's text alike. The comment said that the override is applied.
- The table runs a second time in a package of type "module", where an import does not read the __esModule flag. - New rows: a `// @Bun @bun-cjs` text, an empty .cjs file, jsx and tsx loaders, contents as bytes, and a result with no loader. - require() of an ES module that imports the text (the fetch without a promise). - A Bun.ModuleGraph in the test process itself, and a module that a required ES module imports in a graph. - An import under an overridden Module.wrapper gives what a file gives. - Code coverage: the text is covered when one test file imports it and the next requires it under --isolate.
…plugin-cjs-virtual-module
contents from onLoad() and build.module() as CommonJS
|
Status for 450309b:
|
…ocess output A build.module() callback that is async and awaits nothing returns a promise that is already fulfilled. require() loads its CommonJS source at once. The three `bun test` cases assert stdout, each (pass) or (fail) line, the counts and the exit code in one object. The two .cts and .mts pass-through cases use the run() and json() helpers of the block.
Seven cases deleted their module from require.cache after the last expect. A failed assertion skipped the delete, and the next case that loads the same name got the cached module.
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-24. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Fixes #19279
Part of #39786 (the CommonJS half)
Problem
Bun.pluginthat returns CommonJScontentsfromonLoadorbuild.module()gives a silent empty module: the body never runs.bun testprintsRan 0 testsfor such a file.handleVirtualModuleResult(src/jsc/bindings/ModuleLoader.cpp:408) wraps every transpile result in an ES module provider and never readsisCommonJSModule.Fix
isCommonJSModule.require()evaluates its target and an import callscreateCommonJSModule. Both use the source provider overloads.fetchESMSourceCodeforwards itsBun.ModuleGraphand a pending plugin promise keeps it, so the module goes into that graph'srequire.cache.require()of a pending plugin promise still throws, and nothing loads the text later.test/js/bun/plugin/plugins.test.ts,test/cli/test/coverage.test.ts(43 cases fail on main). Self-reviewed: 15 concerns raised, 14 addressed (Notes).Background
JSCommonJSModulecalls it. Nothing calls it in an ES module.bun test --isolatecaches each file's transpiled source by path (IsolatedModuleCache). Plugin text must stay out. The provider overloads never insert there.contentsthrough the file consumers): it changes functions that every load runs. This PR changes only the plugin arm.Downsides
.textgrows by 2304 bytes (size -A). A pending plugin import allocates 64 bytes, not 48 (heap snapshot).json,tomlandyamlloaders through the same arm stay wrong (Bun.plugin: honor the json, toml, yaml and xml loaders for onLoad and build.module() results #39057).Notes
Repro
Text that the transpiler reads as CommonJS has the bug:
module.exports,exports.x, arequire()call,typeof module, a top-levelthis. The same text in a file on disk works. The tests compare each result with that file.Measurements (release builds of the merge base 5c6d4e2 and of this PR, same machine, same flags)
fetchESMSourceCode<true>. no-pluginrequire(): 129 -> 129 injsFunctionRequireCommonJSand 152 -> 152 infetchCommonJSModule.import.meta.require()of an ES module: 108 -> 108 infetchESMSourceCodeSync. (gdb single-step count of one call, calls stepped over)JSCommonJSModule::evaluateandcreateCommonJSModule(both overloads of each),Zig::SourceProvider::create,IsolatedModuleCache::insert,jsFunctionRequireCommonJS,Bun__onFulfillAsyncModule: 0 bytes changed (nm -Sand a disassembly diff). The ASSERT is not in a release build..text: +2304 bytes (size -A).handleVirtualModuleResult<true>/<false>: +1294 / +907 bytes (nm -S).handleVirtualModuleResult<true>, 12 -> 13 conditional branches, +0 cells for each load (gdb single-step,heapStats()).PendingVirtualModuleResult: 48 -> 64 bytes allocated for each pending plugin import (heap snapshot).require()of a pendingbuild.module():PendingVirtualModulecells 200 -> 0, promises +400 -> +200,unhandledRejectionevents for text that does not parse 200 -> 0.Behaviour changes
coverageThreshold. A throw at load time is no longer hidden behind{}. This includes files in a"type": "module"package that have noimportorexportand callrequire().require()of a promise-returning callback throwsrequire() async module ... is unsupported, Bun no longer transpiles the text when the promise settles. Before, text with a syntax error gave a lateunhandledRejection. A promise that rejects still gives oneunhandledRejection.--disallow-code-generation-from-strings=strict, as ES text from a plugin is.Not fixed here
loader: "json"gives aSyntaxError.toml,yamlandxmlgive{}. Bun.plugin: honor the json, toml, yaml and xml loaders for onLoad and build.module() results #39057 and bun test: Vitest compatibility #44833 have these.Module.wrapperdoes not run the module body. A file on disk has the same result, and the test asserts only that the two are equal.require()applies the override for plugin text, as for a file.require()already loaded makes a source provider for the plugin's text and drops it. For text that is already bundled (// @bun), the dropped provider takes the module's source map entry with it: a frame that issrc.ts:5:13afterrequire()isvirt:bundled:48:18afterimport(). A file on disk keeps its mapping. With--coverage, if that text is not the text of the loaded module, the coverage row follows the plugin's text. By reading, bun test: Vitest compatibility #44833 makes its provider at the same point.require()of a plugin promise that is already rejected still reports anunhandledRejection(Bun.plugin: mark the loader's promise handled when require() cannot wait for a plugin's promise #37038).package.jsonwith"type": "commonjs", is CommonJS on disk and an ES module when a plugin passes it through (bun test: Vitest compatibility #44833 has this).require()of a pending plugin promise still throws (Async Bun plugin onLoad for .ts makes require() treat the module as async #30014).Bun.plugin()cannot safely instrument JavaScript:onLoad()breaks CommonJS #39786 asks for moreonLoadarguments:namespaceproperty is undefined inOnLoadArgsof Bun plugin #3894, Add ImportKind on onLoad callback #27990, Provide file contents in Bun.plugin onLoad callback args #27992.Bun.build. The same plugin object still differs between the two for other result shapes.Relation to #44833
#44833 replaces this arm. It sends plugin
contentstofetchCommonJSModuleNonBuiltinandfetchESMSourceCode, which also fixes the value loaders. It is pinned to a preview build of WebKit and conflicts with main today, so this PR is the interim fix. This PR uses the same early return for a pending promise and the sameModuleGraphfield onPendingVirtualModuleResult.When #44833 merges main after this PR:
ModuleLoader.cppand the 1 ofModuleLoader.h.graphandspecifierJSat the end ofhandleVirtualModuleResult. They merge in without a conflict and nothing reads them there.ZigSourceProvider.cpp. The tests merge without a conflict. bun test: Vitest compatibility #44833 has adescribethat compares with a file in the same way, so the rows that both have can go.The decision on which PR lands first belongs to the author of #44833. If #44833 lands first, this PR closes and its tests move there.
Tests
bun bd test test/js/bun/plugin/plugins.test.ts test/cli/test/coverage.test.ts: 198 pass. With the source of main: 43 fail. Release builds gave the same counts at 197 and 42, before the case for a fulfilled promise was added.ResolvedSourceoverloads fails both--isolatecases: theisNewEntryassertion in a debug build, and the next test file gets the plugin's text for the file on disk. No early return for a pending promise leaves a module inrequire.cache. A null graph at either call site, or no graph in the pending cell, fails aBun.ModuleGraphcase. Never taking theResolvedSourceoverloads fails theModule.wrappercase.ignoreESModuleAnnotationasfalsefails the import rows in a package of typemodule.BUN_JSC_validateExceptionChecks=1on the plugin file: all pass.test/js/bun/plugin/,test/js/bun/test/mock/mock-module*.test.ts,test/cli/test/isolation.test.ts,test/cli/test/coverage.test.ts,test/cli/run/{preload-test,run-cjs,commonjs-invalid,commonjs-no-export,esm-defineProperty,require-and-import-trailing},test/js/node/module/{node-module-module,require-extensions,module-sourcemap},test/bundler/{bundler_compile,bundler_compile_prelinked,bun-build-compile},test/js/node/disallow-code-generation-from-strings.test.ts, and the CommonJS, plugin and require cases oftest/js/bun/module-graph/.test/cli/run/require-cache.test.tshas one case that times out on a release build of main and of this PR alike (don't leak file paths > via import()).Self-review
15 concerns raised, 14 addressed: 5 new test groups (a package of type
module, the fetch without a promise, aBun.ModuleGraphunderbun test, code coverage, a result with noloader), more table rows, a corrected comment, and the text of this body. Not done:BUN_RUNTIME_TRANSPILER_CACHE_PATH.require()(152 -> 153 instructions infetchCommonJSModule). A lookup that skips the dropped provider added 3328 bytes of.text.History
skipIsolationCacheparameter toJSCommonJSModule::evaluateandcreateCommonJSModule, and awasRequireflag. It did not compile after Bun.ModuleGraph: a context per graph for timers and I/O, per-graph CommonJS #42590 gavecreateCommonJSModuleaJSModuleGraph. Both are gone..cts/.mtscases come from fix(runtime): preserve named exports of plugin-loaded CommonJS modules #31770 by @isaacs.no test proof · iteration 11 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/plugin/plugins.test.ts