Repository navigation
Conversation
…process') and forward nextTick args
The browser node:stream polyfill (readable-stream) pulls in the process
npm package's index.js, which is 'module.exports = global.process'. The
build step's --define=global:globalThis rewrites that to
'globalThis.process' before the post-processing .replaceAll runs, so the
'global.process' -> require('process') rewrite never matched. The result
was a stream polyfill whose internal process.nextTick read from
globalThis.process, which is undefined in a browser:
import { Readable } from 'stream';
Readable.from(['a']).on('data', () => {});
// TypeError: Cannot read properties of undefined (reading 'nextTick')
Once that resolved to the process polyfill, a second bug surfaced: the
polyfill's nextTick pushes { fun, args } but drainQueue reads item.array,
so every callback was invoked with no arguments.
Both fixes are in the fallback sources, so the embedded polyfills are
regenerated on build.
|
Reproduced with Self-review flagged the pre-existing |
WalkthroughThe bundler now rewrites ChangesBrowser process fallback fixes
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
LGTM — two one-line fixes with a clear root cause and tests that cover each independently.
What was reviewed:
build-fallbacks.ts: the newglobalThis.processrewrite sits alongside the existingglobal.processone; checked that no fallback source file containsglobalThis.processliterally, soprocess.jswon't self-require after the rewrite.process.js:item.array→item.argsmatches the{ fun, args }shape pushed bynextTick.- Tests follow the neighboring
itBundledpattern, wireerrorto reject, and thenot.toInclude("globalThis.process")assertion guards the regression directly. The existingbrowser/NodePolyfillssnapshot still passing indicates the blanket replace didn't change any other polyfill's exported shape.
Extended reasoning...
Overview
This PR fixes the browser-target node:stream polyfill, which currently crashes in any environment without a real globalThis.process (i.e., an actual browser). Three files touched:
src/node-fallbacks/build-fallbacks.ts— adds one more.replaceAllto the post-bundle text-munging step soglobalThis.process(the result of--define=global:globalThisrunning over theprocessnpm package'smodule.exports = global.process) is rewritten torequire('process'), same as the pre-existingglobal.processrewrite that no longer matched.src/node-fallbacks/process.js— fixes an obvious typo indrainQueue: it readitem.arraybutnextTickpushes{ fun, args }. Callbacks scheduled via the polyfill'snextTickwere receiving zero arguments.test/bundler/bundler_browser.test.ts— two newitBundledcases: one runs a bundledReadable.from()afterdelete globalThis.processand asserts the output contains noglobalThis.process; the other verifiesnextTick(cb, a, b, c)forwards its args.
Security risks
None. This is build-time text post-processing of vendored browser polyfills plus a property-name typo fix in a browser shim. No auth, crypto, filesystem, or untrusted-input parsing is involved.
Level of scrutiny
Low-to-moderate. The replaceAll approach is admittedly brittle (the file itself says so on the line above), but this change extends an existing pattern by one entry rather than introducing a new mechanism. The main risk — that the blanket replace hits an unintended globalThis.processXxx identifier or causes process.js to require itself — was checked: no fallback source contains globalThis.process, and the identical risk already exists for the pre-existing global.process line. The full bundler_browser.test.ts suite (including the large NodePolyfills snapshot that exercises every polyfill's export shape) passes per the PR description, which would catch shape changes in crypto/stream/etc.
Other factors
- Root cause is well-explained and the fix lands at the layer that owns the bug (the post-processing step whose match went stale, and the queue drain that read the wrong field).
- Tests await real events (
data/end), wireerrorto reject, and assert exact stdout — no sleeps or vacuous checks. - robobun confirmed both tests fail on main and pass on this branch.
- No prior reviews or outstanding comments.
--define=global:globalThis rewrites every global.process to globalThis.process before the post-processing runs, so there is nothing left for the old replaceAll to match. The comment now describes the one form that actually appears in the bundled text.
There was a problem hiding this comment.
LGTM — two one-line fixes to the browser node-fallbacks with solid itBundled coverage.
What was reviewed:
build-fallbacks.ts: confirmed--define=global:globalThisruns before post-processing, so the oldglobal.processsearch was dead; checked allglobal.processoccurrences innode_modules/(process, setimmediate, pbkdf2) — each rewrite torequire('process')is semantically correct or improved for the browser target.process.js:nextTickpushes{ fun, args }, soitem.arraywas alwaysundefined— straightforward typo fix; verified the source file itself contains noglobalThis.processso no self-referential rewrite.- Tests wire
errortoreject, await the resolved event, and assert exact stdout — matches the existingbrowser/Node*test shape in this file.
Extended reasoning...
Overview
This PR fixes two bugs in Bun's browser-target node polyfills (src/node-fallbacks/):
build-fallbacks.ts: The post-processing step.replaceAll("global.process", "require('process')")never matched because--define=global:globalThisruns first during bundling, turning everyglobal.processintoglobalThis.processbefore the string replacement sees it. The fix updates the search string toglobalThis.process. This makes the embeddedstream.js(andcrypto.jsvia pbkdf2) route their process references to thenode:processpolyfill instead of relying onglobalThis.processexisting at runtime.process.js:drainQueuereaditem.array, butnextTickpushes{ fun, args }. A one-token typo fix (item.array→item.args) so callback arguments are actually forwarded.
Two new itBundled tests in test/bundler/bundler_browser.test.ts cover both fixes end-to-end by bundling for --target browser, deleting globalThis.process in the runner, and asserting exact stdout.
Security risks
None. This is build-time string post-processing of vendored polyfill bundles that ship inside the Bun binary, plus a typo fix in a browser-only process shim. No auth, crypto correctness, filesystem, or untrusted-input parsing is touched.
Level of scrutiny
Low-to-medium. The build-fallbacks.ts post-processing is explicitly labelled "very brittle" in-file, and the change swaps one exact-string search for another that the existing --define pass guarantees is the actual form present. I grepped src/node-fallbacks/node_modules/ for all global.process/globalThis.process occurrences — the collateral rewrites in setimmediate (Node feature-detect stays false) and pbkdf2 (.browser check now correctly true, .nextTick uses the polyfill) are all semantically correct or better than the previous undefined. The process.js fix is a self-evident field-name mismatch between producer and consumer in the same file.
Other factors
- The PR replaces the dead
global.processline rather than adding alongside it, and documents why in a comment — consistent with REVIEW.md's "delete dead code in the same PR". - Tests follow the existing
browser/Node*shape in the same file:itBundledwithruntimeFiles, error handlers wired toreject, exact-stdout assertion, plus a staticnot.toInclude("globalThis.process")guard on the bundle. - Verified
process.jsitself contains noglobalThis.process, so the blanketreplaceAllcannot introduce a self-referentialrequire('process')in the process polyfill. - No outstanding reviewer comments; CodeRabbit was rate-limited and left no findings.
There was a problem hiding this comment.
LGTM — two clear browser-polyfill bugfixes with end-to-end tests that fail on main.
What was reviewed:
build-fallbacks.ts: confirmed--define=global:globalThisruns before post-processing, so the oldglobal.processreplaceAll was dead; the newglobalThis.processrewrite is applied post-bundle and resolves to the process polyfill at user-bundle time. Checked thatprocess.jsitself contains noglobalThis.process, so no self-reference.process.js:nextTickpushes{fun, args}, soitem.argsis the right read;.apply(null, undefined)was the previous silent zero-arg behavior.- Tests wire
errorto reject, assert exact stdout afterdelete globalThis.process, and thenot.toInclude("globalThis.process")guard catches future regressions in the rewrite.
Extended reasoning...
Overview
Two-line fix in the browser polyfill build pipeline plus two itBundled regression tests. src/node-fallbacks/build-fallbacks.ts swaps a dead .replaceAll("global.process", ...) for .replaceAll("globalThis.process", ...) so the bundled readable-stream (and any other polyfill that transitively pulls in the process npm shim) routes to the node:process polyfill instead of reading globalThis.process at runtime. src/node-fallbacks/process.js fixes drainQueue to read item.args (matching what nextTick pushes) instead of the nonexistent item.array.
Security risks
None. This only affects the build-time text post-processing of browser polyfills embedded in the binary and a queue-item property read in the browser process shim. No auth, crypto, filesystem, or network paths involved.
Level of scrutiny
Low-medium. The replaceAll post-processing is self-described as "very brittle", so the concern is unintended matches — but the old global.process line had identical brittleness and simply never fired because --define=global:globalThis ran first. The new form is what the old code always intended. The blast radius is bounded by the browser/NodePolyfills test, which imports and evaluates every polyfill; that test still passes, and the two new tests exercise the previously-broken path end-to-end (bundle → delete globalThis.process → run) with exact stdout assertions. The item.array → item.args change is a trivially-verifiable typo fix against the queue.push({ fun, args }) two functions down.
Other factors
PR evidence shows both new tests fail on main (debug+ASAN and release) and the full bundler_browser.test.ts suite passes on the branch. Tests follow the existing itBundled conventions in the same file, wire error to reject the awaited promise, and add a not.toInclude("globalThis.process") bundle assertion as a build-time regression guard. No CODEOWNERS on these paths, no outstanding reviewer comments.
|
Closing in favor of #41533. It contains this fix and both tests from this PR, unchanged, together with the other browser polyfill fixes. There, the stream polyfill's |
Repro
The browser
node:streampolyfill is unusable in an environment without a realglobalThis.process(i.e. an actual browser).Cause
readable-streamdepends on theprocessnpm package, whoseindex.jsis justmodule.exports = global.process.build-fallbacks.tsbundles with--define=global:globalThis, so that becomesmodule.exports = globalThis.processin the output. The post-processing step then does.replaceAll("global.process", "require('process')"), which no longer matches because the define already ran. The embeddedstream.jstherefore shipsmodule2.exports = globalThis.processas its process shim, and everyprocess.nextTickinside the stream implementation readsundefined.Once that routed to the
node:processpolyfill, a second pre-existing bug surfaced: the polyfill'snextTickpushes{ fun, args }onto the queue, butdrainQueuereadsitem.array, so every callback was invoked with zero arguments. This brokeReadable'sresume_(stream, state)the moment the first bug was fixed.Fix
build-fallbacks.ts: also rewriteglobalThis.processtorequire('process'), so the stream (and crypto) polyfills pull in the browsernode:processpolyfill instead of the host global.process.js: readitem.argsindrainQueue, matching whatnextTickpushes.Verification
New tests in
test/bundler/bundler_browser.test.ts:browser/NodeStreamWithoutGlobalProcessbundles aReadable.from()consumer for--target browser, asserts the output contains noglobalThis.process, and runs it afterdelete globalThis.process. Before this change the bundle throwsundefined is not an object (evaluating 'process.nextTick').browser/NodeProcessNextTickForwardsArgschecks thatnextTick(cb, a, b, c)forwards its extra arguments. Before this change the callback receivesundefined, undefined, undefinedand the test printsNaN.[review] gate passed · iteration 1 · 3 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 2 passed · 0 rejected · iteration 1
evidence per changed file