@statewalker/cellb 0.8.8 → 0.8.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +1 -1
  2. package/dist/bindings/cjs-module.d.ts +7 -0
  3. package/dist/bindings/cjs-module.js +96 -0
  4. package/dist/bindings/cjs-module.js.map +1 -0
  5. package/dist/bindings/module-registry.d.ts +33 -0
  6. package/dist/bindings/module-registry.js +180 -0
  7. package/dist/bindings/module-registry.js.map +1 -0
  8. package/dist/bindings/worker-loader.d.ts +23 -5
  9. package/dist/bindings/worker-loader.js +75 -4
  10. package/dist/bindings/worker-loader.js.map +1 -1
  11. package/dist/core/handles.d.ts +21 -1
  12. package/dist/core/handles.js +49 -3
  13. package/dist/core/handles.js.map +1 -1
  14. package/dist/core/namespace.js +4 -1
  15. package/dist/core/namespace.js.map +1 -1
  16. package/dist/core/runtime.d.ts +8 -0
  17. package/dist/core/runtime.js +3 -3
  18. package/dist/core/runtime.js.map +1 -1
  19. package/dist/index.d.ts +5 -0
  20. package/dist/index.js +5 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/isolate/browser.d.ts +1 -1
  23. package/dist/isolate/browser.js +3 -1
  24. package/dist/isolate/browser.js.map +1 -1
  25. package/dist/isolate/host.js +20 -2
  26. package/dist/isolate/host.js.map +1 -1
  27. package/dist/isolate/isolate-worker.js +13 -1
  28. package/dist/isolate/isolate-worker.js.map +1 -1
  29. package/dist/isolate/isolate.js +11 -0
  30. package/dist/isolate/isolate.js.map +1 -1
  31. package/dist/isolate/node-entry.js +33 -0
  32. package/dist/isolate/node-entry.js.map +1 -1
  33. package/dist/isolate/protocol.d.ts +1 -0
  34. package/dist/isolate/protocol.js +228 -13
  35. package/dist/isolate/protocol.js.map +1 -1
  36. package/dist/isolate/writable-globals.d.ts +9 -0
  37. package/dist/isolate/writable-globals.js +45 -0
  38. package/dist/isolate/writable-globals.js.map +1 -0
  39. package/dist/node-compat/bundle-files.d.ts +26 -0
  40. package/dist/node-compat/bundle-files.js +210 -0
  41. package/dist/node-compat/bundle-files.js.map +1 -0
  42. package/dist/node-compat/fs.d.ts +13 -1
  43. package/dist/node-compat/fs.js +54 -15
  44. package/dist/node-compat/fs.js.map +1 -1
  45. package/dist/project/browser-modules.d.ts +1 -1
  46. package/dist/project/browser-modules.js +25 -5
  47. package/dist/project/browser-modules.js.map +1 -1
  48. package/dist/project/cloudflare-workers.d.ts +9 -0
  49. package/dist/project/cloudflare-workers.js +14 -0
  50. package/dist/project/cloudflare-workers.js.map +1 -1
  51. package/dist/project/module-rules.js +31 -10
  52. package/dist/project/module-rules.js.map +1 -1
  53. package/dist/project/node-project.d.ts +2 -0
  54. package/dist/project/node-project.js +154 -25
  55. package/dist/project/node-project.js.map +1 -1
  56. package/dist/project/site-loader.js +2 -1
  57. package/dist/project/site-loader.js.map +1 -1
  58. package/dist/project/uint8array-base64.d.ts +7 -0
  59. package/dist/project/uint8array-base64.js +96 -0
  60. package/dist/project/uint8array-base64.js.map +1 -0
  61. package/dist/project/workers-globals-module.d.ts +1 -0
  62. package/dist/project/workers-globals-module.js +3 -0
  63. package/dist/project/workers-globals-module.js.map +1 -1
  64. package/dist/project/wrangler.js +8 -9
  65. package/dist/project/wrangler.js.map +1 -1
  66. package/dist/ws/upgrade.js +18 -1
  67. package/dist/ws/upgrade.js.map +1 -1
  68. package/package.json +10 -10
@@ -1,11 +1,44 @@
1
1
  // A worker thread hosting ONE loaded Worker (an isolate); see src/isolate/protocol.ts.
2
+ import * as nodeModule from "node:module";
2
3
  import { parentPort } from "node:worker_threads";
3
4
  import { nodeSqliteOpener } from "../adapters/node-sqlite.js";
5
+ import { loadedModuleShim, resolveModuleName } from "../bindings/module-registry.js";
4
6
  import { CellsRequest, CellsResponse, WebSocket, WebSocketPair, WebSocketRequestResponsePair, } from "../project/workers-globals-module.js";
5
7
  import { serveIsolate } from "./isolate.js";
8
+ import { makeGlobalsWritable } from "./writable-globals.js";
6
9
  // An exception no request awaits (a timer, ctx.abort() from one) is reported, and the isolate
7
10
  // lives on, as in a browser Dedicated Worker and workerd; Node would end the thread.
8
11
  process.on("uncaughtException", (e) => console.error("Uncaught", e));
12
+ // workerd lets Worker code assign its globals (Kitesurf's DOM shim sets `navigator` and
13
+ // `location`); this realm's getter-only ones become writable (writable-globals.ts).
14
+ makeGlobalsWritable();
15
+ // `import()` in code the loaded Worker builds with `Function` (Kitesurf imports page modules so)
16
+ // names its modules as on workerd, but no bundler saw it: this thread's module hooks resolve such
17
+ // a specifier against the loaded Worker's modules (the registry its bundle publishes) and load a
18
+ // shim that re-exports the bundled module. `registerHooks` is in Node 22.15 and later.
19
+ const LOADED = "cellb-loaded:";
20
+ const registerHooks = nodeModule.registerHooks;
21
+ registerHooks?.({
22
+ resolve(spec, context, next) {
23
+ const loaded = globalThis.__cellbLoadedModules;
24
+ const fromBundle = !context.parentURL || context.parentURL.startsWith("data:");
25
+ const name = loaded && fromBundle ? resolveModuleName(spec, loaded.main, loaded.names) : undefined;
26
+ if (name === undefined)
27
+ return next(spec, context);
28
+ return { url: LOADED + encodeURIComponent(name), shortCircuit: true };
29
+ },
30
+ load(url, context, next) {
31
+ if (!url.startsWith(LOADED))
32
+ return next(url, context);
33
+ const name = decodeURIComponent(url.slice(LOADED.length));
34
+ const loaded = globalThis.__cellbLoadedModules;
35
+ return {
36
+ format: "module",
37
+ shortCircuit: true,
38
+ source: loadedModuleShim(name, loaded?.exportNames[name] ?? []),
39
+ };
40
+ },
41
+ });
9
42
  // This thread is the loaded Worker's realm: its globals are the Workers ones, as in a browser
10
43
  // isolate (src/isolate/isolate-worker.ts). A `Response` that takes `{ status: 101, webSocket }`
11
44
  // and a `WebSocketPair` are what a Worker that accepts WebSockets needs.
