From 4e3bfa73212127938972a62c643436686157804b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:23:34 +0000 Subject: [PATCH 1/4] node:stream: give Stream its members before node:stream has loaded node:net, node:tls and node:crypto load a stream class without internal/stream, the module that stores the members of node:stream on the `Stream` function. A program finds `Stream` above that class. After the program froze, sealed or made it non-extensible, every load of node:stream threw "TypeError: Attempting to define property on object that is not extensible." internal/streams/legacy.ts now defines every member on `Stream` when it makes it, as an accessor that loads internal/stream at the first read. The stores of internal/stream turn the accessors into data properties. On a sealed or frozen `Stream` the accessors stay and answer from the modules that define the members. The setter does what a store to a data property does, so a store through a class below `Stream` goes on that class. A `Stream` that is made while internal/stream loads gets no accessors. No program can see it before internal/stream has stored the members, so that path stays as it was. --- .../builtins/host/features-node.builtins.ts | 2 +- src/js/internal/stream.ts | 27 +--- src/js/internal/streams/legacy.ts | 147 +++++++++++++++++- src/js/internal/streams/state.ts | 3 + src/js/node/stream.ts | 2 - test/js/node/stream/node-stream.test.js | 146 +++++++++++++++++ 6 files changed, 298 insertions(+), 29 deletions(-) diff --git a/src/codegen/builtins/host/features-node.builtins.ts b/src/codegen/builtins/host/features-node.builtins.ts index 8d904c94b223..9b5d5f6dbcc0 100644 --- a/src/codegen/builtins/host/features-node.builtins.ts +++ b/src/codegen/builtins/host/features-node.builtins.ts @@ -222,7 +222,7 @@ export default b.declarations( extendAll(["NodeSmallModules"], "node:util/types", "node:constants"), - extendAll(["Buffer"], "Buffer", "internal/stream", "internal/streams/legacy", "internal/streams/readable"), + extendAll(["Buffer"], "Buffer", "internal/streams/legacy", "internal/streams/readable"), extendAll(["NodeBufferModule", "Buffer"], "node:buffer"), extendAll(["NodeFetch"], "node-fetch", ...nativeBindings("Cpp", "NodeFetch.cpp", "createNodeFetchInternalBinding")), diff --git a/src/js/internal/stream.ts b/src/js/internal/stream.ts index 7256bf2ad1db..4b0b3574d2ce 100644 --- a/src/js/internal/stream.ts +++ b/src/js/internal/stream.ts @@ -3,16 +3,17 @@ const ObjectKeys = Object.keys; const ObjectDefineProperty = Object.defineProperty; +const { setDefaultHighWaterMark, getDefaultHighWaterMark, internals } = require("internal/streams/state"); +// Set before internal/streams/legacy can load: a `Stream` that is made from here on gets its members from the stores below, not as accessors. +internals.streamDefinesItsMembers = true; const customPromisify = Symbol.for("nodejs.util.promisify.custom"); const { streamReturningOperators, promiseReturningOperators } = require("internal/streams/operators"); const compose = require("internal/streams/compose"); -const { setDefaultHighWaterMark, getDefaultHighWaterMark } = require("internal/streams/state"); const { pipeline } = require("internal/streams/pipeline"); const { destroyer } = require("internal/streams/destroy"); const eos = require("internal/streams/end-of-stream"); const utils = require("internal/streams/utils"); -const { isArrayBufferView, isUint8Array } = require("node:util/types"); -const Stream = require("internal/streams/legacy").Stream; +const { Stream, hasLazyMembers, definePromisesAndStream } = require("internal/streams/legacy"); Stream.isDestroyed = utils.isDestroyed; Stream.isDisturbed = utils.isDisturbed; @@ -75,14 +76,9 @@ Stream.compose = compose; Stream.setDefaultHighWaterMark = setDefaultHighWaterMark; Stream.getDefaultHighWaterMark = getDefaultHighWaterMark; -ObjectDefineProperty(Stream, "promises", { - __proto__: null, - configurable: true, - enumerable: true, - get() { - return require("internal/stream.promises"); - }, -}); +if (!hasLazyMembers) definePromisesAndStream(); +// The old name of `finished`. +Stream.eos = eos; ObjectDefineProperty(pipeline, customPromisify, { __proto__: null, @@ -100,13 +96,4 @@ ObjectDefineProperty(eos, customPromisify, { }, }); -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - -Stream._isArrayBufferView = isArrayBufferView; -Stream._isUint8Array = isUint8Array; -Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { - return new $Buffer(chunk.buffer, chunk.byteOffset, chunk.byteLength); -}; - export default Stream; diff --git a/src/js/internal/streams/legacy.ts b/src/js/internal/streams/legacy.ts index e0244c0a30ac..5da88e41bfd0 100644 --- a/src/js/internal/streams/legacy.ts +++ b/src/js/internal/streams/legacy.ts @@ -2,9 +2,17 @@ const EE = require("node:events"); const { isArrayBufferView, isUint8Array } = require("node:util/types"); - -const ReflectOwnKeys = Reflect.ownKeys; +const { internals } = require("internal/streams/state"); + +// Reflect lists a member from when it is first read. internal/primordials, which is loaded behind this one, reads the second ahead of the last two. +const { + ownKeys: ReflectOwnKeys, + getPrototypeOf: _ReflectGetPrototypeOf, + getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor, + defineProperty: ReflectDefineProperty, +} = Reflect; const ArrayIsArray = Array.isArray; +const ObjectDefineProperty = Object.defineProperty; declare global { namespace $Node { @@ -24,7 +32,7 @@ declare global { resume?(): unknown; } - /** `require("node:stream")`. internal/stream.ts adds the members that other modules define. */ + /** `require("node:stream")`. internal/stream.ts stores the members that other modules define. */ interface StreamConstructor { new (options?: EventEmitterOptions): Stream; (this: Stream, options?: EventEmitterOptions): void; @@ -38,8 +46,8 @@ declare global { duplexPair: typeof import("internal/streams/duplexpair").default; pipeline: typeof import("internal/streams/pipeline").default.pipeline; finished: typeof import("internal/streams/end-of-stream").default; - /** The old name of `finished`, which node/stream.ts adds. */ - eos?: typeof import("internal/streams/end-of-stream").default; + /** The old name of `finished`. */ + eos: typeof import("internal/streams/end-of-stream").default; compose: typeof import("internal/streams/compose").default; addAbortSignal: typeof import("internal/streams/add-abort-signal").default.addAbortSignal; destroy: typeof import("internal/streams/destroy").default.destroyer; @@ -179,4 +187,131 @@ Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { return new $Buffer(chunk.buffer, chunk.byteOffset, chunk.byteLength); }; -export default { Stream: Stream as $Node.StreamConstructor, prependListener }; +type LazyMember = Exclude; + +// What internal/stream.ts stores to `Stream` under that name. +function loadMember(name: LazyMember): Function { + switch (name) { + case "isDestroyed": + return require("internal/streams/utils").isDestroyed; + case "isDisturbed": + return require("internal/streams/utils").isDisturbed; + case "isErrored": + return require("internal/streams/utils").isErrored; + case "isReadable": + return require("internal/streams/utils").isReadable; + case "isWritable": + return require("internal/streams/utils").isWritable; + case "Readable": + return require("internal/streams/readable"); + case "Writable": + return require("internal/streams/writable"); + case "Duplex": + return require("internal/streams/duplex"); + case "Transform": + return require("internal/streams/transform"); + case "PassThrough": + return require("internal/streams/passthrough"); + case "duplexPair": + return require("internal/streams/duplexpair"); + case "pipeline": + return require("internal/streams/pipeline").pipeline; + case "addAbortSignal": + return require("internal/streams/add-abort-signal").addAbortSignal; + case "finished": + case "eos": + return require("internal/streams/end-of-stream"); + case "destroy": + return require("internal/streams/destroy").destroyer; + case "compose": + return require("internal/streams/compose"); + case "setDefaultHighWaterMark": + return require("internal/streams/state").setDefaultHighWaterMark; + case "getDefaultHighWaterMark": + return require("internal/streams/state").getDefaultHighWaterMark; + } +} + +function lazyMember(name: LazyMember) { + // As a store to a data property: the value goes on the receiver, a class below `Stream` for `Socket.pipeline = value`. + function set(this: unknown, value: unknown) { + if (!$isObject(this)) return; + const own = ReflectGetOwnPropertyDescriptor(this, name); + if (own === undefined) + ReflectDefineProperty(this, name, { + __proto__: null, + value, + writable: true, + enumerable: true, + configurable: true, + }); + else if (own.writable || own.set === set) + ReflectDefineProperty(this, name, { __proto__: null, value, writable: true }); + } + ObjectDefineProperty(Stream, name, { + __proto__: null, + enumerable: true, + configurable: true, + get() { + // internal/stream stores the members itself once it has begun to load, and a load that throws does so at require("node:stream"). + if (!internals.streamDefinesItsMembers) { + try { + require("internal/stream"); + } catch {} + } + return loadMember(name); + }, + set, + }); +} + +// Modules such as node:net and node:crypto make `Stream` without internal/stream, where a program can freeze it: so it has every member from the start, as an accessor that loads internal/stream. +function defineLazyMembers() { + const names = [ + "isDestroyed", + "isDisturbed", + "isErrored", + "isReadable", + "isWritable", + "Readable", + "Writable", + "Duplex", + "Transform", + "PassThrough", + "duplexPair", + "pipeline", + "addAbortSignal", + "finished", + "destroy", + "compose", + "setDefaultHighWaterMark", + "getDefaultHighWaterMark", + ] as const satisfies readonly LazyMember[]; + for (let i = 0; i < names.length; i++) lazyMember(names[i]); + definePromisesAndStream(); + lazyMember("eos"); +} + +// Behind the members that other modules define and ahead of `eos`, from whichever module puts the members on `Stream`. +function definePromisesAndStream() { + ObjectDefineProperty(Stream, "promises", { + __proto__: null, + configurable: true, + enumerable: true, + get() { + return require("internal/stream.promises"); + }, + }); + // Backwards-compat with node 0.4.x + (Stream as $Node.StreamConstructor).Stream = Stream as $Node.StreamConstructor; +} + +const hasLazyMembers = !internals.streamDefinesItsMembers; +if (hasLazyMembers) defineLazyMembers(); + +export default { + Stream: Stream as $Node.StreamConstructor, + prependListener, + hasLazyMembers, + definePromisesAndStream, +}; diff --git a/src/js/internal/streams/state.ts b/src/js/internal/streams/state.ts index 4bfaa88a67fc..628de5d966e7 100644 --- a/src/js/internal/streams/state.ts +++ b/src/js/internal/streams/state.ts @@ -147,6 +147,8 @@ interface Internals { destroyEndedRequest: ((state: ReadableState, stream: $Node.Readable) => boolean) | undefined; /** Only in what was compiled ahead of time. */ makeObjectReadable?: (highWaterMark: number) => $Node.Readable; + /** internal/stream sets it before it loads its parts: it stores the members of node:stream on `Stream` itself. */ + streamDefinesItsMembers: boolean; } type WritableAccessorName = @@ -183,6 +185,7 @@ const internals: Internals = { onRequestBodyData: undefined, takeRequestCloseTick: undefined, destroyEndedRequest: undefined, + streamDefinesItsMembers: false, }; // TODO(benjamingr) it is likely slower to do it this way than with free functions diff --git a/src/js/node/stream.ts b/src/js/node/stream.ts index f0323f26bf5f..af057cc56ba9 100644 --- a/src/js/node/stream.ts +++ b/src/js/node/stream.ts @@ -3,6 +3,4 @@ const exports = require("internal/stream"); $debug("node:stream loaded"); -exports.eos = require("internal/streams/end-of-stream"); - export default exports; diff --git a/test/js/node/stream/node-stream.test.js b/test/js/node/stream/node-stream.test.js index b7ad335a3448..2bd3ba50c508 100644 --- a/test/js/node/stream/node-stream.test.js +++ b/test/js/node/stream/node-stream.test.js @@ -2041,3 +2041,149 @@ it("Readable.fromWeb's native source accepts pull(view) without the flags array" delete Object.prototype.setFlowing; } }); + +// `Stream`, the exports object of node:stream, is above every stream class. Modules such as node:net, node:tls and +// node:crypto load their class without node:stream, so a program can reach `Stream` there first, and freeze it. +describe("the members of node:stream before node:stream has loaded", () => { + const show = value => (typeof value === "function" ? `function ${value.name}` : typeof value); + // Of the node:stream that this file has imported. + const keys = Object.keys(Stream); + const members = keys.map(key => show(Stream[key])); + const kinds = keys.map(key => ("value" in Object.getOwnPropertyDescriptor(Stream, key) ? "data" : "accessor")); + + // The same three lists, of the node:stream of a child. + const helpers = ` + const show = value => (typeof value === "function" ? "function " + value.name : typeof value); + const describeStream = nodeStream => { + const keys = Object.keys(nodeStream); + return { + keys, + members: keys.map(key => show(nodeStream[key])), + kinds: keys.map(key => ("value" in Object.getOwnPropertyDescriptor(nodeStream, key) ? "data" : "accessor")), + }; + }; + `; + + async function expectChildToPrint(script, expected) { + await using proc = Bun.spawn({ cmd: [bunExe(), "-e", helpers + script], env: bunEnv, stderr: "pipe" }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(JSON.parse(stdout)).toEqual(expected); + expect(exitCode).toBe(0); + } + + it.concurrent.each([ + ["freeze", `require("node:net").Socket`], + ["seal", `require("node:crypto").Hash`], + ["preventExtensions", `require("node:tls").TLSSocket`], + ])("require('node:stream') has them after Object.%s of what is above %s", async (lock, top) => { + // A sealed or frozen `Stream` keeps the accessors that it had for the members, and a store to one does nothing. + // Node.js has data properties there, so a store to a sealed one takes effect. + const keepsAccessors = lock !== "preventExtensions"; + await expectChildToPrint( + ` + for (let object = ${top}; object !== Function.prototype; object = Object.getPrototypeOf(object)) + Object.${lock}(object); + const nodeStream = require("node:stream"); + nodeStream.pipeline = "stored"; + console.log(JSON.stringify({ + isAboveReadable: Object.getPrototypeOf(nodeStream.Readable) === nodeStream, + isExtensible: Object.isExtensible(nodeStream), + others: [typeof require("node:zlib").createGzip, typeof process.stdout.write], + ...describeStream(nodeStream), + })); + `, + { + isAboveReadable: true, + isExtensible: false, + others: ["function", "function"], + keys, + members: keepsAccessors ? members : members.with(keys.indexOf("pipeline"), "string"), + kinds: keepsAccessors + ? keys.map(key => (key.startsWith("_") || key === "Stream" ? "data" : "accessor")) + : kinds, + }, + ); + }); + + it.concurrent("a class of node:net inherits them, and node:stream has the same ones", async () => { + await Promise.all([ + expectChildToPrint( + ` + const { Socket } = require("node:net"); + const Stream = Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Socket))); + const keysBefore = Object.keys(Stream); + const getters = keysBefore.map(key => Object.getOwnPropertyDescriptor(Stream, key).get); + class Below extends Socket {} + Below.pipeline = "stored on the class below"; + const pipeline = Socket.pipeline; + const afterTheFirstRead = describeStream(Stream); + const nodeStream = require("node:stream"); + console.log(JSON.stringify({ + keysBefore, + storedBelow: Object.getOwnPropertyDescriptor(Below, "pipeline"), + afterTheFirstRead, + isTheSameObject: nodeStream === Stream && nodeStream.pipeline === pipeline, + gettersAnswer: keysBefore.filter((key, index) => getters[index] && getters[index]() === nodeStream[key]), + ...describeStream(nodeStream), + })); + `, + { + keysBefore: keys, + storedBelow: { value: "stored on the class below", writable: true, enumerable: true, configurable: true }, + // The first read of one has loaded node:stream. + afterTheFirstRead: { keys, members, kinds }, + isTheSameObject: true, + // What the accessors of before the load return, which is what they return on a sealed or frozen `Stream`. + gettersAnswer: keys.filter(key => !key.startsWith("_") && key !== "Stream"), + keys, + members, + kinds, + }, + ), + // Where node:stream loads first, `Stream` never has the accessors, and ends the same. + expectChildToPrint(`console.log(JSON.stringify(describeStream(require("node:stream"))));`, { + keys, + members, + kinds, + }), + ]); + }); + + it.concurrent("a store through a class below goes where a store to a data property goes", async () => { + await expectChildToPrint( + ` + const { Socket } = require("node:net"); + const Stream = Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Socket))); + class ReadOnly extends Socket {} + Object.defineProperty(ReadOnly, "compose", { value: "read-only", configurable: true }); + class WithAccessor extends Socket { + static get finished() { + return "accessor"; + } + } + class WithMethod extends Socket { + static destroy() {} + } + Reflect.set(Stream, "compose", "stored", ReadOnly); + Reflect.set(Stream, "finished", "stored", WithAccessor); + Reflect.set(Stream, "destroy", "stored", WithMethod); + Reflect.set(Stream, "pipeline", "stored", 5); + console.log(JSON.stringify({ + readOnly: ReadOnly.compose, + withAccessor: WithAccessor.finished, + withMethod: Object.getOwnPropertyDescriptor(WithMethod, "destroy"), + kindsOfStream: ["compose", "finished", "destroy", "pipeline"].map(key => + "value" in Object.getOwnPropertyDescriptor(Stream, key) ? "data" : "accessor", + ), + })); + `, + { + readOnly: "read-only", + withAccessor: "accessor", + withMethod: { value: "stored", writable: true, enumerable: false, configurable: true }, + kindsOfStream: ["accessor", "accessor", "accessor", "accessor"], + }, + ); + }); +}); From abeadaf0f1e879354244f6ec71e2d4b1384ee9a1 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 9 Nov 2026 03:55:28 +0000 Subject: [PATCH 2/4] ci: retrigger From 24b694607793599f9d512adc289e340350b69fca Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:10:59 +0000 Subject: [PATCH 3/4] node:stream/promises: do not read the promises of node:stream The module was `require("node:stream").promises`, a property that a program can delete or replace. It now loads internal/stream.promises, and node:stream with it, as in Node.js. --- src/js/node/stream.promises.ts | 4 +++- test/js/node/stream/node-stream.test.js | 32 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/js/node/stream.promises.ts b/src/js/node/stream.promises.ts index 04aaf0b0c5a9..41dfb535cb2b 100644 --- a/src/js/node/stream.promises.ts +++ b/src/js/node/stream.promises.ts @@ -1,2 +1,4 @@ // Hardcoded module "node:stream/promises" -export default require("node:stream").promises; +// As in Node.js, node:stream loads with it. Not the `promises` of node:stream: a program can delete or replace that. +require("node:stream"); +export default require("internal/stream.promises"); diff --git a/test/js/node/stream/node-stream.test.js b/test/js/node/stream/node-stream.test.js index 2bd3ba50c508..792b7c34147b 100644 --- a/test/js/node/stream/node-stream.test.js +++ b/test/js/node/stream/node-stream.test.js @@ -2186,4 +2186,36 @@ describe("the members of node:stream before node:stream has loaded", () => { }, ); }); + + it.concurrent("node:stream/promises loads after a program deletes the promises of node:stream", async () => { + await Promise.all([ + // Deleted from the `Stream` of node:net, before node:stream has loaded. + expectChildToPrint( + ` + const { Socket } = require("node:net"); + const Stream = Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Socket))); + delete Stream.promises; + console.log(JSON.stringify({ + ofTheModule: Object.keys(require("node:stream/promises")), + ofNodeStream: typeof require("node:stream").promises, + })); + `, + { ofTheModule: ["finished", "pipeline"], ofNodeStream: "undefined" }, + ), + // Deleted after node:stream has loaded. + expectChildToPrint( + ` + const nodeStream = require("node:stream"); + const promises = nodeStream.promises; + delete nodeStream.promises; + console.log(JSON.stringify({ + isTheSameObject: require("node:stream/promises") === promises, + ofTheModule: Object.keys(require("node:stream/promises")), + ofNodeStream: typeof nodeStream.promises, + })); + `, + { isTheSameObject: true, ofTheModule: ["finished", "pipeline"], ofNodeStream: "undefined" }, + ), + ]); + }); }); From ab2890477e26cb33703f94a9dbee4adfea12675c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:28:28 +0000 Subject: [PATCH 4/4] test: node:stream/promises loads node:stream and ignores a replaced promises The test now replaces `promises` after the load and reads the module through import() too, and it checks that node:stream has loaded with the module. --- test/js/node/stream/node-stream.test.js | 30 +++++++++++++------------ 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/test/js/node/stream/node-stream.test.js b/test/js/node/stream/node-stream.test.js index 792b7c34147b..12d1f9106e3f 100644 --- a/test/js/node/stream/node-stream.test.js +++ b/test/js/node/stream/node-stream.test.js @@ -2187,7 +2187,7 @@ describe("the members of node:stream before node:stream has loaded", () => { ); }); - it.concurrent("node:stream/promises loads after a program deletes the promises of node:stream", async () => { + it.concurrent("node:stream/promises loads node:stream and does not read its promises", async () => { await Promise.all([ // Deleted from the `Stream` of node:net, before node:stream has loaded. expectChildToPrint( @@ -2195,26 +2195,28 @@ describe("the members of node:stream before node:stream has loaded", () => { const { Socket } = require("node:net"); const Stream = Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Socket))); delete Stream.promises; - console.log(JSON.stringify({ - ofTheModule: Object.keys(require("node:stream/promises")), - ofNodeStream: typeof require("node:stream").promises, - })); + const ofTheModule = Object.keys(require("node:stream/promises")); + // A data property once node:stream has loaded. + const kindOfPipeline = "value" in Object.getOwnPropertyDescriptor(Stream, "pipeline") ? "data" : "accessor"; + console.log(JSON.stringify({ ofTheModule, kindOfPipeline, ofNodeStream: typeof require("node:stream").promises })); `, - { ofTheModule: ["finished", "pipeline"], ofNodeStream: "undefined" }, + { ofTheModule: ["finished", "pipeline"], kindOfPipeline: "data", ofNodeStream: "undefined" }, ), - // Deleted after node:stream has loaded. + // Replaced after node:stream has loaded. A module that is not an object stops import() with a segmentation fault. expectChildToPrint( ` const nodeStream = require("node:stream"); const promises = nodeStream.promises; - delete nodeStream.promises; - console.log(JSON.stringify({ - isTheSameObject: require("node:stream/promises") === promises, - ofTheModule: Object.keys(require("node:stream/promises")), - ofNodeStream: typeof nodeStream.promises, - })); + Object.defineProperty(nodeStream, "promises", { value: "replaced" }); + import("node:stream/promises").then(imported => { + console.log(JSON.stringify({ + isTheDefaultOfImport: imported.default === promises, + isTheSameObject: require("node:stream/promises") === promises, + ofNodeStream: nodeStream.promises, + })); + }); `, - { isTheSameObject: true, ofTheModule: ["finished", "pipeline"], ofNodeStream: "undefined" }, + { isTheDefaultOfImport: true, isTheSameObject: true, ofNodeStream: "replaced" }, ), ]); });