diff --git a/AGENTS.md b/AGENTS.md index 18c32c6cfa8..d4ec3f3def2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -206,7 +206,7 @@ Be aware that workerd uses tcmalloc for memory allocation in the typical case. W | Bazel build rules | `build/` | Custom `wd_*` macros; `wd_test.bzl` generates 3 test variants | | JS benchmarks | `src/workerd/api/bench.{h,c++}`, `build/wd_bench.bzl` | `bench` handler; runner `BenchController`; report schema `io/bench.capnp`; driver `server/server/bench.rs` | | Streams benchmarks | `src/bench/streams/` | C++ vs TS streams: the same modules under a cell per implementation; see its `AGENTS.md` | -| Clone benchmarks | `src/bench/serialization/` | `structuredClone()` of object graphs, class instances, arrays and strings | +| Clone benchmarks | `src/bench/serialization/` | `structuredClone()`, C++ vs TS (`TS_STRUCTURED_CLONE`): object graphs, arrays, strings, options, cold calls | | TypeScript types | `types/` | Extracted from C++ RTTI + hand-written `defines/*.d.ts`; see `types/AGENTS.md` for detailed typings guidance | | V8 patches | `patches/v8/` | See `docs/v8-updates.md` | | Startup snapshot | `src/workerd/jsg/snapshot.{h,c++}`, `setup.{h,c++}` | Zygote bakes the top level into a V8 snapshot; `STARTUP_SNAPSHOT` autogate; see `docs/startup-snapshot.md` | diff --git a/docs/benchmarking.md b/docs/benchmarking.md index d4433961b09..527969143f4 100644 --- a/docs/benchmarking.md +++ b/docs/benchmarking.md @@ -179,5 +179,6 @@ See [text-encoder-bench.js](../src/workerd/api/tests/text-encoder-bench.js). [src/bench/streams/](../src/bench/streams/AGENTS.md) runs the same benchmarks against the C++ and TypeScript streams implementations, to compare them. [src/bench/serialization/](../src/bench/serialization/structured-clone.js) measures -`structuredClone()` of object graphs, class instances, arrays and strings. +`structuredClone()` of object graphs, class instances, arrays and strings, and its options, +against the C++ and TypeScript implementations, including the first calls in a new isolate. diff --git a/src/bench/serialization/BUILD.bazel b/src/bench/serialization/BUILD.bazel index 07d88f86601..913f24fc4ed 100644 --- a/src/bench/serialization/BUILD.bazel +++ b/src/bench/serialization/BUILD.bazel @@ -1,8 +1,24 @@ load("//:build/wd_bench.bzl", "wd_bench") +# The structuredClone() benchmarks, against the C++ implementation and the +# TypeScript one (TS_STRUCTURED_CLONE). Enabling every autogate enables +# TS_STRUCTURED_CLONE, so the C++ config has no @all-autogates variant; the +# TypeScript config enables TS_STRUCTURED_CLONE itself. + +structured_clone_srcs = [ + "structured-clone.js", + "structured-clone-cold.js", +] + +wd_bench( + src = "structured-clone-cpp.wd-bench", + data = structured_clone_srcs, + generate_all_autogates_variant = False, +) + wd_bench( - src = "structured-clone.wd-bench", - data = ["structured-clone.js"], + src = "structured-clone-ts.wd-bench", + data = structured_clone_srcs, ) wd_bench( diff --git a/src/bench/serialization/structured-clone-cold.js b/src/bench/serialization/structured-clone-cold.js new file mode 100644 index 00000000000..512aba88986 --- /dev/null +++ b/src/bench/serialization/structured-clone-cold.js @@ -0,0 +1,24 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// structuredClone() in a new isolate. The top-level calls are the first in +// their isolate, before V8 has compiled or optimized any of the code they +// run; the startup group's startup:worker case times them, in a new isolate +// for every sample, and its startup:script case times the per-isolate +// bootstrap that installs the function. The module does nothing else at top +// level, so those two cases differ between implementations by those costs +// alone. + +const SMALL = { a: 1, b: 'two', c: [3] }; + +structuredClone(SMALL); +const buffer = new ArrayBuffer(8); +structuredClone(buffer, { transfer: [buffer] }); + +export default { + bench(b) { + // The same call once warm, for comparison. + b.run('small object', () => b.blackBox(structuredClone(SMALL))); + }, +}; diff --git a/src/bench/serialization/structured-clone-cpp.wd-bench b/src/bench/serialization/structured-clone-cpp.wd-bench new file mode 100644 index 00000000000..2d1219bc03d --- /dev/null +++ b/src/bench/serialization/structured-clone-cpp.wd-bench @@ -0,0 +1,20 @@ +using Workerd = import "/workerd/workerd.capnp"; + +# Runs the structuredClone() benchmarks against the C++ JSG method +# (api/global-scope.h). structured-clone-ts.wd-bench runs the same modules +# against the TypeScript one. + +const unitTests :Workerd.Config = ( + services = [ + ( name = "structured-clone", + worker = ( + modules = [(name = "worker", esModule = embed "structured-clone.js")], + ) + ), + ( name = "structured-clone-cold", + worker = ( + modules = [(name = "worker", esModule = embed "structured-clone-cold.js")], + ) + ), + ], +); diff --git a/src/bench/serialization/structured-clone-ts.wd-bench b/src/bench/serialization/structured-clone-ts.wd-bench new file mode 100644 index 00000000000..21f5a470d76 --- /dev/null +++ b/src/bench/serialization/structured-clone-ts.wd-bench @@ -0,0 +1,21 @@ +using Workerd = import "/workerd/workerd.capnp"; + +# Runs the structuredClone() benchmarks against the TypeScript implementation +# (src/per_isolate/structured-clone.ts), with byte-for-byte the same modules +# as structured-clone-cpp.wd-bench. + +const unitTests :Workerd.Config = ( + services = [ + ( name = "structured-clone", + worker = ( + modules = [(name = "worker", esModule = embed "structured-clone.js")], + ) + ), + ( name = "structured-clone-cold", + worker = ( + modules = [(name = "worker", esModule = embed "structured-clone-cold.js")], + ) + ), + ], + autogates = ["workerd-autogate-ts-structured-clone"], +); diff --git a/src/bench/serialization/structured-clone.js b/src/bench/serialization/structured-clone.js index 576796901b8..449c4cb566c 100644 --- a/src/bench/serialization/structured-clone.js +++ b/src/bench/serialization/structured-clone.js @@ -3,7 +3,8 @@ // https://opensource.org/licenses/Apache-2.0 // structuredClone() of object graphs, whose every object the serializer asks its delegate about -// (jsg::Serializer::IsHostObject()), and of arrays and strings, which it does not. +// (jsg::Serializer::IsHostObject()), and of arrays and strings, which it does not; then the +// options, whose conversion is the part the C++ and TypeScript implementations do differently. function tree(depth, width) { if (depth === 0) return { leaf: true, n: 1 }; @@ -35,10 +36,30 @@ const INPUTS = { 'string 8192': 'a'.repeat(8192), }; +const SMALL = { a: 1 }; +const NO_TRANSFER = {}; +const EMPTY_TRANSFER = { transfer: [] }; + export default { bench(b) { for (const [name, input] of Object.entries(INPUTS)) { b.run(name, () => b.blackBox(structuredClone(input))); } + b.run('small object, options without transfer', () => + b.blackBox(structuredClone(SMALL, NO_TRANSFER)) + ); + b.run('small object, empty transfer', () => + b.blackBox(structuredClone(SMALL, EMPTY_TRANSFER)) + ); + // A transferred buffer is detached, so each call needs new ones; the + // allocations cost the same under both implementations. + b.run('transfer 1 ArrayBuffer', () => { + const buffer = new ArrayBuffer(64); + return b.blackBox(structuredClone(buffer, { transfer: [buffer] })); + }); + b.run('transfer 16 ArrayBuffers', () => { + const buffers = Array.from({ length: 16 }, () => new ArrayBuffer(64)); + return b.blackBox(structuredClone(buffers, { transfer: buffers })); + }); }, }; diff --git a/src/bench/serialization/structured-clone.wd-bench b/src/bench/serialization/structured-clone.wd-bench deleted file mode 100644 index 34f6b2675bc..00000000000 --- a/src/bench/serialization/structured-clone.wd-bench +++ /dev/null @@ -1,10 +0,0 @@ -using Workerd = import "/workerd/workerd.capnp"; - -const unitTests :Workerd.Config = ( - services = [( - name = "structured-clone", - worker = ( - modules = [(name = "worker", esModule = embed "structured-clone.js")], - ), - )], -); diff --git a/src/per_isolate/AGENTS.md b/src/per_isolate/AGENTS.md index 4edc47628c4..eb8bdb435a7 100644 --- a/src/per_isolate/AGENTS.md +++ b/src/per_isolate/AGENTS.md @@ -30,6 +30,11 @@ at context creation, before any user code. C++ entry point: - Under the `TS_URL_PATTERN` autogate, `main.ts` installs the TypeScript `URLPattern` (`urlpattern/`), which replaces both C++ implementations; see `urlpattern/AGENTS.md`. +- Under the `TS_STRUCTURED_CLONE` autogate, `main.ts` installs the + TypeScript `structuredClone()` (`structured-clone.ts`, a WebIDL layer over + the native `utils.structuredClone()`), which replaces the C++ method; its + parity suite and divergence ledger are in `src/tests/structured-clone/`, and + its types in `types/defines/structured-clone.d.ts`. - EventTarget subclasses reach the (still C++) EventTarget they extend only through `events/event-target-internals`; see `events/AGENTS.md`. - Modules get `DOMException` from `require('dom-exception')`, which diff --git a/src/per_isolate/main.ts b/src/per_isolate/main.ts index 69b1789bddc..e0c5f76ed74 100644 --- a/src/per_isolate/main.ts +++ b/src/per_isolate/main.ts @@ -447,6 +447,24 @@ if (autogates['ts-url-pattern']) { }); } +// The TypeScript structuredClone() replaces the C++ method, which +// global-scope.h then leaves out. Installed where JSG_METHOD installs it, on +// ServiceWorkerGlobalScope.prototype, with the same attributes (all three +// true). +if (autogates['ts-structured-clone']) { + const { structuredClone } = require('structured-clone'); + ObjectDefineProperties(ObjectGetPrototypeOf(globalThis), { + __proto__: null, + structuredClone: { + __proto__: null, + configurable: true, + enumerable: true, + writable: true, + value: structuredClone, + }, + }); +} + // Internal-only: cloneable classes for testing the serialization protocol // (serialization.ts), such as over RPC. Gated by an experimental flag that // may never lose its experimental annotation. diff --git a/src/per_isolate/per_isolate-env.d.ts b/src/per_isolate/per_isolate-env.d.ts index 6f62b61f691..b97a3383d42 100644 --- a/src/per_isolate/per_isolate-env.d.ts +++ b/src/per_isolate/per_isolate-env.d.ts @@ -241,6 +241,12 @@ declare const utils: { value: unknown ): 'locked' | 'disturbed' | 'readable' | undefined; encodeUtf8(str: string): Uint8Array; + // The structured clone of `value` (jsg::structuredClone), transferring the + // objects in `transfer`, a dense array the caller built. The native + // serializer's rules apply: an ArrayBuffer or a view's buffer is transferred, + // any other object throws a TypeError, and an uncloneable value a + // DataCloneError. Consumed by structured-clone. + structuredClone(value: unknown, transfer: object[] | undefined): unknown; }; // The I/O of a bootstrap API, bound to the request that created it diff --git a/src/per_isolate/structured-clone.ts b/src/per_isolate/structured-clone.ts new file mode 100644 index 00000000000..2cd6b5ad761 --- /dev/null +++ b/src/per_isolate/structured-clone.ts @@ -0,0 +1,129 @@ +'use strict'; + +// The global structuredClone(), installed by main.ts on +// ServiceWorkerGlobalScope.prototype under the TS_STRUCTURED_CLONE autogate, in +// place of the C++ JSG method. +// +// This module is the WebIDL layer: the receiver check, the argument count, and +// the conversion of the StructuredSerializeOptions dictionary. The clone itself +// is the native serializer's, through utils.structuredClone(), so which values +// clone, which objects transfer, and the errors for either are the same as in +// C++. Where the conversion differs from C++ it follows WebIDL; the differences +// are tabled in src/tests/structured-clone/AGENTS.md. + +const { + ArrayPrototypePush, + FunctionPrototypeCall, + ObjectDefineProperty, + SymbolIterator, + TypeError: TypeErrorCtor, +} = primordials; + +const { structuredClone: nativeStructuredClone } = utils; + +// The global proxy, which is the receiver of `globalThis.structuredClone(v)`. +const globalReceiver: unknown = globalThis; + +// The C++ texts, kept where the behaviour matches. +const ILLEGAL_INVOCATION = + 'Illegal invocation: function called with incorrect `this` reference. See ' + + 'https://developers.cloudflare.com/workers/observability/errors/' + + '#illegal-invocation-errors for details.'; +const NO_VALUE = + "Failed to execute 'structuredClone' on 'ServiceWorkerGlobalScope': " + + "parameter 1 is not of type 'Value'."; +const BAD_OPTIONS = + "Failed to execute 'structuredClone' on 'ServiceWorkerGlobalScope': " + + "parameter 2 is not of type 'StructuredCloneOptions'."; +const BAD_TRANSFER = + "Incorrect type for the 'transfer' field on 'StructuredCloneOptions': " + + "the provided value is not of type 'sequence'."; +const BAD_TRANSFER_ITEM = + "Incorrect type for an element of the 'transfer' field on " + + "'StructuredCloneOptions': the provided value is not of type 'object'."; +// After V8's texts for the same failures in for...of. +const ITERATOR_NOT_OBJECT = + 'Result of the Symbol.iterator method is not an object'; +const RESULT_NOT_OBJECT = 'Iterator result is not an object'; + +function isObject(value: unknown): value is object { + return ( + (typeof value === 'object' && value !== null) || typeof value === 'function' + ); +} + +// WebIDL's conversion to sequence: any iterable, consumed through its +// own iterator (the user's, by contract), into an array of our own that the +// native side can read without running user code. Spelled out rather than +// written as for...of, which differs from WebIDL's "create a sequence from an +// iterable" in two observable ways: it reads [Symbol.iterator] a second time +// after the check, and it closes the iterator when an element is rejected. +function toObjectSequence(value: unknown): object[] { + if (!isObject(value)) { + throw new TypeErrorCtor(BAD_TRANSFER); + } + const method: unknown = (value as Record)[SymbolIterator]; + if (typeof method !== 'function') { + throw new TypeErrorCtor(BAD_TRANSFER); + } + const iterator: unknown = FunctionPrototypeCall(method, value); + if (!isObject(iterator)) { + throw new TypeErrorCtor(ITERATOR_NOT_OBJECT); + } + const next = (iterator as { next?: unknown }).next; + const list: object[] = []; + for (;;) { + const result: unknown = FunctionPrototypeCall( + next as (this: unknown) => unknown, + iterator + ); + if (!isObject(result)) { + throw new TypeErrorCtor(RESULT_NOT_OBJECT); + } + if ((result as { done?: unknown }).done) { + return list; + } + const item = (result as { value?: unknown }).value; + if (!isObject(item)) { + throw new TypeErrorCtor(BAD_TRANSFER_ITEM); + } + ArrayPrototypePush(list, item); + } +} + +// A method, so the function has no `prototype` and is not a constructor, like +// the JSG method it replaces. +const { structuredClone } = { + structuredClone(this: unknown, value: unknown, options?: unknown): unknown { + // WebIDL: an operation of the global takes undefined or null as the + // global itself. + if (this != null && this !== globalReceiver) { + throw new TypeErrorCtor(ILLEGAL_INVOCATION); + } + if (arguments.length === 0) { + throw new TypeErrorCtor(NO_VALUE); + } + let transfer: object[] | undefined; + if (options != null) { + if (!isObject(options)) { + throw new TypeErrorCtor(BAD_OPTIONS); + } + const list = (options as { transfer?: unknown }).transfer; + if (list !== undefined) { + transfer = toObjectSequence(list); + } + } + return nativeStructuredClone(value, transfer); + }, +}; + +// WebIDL: the optional options argument does not count. +ObjectDefineProperty(structuredClone, 'length', { + __proto__: null, + configurable: true, + enumerable: false, + writable: false, + value: 1, +}); + +module.exports = { structuredClone }; diff --git a/src/tests/structured-clone/AGENTS.md b/src/tests/structured-clone/AGENTS.md new file mode 100644 index 00000000000..20d1890903f --- /dev/null +++ b/src/tests/structured-clone/AGENTS.md @@ -0,0 +1,72 @@ +# src/tests/structured-clone/ + +Tests for the global `structuredClone()`. Every test runs against both +implementations: + +- the C++ JSG method, `ServiceWorkerGlobalScope::structuredClone` in + `src/workerd/api/global-scope.c++`; +- the TypeScript one, `src/per_isolate/structured-clone.ts`. `main.ts` installs + it under the `TS_STRUCTURED_CLONE` autogate, and `global-scope.h` then + leaves the C++ method out. + +The layout follows `src/tests/streams/AGENTS.md`: + +- `structured-clone-modules.capnp` lists the modules once. +- `structured-clone-cpp.wd-test` and `structured-clone-ts.wd-test` run that list. +- `main.js` re-exports every test by name. +- `which-impl.js` exports `usingTsImpl`, read from the cell's `USING_TS_IMPL` + binding, since user code cannot read the autogate. + +Both implementations clone with the same native serializer, `jsg::structuredClone` +in `src/workerd/jsg/ser.c++`. The TypeScript one reaches it through +`utils.structuredClone()`. Everything about the clone itself is therefore parity: +which values clone, which objects transfer, and the `DataCloneError` and +`TypeError` texts (`cloning.js`). The implementations differ only in the +WebIDL layer in front of the serializer. TypeScript follows WebIDL there; C++ +follows JSG's conversions. + +## Divergence ledger (C++ vs TypeScript) + +| # | Area | C++ | TypeScript | Pinned in | +| --- | --- | --- | --- | --- | +| 1 | `structuredClone.length` | 0 | 1 (WebIDL: the optional options argument does not count) | `functionShape` | +| 2 | Source text | `function structuredClone() { [native code] }` | the method's source | `sourceText` | +| 3 | Values accepted as `transfer` | Arrays only, so not Sets, iterators, or Proxies of arrays | any iterable (WebIDL `sequence`), including those three, read as WebIDL reads one: `[Symbol.iterator]` and `next` once each, and the iterator not closed when an element is rejected | `iterablesOtherThanArrays`, `iteratorMethodReadOnce`, `nextReadOnce`, `iteratorNotClosedOnRejectedElement`, `nonObjectIteratorRejected`, `nonObjectIteratorResultRejected` | +| 4 | Message when `transfer` is rejected (primitives, `null`, non-iterable objects; a TypeError in both) | `... is not of type 'Array'.` | `... is not of type 'sequence'.` | `nonObjectMemberRejected`, `nonIterableObjectRejected` | +| 5 | A non-object `transfer` element, including an array hole (a TypeError in both) | reaches the serializer: `Object is not transferable` | rejected by the conversion: `... an element of the 'transfer' field ... not of type 'object'.` | `nonObjectElementsRejected` | +| 6 | An array's `[Symbol.iterator]` | not called; elements read by index | called once (WebIDL iterates the sequence, user iterator by contract) | `arrayIteratorUse` | + +## Parity worth knowing + +All of these are spec deviations shared by both implementations, and so pinned +as parity: + +- **Receiver.** `undefined`, `null` and the global are accepted. Any other + receiver throws JSG's illegal-invocation `TypeError`. The check runs before + any argument is read. +- **Argument count.** A call with no arguments throws JSG's `parameter 1 is + not of type 'Value'` `TypeError`. +- **Options.** `undefined` and `null` mean no options. Any object, including + functions and arrays, is a dictionary. A primitive throws `parameter 2 is + not of type 'StructuredCloneOptions'`. +- **When `transfer` is read.** It is read once, through the prototype chain, + before the value is serialized. +- **Transfer semantics.** These come from the serializer: + - A view transfers its buffer. + - Duplicates and already-detached buffers are accepted, where the spec says + DataCloneError. + - A non-ArrayBuffer object throws a `TypeError`, where the spec says + DataCloneError. + - Shared memory is not transferable. + - Buffers are detached only after the value is written. + +## Running + +``` +bazel test //src/tests/structured-clone/... +``` + +Targets: `structured-clone-cpp@` and `structured-clone-ts@`, each with an +`@all-compat-flags` variant. Only the TypeScript cell has `@all-autogates`: +enabling every autogate enables `TS_STRUCTURED_CLONE`, which would run the +TypeScript implementation under the C++ cell. diff --git a/src/tests/structured-clone/BUILD.bazel b/src/tests/structured-clone/BUILD.bazel new file mode 100644 index 00000000000..90962db0196 --- /dev/null +++ b/src/tests/structured-clone/BUILD.bazel @@ -0,0 +1,23 @@ +load("//:build/wd_test.bzl", "wd_test") + +# The structuredClone suite runs the same test modules under two configs: +# structured-clone-cpp against the C++ JSG method, structured-clone-ts against +# the TypeScript implementation. +# +# The C++ cell disables the @all-autogates variant: enabling every autogate +# enables TS_STRUCTURED_CLONE, which swaps in the TypeScript implementation +# under a cell whose USING_TS_IMPL binding says C++. The TypeScript cell +# enables TS_STRUCTURED_CLONE itself. + +structured_clone_suite_srcs = glob(["*.js"]) + ["structured-clone-modules.capnp"] + +wd_test( + src = "structured-clone-cpp.wd-test", + data = structured_clone_suite_srcs, + generate_all_autogates_variant = False, +) + +wd_test( + src = "structured-clone-ts.wd-test", + data = structured_clone_suite_srcs, +) diff --git a/src/tests/structured-clone/api-surface.js b/src/tests/structured-clone/api-surface.js new file mode 100644 index 00000000000..8c0d8df24e2 --- /dev/null +++ b/src/tests/structured-clone/api-surface.js @@ -0,0 +1,96 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// Where structuredClone lives and the shape of the function. Divergences: +// length is 0 in C++ and 1 in TypeScript (WebIDL: the optional options +// argument does not count), ledger #1; the source text is native code only in +// C++, ledger #2. + +import { deepStrictEqual, strictEqual, throws } from 'node:assert'; +import { usingTsImpl } from 'which-impl'; + +export const placement = { + test() { + // A method of ServiceWorkerGlobalScope.prototype, not an own property of + // the global, and the only one on the chain. + strictEqual(Object.hasOwn(globalThis, 'structuredClone'), false); + const proto = Object.getPrototypeOf(globalThis); + deepStrictEqual(Object.getOwnPropertyDescriptor(proto, 'structuredClone'), { + value: proto.structuredClone, + writable: true, + enumerable: true, + configurable: true, + }); + for ( + let p = Object.getPrototypeOf(proto); + p; + p = Object.getPrototypeOf(p) + ) { + strictEqual(Object.hasOwn(p, 'structuredClone'), false); + } + strictEqual(globalThis.structuredClone, proto.structuredClone); + }, +}; + +export const functionShape = { + test() { + strictEqual(structuredClone.name, 'structuredClone'); + strictEqual(structuredClone.length, usingTsImpl ? 1 : 0); + deepStrictEqual(Reflect.ownKeys(structuredClone), ['length', 'name']); + deepStrictEqual( + Object.getOwnPropertyDescriptor(structuredClone, 'length'), + { + value: usingTsImpl ? 1 : 0, + writable: false, + enumerable: false, + configurable: true, + } + ); + strictEqual(Object.getPrototypeOf(structuredClone), Function.prototype); + }, +}; + +export const notAConstructor = { + test() { + throws(() => new structuredClone(1), { + name: 'TypeError', + message: /is not a constructor/, + }); + }, +}; + +export const sourceText = { + test() { + const source = Function.prototype.toString.call(structuredClone); + strictEqual( + source === 'function structuredClone() { [native code] }', + !usingTsImpl + ); + strictEqual(source.startsWith('structuredClone('), usingTsImpl); + }, +}; + +export const replaceableAndDeletable = { + test() { + const proto = Object.getPrototypeOf(globalThis); + const original = proto.structuredClone; + try { + globalThis.structuredClone = 'shadowed'; + strictEqual(Object.hasOwn(globalThis, 'structuredClone'), true); + strictEqual(proto.structuredClone, original); + delete globalThis.structuredClone; + strictEqual(globalThis.structuredClone, original); + delete proto.structuredClone; + strictEqual('structuredClone' in globalThis, false); + } finally { + delete globalThis.structuredClone; + Object.defineProperty(proto, 'structuredClone', { + value: original, + writable: true, + enumerable: true, + configurable: true, + }); + } + }, +}; diff --git a/src/tests/structured-clone/arguments.js b/src/tests/structured-clone/arguments.js new file mode 100644 index 00000000000..892d0a7b45a --- /dev/null +++ b/src/tests/structured-clone/arguments.js @@ -0,0 +1,94 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// The argument count and the conversion of the options dictionary, the same +// in both. + +import { strictEqual, throws } from 'node:assert'; + +const BAD_OPTIONS = + "Failed to execute 'structuredClone' on 'ServiceWorkerGlobalScope': " + + "parameter 2 is not of type 'StructuredCloneOptions'."; + +export const valueIsRequired = { + test() { + throws(() => structuredClone(), { + name: 'TypeError', + message: + "Failed to execute 'structuredClone' on 'ServiceWorkerGlobalScope': " + + "parameter 1 is not of type 'Value'.", + }); + strictEqual(structuredClone(undefined), undefined); + }, +}; + +export const extraArgumentsIgnored = { + test() { + strictEqual(structuredClone(1, undefined, 3), 1); + }, +}; + +export const absentOptions = { + test() { + strictEqual(structuredClone(1, undefined), 1); + strictEqual(structuredClone(1, null), 1); + }, +}; + +export const objectOptions = { + test() { + // Any object is a dictionary, including functions and arrays, and an + // absent or undefined transfer member transfers nothing. + for (const options of [{}, [], () => {}, { transfer: undefined }]) { + strictEqual(structuredClone(1, options), 1); + } + }, +}; + +export const primitiveOptionsRejected = { + test() { + for (const options of [1, 's', true, Symbol('x'), 1n]) { + throws(() => structuredClone(1, options), { + name: 'TypeError', + message: BAD_OPTIONS, + }); + } + }, +}; + +export const transferMemberLookup = { + test() { + // Read once, through the prototype chain, before the value is serialized. + const log = []; + const options = Object.create({ + get transfer() { + log.push('transfer'); + return []; + }, + }); + const value = { + get x() { + log.push('value'); + return 1; + }, + }; + strictEqual(structuredClone(value, options).x, 1); + strictEqual(log.join(), 'transfer,value'); + }, +}; + +export const transferGetterThrows = { + test() { + const error = new RangeError('boom'); + throws( + () => + structuredClone(1, { + get transfer() { + throw error; + }, + }), + (e) => e === error + ); + }, +}; diff --git a/src/tests/structured-clone/cloning.js b/src/tests/structured-clone/cloning.js new file mode 100644 index 00000000000..cf15eb746d0 --- /dev/null +++ b/src/tests/structured-clone/cloning.js @@ -0,0 +1,125 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// The clone itself, which both implementations leave to the native +// serializer: these assertions hold identically. + +import { + deepStrictEqual, + notStrictEqual, + ok, + strictEqual, + throws, +} from 'node:assert'; + +export const plainValues = { + test() { + for (const value of [undefined, null, true, 0, -0, NaN, 1n, 'str']) { + ok(Object.is(structuredClone(value), value)); + } + const value = { + a: [1, { b: new Map([[1, new Set([2])]]) }], + d: new Date(0), + }; + value.self = value; + const clone = structuredClone(value); + notStrictEqual(clone, value); + strictEqual(clone.self, clone); + deepStrictEqual(clone.a[1].b, new Map([[1, new Set([2])]])); + strictEqual(clone.d.getTime(), 0); + }, +}; + +export const hostObjects = { + test() { + const headers = new Headers({ a: '1' }); + const clone = structuredClone(headers); + ok(clone instanceof Headers); + notStrictEqual(clone, headers); + strictEqual(clone.get('a'), '1'); + }, +}; + +export const uncloneableValues = { + test() { + for (const [value, text] of [ + [() => {}, '() => {} could not be cloned.'], + [Symbol('s'), 'Symbol(s) could not be cloned.'], + [new WeakMap(), '# could not be cloned.'], + ]) { + throws( + () => structuredClone(value), + (e) => { + ok(e instanceof DOMException); + strictEqual(e.name, 'DataCloneError'); + strictEqual(e.code, 25); + strictEqual(e.message, text); + return true; + } + ); + } + }, +}; + +export const valueGetterThrows = { + test() { + const error = new RangeError('inner'); + throws( + () => + structuredClone({ + get x() { + throw error; + }, + }), + (e) => e === error + ); + }, +}; + +export const transferSemantics = { + test() { + { + // A view transfers its buffer. + const view = new Uint8Array([1, 2, 3]); + const clone = structuredClone(view, { transfer: [view] }); + strictEqual(view.byteLength, 0); + deepStrictEqual([...clone], [1, 2, 3]); + } + { + // Duplicates and an already-detached buffer are accepted. + const buffer = new ArrayBuffer(4); + structuredClone(buffer, { transfer: [buffer, buffer] }); + strictEqual(buffer.byteLength, 0); + structuredClone(buffer, { transfer: [buffer] }); + } + { + // A transferred buffer is detached only after the value is written. + const buffer = new ArrayBuffer(4); + const value = { + get size() { + return buffer.byteLength; + }, + }; + strictEqual(structuredClone(value, { transfer: [buffer] }).size, 4); + strictEqual(buffer.byteLength, 0); + } + { + // Shared memory is not transferable: a SharedArrayBuffer is not an + // ArrayBuffer, and a view over one has a buffer that cannot be detached. + const shared = new SharedArrayBuffer(4); + throws(() => structuredClone(shared, { transfer: [shared] }), { + name: 'TypeError', + message: 'Object is not transferable', + }); + const view = new Uint8Array(shared); + throws( + () => structuredClone(view, { transfer: [view] }), + (e) => + e instanceof DOMException && + e.name === 'DataCloneError' && + e.message === 'Object is not transferable.' + ); + } + }, +}; diff --git a/src/tests/structured-clone/main.js b/src/tests/structured-clone/main.js new file mode 100644 index 00000000000..5bb145477fc --- /dev/null +++ b/src/tests/structured-clone/main.js @@ -0,0 +1,57 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// Entry point for the structuredClone suite. Re-exports are explicit (not +// `export *`) so a name collision between modules is a load-time SyntaxError +// instead of a silently dropped test. + +export { + placement, + functionShape, + notAConstructor, + sourceText, + replaceableAndDeletable, +} from 'api-surface'; + +export { + acceptedReceivers, + rejectedReceivers, + receiverCheckedBeforeArguments, +} from 'receiver'; + +export { + valueIsRequired, + extraArgumentsIgnored, + absentOptions, + objectOptions, + primitiveOptionsRejected, + transferMemberLookup, + transferGetterThrows, +} from 'arguments'; + +export { + arrayTransfers, + nonObjectMemberRejected, + nonIterableObjectRejected, + iterablesOtherThanArrays, + nonObjectElementsRejected, + nonTransferableObjectsRejected, + arrayIteratorUse, + elementGetters, + iteratorMethodReadOnce, + nextReadOnce, + iteratorNotClosedOnRejectedElement, + nonObjectIteratorRejected, + nonObjectIteratorResultRejected, +} from 'transfer-conversion'; + +export { + plainValues, + hostObjects, + uncloneableValues, + valueGetterThrows, + transferSemantics, +} from 'cloning'; + +export { patchedBuiltins, errorsUseTheRealTypeError } from 'pollution'; diff --git a/src/tests/structured-clone/pollution.js b/src/tests/structured-clone/pollution.js new file mode 100644 index 00000000000..96f0183ea32 --- /dev/null +++ b/src/tests/structured-clone/pollution.js @@ -0,0 +1,64 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// Built-ins that user code patches after startup do not reach the +// conversion, other than the iterator the transfer member is read through +// (see transfer-conversion.js). + +import { deepStrictEqual, strictEqual } from 'node:assert'; + +// Captured so the helper still works while Object.defineProperty is patched. +const { defineProperty, getOwnPropertyDescriptor } = Reflect; + +function withPatched(object, key, value, fn) { + const saved = getOwnPropertyDescriptor(object, key); + defineProperty(object, key, { + value, + writable: true, + configurable: true, + }); + try { + fn(); + } finally { + defineProperty(object, key, saved); + } +} + +export const patchedBuiltins = { + test() { + const boom = () => { + throw new Error('patched built-in was called'); + }; + const buffer = new ArrayBuffer(4); + let clone; + withPatched(Array.prototype, 'push', boom, () => { + withPatched(Object, 'defineProperty', boom, () => { + withPatched(globalThis, 'TypeError', boom, () => { + clone = structuredClone(buffer, { transfer: [buffer] }); + }); + }); + }); + deepStrictEqual([buffer.byteLength, clone.byteLength], [0, 4]); + }, +}; + +export const errorsUseTheRealTypeError = { + test() { + const RealTypeError = TypeError; + let error; + withPatched( + globalThis, + 'TypeError', + function NotTypeError() {}, + () => { + try { + structuredClone(1, 1); + } catch (e) { + error = e; + } + } + ); + strictEqual(Object.getPrototypeOf(error), RealTypeError.prototype); + }, +}; diff --git a/src/tests/structured-clone/receiver.js b/src/tests/structured-clone/receiver.js new file mode 100644 index 00000000000..14c596318e6 --- /dev/null +++ b/src/tests/structured-clone/receiver.js @@ -0,0 +1,60 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// The receiver check: the global, undefined (a plain call) or null is +// accepted, as WebIDL has it for an operation of the global; anything else is +// an illegal invocation, with the same TypeError in both. + +import { strictEqual, throws } from 'node:assert'; + +const ILLEGAL_INVOCATION = + 'Illegal invocation: function called with incorrect `this` reference. See ' + + 'https://developers.cloudflare.com/workers/observability/errors/' + + '#illegal-invocation-errors for details.'; + +export const acceptedReceivers = { + test() { + const sc = structuredClone; + strictEqual(sc(1), 1); + strictEqual(sc.call(undefined, 2), 2); + strictEqual(sc.call(null, 3), 3); + strictEqual(sc.call(globalThis, 3), 3); + strictEqual(globalThis.structuredClone(4), 4); + strictEqual(Reflect.apply(sc, globalThis, [5]), 5); + }, +}; + +export const rejectedReceivers = { + test() { + const sc = structuredClone; + for (const receiver of [ + {}, + 42, + 'str', + Object.create(globalThis), + Object.getPrototypeOf(globalThis), + ]) { + throws(() => sc.call(receiver, 1), { + name: 'TypeError', + message: ILLEGAL_INVOCATION, + }); + } + }, +}; + +export const receiverCheckedBeforeArguments = { + test() { + let read = false; + const options = { + get transfer() { + read = true; + return []; + }, + }; + throws(() => structuredClone.call({}, 1, options), { + message: ILLEGAL_INVOCATION, + }); + strictEqual(read, false); + }, +}; diff --git a/src/tests/structured-clone/structured-clone-cpp.wd-test b/src/tests/structured-clone/structured-clone-cpp.wd-test new file mode 100644 index 00000000000..9a458b3fbb7 --- /dev/null +++ b/src/tests/structured-clone/structured-clone-cpp.wd-test @@ -0,0 +1,21 @@ +using Workerd = import "/workerd/workerd.capnp"; +using StructuredCloneModules = import "structured-clone-modules.capnp"; + +# Runs the structuredClone suite against the C++ JSG method; +# structured-clone-ts.wd-test runs the identical modules against the +# TypeScript implementation. +# +# No compatibilityDate: the wd_test variants supply the date axis and the +# tests must hold at both extremes. structuredClone consults no flags. + +const unitTests :Workerd.Config = ( + services = [ + ( name = "structured-clone-cpp", + worker = ( + modules = StructuredCloneModules.modules, + compatibilityFlags = ["nodejs_compat"], + bindings = [(name = "USING_TS_IMPL", json = "false")], + ) + ), + ], +); diff --git a/src/tests/structured-clone/structured-clone-modules.capnp b/src/tests/structured-clone/structured-clone-modules.capnp new file mode 100644 index 00000000000..dea3e899e90 --- /dev/null +++ b/src/tests/structured-clone/structured-clone-modules.capnp @@ -0,0 +1,18 @@ +# Single source of truth for the structuredClone suite's module set; both +# cells reference this constant so the two implementations run exactly the +# same embedded code. embed paths resolve relative to THIS file. + +@0xc1f3d7a2b84e6905; + +using Workerd = import "/workerd/workerd.capnp"; + +const modules :List(Workerd.Worker.Module) = [ + (name = "main", esModule = embed "main.js"), + (name = "which-impl", esModule = embed "which-impl.js"), + (name = "api-surface", esModule = embed "api-surface.js"), + (name = "receiver", esModule = embed "receiver.js"), + (name = "arguments", esModule = embed "arguments.js"), + (name = "transfer-conversion", esModule = embed "transfer-conversion.js"), + (name = "cloning", esModule = embed "cloning.js"), + (name = "pollution", esModule = embed "pollution.js"), +]; diff --git a/src/tests/structured-clone/structured-clone-ts.wd-test b/src/tests/structured-clone/structured-clone-ts.wd-test new file mode 100644 index 00000000000..f35fc821355 --- /dev/null +++ b/src/tests/structured-clone/structured-clone-ts.wd-test @@ -0,0 +1,20 @@ +using Workerd = import "/workerd/workerd.capnp"; +using StructuredCloneModules = import "structured-clone-modules.capnp"; + +# Runs the structuredClone suite against the TypeScript implementation +# (src/per_isolate/structured-clone.ts, under the TS_STRUCTURED_CLONE +# autogate), with byte-for-byte the same modules as +# structured-clone-cpp.wd-test. + +const unitTests :Workerd.Config = ( + services = [ + ( name = "structured-clone-ts", + worker = ( + modules = StructuredCloneModules.modules, + compatibilityFlags = ["nodejs_compat"], + bindings = [(name = "USING_TS_IMPL", json = "true")], + ) + ), + ], + autogates = ["workerd-autogate-ts-structured-clone"], +); diff --git a/src/tests/structured-clone/transfer-conversion.js b/src/tests/structured-clone/transfer-conversion.js new file mode 100644 index 00000000000..308fc08674c --- /dev/null +++ b/src/tests/structured-clone/transfer-conversion.js @@ -0,0 +1,268 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// Conversion of the transfer member. C++ converts it as an Array, read by +// index; TypeScript as a WebIDL sequence, read through its iterator. +// Divergences: which values are accepted (ledger #3), the messages for a +// rejected member or element (#4, #5), and whether an array's iterator runs +// (#6). + +import { deepStrictEqual, strictEqual, throws } from 'node:assert'; +import { usingTsImpl } from 'which-impl'; + +const CPP_BAD_TRANSFER = + "Incorrect type for the 'transfer' field on 'StructuredCloneOptions': " + + "the provided value is not of type 'Array'."; +const TS_BAD_TRANSFER = + "Incorrect type for the 'transfer' field on 'StructuredCloneOptions': " + + "the provided value is not of type 'sequence'."; +const CPP_BAD_ITEM = 'Object is not transferable'; +const TS_BAD_ITEM = + "Incorrect type for an element of the 'transfer' field on " + + "'StructuredCloneOptions': the provided value is not of type 'object'."; + +function transferred(transfer, buffer) { + const clone = structuredClone(buffer, { transfer }); + return [buffer.byteLength, clone.byteLength]; +} + +export const arrayTransfers = { + test() { + const buffer = new ArrayBuffer(4); + deepStrictEqual(transferred([buffer], buffer), [0, 4]); + }, +}; + +export const nonObjectMemberRejected = { + test() { + for (const transfer of [null, 1, 'ab', true, Symbol('s')]) { + throws(() => structuredClone(1, { transfer }), { + name: 'TypeError', + message: usingTsImpl ? TS_BAD_TRANSFER : CPP_BAD_TRANSFER, + }); + } + }, +}; + +export const nonIterableObjectRejected = { + test() { + const buffer = new ArrayBuffer(4); + for (const transfer of [{}, { length: 1, 0: buffer }, () => {}]) { + throws(() => structuredClone(buffer, { transfer }), { + name: 'TypeError', + message: usingTsImpl ? TS_BAD_TRANSFER : CPP_BAD_TRANSFER, + }); + strictEqual(buffer.byteLength, 4); + } + }, +}; + +export const iterablesOtherThanArrays = { + test() { + const makers = [ + (b) => new Set([b]), + (b) => + (function* () { + yield b; + })(), + (b) => new Proxy([b], {}), + ]; + for (const make of makers) { + const buffer = new ArrayBuffer(4); + if (usingTsImpl) { + deepStrictEqual(transferred(make(buffer), buffer), [0, 4]); + } else { + throws(() => transferred(make(buffer), buffer), { + name: 'TypeError', + message: CPP_BAD_TRANSFER, + }); + strictEqual(buffer.byteLength, 4); + } + } + }, +}; + +export const nonObjectElementsRejected = { + test() { + // eslint-disable-next-line no-sparse-arrays + for (const transfer of [[1], [null], [undefined], ['s'], [, 1]]) { + throws(() => structuredClone(1, { transfer }), { + name: 'TypeError', + message: usingTsImpl ? TS_BAD_ITEM : CPP_BAD_ITEM, + }); + } + }, +}; + +export const nonTransferableObjectsRejected = { + test() { + // Object elements pass the conversion in both and reach the native + // serializer, which transfers only ArrayBuffers. + for (const item of [{}, [], () => {}, new Map()]) { + throws(() => structuredClone(1, { transfer: [item] }), { + name: 'TypeError', + message: CPP_BAD_ITEM, + }); + } + }, +}; + +export const arrayIteratorUse = { + test() { + const saved = Array.prototype[Symbol.iterator]; + let calls = 0; + Array.prototype[Symbol.iterator] = function () { + calls++; + return saved.call(this); + }; + const buffer = new ArrayBuffer(4); + let clone; + try { + clone = structuredClone(buffer, { transfer: [buffer] }); + } finally { + Array.prototype[Symbol.iterator] = saved; + } + strictEqual(calls, usingTsImpl ? 1 : 0); + deepStrictEqual([buffer.byteLength, clone.byteLength], [0, 4]); + }, +}; + +export const elementGetters = { + test() { + // Each element is read once in both. + const buffer = new ArrayBuffer(4); + let reads = 0; + const transfer = []; + Object.defineProperty(transfer, 0, { + get() { + reads++; + return buffer; + }, + }); + deepStrictEqual(transferred(transfer, buffer), [0, 4]); + strictEqual(reads, 1); + }, +}; + +// The remaining tests use iterables that are not Arrays, so C++ rejects each +// one as a whole, without reading [Symbol.iterator] (ledger #3). They pin how +// TypeScript reads one, which follows WebIDL's "create a sequence from an +// iterable" rather than for...of. + +function rejectedByCpp(transfer, buffer) { + throws(() => structuredClone(buffer, { transfer }), { + name: 'TypeError', + message: CPP_BAD_TRANSFER, + }); + strictEqual(buffer.byteLength, 4); +} + +export const iteratorMethodReadOnce = { + test() { + const buffer = new ArrayBuffer(4); + let reads = 0; + const transfer = { + get [Symbol.iterator]() { + reads++; + return () => [buffer].values(); + }, + }; + if (usingTsImpl) { + deepStrictEqual(transferred(transfer, buffer), [0, 4]); + strictEqual(reads, 1); + } else { + rejectedByCpp(transfer, buffer); + strictEqual(reads, 0); + } + }, +}; + +export const nextReadOnce = { + test() { + const buffer = new ArrayBuffer(4); + const other = new ArrayBuffer(4); + let reads = 0; + const transfer = { + [Symbol.iterator]() { + const inner = [buffer, other].values(); + return { + get next() { + reads++; + return () => inner.next(); + }, + }; + }, + }; + if (usingTsImpl) { + deepStrictEqual(transferred(transfer, buffer), [0, 4]); + strictEqual(other.byteLength, 0); + strictEqual(reads, 1); + } else { + rejectedByCpp(transfer, buffer); + strictEqual(reads, 0); + } + }, +}; + +export const iteratorNotClosedOnRejectedElement = { + test() { + const buffer = new ArrayBuffer(4); + let returns = 0; + const transfer = { + [Symbol.iterator]() { + return { + next: () => ({ done: false, value: 1 }), + return() { + returns++; + return {}; + }, + }; + }, + }; + if (usingTsImpl) { + throws(() => structuredClone(buffer, { transfer }), { + name: 'TypeError', + message: TS_BAD_ITEM, + }); + strictEqual(buffer.byteLength, 4); + } else { + rejectedByCpp(transfer, buffer); + } + strictEqual(returns, 0); + }, +}; + +export const nonObjectIteratorRejected = { + test() { + const buffer = new ArrayBuffer(4); + const transfer = { [Symbol.iterator]: () => 1 }; + if (usingTsImpl) { + throws(() => structuredClone(buffer, { transfer }), { + name: 'TypeError', + message: 'Result of the Symbol.iterator method is not an object', + }); + strictEqual(buffer.byteLength, 4); + } else { + rejectedByCpp(transfer, buffer); + } + }, +}; + +export const nonObjectIteratorResultRejected = { + test() { + const buffer = new ArrayBuffer(4); + const transfer = { + [Symbol.iterator]: () => ({ next: () => 1 }), + }; + if (usingTsImpl) { + throws(() => structuredClone(buffer, { transfer }), { + name: 'TypeError', + message: 'Iterator result is not an object', + }); + strictEqual(buffer.byteLength, 4); + } else { + rejectedByCpp(transfer, buffer); + } + }, +}; diff --git a/src/tests/structured-clone/which-impl.js b/src/tests/structured-clone/which-impl.js new file mode 100644 index 00000000000..0bf66b0115c --- /dev/null +++ b/src/tests/structured-clone/which-impl.js @@ -0,0 +1,11 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// Which structuredClone implementation this cell runs, so tests can pin each +// side of a deliberate divergence exactly. The implementation is selected by +// the TS_STRUCTURED_CLONE autogate, which user code cannot read, so each cell +// says which one it is meant to run through its USING_TS_IMPL binding. +import { env } from 'cloudflare:workers'; + +export const usingTsImpl = env.USING_TS_IMPL === true; diff --git a/src/workerd/api/global-scope.h b/src/workerd/api/global-scope.h index 47885833bdf..f545ff4b365 100644 --- a/src/workerd/api/global-scope.h +++ b/src/workerd/api/global-scope.h @@ -850,7 +850,8 @@ class ServiceWorkerGlobalScope: public WorkerGlobalScope { struct StructuredCloneOptions { jsg::Optional>> transfer; JSG_STRUCT(transfer); - JSG_STRUCT_TS_OVERRIDE(StructuredSerializeOptions); + // Declared in types/defines/structured-clone.d.ts. + JSG_STRUCT_TS_OVERRIDE(type StructuredSerializeOptions = never); }; jsg::JsValue structuredClone( @@ -963,7 +964,13 @@ class ServiceWorkerGlobalScope: public WorkerGlobalScope { JSG_METHOD(setInterval); JSG_METHOD(clearInterval); JSG_METHOD(queueMicrotask); - JSG_METHOD(structuredClone); + // Under the TS_STRUCTURED_CLONE autogate, the per-isolate bootstrap installs the TypeScript + // structuredClone() instead. Its types come from types/defines/structured-clone.d.ts, not from + // this method (the JSG_TS_OVERRIDE below omits it), so they do not depend on whether this + // method is registered. + if (!util::Autogate::isEnabled(util::AutogateKey::TS_STRUCTURED_CLONE)) { + JSG_METHOD(structuredClone); + } JSG_METHOD(reportError); JSG_METHOD(fetch); @@ -1269,6 +1276,7 @@ class ServiceWorkerGlobalScope: public WorkerGlobalScope { // `instantiate()` override taking a `BufferSource` and `instantiateStreaming()` are omitted. // `Module` is also declared `abstract` to disable its `BufferSource` constructor. + // structuredClone() is declared in types/defines/structured-clone.d.ts. JSG_TS_OVERRIDE({ setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; @@ -1276,7 +1284,7 @@ class ServiceWorkerGlobalScope: public WorkerGlobalScope { setInterval(callback: (...args: any[]) => void, msDelay?: number): number; setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - structuredClone(value: T, options?: StructuredSerializeOptions): T; + structuredClone: never; queueMicrotask(task: Function): void; fetch(input: RequestInfo | URL, init?: RequestInit): Promise; diff --git a/src/workerd/api/per-isolate-bootstrap.c++ b/src/workerd/api/per-isolate-bootstrap.c++ index 5c66e3c6710..4a1b47a59c0 100644 --- a/src/workerd/api/per-isolate-bootstrap.c++ +++ b/src/workerd/api/per-isolate-bootstrap.c++ @@ -528,6 +528,27 @@ static void GetPrivateSymbol(const v8::FunctionCallbackInfo& args) { }); } +// The structured clone of a value, backing the TypeScript structuredClone(). The +// caller has already converted the options, so the second argument is undefined +// or a dense array it built itself, whose elements are objects to transfer; +// reading them cannot run user code. Serialization can run user code (getters) +// and throws a DataCloneError for an uncloneable value. Plain method: it +// allocates and can throw. +static void StructuredClone(const v8::FunctionCallbackInfo& args) { + jsg::liftKj(args, [&]() -> v8::Local { + auto& js = jsg::Lock::from(args.GetIsolate()); + kj::Maybe> transfer; + KJ_IF_SOME(list, jsg::JsValue(args[1]).tryCast()) { + auto builder = kj::heapArrayBuilder(list.size()); + for (auto i: kj::zeroTo(list.size())) { + builder.add(list.get(js, i)); + } + transfer = builder.finish(); + } + return jsg::JsValue(args[0]).structuredClone(js, kj::mv(transfer)); + }); +} + static const v8::CFunction fast_mark_promise_handled_ = v8::CFunction::Make(MarkPromiseHandledFastApi); @@ -608,6 +629,7 @@ jsg::JsRef createUtilsObject(jsg::Lock& js) { "mimeTypeEssence", "readableStreamState", "DOMExceptionBase", + "structuredClone", }; auto tmpl = v8::DictionaryTemplate::New(js.v8Isolate, names); v8::MaybeLocal values[] = { @@ -651,6 +673,7 @@ jsg::JsRef createUtilsObject(jsg::Lock& js) { getMethod(js, MimeTypeEssence), getMethod(js, ReadableStreamState), v8::Local(jsg::getBootstrapDomExceptionBase(js)), + getMethod(js, StructuredClone), }; static_assert(kj::arrayPtr(names).size() == kj::arrayPtr(values).size()); diff --git a/src/workerd/util/autogate.h b/src/workerd/util/autogate.h index f847d3538dd..59b3f7ef9f4 100644 --- a/src/workerd/util/autogate.h +++ b/src/workerd/util/autogate.h @@ -118,6 +118,10 @@ namespace workerd::util { (src/per_isolate/dom-exception.ts), whose instances are native errors, rather than the C++ \ class in jsg/dom-exception.h. */ \ V(TS_DOM_EXCEPTION) \ + /* The global structuredClone() is the TypeScript implementation from the per-isolate \ + bootstrap (src/per_isolate/structured-clone.ts), a WebIDL layer over the same native \ + serializer, rather than the C++ method in api/global-scope.h. */ \ + V(TS_STRUCTURED_CLONE) \ /* KILL SWITCH: unlike most autogates, enabling this one turns a feature OFF. \ By default, each Durable Object instance can have at most 32768 non-hibernatable WebSockets \ open, whether accepted with accept() or opened with `new WebSocket(url)`; accepting or \ diff --git a/types/AGENTS.md b/types/AGENTS.md index aeca45769ae..81f76efde2e 100644 --- a/types/AGENTS.md +++ b/types/AGENTS.md @@ -50,7 +50,7 @@ Types in this project come from three layers. Changes must be made in the correc | ------------------------ | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | **C++ RTTI** | `src/workerd/api/*.h` (JSG macros) | Types derived from C++ classes — the generator extracts these automatically | | **`JSG_TS_OVERRIDE`** | Same `.h` files, inside `JSG_RESOURCE_TYPE` blocks | When the auto-generated TS signature needs adjustment (e.g., conditional properties, union narrowing) | -| **Hand-written defines** | `types/defines/*.d.ts` | Types for APIs not expressible via C++ RTTI (Cloudflare product bindings like AI, D1, R2, Vectorize, etc.), and for APIs the per-isolate bootstrap implements, whose C++ counterparts declare `JSG_TS_OVERRIDE(type X = never)` (`dom-exception.d.ts`, `url.d.ts`, `urlpattern.d.ts`) | +| **Hand-written defines** | `types/defines/*.d.ts` | Types for APIs not expressible via C++ RTTI (Cloudflare product bindings like AI, D1, R2, Vectorize, etc.), and for APIs the per-isolate bootstrap implements, whose C++ counterparts declare `JSG_TS_OVERRIDE(type X = never)` (`dom-exception.d.ts`, `url.d.ts`, `urlpattern.d.ts`) or, for a global scope method, a `never` member in the global scope's override (`structured-clone.d.ts`) | Do **not** edit files in `generated-snapshot/` directly — they are overwritten by `just generate-types`. If the generated output looks wrong, fix the source layer (C++ RTTI, `JSG_TS_OVERRIDE`, or `defines/`). diff --git a/types/defines/structured-clone.d.ts b/types/defines/structured-clone.d.ts new file mode 100644 index 00000000000..76c8adb60d6 --- /dev/null +++ b/types/defines/structured-clone.d.ts @@ -0,0 +1,11 @@ +interface StructuredSerializeOptions { + transfer?: any[]; +} +interface ServiceWorkerGlobalScope { + structuredClone(value: T, options?: StructuredSerializeOptions): T; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions +): T; diff --git a/types/generated-snapshot/experimental/index.d.ts b/types/generated-snapshot/experimental/index.d.ts index 1cc23ba5a49..b80d733b10c 100755 --- a/types/generated-snapshot/experimental/index.d.ts +++ b/types/generated-snapshot/experimental/index.d.ts @@ -252,7 +252,6 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { ): number; clearInterval(timeoutId: number | null): void; queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; reportError(error: any): void; fetch( input: RequestInfo | URL, @@ -389,11 +388,6 @@ declare function setInterval( declare function clearInterval(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ declare function queueMicrotask(task: Function): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -declare function structuredClone( - value: T, - options?: StructuredSerializeOptions, -): T; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ declare function reportError(error: any): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ @@ -517,9 +511,6 @@ interface ExportedHandler< email?: EmailExportedHandler; queue?: ExportedHandlerQueueHandler; } -interface StructuredSerializeOptions { - transfer?: any[]; -} declare abstract class Navigator { sendBeacon(url: string, body?: BodyInit): boolean; readonly userAgent: string; @@ -17598,6 +17589,17 @@ interface AlreadyUploadedError extends StreamError { interface TooManyWatermarksError extends StreamError { name: "TooManyWatermarksError"; } +interface StructuredSerializeOptions { + transfer?: any[]; +} +interface ServiceWorkerGlobalScope { + structuredClone(value: T, options?: StructuredSerializeOptions): T; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; type MarkdownDocument = { name: string; blob: Blob; diff --git a/types/generated-snapshot/experimental/index.ts b/types/generated-snapshot/experimental/index.ts index 434b73b9a23..597487c192f 100755 --- a/types/generated-snapshot/experimental/index.ts +++ b/types/generated-snapshot/experimental/index.ts @@ -252,7 +252,6 @@ export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { ): number; clearInterval(timeoutId: number | null): void; queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; reportError(error: any): void; fetch( input: RequestInfo | URL, @@ -391,11 +390,6 @@ export declare function setInterval( export declare function clearInterval(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ export declare function queueMicrotask(task: Function): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -export declare function structuredClone( - value: T, - options?: StructuredSerializeOptions, -): T; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ export declare function reportError(error: any): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ @@ -519,9 +513,6 @@ export interface ExportedHandler< email?: EmailExportedHandler; queue?: ExportedHandlerQueueHandler; } -export interface StructuredSerializeOptions { - transfer?: any[]; -} export declare abstract class Navigator { sendBeacon(url: string, body?: BodyInit): boolean; readonly userAgent: string; @@ -17498,6 +17489,17 @@ export interface AlreadyUploadedError extends StreamError { export interface TooManyWatermarksError extends StreamError { name: "TooManyWatermarksError"; } +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export interface ServiceWorkerGlobalScope { + structuredClone(value: T, options?: StructuredSerializeOptions): T; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; export type MarkdownDocument = { name: string; blob: Blob; diff --git a/types/generated-snapshot/index.d.ts b/types/generated-snapshot/index.d.ts index 80212409959..09b3d1c562f 100755 --- a/types/generated-snapshot/index.d.ts +++ b/types/generated-snapshot/index.d.ts @@ -251,7 +251,6 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { ): number; clearInterval(timeoutId: number | null): void; queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; reportError(error: any): void; fetch( input: RequestInfo | URL, @@ -390,11 +389,6 @@ declare function setInterval( declare function clearInterval(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ declare function queueMicrotask(task: Function): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -declare function structuredClone( - value: T, - options?: StructuredSerializeOptions, -): T; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ declare function reportError(error: any): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ @@ -517,9 +511,6 @@ interface ExportedHandler< email?: EmailExportedHandler; queue?: ExportedHandlerQueueHandler; } -interface StructuredSerializeOptions { - transfer?: any[]; -} declare abstract class Navigator { sendBeacon(url: string, body?: BodyInit): boolean; readonly userAgent: string; @@ -17231,6 +17222,17 @@ interface AlreadyUploadedError extends StreamError { interface TooManyWatermarksError extends StreamError { name: "TooManyWatermarksError"; } +interface StructuredSerializeOptions { + transfer?: any[]; +} +interface ServiceWorkerGlobalScope { + structuredClone(value: T, options?: StructuredSerializeOptions): T; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; type MarkdownDocument = { name: string; blob: Blob; diff --git a/types/generated-snapshot/index.ts b/types/generated-snapshot/index.ts index 519aa0b8b17..dfe5d8d597a 100755 --- a/types/generated-snapshot/index.ts +++ b/types/generated-snapshot/index.ts @@ -251,7 +251,6 @@ export interface ServiceWorkerGlobalScope extends WorkerGlobalScope { ): number; clearInterval(timeoutId: number | null): void; queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; reportError(error: any): void; fetch( input: RequestInfo | URL, @@ -392,11 +391,6 @@ export declare function setInterval( export declare function clearInterval(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ export declare function queueMicrotask(task: Function): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -export declare function structuredClone( - value: T, - options?: StructuredSerializeOptions, -): T; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ export declare function reportError(error: any): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ @@ -519,9 +513,6 @@ export interface ExportedHandler< email?: EmailExportedHandler; queue?: ExportedHandlerQueueHandler; } -export interface StructuredSerializeOptions { - transfer?: any[]; -} export declare abstract class Navigator { sendBeacon(url: string, body?: BodyInit): boolean; readonly userAgent: string; @@ -17134,6 +17125,17 @@ export interface AlreadyUploadedError extends StreamError { export interface TooManyWatermarksError extends StreamError { name: "TooManyWatermarksError"; } +export interface StructuredSerializeOptions { + transfer?: any[]; +} +export interface ServiceWorkerGlobalScope { + structuredClone(value: T, options?: StructuredSerializeOptions): T; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ +export declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T; export type MarkdownDocument = { name: string; blob: Blob; diff --git a/types/test/types/structured-clone.ts b/types/test/types/structured-clone.ts new file mode 100644 index 00000000000..84b67ca8bf1 --- /dev/null +++ b/types/test/types/structured-clone.ts @@ -0,0 +1,30 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// structuredClone() is declared in types/defines/structured-clone.d.ts rather +// than generated from the C++ method, so these hold whichever implementation +// the runtime installs. + +import { expectTypeOf } from 'expect-type'; + +expectTypeOf(structuredClone({ a: 1 })).toEqualTypeOf<{ a: number }>(); +expectTypeOf(structuredClone('s')).toEqualTypeOf(); + +const buffer = new ArrayBuffer(8); +expectTypeOf(structuredClone(buffer, { transfer: [buffer] })).toEqualTypeOf(); +structuredClone(1, {}); +structuredClone(1, undefined); +// @ts-expect-error the value argument is required. +structuredClone(); +// @ts-expect-error transfer is a list. +structuredClone(buffer, { transfer: buffer }); + +expectTypeOf().toEqualTypeOf<{ transfer?: any[] }>(); + +// The global scope declares it too. +expectTypeOf(globalThis.structuredClone).toEqualTypeOf(structuredClone); +expectTypeOf(self.structuredClone).toEqualTypeOf(structuredClone); +expectTypeOf().toEqualTypeOf< + typeof structuredClone +>();