@@ -1 +1 @@
1
- {"version":3,"file":"node-entry.js","sourceRoot":"","sources":["../../src/isolate/node-entry.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EACL,YAAY,EACZ,aAAa,EACb,SAAS,EACT,aAAa,EACb,4BAA4B,GAC7B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,8FAA8F;AAC9F,qFAAqF;AACrF,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,CAAC;AAErE,8FAA8F;AAC9F,gGAAgG;AAChG,yEAAyE;AACzE,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE;IACxB,OAAO,EAAE,YAAY;IACrB,QAAQ,EAAE,aAAa;IACvB,SAAS;IACT,aAAa;IACb,4BAA4B;CAC7B,CAAC,CAAC;AAEH,YAAY,CACV,UAAiC,EACjC,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CACnB,MAAM,CAAC,+BAA+B,MAAM,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;AACvF,wFAAwF;AACxF,0FAA0F;AAC1F,sFAAsF;AACtF,EAAE,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,EAAE,CAC9E,CAAC","sourcesContent":["// A worker thread hosting ONE loaded Worker (an isolate); see src/isolate/protocol.ts.\nimport { parentPort } from \"node:worker_threads\";\nimport { nodeSqliteOpener } from \"../adapters/node-sqlite.js\";\nimport {\n CellsRequest,\n CellsResponse,\n WebSocket,\n WebSocketPair,\n WebSocketRequestResponsePair,\n} from \"../project/workers-globals-module.js\";\nimport { serveIsolate } from \"./isolate.js\";\nimport type { PortLike } from \"./protocol.js\";\n\n// An exception no request awaits (a timer, ctx.abort() from one) is reported, and the isolate\n// lives on, as in a browser Dedicated Worker and workerd; Node would end the thread.\nprocess.on(\"uncaughtException\", (e) => console.error(\"Uncaught\", e));\n\n// This thread is the loaded Worker's realm: its globals are the Workers ones, as in a browser\n// isolate (src/isolate/isolate-worker.ts). A `Response` that takes `{ status: 101, webSocket }`\n// and a `WebSocketPair` are what a Worker that accepts WebSockets needs.\nObject.assign(globalThis, {\n Request: CellsRequest,\n Response: CellsResponse,\n WebSocket,\n WebSocketPair,\n WebSocketRequestResponsePair,\n});\n\nserveIsolate(\n parentPort as unknown as PortLike,\n async ({ source }) =>\n import(`data:text/javascript;base64,${Buffer.from(source ?? \"\").toString(\"base64\")}`),\n // Facets of the loaded code keep their SQLite here: files under `dataDir` when the host\n // gives one, else temporary files (lost with the isolate, as in memory). The isolate logs\n // every commit's pages to its host, so they are read from the WAL, not from an image.\n { openSql: (load) => nodeSqliteOpener(load?.dataDir, { pageCapture: true }) },\n);\n"]}
1
+ {"version":3,"file":"node-entry.js","sourceRoot":"","sources":["../../src/isolate/node-entry.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,OAAO,KAAK,UAAU,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACrF,OAAO,EACL,YAAY,EACZ,aAAa,EACb,SAAS,EACT,aAAa,EACb,4BAA4B,GAC7B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,8FAA8F;AAC9F,qFAAqF;AACrF,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CA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AM,EAAE,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SAChE,CAAC;IACJ,CAAC;CACF,CAAC,CAAC;AAEH,8FAA8F;AAC9F,gGAAgG;AAChG,yEAAyE;AACzE,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE;IACxB,OAAO,EAAE,YAAY;IACrB,QAAQ,EAAE,aAAa;IACvB,SAAS;IACT,aAAa;IACb,4BAA4B;CAC7B,CAAC,CAAC;AAEH,YAAY,CACV,UAAiC,EACjC,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CACnB,MAAM,CAAC,+BAA+B,MAAM,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;AACvF,wFAAwF;AACxF,0FAA0F;AAC1F,sFAAsF;AACtF,EAAE,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,EAAE,CAC9E,CAAC","sourcesContent":["// A worker thread hosting ONE loaded Worker (an isolate); see src/isolate/protocol.ts.\nimport * as nodeModule from \"node:module\";\nimport { parentPort } from \"node:worker_threads\";\nimport { nodeSqliteOpener } from \"../adapters/node-sqlite.js\";\nimport { loadedModuleShim, resolveModuleName } from \"../bindings/module-registry.js\";\nimport {\n CellsRequest,\n CellsResponse,\n WebSocket,\n WebSocketPair,\n WebSocketRequestResponsePair,\n} from \"../project/workers-globals-module.js\";\nimport { serveIsolate } from \"./isolate.js\";\nimport type { PortLike } from \"./protocol.js\";\nimport { makeGlobalsWritable } from \"./writable-globals.js\";\n\n// An exception no request awaits (a timer, ctx.abort() from one) is reported, and the isolate\n// lives on, as in a browser Dedicated Worker and workerd; Node would end the thread.\nprocess.on(\"uncaughtException\", (e) => console.error(\"Uncaught\", e));\n\n// workerd lets Worker code assign its globals (Kitesurf's DOM shim sets `navigator` and\n// `location`); this realm's getter-only ones become writable (writable-globals.ts).\nmakeGlobalsWritable();\n\n// `import()` in code the loaded Worker builds with `Function` (Kitesurf imports page modules so)\n// names its modules as on workerd, but no bundler saw it: this thread's module hooks resolve such\n// a specifier against the loaded Worker's modules (the registry its bundle publishes) and load a\n// shim that re-exports the bundled module. `registerHooks` is in Node 22.15 and later.\nconst LOADED = \"cellb-loaded:\";\ntype LoadedModules = { main: string; names: Set<string>; exportNames: Record<string, string[]> };\nconst registerHooks = (nodeModule as { registerHooks?: (hooks: object) => unknown }).registerHooks;\nregisterHooks?.({\n resolve(spec: string, context: { parentURL?: string }, next: (s: string, c: object) => unknown) {\n const loaded = (globalThis as { __cellbLoadedModules?: LoadedModules }).__cellbLoadedModules;\n const fromBundle = !context.parentURL || context.parentURL.startsWith(\"data:\");\n const name =\n loaded && fromBundle ? resolveModuleName(spec, loaded.main, loaded.names) : undefined;\n if (name === undefined) return next(spec, context);\n return { url: LOADED + encodeURIComponent(name), shortCircuit: true };\n },\n load(url: string, context: object, next: (u: string, c: object) => unknown) {\n if (!url.startsWith(LOADED)) return next(url, context);\n const name = decodeURIComponent(url.slice(LOADED.length));\n const loaded = (globalThis as { __cellbLoadedModules?: LoadedModules }).__cellbLoadedModules;\n return {\n format: \"module\",\n shortCircuit: true,\n source: loadedModuleShim(name, loaded?.exportNames[name] ?? []),\n };\n },\n});\n\n// This thread is the loaded Worker's realm: its globals are the Workers ones, as in a browser\n// isolate (src/isolate/isolate-worker.ts). A `Response` that takes `{ status: 101, webSocket }`\n// and a `WebSocketPair` are what a Worker that accepts WebSockets needs.\nObject.assign(globalThis, {\n Request: CellsRequest,\n Response: CellsResponse,\n WebSocket,\n WebSocketPair,\n WebSocketRequestResponsePair,\n});\n\nserveIsolate(\n parentPort as unknown as PortLike,\n async ({ source }) =>\n import(`data:text/javascript;base64,${Buffer.from(source ?? \"\").toString(\"base64\")}`),\n // Facets of the loaded code keep their SQLite here: files under `dataDir` when the host\n // gives one, else temporary files (lost with the isolate, as in memory). The isolate logs\n // every commit's pages to its host, so they are read from the WAL, not from an image.\n { openSql: (load) => nodeSqliteOpener(load?.dataDir, { pageCapture: true }) },\n);\n"]}
@@ -60,6 +60,7 @@ type Handle = (msg: any) => Promise<unknown>;
60
60
  export declare function hostPort(port: PortLike, handle: Handle, outbound?: (req: Request) => Promise<Response>): Promise<{
61
61
  call: Call;
62
62
  fetch: Fetch;
63
+ close(reason: unknown): Promise<void>;
63
64
  }>;
64
65
  /**
65
66
  * The isolate's end: accepts the ports the host opens. Everything the isolate calls the host
@@ -11,23 +11,27 @@ import { carryWebSocketHeaders } from "../ws/upgrade.js";
11
11
  * `fetch()` (its `globalOutbound` Fetcher).
12
12
  */
13
13
  export async function hostPort(port, handle, outbound) {
14
+ const bodies = new Bodies();
14
15
  const mux = multiplexPort(messageTarget(port), {
15
16
  codec: structuredCodec,
16
17
  side: "initiator",
17
18
  maxPorts: maxPorts(),
18
19
  onPort(p, meta) {
19
20
  const m = meta;
21
+ if (m?.kind === "body")
22
+ return bodies.serve(p, m.id);
20
23
  if (m?.kind !== "outbound" || !outbound)
21
24
  return false;
22
25
  serveFetch(p, m.url, outbound);
23
26
  return true;
24
27
  },
25
28
  });
26
- const call = callsOver(await mux.openPort({ kind: "calls" }), handle);
29
+ const call = callsOver(await mux.openPort({ kind: "calls" }), handle, mux, bodies);
27
30
  const fetch = (target, req) => isUpgrade(req)
28
31
  ? upgradeOver(mux, { kind: "upgrade", target }, req)
29
32
  : fetchOver(mux, { kind: "fetch", target }, req);
30
- return { call, fetch };
33
+ // Closing the multiplexer rejects every call in flight, and every later one, with `reason`.
34
+ return { call, fetch, close: (reason) => mux.close(reason) };
31
35
  }
32
36
  /**
33
37
  * The isolate's end: accepts the ports the host opens. Everything the isolate calls the host
@@ -36,12 +40,15 @@ export async function hostPort(port, handle, outbound) {
36
40
  */
37
41
  export function isolatePort(port, handle, fetch) {
38
42
  let calls;
43
+ const bodies = new Bodies();
39
44
  const mux = multiplexPort(messageTarget(port), {
40
45
  codec: structuredCodec,
41
46
  side: "responder",
42
47
  maxPorts: maxPorts(),
43
48
  onPort(p, meta) {
44
49
  const m = meta;
50
+ if (m?.kind === "body")
51
+ return bodies.serve(p, m.id);
45
52
  if (m?.kind === "fetch") {
46
53
  serveFetch(p, m.url, (r) => fetch(m.target, r));
47
54
  return true;
@@ -52,7 +59,7 @@ export function isolatePort(port, handle, fetch) {
52
59
  }
53
60
  if (m?.kind !== "calls" || calls)
54
61
  return false;
55
- calls = callsOver(p, handle);
62
+ calls = callsOver(p, handle, mux, bodies);
56
63
  return true;
57
64
  },
58
65
  });
@@ -173,6 +180,170 @@ function serveUpgrade(p, meta, fetch) {
173
180
  void p.close?.();
174
181
  })();
175
182
  }
183
+ /** Marks a Request, Response, Headers or ReadableStream in a message: `{ [WIRE]: kind, … }`. */
184
+ const WIRE = "\u0000cellb.wire";
185
+ // The realm's own classes, before the isolate entry replaces the globals with its subclasses
186
+ // (CellsRequest, CellsResponse): instances of either are instances of these.
187
+ const NativeRequest = globalThis.Request;
188
+ const NativeResponse = globalThis.Response;
189
+ const NativeHeaders = globalThis.Headers;
190
+ const NativeReadableStream = globalThis.ReadableStream;
191
+ /**
192
+ * The bodies one side has sent and the other has not read yet, by id. The reader opens a port
193
+ * `{ kind: "body", id }` on the multiplexer when it first pulls, and the body streams over it,
194
+ * as a fetch's body does; a reader that drops the body unread sends `release {body}` instead.
195
+ */
196
+ class Bodies {
197
+ #last = 0;
198
+ #streams = new Map();
199
+ add(stream) {
200
+ this.#streams.set(++this.#last, stream);
201
+ return this.#last;
202
+ }
203
+ /** The last id handed out, for `releaseSince`. */
204
+ mark() {
205
+ return this.#last;
206
+ }
207
+ /** Releases the bodies added after `mark` (a message that could not be sent). */
208
+ releaseSince(mark) {
209
+ for (let id = mark + 1; id <= this.#last; id++)
210
+ this.release(id);
211
+ }
212
+ release(id) {
213
+ const stream = this.#streams.get(id);
214
+ this.#streams.delete(id);
215
+ void stream?.cancel().catch(() => { });
216
+ }
217
+ /** Serves body `id` on port `p`; false (the port is refused) if there is no such body. */
218
+ serve(p, id) {
219
+ const stream = this.#streams.get(id);
220
+ if (!stream)
221
+ return false;
222
+ this.#streams.delete(id);
223
+ const encoder = new TextEncoder();
224
+ serveDuplexOverPort(p, async function* () {
225
+ // A reader, not `for await`: not every engine iterates a ReadableStream (Safari).
226
+ const reader = stream.getReader();
227
+ try {
228
+ for (;;) {
229
+ const { done, value: chunk } = await reader.read();
230
+ if (done)
231
+ return;
232
+ yield typeof chunk === "string"
233
+ ? encoder.encode(chunk)
234
+ : ArrayBuffer.isView(chunk)
235
+ ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)
236
+ : new Uint8Array(chunk);
237
+ }
238
+ }
239
+ finally {
240
+ // The reader stopped early (the port was abandoned): the stream is cancelled.
241
+ void reader.cancel().catch(() => { });
242
+ }
243
+ });
244
+ return true;
245
+ }
246
+ }
247
+ /**
248
+ * A Request, Response, Headers or ReadableStream as a message can carry it (workerd's RPC passes
249
+ * them; a port cannot clone them): its head copied, its body registered in `bodies` to stream
250
+ * when read. Anything else is returned as it is.
251
+ */
252
+ function toWire(v, bodies) {
253
+ if (v instanceof NativeHeaders)
254
+ return { [WIRE]: "headers", entries: [...v] };
255
+ if (v instanceof NativeReadableStream)
256
+ return { [WIRE]: "stream", body: bodies.add(v) };
257
+ if (v instanceof NativeResponse) {
258
+ if (v.webSocket)
259
+ throw new DOMException("A WebSocket response cannot be passed in an RPC call; return it from fetch().", "DataCloneError");
260
+ return {
261
+ [WIRE]: "response",
262
+ status: v.status,
263
+ statusText: v.statusText,
264
+ url: v.url,
265
+ headers: [...v.headers],
266
+ body: v.body ? bodies.add(v.body) : null,
267
+ };
268
+ }
269
+ if (v instanceof NativeRequest)
270
+ return {
271
+ [WIRE]: "request",
272
+ url: v.url,
273
+ method: v.method,
274
+ headers: [...v.headers],
275
+ redirect: v.redirect,
276
+ body: v.body ? bodies.add(v.body) : null,
277
+ };
278
+ return v;
279
+ }
280
+ /** Releases a body that was never read, once its stream is collected. */
281
+ const unread = new FinalizationRegistry((release) => release());
282
+ /**
283
+ * The other side's body `id` as a stream: the first pull opens its port, so a body nobody
284
+ * reads costs nothing but its release.
285
+ */
286
+ function remoteBody(mux, id, release) {
287
+ let chunks;
288
+ const token = {};
289
+ const stream = new NativeReadableStream({
290
+ async pull(controller) {
291
+ if (!chunks) {
292
+ unread.unregister(token);
293
+ const port = await mux.openPort({ kind: "body", id });
294
+ chunks = duplexOverPort(port)([])[Symbol.asyncIterator]();
295
+ }
296
+ const { done, value } = await chunks.next();
297
+ if (done)
298
+ controller.close();
299
+ else
300
+ controller.enqueue(value);
301
+ },
302
+ async cancel(reason) {
303
+ if (chunks)
304
+ await chunks.return?.(reason);
305
+ else {
306
+ unread.unregister(token);
307
+ release(id);
308
+ }
309
+ },
310
+ });
311
+ unread.register(stream, () => release(id), token);
312
+ return stream;
313
+ }
314
+ /** Statuses whose Response has no body. */
315
+ const NULL_BODY = [101, 103, 204, 205, 304];
316
+ /** The value `toWire` described, rebuilt; its body streams from the other side when read. */
317
+ function fromWire(v, mux, release) {
318
+ const body = (id) => (id === null ? null : remoteBody(mux, id, release));
319
+ switch (v[WIRE]) {
320
+ case "headers":
321
+ return new Headers(v.entries);
322
+ case "stream":
323
+ return body(v.body);
324
+ case "response": {
325
+ if (NULL_BODY.includes(v.status) && v.body !== null)
326
+ release(v.body);
327
+ const res = new Response(NULL_BODY.includes(v.status) ? null : body(v.body), {
328
+ status: v.status,
329
+ statusText: v.statusText,
330
+ headers: v.headers,
331
+ });
332
+ if (v.url)
333
+ Object.defineProperty(res, "url", { value: v.url, enumerable: true });
334
+ return res;
335
+ }
336
+ case "request":
337
+ return new Request(v.url, {
338
+ method: v.method,
339
+ headers: v.headers,
340
+ redirect: v.redirect,
341
+ body: body(v.body),
342
+ duplex: "half",
343
+ });
344
+ }
345
+ return v;
346
+ }
176
347
  /** Marks a value passed by reference in a message: `{ [REF]: id }`. */
177
348
  const REF = "\u0000cellb.ref";
178
349
  /**
@@ -182,17 +353,26 @@ const REF = "\u0000cellb.ref";
182
353
  * value runs the value's own `Symbol.dispose`, as workerd does for an `RpcTarget`. A call
183
354
  * returns an RpcPromise: calls on it go to the other side at once, naming its answer.
184
355
  */
185
- function callsOver(port, handle) {
356
+ function callsOver(port, handle, mux, bodies) {
186
357
  const values = new Map();
187
358
  const answers = new Map();
188
359
  let lastAnswer = 0;
189
360
  const holders = new Map();
190
361
  let lastId = 0;
191
- const encode = (v) => cloneable(cross(v, (x) => {
192
- values.set(++lastId, x);
193
- holders.set(x, (holders.get(x) ?? 0) + 1);
194
- return { [REF]: lastId };
195
- }, (x) => x));
362
+ const encode = (v) => {
363
+ const mark = bodies.mark();
364
+ try {
365
+ return cloneable(cross(v, (x) => {
366
+ values.set(++lastId, x);
367
+ holders.set(x, (holders.get(x) ?? 0) + 1);
368
+ return { [REF]: lastId };
369
+ }, (x) => toWire(x, bodies)));
370
+ }
371
+ catch (e) {
372
+ bodies.releaseSince(mark); // the message is not sent: nobody will read its bodies
373
+ throw e;
374
+ }
375
+ };
196
376
  const release = (id) => {
197
377
  const v = values.get(id);
198
378
  if (!values.delete(id))
@@ -206,9 +386,31 @@ function callsOver(port, handle) {
206
386
  }
207
387
  };
208
388
  const send = (msg) => callPort(port, msg, { timeout: NO_TIMEOUT }).catch(() => { });
209
- const collected = new FinalizationRegistry((id) => send({ type: "release", id }));
389
+ // Stubs of one id held here: `dup()` makes another, and the id is released (and the other
390
+ // side's value with it, once no other id holds it) when the last of them is disposed or
391
+ // collected.
392
+ const local = new Map();
393
+ const drop = (id) => {
394
+ const n = (local.get(id) ?? 1) - 1;
395
+ if (n)
396
+ local.set(id, n);
397
+ else {
398
+ local.delete(id);
399
+ send({ type: "release", id });
400
+ }
401
+ };
402
+ const collected = new FinalizationRegistry(drop);
210
403
  const stubOf = (id) => {
211
- const invoke = (path, args) => call({ type: "ref", id, path, args });
404
+ local.set(id, (local.get(id) ?? 0) + 1);
405
+ let disposed = false;
406
+ const live = () => {
407
+ if (disposed)
408
+ throw new Error("A stub was used after it was disposed.");
409
+ };
410
+ const invoke = (path, args) => {
411
+ live();
412
+ return call({ type: "ref", id, path, args });
413
+ };
212
414
  const stub = new Proxy(() => { }, {
213
415
  apply: (_t, _this, args) => invoke([], args),
214
416
  get(_t, prop) {
@@ -216,11 +418,20 @@ function callsOver(port, handle) {
216
418
  return true;
217
419
  if (prop === Symbol.dispose)
218
420
  return () => {
421
+ if (disposed)
422
+ return;
423
+ disposed = true;
219
424
  collected.unregister(stub);
220
- send({ type: "release", id });
425
+ drop(id);
221
426
  };
222
427
  if (prop === "then" || typeof prop === "symbol")
223
428
  return undefined;
429
+ // workerd's `stub.dup()`: another stub of the same value, disposed on its own.
430
+ if (prop === "dup")
431
+ return () => {
432
+ live();
433
+ return stubOf(id);
434
+ };
224
435
  return (...args) => invoke([prop], args);
225
436
  },
226
437
  });
@@ -233,6 +444,8 @@ function callsOver(port, handle) {
233
444
  for (let i = 0; i < v.length; i++)
234
445
  v[i] = decode(v[i]);
235
446
  else if (v && Object.getPrototypeOf(v) === Object.prototype) {
447
+ if (typeof v[WIRE] === "string")
448
+ return fromWire(v, mux, (body) => send({ type: "release", body }));
236
449
  if (typeof v[REF] === "number")
237
450
  return stubOf(v[REF]);
238
451
  for (const k of Object.keys(v))
@@ -254,7 +467,9 @@ function callsOver(port, handle) {
254
467
  // settles.
255
468
  const serve = async (m) => {
256
469
  if (m.type === "release") {
257
- if (m.answer === undefined)
470
+ if (m.body !== undefined)
471
+ bodies.release(m.body);
472
+ else if (m.answer === undefined)
258
473
  release(m.id);
259
474
  else
260
475
  answers.delete(m.answer);
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/isolate/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EACL,QA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/B,MAAM,SAAS,GAAG,IAAI,GAAG,EAAoC,CAAC;IAC9D,OAAO;QACL,WAAW,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,QAAQ,CAAC;QAC/D,gBAAgB,CAAC,KAAK,EAAE,EAAE;YACxB,MAAM,QAAQ,GAAG,CAAC,IAAa,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,EAAkB,CAAC,CAAC;YACtE,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;YAC5B,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAC1B,CAAC;QACD,mBAAmB,CAAC,KAAK,EAAE,EAAE;YAC3B,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,CAAE,CAAC,CAAC;YAC1C,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { fetchOverDuplex, serveFetchOverDuplex } from \"@statewalker/webrun-http-streams\";\nimport {\n callPort,\n duplexOverPort,\n getPortCloseSignal,\n listenPort,\n type MessageTarget,\n multiplexPort,\n NO_TIMEOUT,\n type PortMux,\n serveDuplexOverPort,\n structuredCodec,\n} from \"@statewalker/webrun-rpc\";\nimport { cross, pipeTo, rpcPromise, STUB } from \"../core/handles.js\";\nimport { withUrl } from \"../core/request-body.js\";\nimport type { Frame } from \"../ws/frames.js\";\nimport { CellsResponse, CfWebSocket, takeClientEnd } from \"../ws/server.js\";\nimport { carryWebSocketHeaders } from \"../ws/upgrade.js\";\n\n/**\n * Isolation for loaded Workers (celld runs each in its own V8 isolate): the loaded code runs\n * in a separate realm — a worker thread on Node, a Dedicated Worker in browsers — and talks\n * to the host over one MessagePort, multiplexed with `@statewalker/webrun-rpc`. The host keeps\n * everything else: bindings in the loaded Worker's env are reached through stubs, and its logs\n * come back for Tail Workers. Errors cross with their own properties (`name`, `code`, …).\n * Functions, `RpcTarget`s and stubs anywhere in a call or result cross by reference (as\n * workerd passes them): the far side gets a stub whose calls come back.\n *\n * Calls (one port, both directions; each names an `answer`, which the serving side keeps until\n * the caller has the result, so calls on it can be sent before then — promise pipelining):\n * host → isolate load {source|url, env, outbound} → loaded {exports}\n * call {name, method, args, props} → result\n * isolate → host log {level, args}\n * either way ref {id|on, path, args} (a call on a stub of the other side's value, or\n * on answer `on`: `path` is the property path\n * called, [] the value itself)\n * release {id|answer} (that stub was disposed or collected; the caller\n * has that answer)\n * Fetches: one port per request (meta: its target and URL), HTTP/1.1 with streamed bodies,\n * as cells-http over a port (src/transport/port.ts): host → isolate to an export or facet,\n * isolate → host for the loaded code's global `fetch()` when a `globalOutbound` Fetcher routes it.\n * A WebSocket upgrade (host → isolate) has a port of its own instead, since HTTP/1.1 drops the\n * `Upgrade` header: its meta carries the request's method and headers; the isolate answers with\n * the response's head and closes the port. A 101's head carries the socket's own MessagePort,\n * transferred, and the frames the server sent before the 101 (replayed by the host's end): the\n * socket's frames then go straight between the client and the isolate, outside the multiplexer\n * and through no relay in the isolate, so open sockets hold none of its ports (it allows\n * `maxPorts` at once) and a socket's 1001 reaches its client before the isolate ends.\n */\nexport interface PortLike {\n postMessage(msg: unknown, transfer?: Transferable[]): void;\n addEventListener?(type: \"message\", fn: (e: { data: unknown }) => void): void;\n removeEventListener?(type: \"message\", fn: (e: { data: unknown }) => void): void;\n on?(type: \"message\", fn: (data: unknown) => void): void;\n off?(type: \"message\", fn: (data: unknown) => void): void;\n start?(): void;\n}\n\n/** Where a fetch goes in the isolate: an export of the loaded Worker, or one of its facets. */\nexport type FetchTarget =\n | { name: string; props?: unknown }\n | { className: string; cellKey: string };\ntype Fetch = (target: FetchTarget, req: Request) => Promise<Response>;\n\nexport type Call = <T = unknown>(msg: object) => Promise<T>;\ntype Handle = (msg: any) => Promise<unknown>;\n\n/**\n * The host's end of an isolate's port: one webrun-rpc multiplexer over it, a calls port on\n * which each side calls the other (`callPort`/`listenPort`, no timeout: a call lasts as long\n * as the work it starts), and a port per fetch. `outbound` serves the loaded code's global\n * `fetch()` (its `globalOutbound` Fetcher).\n */\nexport async function hostPort(\n port: PortLike,\n handle: Handle,\n outbound?: (req: Request) => Promise<Response>,\n): Promise<{ call: Call; fetch: Fetch }> {\n const mux = multiplexPort(messageTarget(port), {\n codec: structuredCodec,\n side: \"initiator\",\n maxPorts: maxPorts(),\n onPort(p, meta) {\n const m = meta as { kind?: string; url: string } | undefined;\n if (m?.kind !== \"outbound\" || !outbound) return false;\n serveFetch(p, m.url, outbound);\n return true;\n },\n });\n const call = callsOver(await mux.openPort({ kind: \"calls\" }), handle);\n const fetch: Fetch = (target, req) =>\n isUpgrade(req)\n ? upgradeOver(mux, { kind: \"upgrade\", target }, req)\n : fetchOver(mux, { kind: \"fetch\", target }, req);\n return { call, fetch };\n}\n\n/**\n * The isolate's end: accepts the ports the host opens. Everything the isolate calls the host\n * for happens while serving a host call, so the calls port is open by then. `outbound` sends\n * a fetch to the host's `globalOutbound`.\n */\nexport function isolatePort(\n port: PortLike,\n handle: Handle,\n fetch: Fetch,\n): { call: Call; outbound: (req: Request) => Promise<Response> } {\n let calls: Call | undefined;\n const mux = multiplexPort(messageTarget(port), {\n codec: structuredCodec,\n side: \"responder\",\n maxPorts: maxPorts(),\n onPort(p, meta) {\n const m = meta as { kind?: string; target: FetchTarget; url: string } | undefined;\n if (m?.kind === \"fetch\") {\n serveFetch(p, m.url, (r) => fetch(m.target, r));\n return true;\n }\n if (m?.kind === \"upgrade\") {\n serveUpgrade(p, m as unknown as UpgradeMeta, (r) => fetch(m.target, r));\n return true;\n }\n if (m?.kind !== \"calls\" || calls) return false;\n calls = callsOver(p, handle);\n return true;\n },\n });\n return {\n call: (msg) => calls!(msg),\n outbound: (req) => fetchOver(mux, { kind: \"outbound\" }, req),\n };\n}\n\n/** A fetch over a new port of `mux`; the URL rides in the meta (the HTTP/1.1 wire drops its scheme). */\nfunction fetchOver(mux: PortMux, meta: object, req: Request): Promise<Response> {\n return fetchOverDuplex(\n (input) =>\n (async function* () {\n yield* duplexOverPort(await mux.openPort({ ...meta, url: req.url }))(input);\n })(),\n req,\n );\n}\n\n/** Serves the fetch on port `p` (its URL from the meta) with `fetch`. */\nfunction serveFetch(p: MessageTarget, url: string, fetch: (req: Request) => Promise<Response>) {\n serveDuplexOverPort(\n p,\n serveFetchOverDuplex((req) => withUrl(req, url).then(fetch).catch(throwOwn)),\n );\n}\n\nconst isUpgrade = (req: Request) => req.headers.get(\"upgrade\")?.toLowerCase() === \"websocket\";\n\ninterface UpgradeMeta {\n url: string;\n method: string;\n headers: [string, string][];\n}\n/**\n * Ports of an isolate's multiplexer open at once: the calls port, and one per fetch or upgrade\n * in flight (each closes when its exchange ends). `globalThis.__cellbMaxPorts` overrides it, as\n * for src/transport/port.ts.\n */\nconst maxPorts = () => (globalThis as { __cellbMaxPorts?: number }).__cellbMaxPorts ?? 4096;\n\n/** The isolate's answer to an upgrade: the head of its response, or the error it threw. */\ntype UpgradeHead =\n | {\n status: number;\n statusText?: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n /** A 101's socket: the port of its client end, transferred. */\n socket?: MessagePort;\n /** A 101's frames that reached its client end before the hand-over. */\n frames?: Frame[];\n }\n | { error: unknown };\n\n/** Statuses whose response has no body (`new Response(body, …)` refuses one). */\nconst nullBody = (status: number) => [101, 204, 205, 304].includes(status);\n\n/**\n * A WebSocket upgrade over a port of its own, closed once the isolate's answer is in. A 101\n * becomes a Workers response whose `webSocket` is a client end over the socket's own port.\n */\nasync function upgradeOver(mux: PortMux, meta: object, req: Request): Promise<Response> {\n const p = await mux.openPort({\n ...meta,\n url: req.url,\n method: req.method,\n headers: [...req.headers],\n } satisfies UpgradeMeta);\n return new Promise((resolve, reject) => {\n // A port closed without an answer (the isolate refused it, or could not post one)\n // fails the upgrade rather than leaving it pending.\n const closed = getPortCloseSignal(p);\n const onClosed = () => {\n p.removeEventListener(\"message\", onHead);\n reject(\n closed?.reason ?? new Error(\"cellb: the isolate closed the upgrade without an answer\"),\n );\n };\n closed?.addEventListener(\"abort\", onClosed, { once: true });\n const onHead = (e: MessageEvent) => {\n p.removeEventListener(\"message\", onHead);\n closed?.removeEventListener(\"abort\", onClosed);\n void p.close?.();\n try {\n const head = e.data as UpgradeHead;\n if (\"error\" in head) throw head.error;\n if (head.status === 101 && head.socket)\n return resolve(\n new CellsResponse(null, {\n status: 101,\n headers: head.headers,\n webSocket: new CfWebSocket(head.socket, head.frames),\n }),\n );\n resolve(\n new Response(nullBody(head.status) ? null : head.body, {\n status: head.status,\n statusText: head.statusText,\n headers: head.headers,\n }),\n );\n } catch (err) {\n reject(err);\n }\n };\n p.addEventListener(\"message\", onHead);\n void p.start?.();\n });\n}\n\n/** Serves an upgrade on port `p`: a 101 hands over its client end's port; then `p` closes. */\nfunction serveUpgrade(\n p: MessageTarget,\n meta: UpgradeMeta,\n fetch: (req: Request) => Promise<Response>,\n) {\n // A browser drops `Upgrade` and `Sec-WebSocket-*` from `new Request()`: carried over here.\n const headers = new Headers(meta.headers);\n const req = carryWebSocketHeaders(\n headers,\n new Request(meta.url, { method: meta.method, headers }),\n );\n const answer = (head: UpgradeHead, transfer: Transferable[] = []) => {\n try {\n // The multiplexer drops a message it cannot copy, so check before posting; a 101\n // head is not checked, since its socket port is transferred rather than copied.\n if (transfer.length === 0) cloneable(head);\n p.postMessage(head, transfer);\n } catch {\n // An error that cannot be copied (a function in its `cause`, say): its name and message.\n const e = (head as { error?: { name?: unknown; message?: unknown } }).error;\n p.postMessage({\n error: Object.assign(new Error(String(e?.message ?? e)), {\n name: String(e?.name ?? \"Error\"),\n }),\n } satisfies UpgradeHead);\n }\n };\n void (async () => {\n try {\n const res = await fetch(req);\n const ws = (res as { webSocket?: CfWebSocket | null }).webSocket;\n if (res.status === 101 && ws) {\n const { port: socket, frames } = takeClientEnd(ws);\n answer({ status: 101, headers: [...res.headers], body: null, socket, frames }, [socket]);\n } else\n answer({\n status: res.status,\n statusText: res.statusText,\n headers: [...res.headers],\n body: nullBody(res.status) ? null : await res.arrayBuffer(),\n });\n } catch (error) {\n answer({ error });\n }\n void p.close?.();\n })();\n}\n\n/** Marks a value passed by reference in a message: `{ [REF]: id }`. */\nconst REF = \"\\u0000cellb.ref\";\n\n/**\n * The calls of one port, with values passed by reference: each side keeps the values it\n * passed (by id, and how many ids hold each); the other side calls them through stubs. A\n * stub's `Symbol.dispose` (or its garbage collection) releases its id; the last release of a\n * value runs the value's own `Symbol.dispose`, as workerd does for an `RpcTarget`. A call\n * returns an RpcPromise: calls on it go to the other side at once, naming its answer.\n */\nfunction callsOver(port: MessageTarget, handle: Handle): Call {\n const values = new Map<number, any>();\n const answers = new Map<number, unknown>();\n let lastAnswer = 0;\n const holders = new Map<unknown, number>();\n let lastId = 0;\n const encode = (v: unknown) =>\n cloneable(\n cross(\n v,\n (x) => {\n values.set(++lastId, x);\n holders.set(x, (holders.get(x) ?? 0) + 1);\n return { [REF]: lastId };\n },\n (x) => x, // the port copies the rest\n ),\n );\n const release = (id: number) => {\n const v = values.get(id);\n if (!values.delete(id)) return;\n const n = (holders.get(v) ?? 1) - 1;\n if (n) holders.set(v, n);\n else {\n holders.delete(v);\n v[Symbol.dispose]?.();\n }\n };\n const send = (msg: object) => callPort(port, msg, { timeout: NO_TIMEOUT }).catch(() => {});\n const collected = new FinalizationRegistry<number>((id) => send({ type: \"release\", id }));\n const stubOf = (id: number) => {\n const invoke = (path: string[], args: unknown[]) => call({ type: \"ref\", id, path, args });\n const stub: any = new Proxy(() => {}, {\n apply: (_t, _this, args) => invoke([], args),\n get(_t, prop) {\n if (prop === STUB) return true;\n if (prop === Symbol.dispose)\n return () => {\n collected.unregister(stub);\n send({ type: \"release\", id });\n };\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n return (...args: unknown[]) => invoke([prop], args);\n },\n });\n collected.register(stub, id, stub);\n return stub;\n };\n // Messages arrive as fresh copies: stubs replace the markers in place.\n const decode = (v: any): any => {\n if (Array.isArray(v)) for (let i = 0; i < v.length; i++) v[i] = decode(v[i]);\n else if (v && Object.getPrototypeOf(v) === Object.prototype) {\n if (typeof v[REF] === \"number\") return stubOf(v[REF]);\n for (const k of Object.keys(v)) v[k] = decode(v[k]);\n }\n return v;\n };\n const run = (m: any): unknown => {\n if (m.type !== \"ref\") return handle(m);\n if (m.on !== undefined) return pipeTo(answers.get(m.on), m.path, m.args);\n const v = values.get(m.id);\n if (v === undefined) throw new Error(\"A stub was used after it was disposed.\");\n return pipeTo(v, m.path, m.args);\n };\n // The answer is kept as the message arrives: a pipelined call on it may arrive before it\n // settles.\n const serve = async (m: any) => {\n if (m.type === \"release\") {\n if (m.answer === undefined) release(m.id);\n else answers.delete(m.answer);\n return;\n }\n let r: unknown;\n try {\n r = run(m);\n } catch (e) {\n r = Promise.reject(e);\n }\n answers.set(m.answer, r);\n return r;\n };\n listenPort(port, (msg) => serve(decode(msg)).then(encode).catch(throwOwn));\n const call: Call = (msg) => {\n const answer = ++lastAnswer;\n const result = (async () =>\n decode(await callPort(port, encode({ ...msg, answer }), { timeout: NO_TIMEOUT })))();\n // Calls on the answer sent before now are ahead of this release on the port.\n const done = () => send({ type: \"release\", answer });\n result.then(done, done);\n return rpcPromise(result, (path, args) => call({ type: \"ref\", on: answer, path, args }));\n };\n return call;\n}\n\n/** Errors cross with their own properties (so `code` does); `name` is inherited, so copy it. */\nfunction throwOwn(e: unknown): never {\n if (e && typeof e === \"object\")\n Object.defineProperty(e, \"name\", { value: (e as Error).name, enumerable: true });\n throw e;\n}\n\n/**\n * Throws `DataCloneError` for a value the port cannot carry: the multiplexer drops a message\n * it fails to post, and the call would wait forever.\n */\nfunction cloneable<T>(value: T): T {\n structuredClone(value);\n return value;\n}\n\n/** A worker_threads Worker is an EventEmitter; MessagePorts and Dedicated Workers are targets. */\nfunction messageTarget(port: PortLike): MessageTarget {\n if (port.addEventListener) return port as MessageTarget;\n const on = port.on!.bind(port);\n const listeners = new Map<unknown, (data: unknown) => void>();\n return {\n postMessage: (msg, transfer) => port.postMessage(msg, transfer),\n addEventListener(_type, fn) {\n const listener = (data: unknown) => void fn({ data } as MessageEvent);\n listeners.set(fn, listener);\n on(\"message\", listener);\n },\n removeEventListener(_type, fn) {\n port.off?.(\"message\", listeners.get(fn)!);\n listeners.delete(fn);\n },\n };\n}\n"]}
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/isolate/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EACL,QAAQ,EACR,cAAc,EACd,kBAAkB,EAClB,UAAU,EAEV,aAAa,EACb,UAAU,EAEV,mBAAmB,EACnB,eAAe,GAChB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAElD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC5E,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAkDzD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,IAAc,EACd,MAAc,EACd,QAA8C;IAE9C,MAAM,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;IAC5B,MAAM,GAAG,GAAG,aAAa,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE;QAC7C,KAAK,EAAE,eAAe;QACtB,IAAI,EAAE,WAAW;QACjB,QAAQ,EAAE,QAAQ,EAAE;QACpB,MAAM,CAAC,CAAC,EAAE,IAAI;YACZ,MAAM,CAAC,GAAG,IAA8D,CAAC;YACzE,IAAI,CAAC,EAAE,IAAI,KAAK,MAAM;gBAAE,OAAO,MAAM,CAAC,KAAK,CA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AAG,IAAI,CAAC,EAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC/B,MAAM,SAAS,GAAG,IAAI,GAAG,EAAoC,CAAC;IAC9D,OAAO;QACL,WAAW,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,QAAQ,CAAC;QAC/D,gBAAgB,CAAC,KAAK,EAAE,EAAE;YACxB,MAAM,QAAQ,GAAG,CAAC,IAAa,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,EAAkB,CAAC,CAAC;YACtE,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;YAC5B,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAC1B,CAAC;QACD,mBAAmB,CAAC,KAAK,EAAE,EAAE;YAC3B,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,CAAE,CAAC,CAAC;YAC1C,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { fetchOverDuplex, serveFetchOverDuplex } from \"@statewalker/webrun-http-streams\";\nimport {\n callPort,\n duplexOverPort,\n getPortCloseSignal,\n listenPort,\n type MessageTarget,\n multiplexPort,\n NO_TIMEOUT,\n type PortMux,\n serveDuplexOverPort,\n structuredCodec,\n} from \"@statewalker/webrun-rpc\";\nimport { cross, pipeTo, rpcPromise, STUB } from \"../core/handles.js\";\nimport { withUrl } from \"../core/request-body.js\";\nimport type { Frame } from \"../ws/frames.js\";\nimport { CellsResponse, CfWebSocket, takeClientEnd } from \"../ws/server.js\";\nimport { carryWebSocketHeaders } from \"../ws/upgrade.js\";\n\n/**\n * Isolation for loaded Workers (celld runs each in its own V8 isolate): the loaded code runs\n * in a separate realm — a worker thread on Node, a Dedicated Worker in browsers — and talks\n * to the host over one MessagePort, multiplexed with `@statewalker/webrun-rpc`. The host keeps\n * everything else: bindings in the loaded Worker's env are reached through stubs, and its logs\n * come back for Tail Workers. Errors cross with their own properties (`name`, `code`, …).\n * Functions, `RpcTarget`s and stubs anywhere in a call or result cross by reference (as\n * workerd passes them): the far side gets a stub whose calls come back.\n *\n * Calls (one port, both directions; each names an `answer`, which the serving side keeps until\n * the caller has the result, so calls on it can be sent before then — promise pipelining):\n * host → isolate load {source|url, env, outbound} → loaded {exports}\n * call {name, method, args, props} → result\n * isolate → host log {level, args}\n * either way ref {id|on, path, args} (a call on a stub of the other side's value, or\n * on answer `on`: `path` is the property path\n * called, [] the value itself)\n * release {id|answer} (that stub was disposed or collected; the caller\n * has that answer)\n * Fetches: one port per request (meta: its target and URL), HTTP/1.1 with streamed bodies,\n * as cells-http over a port (src/transport/port.ts): host → isolate to an export or facet,\n * isolate → host for the loaded code's global `fetch()` when a `globalOutbound` Fetcher routes it.\n * A WebSocket upgrade (host → isolate) has a port of its own instead, since HTTP/1.1 drops the\n * `Upgrade` header: its meta carries the request's method and headers; the isolate answers with\n * the response's head and closes the port. A 101's head carries the socket's own MessagePort,\n * transferred, and the frames the server sent before the 101 (replayed by the host's end): the\n * socket's frames then go straight between the client and the isolate, outside the multiplexer\n * and through no relay in the isolate, so open sockets hold none of its ports (it allows\n * `maxPorts` at once) and a socket's 1001 reaches its client before the isolate ends.\n */\nexport interface PortLike {\n postMessage(msg: unknown, transfer?: Transferable[]): void;\n addEventListener?(type: \"message\", fn: (e: { data: unknown }) => void): void;\n removeEventListener?(type: \"message\", fn: (e: { data: unknown }) => void): void;\n on?(type: \"message\", fn: (data: unknown) => void): void;\n off?(type: \"message\", fn: (data: unknown) => void): void;\n start?(): void;\n}\n\n/** Where a fetch goes in the isolate: an export of the loaded Worker, or one of its facets. */\nexport type FetchTarget =\n | { name: string; props?: unknown }\n | { className: string; cellKey: string };\ntype Fetch = (target: FetchTarget, req: Request) => Promise<Response>;\n\nexport type Call = <T = unknown>(msg: object) => Promise<T>;\ntype Handle = (msg: any) => Promise<unknown>;\n\n/**\n * The host's end of an isolate's port: one webrun-rpc multiplexer over it, a calls port on\n * which each side calls the other (`callPort`/`listenPort`, no timeout: a call lasts as long\n * as the work it starts), and a port per fetch. `outbound` serves the loaded code's global\n * `fetch()` (its `globalOutbound` Fetcher).\n */\nexport async function hostPort(\n port: PortLike,\n handle: Handle,\n outbound?: (req: Request) => Promise<Response>,\n): Promise<{ call: Call; fetch: Fetch; close(reason: unknown): Promise<void> }> {\n const bodies = new Bodies();\n const mux = multiplexPort(messageTarget(port), {\n codec: structuredCodec,\n side: \"initiator\",\n maxPorts: maxPorts(),\n onPort(p, meta) {\n const m = meta as { kind?: string; url: string; id: number } | undefined;\n if (m?.kind === \"body\") return bodies.serve(p, m.id);\n if (m?.kind !== \"outbound\" || !outbound) return false;\n serveFetch(p, m.url, outbound);\n return true;\n },\n });\n const call = callsOver(await mux.openPort({ kind: \"calls\" }), handle, mux, bodies);\n const fetch: Fetch = (target, req) =>\n isUpgrade(req)\n ? upgradeOver(mux, { kind: \"upgrade\", target }, req)\n : fetchOver(mux, { kind: \"fetch\", target }, req);\n // Closing the multiplexer rejects every call in flight, and every later one, with `reason`.\n return { call, fetch, close: (reason) => mux.close(reason) };\n}\n\n/**\n * The isolate's end: accepts the ports the host opens. Everything the isolate calls the host\n * for happens while serving a host call, so the calls port is open by then. `outbound` sends\n * a fetch to the host's `globalOutbound`.\n */\nexport function isolatePort(\n port: PortLike,\n handle: Handle,\n fetch: Fetch,\n): { call: Call; outbound: (req: Request) => Promise<Response> } {\n let calls: Call | undefined;\n const bodies = new Bodies();\n const mux: PortMux = multiplexPort(messageTarget(port), {\n codec: structuredCodec,\n side: \"responder\",\n maxPorts: maxPorts(),\n onPort(p, meta) {\n const m = meta as { kind?: string; target: FetchTarget; url: string; id: number } | undefined;\n if (m?.kind === \"body\") return bodies.serve(p, m.id);\n if (m?.kind === \"fetch\") {\n serveFetch(p, m.url, (r) => fetch(m.target, r));\n return true;\n }\n if (m?.kind === \"upgrade\") {\n serveUpgrade(p, m as unknown as UpgradeMeta, (r) => fetch(m.target, r));\n return true;\n }\n if (m?.kind !== \"calls\" || calls) return false;\n calls = callsOver(p, handle, mux, bodies);\n return true;\n },\n });\n return {\n call: (msg) => calls!(msg),\n outbound: (req) => fetchOver(mux, { kind: \"outbound\" }, req),\n };\n}\n\n/** A fetch over a new port of `mux`; the URL rides in the meta (the HTTP/1.1 wire drops its scheme). */\nfunction fetchOver(mux: PortMux, meta: object, req: Request): Promise<Response> {\n return fetchOverDuplex(\n (input) =>\n (async function* () {\n yield* duplexOverPort(await mux.openPort({ ...meta, url: req.url }))(input);\n })(),\n req,\n );\n}\n\n/** Serves the fetch on port `p` (its URL from the meta) with `fetch`. */\nfunction serveFetch(p: MessageTarget, url: string, fetch: (req: Request) => Promise<Response>) {\n serveDuplexOverPort(\n p,\n serveFetchOverDuplex((req) => withUrl(req, url).then(fetch).catch(throwOwn)),\n );\n}\n\nconst isUpgrade = (req: Request) => req.headers.get(\"upgrade\")?.toLowerCase() === \"websocket\";\n\ninterface UpgradeMeta {\n url: string;\n method: string;\n headers: [string, string][];\n}\n/**\n * Ports of an isolate's multiplexer open at once: the calls port, and one per fetch or upgrade\n * in flight (each closes when its exchange ends). `globalThis.__cellbMaxPorts` overrides it, as\n * for src/transport/port.ts.\n */\nconst maxPorts = () => (globalThis as { __cellbMaxPorts?: number }).__cellbMaxPorts ?? 4096;\n\n/** The isolate's answer to an upgrade: the head of its response, or the error it threw. */\ntype UpgradeHead =\n | {\n status: number;\n statusText?: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n /** A 101's socket: the port of its client end, transferred. */\n socket?: MessagePort;\n /** A 101's frames that reached its client end before the hand-over. */\n frames?: Frame[];\n }\n | { error: unknown };\n\n/** Statuses whose response has no body (`new Response(body, …)` refuses one). */\nconst nullBody = (status: number) => [101, 204, 205, 304].includes(status);\n\n/**\n * A WebSocket upgrade over a port of its own, closed once the isolate's answer is in. A 101\n * becomes a Workers response whose `webSocket` is a client end over the socket's own port.\n */\nasync function upgradeOver(mux: PortMux, meta: object, req: Request): Promise<Response> {\n const p = await mux.openPort({\n ...meta,\n url: req.url,\n method: req.method,\n headers: [...req.headers],\n } satisfies UpgradeMeta);\n return new Promise((resolve, reject) => {\n // A port closed without an answer (the isolate refused it, or could not post one)\n // fails the upgrade rather than leaving it pending.\n const closed = getPortCloseSignal(p);\n const onClosed = () => {\n p.removeEventListener(\"message\", onHead);\n reject(\n closed?.reason ?? new Error(\"cellb: the isolate closed the upgrade without an answer\"),\n );\n };\n closed?.addEventListener(\"abort\", onClosed, { once: true });\n const onHead = (e: MessageEvent) => {\n p.removeEventListener(\"message\", onHead);\n closed?.removeEventListener(\"abort\", onClosed);\n void p.close?.();\n try {\n const head = e.data as UpgradeHead;\n if (\"error\" in head) throw head.error;\n if (head.status === 101 && head.socket)\n return resolve(\n new CellsResponse(null, {\n status: 101,\n headers: head.headers,\n webSocket: new CfWebSocket(head.socket, head.frames),\n }),\n );\n resolve(\n new Response(nullBody(head.status) ? null : head.body, {\n status: head.status,\n statusText: head.statusText,\n headers: head.headers,\n }),\n );\n } catch (err) {\n reject(err);\n }\n };\n p.addEventListener(\"message\", onHead);\n void p.start?.();\n });\n}\n\n/** Serves an upgrade on port `p`: a 101 hands over its client end's port; then `p` closes. */\nfunction serveUpgrade(\n p: MessageTarget,\n meta: UpgradeMeta,\n fetch: (req: Request) => Promise<Response>,\n) {\n // A browser drops `Upgrade` and `Sec-WebSocket-*` from `new Request()`: carried over here.\n const headers = new Headers(meta.headers);\n const req = carryWebSocketHeaders(\n headers,\n new Request(meta.url, { method: meta.method, headers }),\n );\n const answer = (head: UpgradeHead, transfer: Transferable[] = []) => {\n try {\n // The multiplexer drops a message it cannot copy, so check before posting; a 101\n // head is not checked, since its socket port is transferred rather than copied.\n if (transfer.length === 0) cloneable(head);\n p.postMessage(head, transfer);\n } catch {\n // An error that cannot be copied (a function in its `cause`, say): its name and message.\n const e = (head as { error?: { name?: unknown; message?: unknown } }).error;\n p.postMessage({\n error: Object.assign(new Error(String(e?.message ?? e)), {\n name: String(e?.name ?? \"Error\"),\n }),\n } satisfies UpgradeHead);\n }\n };\n void (async () => {\n try {\n const res = await fetch(req);\n const ws = (res as { webSocket?: CfWebSocket | null }).webSocket;\n if (res.status === 101 && ws) {\n const { port: socket, frames } = takeClientEnd(ws);\n answer({ status: 101, headers: [...res.headers], body: null, socket, frames }, [socket]);\n } else\n answer({\n status: res.status,\n statusText: res.statusText,\n headers: [...res.headers],\n body: nullBody(res.status) ? null : await res.arrayBuffer(),\n });\n } catch (error) {\n answer({ error });\n }\n void p.close?.();\n })();\n}\n\n/** Marks a Request, Response, Headers or ReadableStream in a message: `{ [WIRE]: kind, … }`. */\nconst WIRE = \"\\u0000cellb.wire\";\n\n// The realm's own classes, before the isolate entry replaces the globals with its subclasses\n// (CellsRequest, CellsResponse): instances of either are instances of these.\nconst NativeRequest = globalThis.Request;\nconst NativeResponse = globalThis.Response;\nconst NativeHeaders = globalThis.Headers;\nconst NativeReadableStream = globalThis.ReadableStream;\n\n/**\n * The bodies one side has sent and the other has not read yet, by id. The reader opens a port\n * `{ kind: \"body\", id }` on the multiplexer when it first pulls, and the body streams over it,\n * as a fetch's body does; a reader that drops the body unread sends `release {body}` instead.\n */\nclass Bodies {\n #last = 0;\n #streams = new Map<number, ReadableStream>();\n add(stream: ReadableStream): number {\n this.#streams.set(++this.#last, stream);\n return this.#last;\n }\n /** The last id handed out, for `releaseSince`. */\n mark(): number {\n return this.#last;\n }\n /** Releases the bodies added after `mark` (a message that could not be sent). */\n releaseSince(mark: number): void {\n for (let id = mark + 1; id <= this.#last; id++) this.release(id);\n }\n release(id: number): void {\n const stream = this.#streams.get(id);\n this.#streams.delete(id);\n void stream?.cancel().catch(() => {});\n }\n /** Serves body `id` on port `p`; false (the port is refused) if there is no such body. */\n serve(p: MessageTarget, id: number): boolean {\n const stream = this.#streams.get(id);\n if (!stream) return false;\n this.#streams.delete(id);\n const encoder = new TextEncoder();\n serveDuplexOverPort(p, async function* () {\n // A reader, not `for await`: not every engine iterates a ReadableStream (Safari).\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value: chunk } = await reader.read();\n if (done) return;\n yield typeof chunk === \"string\"\n ? encoder.encode(chunk)\n : ArrayBuffer.isView(chunk)\n ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n : new Uint8Array(chunk as ArrayBuffer);\n }\n } finally {\n // The reader stopped early (the port was abandoned): the stream is cancelled.\n void reader.cancel().catch(() => {});\n }\n });\n return true;\n }\n}\n\n/**\n * A Request, Response, Headers or ReadableStream as a message can carry it (workerd's RPC passes\n * them; a port cannot clone them): its head copied, its body registered in `bodies` to stream\n * when read. Anything else is returned as it is.\n */\nfunction toWire(v: unknown, bodies: Bodies): unknown {\n if (v instanceof NativeHeaders) return { [WIRE]: \"headers\", entries: [...v] };\n if (v instanceof NativeReadableStream) return { [WIRE]: \"stream\", body: bodies.add(v) };\n if (v instanceof NativeResponse) {\n if ((v as { webSocket?: unknown }).webSocket)\n throw new DOMException(\n \"A WebSocket response cannot be passed in an RPC call; return it from fetch().\",\n \"DataCloneError\",\n );\n return {\n [WIRE]: \"response\",\n status: v.status,\n statusText: v.statusText,\n url: v.url,\n headers: [...v.headers],\n body: v.body ? bodies.add(v.body) : null,\n };\n }\n if (v instanceof NativeRequest)\n return {\n [WIRE]: \"request\",\n url: v.url,\n method: v.method,\n headers: [...v.headers],\n redirect: v.redirect,\n body: v.body ? bodies.add(v.body) : null,\n };\n return v;\n}\n\n/** Releases a body that was never read, once its stream is collected. */\nconst unread = new FinalizationRegistry<() => void>((release) => release());\n\n/**\n * The other side's body `id` as a stream: the first pull opens its port, so a body nobody\n * reads costs nothing but its release.\n */\nfunction remoteBody(mux: PortMux, id: number, release: (id: number) => void): ReadableStream {\n let chunks: AsyncIterator<Uint8Array> | undefined;\n const token = {};\n const stream = new NativeReadableStream<Uint8Array>({\n async pull(controller) {\n if (!chunks) {\n unread.unregister(token);\n const port = await mux.openPort({ kind: \"body\", id });\n chunks = duplexOverPort(port)([])[Symbol.asyncIterator]();\n }\n const { done, value } = await chunks.next();\n if (done) controller.close();\n else controller.enqueue(value);\n },\n async cancel(reason) {\n if (chunks) await chunks.return?.(reason);\n else {\n unread.unregister(token);\n release(id);\n }\n },\n });\n unread.register(stream, () => release(id), token);\n return stream;\n}\n\n/** Statuses whose Response has no body. */\nconst NULL_BODY = [101, 103, 204, 205, 304];\n\n/** The value `toWire` described, rebuilt; its body streams from the other side when read. */\nfunction fromWire(v: any, mux: PortMux, release: (id: number) => void): unknown {\n const body = (id: number | null) => (id === null ? null : remoteBody(mux, id, release));\n switch (v[WIRE]) {\n case \"headers\":\n return new Headers(v.entries);\n case \"stream\":\n return body(v.body);\n case \"response\": {\n if (NULL_BODY.includes(v.status) && v.body !== null) release(v.body);\n const res = new Response(NULL_BODY.includes(v.status) ? null : body(v.body), {\n status: v.status,\n statusText: v.statusText,\n headers: v.headers,\n });\n if (v.url) Object.defineProperty(res, \"url\", { value: v.url, enumerable: true });\n return res;\n }\n case \"request\":\n return new Request(v.url, {\n method: v.method,\n headers: v.headers,\n redirect: v.redirect,\n body: body(v.body),\n duplex: \"half\",\n } as RequestInit);\n }\n return v;\n}\n\n/** Marks a value passed by reference in a message: `{ [REF]: id }`. */\nconst REF = \"\\u0000cellb.ref\";\n\n/**\n * The calls of one port, with values passed by reference: each side keeps the values it\n * passed (by id, and how many ids hold each); the other side calls them through stubs. A\n * stub's `Symbol.dispose` (or its garbage collection) releases its id; the last release of a\n * value runs the value's own `Symbol.dispose`, as workerd does for an `RpcTarget`. A call\n * returns an RpcPromise: calls on it go to the other side at once, naming its answer.\n */\nfunction callsOver(port: MessageTarget, handle: Handle, mux: PortMux, bodies: Bodies): Call {\n const values = new Map<number, any>();\n const answers = new Map<number, unknown>();\n let lastAnswer = 0;\n const holders = new Map<unknown, number>();\n let lastId = 0;\n const encode = (v: unknown) => {\n const mark = bodies.mark();\n try {\n return cloneable(\n cross(\n v,\n (x) => {\n values.set(++lastId, x);\n holders.set(x, (holders.get(x) ?? 0) + 1);\n return { [REF]: lastId };\n },\n (x) => toWire(x, bodies), // Requests, Responses, Headers, streams; the port copies the rest\n ),\n );\n } catch (e) {\n bodies.releaseSince(mark); // the message is not sent: nobody will read its bodies\n throw e;\n }\n };\n const release = (id: number) => {\n const v = values.get(id);\n if (!values.delete(id)) return;\n const n = (holders.get(v) ?? 1) - 1;\n if (n) holders.set(v, n);\n else {\n holders.delete(v);\n v[Symbol.dispose]?.();\n }\n };\n const send = (msg: object) => callPort(port, msg, { timeout: NO_TIMEOUT }).catch(() => {});\n // Stubs of one id held here: `dup()` makes another, and the id is released (and the other\n // side's value with it, once no other id holds it) when the last of them is disposed or\n // collected.\n const local = new Map<number, number>();\n const drop = (id: number) => {\n const n = (local.get(id) ?? 1) - 1;\n if (n) local.set(id, n);\n else {\n local.delete(id);\n send({ type: \"release\", id });\n }\n };\n const collected = new FinalizationRegistry<number>(drop);\n const stubOf = (id: number) => {\n local.set(id, (local.get(id) ?? 0) + 1);\n let disposed = false;\n const live = () => {\n if (disposed) throw new Error(\"A stub was used after it was disposed.\");\n };\n const invoke = (path: string[], args: unknown[]) => {\n live();\n return call({ type: \"ref\", id, path, args });\n };\n const stub: any = new Proxy(() => {}, {\n apply: (_t, _this, args) => invoke([], args),\n get(_t, prop) {\n if (prop === STUB) return true;\n if (prop === Symbol.dispose)\n return () => {\n if (disposed) return;\n disposed = true;\n collected.unregister(stub);\n drop(id);\n };\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n // workerd's `stub.dup()`: another stub of the same value, disposed on its own.\n if (prop === \"dup\")\n return () => {\n live();\n return stubOf(id);\n };\n return (...args: unknown[]) => invoke([prop], args);\n },\n });\n collected.register(stub, id, stub);\n return stub;\n };\n // Messages arrive as fresh copies: stubs replace the markers in place.\n const decode = (v: any): any => {\n if (Array.isArray(v)) for (let i = 0; i < v.length; i++) v[i] = decode(v[i]);\n else if (v && Object.getPrototypeOf(v) === Object.prototype) {\n if (typeof v[WIRE] === \"string\")\n return fromWire(v, mux, (body) => send({ type: \"release\", body }));\n if (typeof v[REF] === \"number\") return stubOf(v[REF]);\n for (const k of Object.keys(v)) v[k] = decode(v[k]);\n }\n return v;\n };\n const run = (m: any): unknown => {\n if (m.type !== \"ref\") return handle(m);\n if (m.on !== undefined) return pipeTo(answers.get(m.on), m.path, m.args);\n const v = values.get(m.id);\n if (v === undefined) throw new Error(\"A stub was used after it was disposed.\");\n return pipeTo(v, m.path, m.args);\n };\n // The answer is kept as the message arrives: a pipelined call on it may arrive before it\n // settles.\n const serve = async (m: any) => {\n if (m.type === \"release\") {\n if (m.body !== undefined) bodies.release(m.body);\n else if (m.answer === undefined) release(m.id);\n else answers.delete(m.answer);\n return;\n }\n let r: unknown;\n try {\n r = run(m);\n } catch (e) {\n r = Promise.reject(e);\n }\n answers.set(m.answer, r);\n return r;\n };\n listenPort(port, (msg) => serve(decode(msg)).then(encode).catch(throwOwn));\n const call: Call = (msg) => {\n const answer = ++lastAnswer;\n const result = (async () =>\n decode(await callPort(port, encode({ ...msg, answer }), { timeout: NO_TIMEOUT })))();\n // Calls on the answer sent before now are ahead of this release on the port.\n const done = () => send({ type: \"release\", answer });\n result.then(done, done);\n return rpcPromise(result, (path, args) => call({ type: \"ref\", on: answer, path, args }));\n };\n return call;\n}\n\n/** Errors cross with their own properties (so `code` does); `name` is inherited, so copy it. */\nfunction throwOwn(e: unknown): never {\n if (e && typeof e === \"object\")\n Object.defineProperty(e, \"name\", { value: (e as Error).name, enumerable: true });\n throw e;\n}\n\n/**\n * Throws `DataCloneError` for a value the port cannot carry: the multiplexer drops a message\n * it fails to post, and the call would wait forever.\n */\nfunction cloneable<T>(value: T): T {\n structuredClone(value);\n return value;\n}\n\n/** A worker_threads Worker is an EventEmitter; MessagePorts and Dedicated Workers are targets. */\nfunction messageTarget(port: PortLike): MessageTarget {\n if (port.addEventListener) return port as MessageTarget;\n const on = port.on!.bind(port);\n const listeners = new Map<unknown, (data: unknown) => void>();\n return {\n postMessage: (msg, transfer) => port.postMessage(msg, transfer),\n addEventListener(_type, fn) {\n const listener = (data: unknown) => void fn({ data } as MessageEvent);\n listeners.set(fn, listener);\n on(\"message\", listener);\n },\n removeEventListener(_type, fn) {\n port.off?.(\"message\", listeners.get(fn)!);\n listeners.delete(fn);\n },\n };\n}\n"]}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * workerd's globals are plain properties that Worker code may assign: Kitesurf's DOM shim sets
3
+ * `globalThis.navigator` and `globalThis.location`. The realm an isolate runs in has getters
4
+ * without setters for some of its own (Node's `navigator`; a Dedicated Worker's `location`,
5
+ * `navigator`, `origin`, … on WorkerGlobalScope.prototype), and assigning one throws in strict
6
+ * mode. The isolate is the loaded Worker's realm, so each such global becomes a writable data
7
+ * property of `globalThis` holding the value it has now.
8
+ */
9
+ export declare function makeGlobalsWritable(): string[];
@@ -0,0 +1,45 @@
1
+ /**
2
+ * workerd's globals are plain properties that Worker code may assign: Kitesurf's DOM shim sets
3
+ * `globalThis.navigator` and `globalThis.location`. The realm an isolate runs in has getters
4
+ * without setters for some of its own (Node's `navigator`; a Dedicated Worker's `location`,
5
+ * `navigator`, `origin`, … on WorkerGlobalScope.prototype), and assigning one throws in strict
6
+ * mode. The isolate is the loaded Worker's realm, so each such global becomes a writable data
7
+ * property of `globalThis` holding the value it has now.
8
+ */
9
+ export function makeGlobalsWritable() {
10
+ const changed = [];
11
+ const seen = new Set();
12
+ for (let o = globalThis; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) {
13
+ for (const key of Reflect.ownKeys(o)) {
14
+ if (seen.has(key))
15
+ continue;
16
+ seen.add(key);
17
+ const d = Object.getOwnPropertyDescriptor(o, key);
18
+ if (!d?.get || d.set)
19
+ continue;
20
+ if (o === globalThis && !d.configurable)
21
+ continue;
22
+ let value;
23
+ try {
24
+ value = Reflect.get(globalThis, key);
25
+ }
26
+ catch {
27
+ continue; // a getter that throws here (an API this realm refuses) stays as it is
28
+ }
29
+ try {
30
+ Object.defineProperty(globalThis, key, {
31
+ value,
32
+ writable: true,
33
+ configurable: true,
34
+ enumerable: d.enumerable,
35
+ });
36
+ changed.push(String(key));
37
+ }
38
+ catch {
39
+ // not redefinable in this realm
40
+ }
41
+ }
42
+ }
43
+ return changed;
44
+ }
45
+ //# sourceMappingURL=writable-globals.js.map