Skip to content

node-fallbacks: give no polyfill binding the name of a page global - #48663

Open
robobun wants to merge 2 commits into
robobun/f06787a0/browser-polyfills-globals-and-exportsfrom
robobun/43c0b39f/polyfill-names-not-browser-globals
Open

robobun wants to merge 2 commits into
robobun/f06787a0/browser-polyfills-globals-and-exportsfrom
robobun/43c0b39f/polyfill-names-not-browser-globals

Conversation

@robobun

@robobun robobun commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Merge into the branch of #41533.

Problem

  • Six polyfill bindings have the name of the global they read (var URL = globalThis.URL). A classic script declares URL first, so a host that inherits URL reads undefined: url.parse() throws TypeError: URL is not a constructor in a Firefox 160 content script and in workerd. Regression of v1.2.14 (Fix Node browser fallbacks to have util.inherit and other size improvements #19783).
  • export const browser = true (src/node-fallbacks/process.js:52) replaces the extension API: in a Chrome 153 content script, browser.runtime.getURL throws TypeError: Cannot read properties of undefined (reading 'getURL').

Fix

Background

  • bun build --target=browser inlines src/node-fallbacks/ for node:x imports. A polyfill's top-level binding stays a top-level var.
  • A classic script (plain <script src>, extension content script) declares its top-level names on the global object.
  • Considered reserved names in the renamer: it adds a pass to every browser chunk and renames user-written names. --format=iife is experimental.

Downsides

Notes

Why a PR into the branch of #41533. #41533 owns the rule "no binding with the name of a global". It also makes browser worse: its build binds process for the npm packages with an import of the process polyfill, so the browser binding is in the bundle of 7 of 23 polyfills (assert, crypto, http, https, process, stream, zlib). On main it is in 1 (process). I cannot push to #41533, so this PR has its branch as the base. Merging it adds the commit to that branch. No user reported any of the seven names. The six alias names also break on main today, so a cut against main is possible if that is preferred.

The three ways such a binding breaks a classic script. The script declares its top-level var, function and class names on the global object before it runs.

  • It hides a global that the host inherits. The six: File, Blob (buffer.js), TextEncoder, TextDecoder (util.js), URL, URLSearchParams (url.js).
  • It replaces a global: browser (process.js).
  • It declares a global on a host that has none. The window of jsdom 25.0.1 has no TextEncoder. On such a host the bundle declared one.

What I ran. Bundles are the default output of bun build --target=browser, built with the debug build of this branch. "Before" is the #41533 head 61411816a4e.

  • Firefox 160.0, MV3 content script ["bundle.js", "after.js"]. The entry imports a CommonJS dependency that requires util and url, and URL from node:url, Blob from node:buffer. Before, and with bun 1.4.3-canary.1: TextEncoder is not a constructor, URL is not a constructor, Blob is not a constructor in the bundle, and the six are own properties with the value undefined in after.js. After: all work, no own property.
  • workerd 2026-11-10, serviceWorkerScript, entry import { parse } from "node:url". Before, and with bun 1.4.3-canary.1: TypeError: URL is not a constructor, globalThis.URL is undefined (own). After: example.com, URL is inherited. A bundle built with bun 1.2.13 works (var { URL: J, URLSearchParams: X } = globalThis), one built with 1.2.14 throws. Fix Node browser fallbacks to have util.inherit and other size improvements #19783 (8aae5342704) replaced esbuild --minify with bun build --minify-syntax for the polyfills, so their names are no longer mangled.
  • Chrome 153.0.8010.52, MV3 content script ["pre.js", "bundle.js", "post.js"], entry import { Readable } from "node:stream"; const api = globalThis.browser ?? globalThis.chrome;. Before: typeof api is boolean in the bundle, and browser.runtime.getURL throws in post.js. After: browser is the extension API in both.

The default export. build-fallbacks.ts gives an ES module without a default export one that has every named export. It wrote { TextEncoder, ... }, which reads a binding called TextEncoder. With the export renamed, that is the global: ReferenceError on a host without it. The build now reads local for export { local as name }, and the name of the export for any other one. It fails for names that another module exports (export ... from). The 23 built polyfills are byte-identical to a build with hand-written defaults in util.js and process.js.

The by-name test. It builds each polyfill alone, because the bundler numbers a binding when another module of the bundle reads a global of that name (one bundle of all polyfills hides escape).

  • Names: the test loads each bundle into a node:vm context whose global object it emptied, with a first statement that throws. The engine declares the var and function names and runs nothing. Classes come from the text.
  • Globals: bun lint with no-undef and the environments browser, worker, serviceworker, webextensions. A name that it does not report is a global. With the names of Object.prototype, that table knows 1,219 of the 1,243 names of window in Chrome 153. no-redeclare with builtinGlobals is the direct rule, but with an ESLint 8 config its table knows 806 (no URLPattern), and with an oxlint config it knows ECMAScript names only and reports every scope.
  • The last bundle is a script that declares browser, escape, a class File and a numbered queueMicrotask. The test expects exactly those four, so a run that sees nothing fails.
  • Mutations that fail it: escape back in querystring.js, var console = globalThis.console in console.js (the first line of console.js in bundler: return the module.exports export from require() of an ES module #42092), const Symbol = globalThis.Symbol in timers.js (printed as Symbol2).
  • With the same method: 16 names in 14 of 23 bundles with bun 1.4.3-canary.1, 7 names in 13 at the node-fallbacks: bind free process and Buffer in the browser polyfills, fix util, process and timers, make require() of assert and events callable #41533 head, 0 here.

Behaviour change in a classic script. Before, a binding such as var TextEncoder was the property of the global object. A page that defined or replaced the global after the bundle also changed the export. Now each of the six is read once, when the bundle loads, as in a module script. browser/NodePolyfillExportsOfGlobals has a run for it, and the README of src/node-fallbacks states it.

Numbers (#41533 head against this PR).

  • Embedded polyfills: +288 B text, +69 B zstd over 23 files. buffer.js, process.js, url.js and util.js change. constants.js and os.js are byte-identical.
  • User bundle of buffer, process, url and util with named imports: +266 B plain (90,795 to 91,061), +0 B minified. import constants from "node:constants": +0 B. Minified one-polyfill bundles that change in size: 0 of 23. Plain ones: 13 of 23 grow by 30 to 224 B.
  • Script-scope declarations over the 23 bundles: 2,618 before and after.
  • Classic script with those four polyfills: own properties added 207 to 214, globals replaced 1 to 0, names declared on a host without the six 6 to 0.
  • Export names changed: 0. Named exports that differ from the default object: 0. Function or class .name values changed: 0.
  • Diff: +236/-18 in 7 files. Native and bundler lines: 0.
  • New cases: 3 builds (26 entries), 1 lint spawn. Over 5 debug runs: 8.3 to 11.6 s, 2.0 to 2.8 s, 2.4 to 3.1 s.

Not fixed here. These still share a name with the page in a classic script.

  • Names that only a page defines: Buffer, and the bindings of process.js (env, title, version, on, emit).
  • import * as data from "./data.json" prints the keys as top-level vars (var name).
  • import { setTimeout } from "node:timers/promises" (a builtin without a polyfill) prints var {setTimeout} = (() => ({}));.
  • Top-level names of user code and npm packages (Function conflict using bun build together with Chart.JS #14110).
  • Names that the test does not know: 24 of the 1,243 of Chrome 153, 16 of them webkit names.

--format=iife shares no name. It is marked experimental in docs/bundler/index.mdx, and a bundle with a CommonJS entry never runs that entry.

Other open PRs in these files. #42092 has var console = globalThis.console; in console.js: the new test reports it. #48629 adds a second export { local as name } line to util.js: the default export reads it.

Self-review. 34 concerns, 26 addressed: the default export is read from the source, the by-name test sees the names that a context owns and the numbered ones and has a script that must be reported, the tests have a host that inherits its globals and one that changes them later. Not done: 5 ask for these commits in #41533 itself (this PR has its branch as the base), 1 asks for a cut against main with all 16 names of main (that overlaps #41533), 2 ask for reserved names in the renamer (a question for #14110).

A classic script declares its top-level `var`, `function` and `class`
names on the global object before it runs. `bun build --target=browser`
keeps each top-level binding of an ES module polyfill as such a
declaration. So a binding with the name of a global does one of these:

- It hides a global that the host inherits. `var { URL, URLSearchParams }
  = globalThis` leaves both `undefined` in a content script of Firefox
  and in a service-worker script of workerd, where `url.parse()` then
  throws `TypeError: URL is not a constructor`.
- It replaces the global. `export const browser = true` replaces the
  extension API of a content script.
- It declares a global on a host that has none.

Seven such bindings were left: `File`, `Blob`, `TextEncoder`,
`TextDecoder`, `URL`, `URLSearchParams` and `browser`. Each has another
local name now and is exported with `export { local as name }`.

The default export that build-fallbacks.ts adds reads `local` for such
an export. The build fails for an export that is not a binding of the
file.

The test browser/NodePolyfillsDeclareNoPageGlobal lists the names that
the bundle of each polyfill declares, and `bun lint` says which of them
are globals of a page, a worker or an extension.
@robobun

robobun commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:20 AM PT - Nov 12th, 2026

❌ @robobun, your commit b480e09 has 1 failures in Build #140432 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 48663

That installs a local version of the PR into your bun-48663 executable, so you can run:

bun-48663 --bun

@robobun

robobun commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: ready for review. One CI test is red: a file-size check that the base of this stack still has. PR: #48663 (base: the branch of #41533).

CI. test/aot/loader-access-in-unreachable-code.test.ts fails on debian 13 aarch64, in builds 140418 and 140432. The base alone passes it. The test compares the file sizes of two compiled programs with a limit of 32 KB. Main says that this size moves in pages of 64 KB on arm64 Linux with each change to the code, and main no longer measures it (#48120, #48478). This PR changes the binary by 69 bytes of embedded polyfill text. The stack is on main of 2026-11-07 and still has the old test, so the failure stays until #41524 and #41533 take main. Build 140432 finished with 187 of 188 jobs green. Every other failure passed on a retry. test/bundler/bundler_browser.test.ts passed on every lane.

How I reproduced the bug, with the default output of bun build --target=browser at the #41533 head 61411816a4e:

  • Firefox 160, MV3 content script. Entry: a CommonJS dependency that calls new (require("util").TextEncoder)() and require("url").parse("http://bücher.example/"). Result: TypeError: TextEncoder is not a constructor, TypeError: URL is not a constructor. In the next content script file, URL, URLSearchParams, TextEncoder, TextDecoder, Blob and File are undefined.
  • workerd, serviceWorkerScript. Entry: import { parse } from "node:url". Result: TypeError: URL is not a constructor.
  • Chrome 153, MV3 content script. Entry: import { Readable } from "node:stream". Result: browser === true, and browser.runtime.getURL throws TypeError: Cannot read properties of undefined (reading 'getURL').
  • node:vm: test/bundler/bundler_browser.test.ts has a host that inherits its globals, a host without them, and an extension page. 4 cases fail on the node-fallbacks: bind free process and Buffer in the browser polyfills, fix util, process and timers, make require() of assert and events callable #41533 sources and pass here.

The first two also fail with bun 1.4.3-canary.1.

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings, I also checked whether the new throw in build-fallbacks.ts for exports without a local binding (destructured export const {...}, export ... from) can fire on the current tree: every polyfill that uses those forms (console, domain, http, https, punycode, querystring, string_decoder, sys, zlib) already has an explicit default export, so needsDefault is false for them and the synthesized default is only generated for files whose exports the regex covers. I did not run the polyfill build or the bundler test suite; the "0 names after" claim rests on the PR's own runs.

Extended reasoning...

The change renames six global-shadowing bindings in four browser polyfills (buffer, process, url, util) to local names re-exported under the original name, extends the codegen in build-fallbacks.ts with a regex scan so the synthesized default export reads the local binding, and adds three bundler tests plus a README section. It touches no security-sensitive surface. Four findings were posted inline (a classic-script behavior change for pages that replace globals after load, a lint spawn that ignores exit code and stderr, a regex that misses destructured exports, and duplicated rationale comments), so a human should weigh the behavior change; the ruled-out note records that the codegen throw is unreachable for the polyfills currently in the tree.

Comment thread src/node-fallbacks/util.js Resolved
Comment thread test/bundler/bundler_browser.test.ts Resolved
Comment thread src/node-fallbacks/build-fallbacks.ts Resolved
Comment thread src/node-fallbacks/buffer.js Resolved
…added default export

The default export that build-fallbacks.ts adds reads an export as a
binding of the same name, unless `export { local as name }` gives
another one. So `export const { a, b } = x` builds again. The build
fails only for names that another module exports.

The by-name test checks the exit code of the linter and shows what the
linter printed. The comments at the renamed bindings point at the
README, which also says that such an export has the value of load time.
@robobun

robobun commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. b480e09 takes three of the four suggestions:

  • Destructured exports (build-fallbacks.ts). The added default export reads an export as a binding of the same name, unless export { local as name } gives another one. export const { a, b } = pkg without a default export builds again. The build fails only for names that another module exports.
  • Exit code of the linter (browser/NodePolyfillsDeclareNoPageGlobal). The test expects exit code 1 and shows the stderr of the linter when the code is another one.
  • Comments. One line at each of the four sites, and the README section has the reason.

I kept the read at load for the six exports. A module script always had it, and on the base a classic script followed a later global only through a named or a namespace import, not through the default import. The README now states the value of such an export, and the run host-changes-them.js pins it.

The 23 built polyfills are byte-identical to the ones of the first commit. test/bundler/bundler_browser.test.ts: 49 pass, and 4 of them fail on the sources of #41533.

@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 branch has not been deployed

No deployments
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.

1 participant