@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 +1 @@
1
- {"version":3,"file":"worker-loader.js","sourceRoot":"","sources":["../../src/bindings/worker-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,KAAK,EACL,UAAU,EAEV,cAAc,EACd,QAAQ,EAER,MAAM,EACN,MAAM,EACN,UAAU,GACX,MAAM,oBAAoB,CAAC;AAE5B,qFAAqF;AACrF,MAAM,kBAAkB,GACtB,yQAAyQ,CAAC;AAmC5Q;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,KAAoC;IAC7D,IAAI,OAAO,KAAK,KAA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AAC,CAAC,IAAI,CAAC,CAAC,CACtD;qCACF,CAAC;gCACJ,CAAC,CAAC,CAAC;gCACH,OAAO,UAAU,CACf,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EACpB,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CACnD,CAAC;4BACJ,CAAC,CAAC;wBACJ,CAAC;qBACF,CACF,CAAC;gBACJ,CAAC;aACF,CAAC;QACJ,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n classHandle,\n cross,\n ctxExports,\n type DurableObjectClass,\n entrypointStub,\n ISOLATED,\n type IsolatedClass,\n pipeTo,\n REFUSE,\n rpcPromise,\n} from \"../core/handles.js\";\n\n/** workerd's refusal of a loaded Worker's entrypoint passed on to another Worker. */\nconst DYNAMIC_ENTRYPOINT =\n \"Entrypoints to dynamically-loaded workers cannot be transferred to other Workers, because the system does not know how to reload this Worker from scratch. Instead, have the parent Worker expose an entrypoint which constructs the dynamic worker and forwards to it.\";\n\n/** What `env.LOADER.get(id, () => code)` returns from its callback (workerd's WorkerCode). */\nexport interface WorkerCode {\n compatibilityDate?: string;\n compatibilityFlags?: string[];\n mainModule: string;\n modules: Record<\n string,\n | string\n | { js?: string; esModule?: string; text?: string; json?: unknown; wasm?: BufferSource }\n | { data: BufferSource }\n >;\n env?: Record<string, unknown>;\n globalOutbound?: unknown;\n /** Tail Workers: stubs whose `tail(events)` receives each invocation's logs and exceptions. */\n tails?: { tail(events: TailEvent[]): unknown }[];\n}\n\nexport interface TailLog {\n message: unknown[];\n level: string;\n timestamp: number;\n}\n\nexport interface TailEvent {\n scriptName: string;\n outcome: \"ok\" | \"exception\";\n eventTimestamp: number;\n event: { request?: { url: string; method: string } } | null;\n logs: TailLog[];\n exceptions: { name: string; message: string; timestamp: number }[];\n diagnosticsChannelEvents: unknown[];\n}\n\n/**\n * One `WorkerCode.modules` entry as ES module source; text and JSON become a default export,\n * wasm bytes a compiled `WebAssembly.Module`.\n */\nexport function moduleText(entry: WorkerCode[\"modules\"][string]): string {\n if (typeof entry === \"string\") return entry;\n const m = entry as Exclude<typeof entry, { data: BufferSource }>; // workerLoader refuses data\n if (m.wasm) {\n const bytes = ArrayBuffer.isView(m.wasm)\n ? new Uint8Array(m.wasm.buffer, m.wasm.byteOffset, m.wasm.byteLength)\n : new Uint8Array(m.wasm);\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return `export default new WebAssembly.Module(Uint8Array.from(atob(\"${btoa(bin)}\"), (c) => c.charCodeAt(0)));`;\n }\n return m.js ?? m.esModule ?? `export default ${JSON.stringify(m.text ?? m.json)};`;\n}\n\n/**\n * The `fetch` loaded code sees, from `WorkerCode.globalOutbound`: omitted → the loader's own\n * (undefined: no override); `null` → every fetch throws; a Fetcher → each fetch goes through it.\n */\nexport function outboundFetch(code: WorkerCode): typeof fetch | undefined {\n const o = code.globalOutbound as { fetch?: typeof fetch } | null | undefined;\n if (o === undefined) return undefined;\n if (o === null)\n return (async () => {\n throw new Error(\n \"This worker is not permitted to access the internet via global functions like fetch(). It must use capabilities (such as bindings in 'env') to talk to the outside world.\",\n );\n }) as typeof fetch;\n if (typeof o.fetch === \"function\")\n return ((input: RequestInfo | URL, init?: RequestInit) =>\n o.fetch!(input, init)) as typeof fetch;\n throw new TypeError(\"globalOutbound must be null or a Fetcher\");\n}\n\n/** Where the `console` of loaded code writes (the host forwards to the real console too). */\nexport type LogSink = (level: string, args: unknown[]) => void;\n\n/** Compiles a WorkerCode into a module namespace (host specific: esbuild on Node, webrun-modules in browsers). */\nexport type ModuleLoader = (\n id: string,\n code: WorkerCode,\n logs?: LogSink,\n) => Promise<Record<string, unknown>>;\n\n/**\n * The Worker Loader binding (`worker_loaders` in wrangler config): runtime-loaded code,\n * cached by id; the callback runs only when the id is not loaded yet.\n */\nexport function workerLoader(load: ModuleLoader, opts: { classes?: ModuleLoader } = {}) {\n // With isolated loading, Durable Object classes (facets) still load in this realm.\n const classCache = new Map<string, Promise<{ module: Record<string, unknown>; env: unknown }>>();\n type Loaded = {\n module: Record<string, unknown>;\n env: unknown;\n /** ctx.exports of the loaded code (empty for an isolated module: the isolate builds its own). */\n exports: Record<string, unknown>;\n code: WorkerCode;\n logs: TailLog[];\n };\n const cache = new Map<string, Promise<Loaded>>();\n let anonymous = 0;\n const loader = {\n /** Compiles and runs code without the id cache (a fresh Worker per call). */\n load(code: WorkerCode) {\n return loader.get(\n `__load-${++anonymous}-${Math.random().toString(36).slice(2)}`,\n () => code,\n false,\n );\n },\n get(id: string, getCode: () => WorkerCode | Promise<WorkerCode>, cached = true) {\n let own: Promise<Loaded> | undefined; // load(): memoized per handle, not in the id cache\n const loaded = () => {\n let p = cached ? cache.get(id) : own;\n if (!p) {\n p = (async () => {\n const code = await getCode();\n // celld takes module source and wasm bytes only, not `data` modules.\n for (const [name, m] of Object.entries(code.modules))\n if (typeof m === \"object\" && \"data\" in m)\n throw new Error(`worker loader: module \"${name}\" must be a string or wasm bytes`);\n const logs: TailLog[] = [];\n const sink: LogSink = (level, message) =>\n logs.push({ level, message, timestamp: Date.now() });\n const module = await load(id, code, sink);\n const env = code.env ?? {};\n return { module, env, exports: ctxExports(module, env), code, logs };\n })();\n p.catch(() => cache.delete(id));\n if (cached) cache.set(id, p);\n else own = p;\n }\n return p;\n };\n /**\n * Runs one invocation of loaded code, then hands its logs/exceptions to the Tail Workers.\n * Returns the run's result as is (an RpcPromise stays one, for pipelining).\n */\n const traced = (l: Loaded, request: Request | undefined, run: () => unknown): unknown => {\n const from = l.logs.length;\n const t0 = Date.now();\n let r: unknown;\n try {\n r = run();\n } catch (e) {\n r = Promise.reject(e);\n }\n const report = (exceptions: TailEvent[\"exceptions\"]) => {\n const event: TailEvent = {\n scriptName: id,\n outcome: exceptions.length ? \"exception\" : \"ok\",\n eventTimestamp: t0,\n event: request ? { request: { url: request.url, method: request.method } } : null,\n logs: l.logs.splice(from),\n exceptions,\n diagnosticsChannelEvents: [],\n };\n for (const t of l.code.tails ?? []) void Promise.resolve(t.tail([event])).catch(() => {});\n };\n Promise.resolve(r).then(\n () => report([]),\n (e) =>\n report([\n {\n name: (e as Error)?.name ?? \"Error\",\n message: String((e as Error)?.message ?? e),\n timestamp: Date.now(),\n },\n ]),\n );\n return r;\n };\n return {\n getDurableObjectClass(name: string) {\n const classesLoaded = () => {\n let p = classCache.get(id);\n if (!p) {\n p = (async () => {\n const code = await getCode();\n return { module: await opts.classes!(id, code), env: code.env ?? {} };\n })();\n classCache.set(id, p);\n }\n return p;\n };\n return classHandle(async () => {\n if (!opts.classes) {\n const iso = (await loaded()).module[ISOLATED as unknown as string] as\n | ((name: string) => IsolatedClass)\n | undefined;\n if (iso) return { isolated: iso(name) };\n }\n const { module, env } = opts.classes ? await classesLoaded() : await loaded();\n const cls = module[name];\n if (typeof cls !== \"function\")\n throw new Error(`Loaded worker \"${id}\" does not export class \"${name}\"`);\n return { cls: cls as DurableObjectClass, env };\n });\n },\n /** Releases the loaded Worker: the id leaves the cache; a later get() loads again. */\n dispose() {\n cache.delete(id);\n },\n getEntrypoint(name = \"default\", options: { props?: unknown } = {}) {\n // Props cross now (workerd serializes them here): a refusal is a rejected promise,\n // so `await` and `assert.rejects` see it.\n try {\n cross(options.props);\n } catch (e) {\n const refused = Promise.reject(e);\n refused.catch(() => {});\n return refused as never;\n }\n return new Proxy(\n {},\n {\n get(_t, prop) {\n if (prop === REFUSE) return DYNAMIC_ENTRYPOINT;\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n return (...args: unknown[]) => {\n // Boxed, so awaiting the load does not await the call: calls on its\n // RpcPromise are pipelined.\n const run = loaded().then((l) => {\n const stub = entrypointStub(l.module[name], l.env, options.props, l.exports);\n const request =\n prop === \"fetch\"\n ? new Request(args[0] as RequestInfo, args[1] as RequestInit)\n : undefined;\n return {\n r: traced(l, request, () =>\n stub[prop as string](...(request ? [request] : args)),\n ),\n };\n });\n return rpcPromise(\n run.then((b) => b.r),\n (path, a) => run.then((b) => pipeTo(b.r, path, a)),\n );\n };\n },\n },\n );\n },\n };\n },\n };\n return loader;\n}\n"]}
1
+ {"version":3,"file":"worker-loader.js","sourceRoot":"","sources":["../../src/bindings/worker-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,KAAK,EACL,UAAU,EAEV,cAAc,EACd,QAAQ,EAER,QAAQ,EACR,MAAM,EACN,MAAM,EACN,UAAU,GACX,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD,qFAAqF;AACrF,MAAM,kBAAkB,GACtB,yQAAyQ,CAAC;AA2C5Q;;;;GAIG;AACH,MAAM,UAAU,UAAU,CACxB,KAAoC,EACpC,IAAI,GAAG,YAAY,EACnB,KAA2B;IAE3B,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5C,MAAM,CAAC,GAAG,KAAsD,CAAC,CAAC,4BAA4B;IAC9F,IAAI,OAAO,CAAC,CAAC,GAAG,KAAK,QAAQ;QAAE,OAAO,cAAc,CAAC,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IACzE,IAAI,CAAC,CAAC,IAAI,YAAY,WAAW,CAAC,MAAM;QACtC,OAAO,6BAA6B,UAAU,IAAI,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC;IAC9F,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QACX,MAAM,KAAK,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;YACtC,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,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AC,CAAC;gCACH,OAAO,UAAU,CACf,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EACpB,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CACnD,CAAC;4BACJ,CAAC,CAAC;wBACJ,CAAC;qBACF,CACF,CAAC;oBACF,OAAO,UAAU,CAAC;gBACpB,CAAC;aACF,CAAC;QACJ,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n classHandle,\n cross,\n ctxExports,\n type DurableObjectClass,\n entrypointStub,\n ISOLATED,\n type IsolatedClass,\n ON_ABORT,\n pipeTo,\n REFUSE,\n rpcPromise,\n} from \"../core/handles.js\";\nimport { commonJsModule } from \"./cjs-module.js\";\n\n/** workerd's refusal of a loaded Worker's entrypoint passed on to another Worker. */\nconst DYNAMIC_ENTRYPOINT =\n \"Entrypoints to dynamically-loaded workers cannot be transferred to other Workers, because the system does not know how to reload this Worker from scratch. Instead, have the parent Worker expose an entrypoint which constructs the dynamic worker and forwards to it.\";\n\n/** What `env.LOADER.get(id, () => code)` returns from its callback (workerd's WorkerCode). */\nexport interface WorkerCode {\n compatibilityDate?: string;\n compatibilityFlags?: string[];\n mainModule: string;\n modules: Record<\n string,\n | string\n | {\n js?: string;\n esModule?: string;\n cjs?: string;\n text?: string;\n json?: unknown;\n /** The bytes, or (from `compileWasmModules`) the compiled module. */\n wasm?: BufferSource | WebAssembly.Module;\n }\n | { data: BufferSource }\n >;\n env?: Record<string, unknown>;\n globalOutbound?: unknown;\n /** Tail Workers: stubs whose `tail(events)` receives each invocation's logs and exceptions. */\n tails?: { tail(events: TailEvent[]): unknown }[];\n}\n\nexport interface TailLog {\n message: unknown[];\n level: string;\n timestamp: number;\n}\n\nexport interface TailEvent {\n scriptName: string;\n outcome: \"ok\" | \"exception\";\n eventTimestamp: number;\n event: { request?: { url: string; method: string } } | null;\n logs: TailLog[];\n exceptions: { name: string; message: string; timestamp: number }[];\n diagnosticsChannelEvents: unknown[];\n}\n\n/**\n * One `WorkerCode.modules` entry as ES module source; text and JSON become a default export,\n * wasm bytes a compiled `WebAssembly.Module`, and a CommonJS module's `module.exports` the\n * default export. `name` names a CommonJS module in stack traces.\n */\nexport function moduleText(\n entry: WorkerCode[\"modules\"][string],\n name = \"module.cjs\",\n names?: ReadonlySet<string>,\n): string {\n if (typeof entry === \"string\") return entry;\n const m = entry as Exclude<typeof entry, { data: BufferSource }>; // workerLoader refuses data\n if (typeof m.cjs === \"string\") return commonJsModule(m.cjs, name, names);\n if (m.wasm instanceof WebAssembly.Module)\n return `export default globalThis.${WASM_TABLE}[${JSON.stringify(wasmModuleKey(m.wasm))}];`;\n if (m.wasm) {\n const bytes = ArrayBuffer.isView(m.wasm)\n ? new Uint8Array(m.wasm.buffer, m.wasm.byteOffset, m.wasm.byteLength)\n : new Uint8Array(m.wasm);\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return `export default new WebAssembly.Module(Uint8Array.from(atob(\"${btoa(bin)}\"), (c) => c.charCodeAt(0)));`;\n }\n return m.js ?? m.esModule ?? `export default ${JSON.stringify(m.text ?? m.json)};`;\n}\n\n/** The realm's table of compiled wasm modules of loaded code, by key. */\nexport const WASM_TABLE = \"__cellsWasmModules\";\nconst keys = new WeakMap<WebAssembly.Module, string>();\nlet lastKey = 0;\n\n/** The key of `mod` in this realm's wasm table (registered on first use). */\nexport function wasmModuleKey(mod: WebAssembly.Module): string {\n let key = keys.get(mod);\n if (!key) {\n key = `w${++lastKey}`;\n keys.set(mod, key);\n registerWasmModules({ [key]: mod });\n }\n return key;\n}\n\n/** Puts compiled modules in this realm's wasm table (an isolate receives its loader's). */\nexport function registerWasmModules(modules: Record<string, WebAssembly.Module>): void {\n const g = globalThis as Record<string, unknown>;\n g[WASM_TABLE] ??= {};\n Object.assign(g[WASM_TABLE] as Record<string, WebAssembly.Module>, modules);\n}\n\n/** The table entries the wasm modules of `code` use (what an isolate needs of this realm's table). */\nexport function wasmModulesOf(code: WorkerCode): Record<string, WebAssembly.Module> {\n const out: Record<string, WebAssembly.Module> = {};\n for (const m of Object.values(code.modules))\n if (typeof m === \"object\" && \"wasm\" in m && m.wasm instanceof WebAssembly.Module)\n out[wasmModuleKey(m.wasm)] = m.wasm;\n return out;\n}\n\nconst compiled = new WeakMap<object, Promise<WebAssembly.Module>>();\n\n/**\n * `code` with each `wasm` module compiled (asynchronously, once per bytes object: Kitesurf hands\n * the same ArrayBuffer to every page's Worker), so loaders put a compiled module in the realm's\n * table instead of the bytes as base64 text, which a large module makes slow to build, parse,\n * decode and compile synchronously on every load.\n */\nexport async function compileWasmModules(code: WorkerCode): Promise<WorkerCode> {\n let modules: WorkerCode[\"modules\"] | undefined;\n for (const [name, m] of Object.entries(code.modules)) {\n if (typeof m !== \"object\" || !(\"wasm\" in m) || !m.wasm) continue;\n if (m.wasm instanceof WebAssembly.Module) continue;\n const bytes = m.wasm;\n let p = compiled.get(bytes);\n if (!p) {\n p = WebAssembly.compile(bytes);\n compiled.set(bytes, p);\n p.catch(() => compiled.delete(bytes));\n }\n modules ??= { ...code.modules };\n modules[name] = { ...m, wasm: await p };\n }\n return modules ? { ...code, modules } : code;\n}\n\n/**\n * The `fetch` loaded code sees, from `WorkerCode.globalOutbound`: omitted → the loader's own\n * (undefined: no override); `null` → every fetch throws; a Fetcher → each fetch goes through it.\n */\nexport function outboundFetch(code: WorkerCode): typeof fetch | undefined {\n const o = code.globalOutbound as { fetch?: typeof fetch } | null | undefined;\n if (o === undefined) return undefined;\n if (o === null)\n return (async () => {\n throw new Error(\n \"This worker is not permitted to access the internet via global functions like fetch(). It must use capabilities (such as bindings in 'env') to talk to the outside world.\",\n );\n }) as typeof fetch;\n if (typeof o.fetch === \"function\")\n return ((input: RequestInfo | URL, init?: RequestInit) =>\n o.fetch!(input, init)) as typeof fetch;\n throw new TypeError(\"globalOutbound must be null or a Fetcher\");\n}\n\n/** Where the `console` of loaded code writes (the host forwards to the real console too). */\nexport type LogSink = (level: string, args: unknown[]) => void;\n\n/** Compiles a WorkerCode into a module namespace (host specific: esbuild on Node, webrun-modules in browsers). */\nexport type ModuleLoader = (\n id: string,\n code: WorkerCode,\n logs?: LogSink,\n) => Promise<Record<string, unknown>>;\n\n/**\n * The Worker Loader binding (`worker_loaders` in wrangler config): runtime-loaded code,\n * cached by id; the callback runs only when the id is not loaded yet.\n */\nexport function workerLoader(load: ModuleLoader, opts: { classes?: ModuleLoader } = {}) {\n // With isolated loading, Durable Object classes (facets) still load in this realm.\n const classCache = new Map<string, Promise<{ module: Record<string, unknown>; env: unknown }>>();\n type Loaded = {\n module: Record<string, unknown>;\n env: unknown;\n /** ctx.exports of the loaded code (empty for an isolated module: the isolate builds its own). */\n exports: Record<string, unknown>;\n code: WorkerCode;\n logs: TailLog[];\n };\n const cache = new Map<string, Promise<Loaded>>();\n let anonymous = 0;\n const loader = {\n /** Compiles and runs code without the id cache (a fresh Worker per call). */\n load(code: WorkerCode) {\n return loader.get(\n `__load-${++anonymous}-${Math.random().toString(36).slice(2)}`,\n () => code,\n false,\n );\n },\n get(id: string, getCode: () => WorkerCode | Promise<WorkerCode>, cached = true) {\n let own: Promise<Loaded> | undefined; // load(): memoized per handle, not in the id cache\n const loaded = () => {\n let p = cached ? cache.get(id) : own;\n if (!p) {\n p = (async () => {\n const code = await getCode();\n // celld takes module source and wasm bytes only, not `data` modules.\n for (const [name, m] of Object.entries(code.modules))\n if (typeof m === \"object\" && \"data\" in m)\n throw new Error(`worker loader: module \"${name}\" must be a string or wasm bytes`);\n const logs: TailLog[] = [];\n const sink: LogSink = (level, message) =>\n logs.push({ level, message, timestamp: Date.now() });\n const module = await load(id, code, sink);\n // Its isolate ended (`abortIsolate()`): the next get() of this id loads it again.\n (\n (module as Record<symbol, unknown>)[ON_ABORT] as\n | ((forget: () => void) => void)\n | undefined\n )?.(() => {\n if (cache.get(id) === p) cache.delete(id);\n if (own === p) own = undefined;\n });\n const env = code.env ?? {};\n return { module, env, exports: ctxExports(module, env), code, logs };\n })();\n p.catch(() => cache.delete(id));\n if (cached) cache.set(id, p);\n else own = p;\n }\n return p;\n };\n /**\n * Runs one invocation of loaded code, then hands its logs/exceptions to the Tail Workers.\n * Returns the run's result as is (an RpcPromise stays one, for pipelining).\n */\n const traced = (l: Loaded, request: Request | undefined, run: () => unknown): unknown => {\n const from = l.logs.length;\n const t0 = Date.now();\n let r: unknown;\n try {\n r = run();\n } catch (e) {\n r = Promise.reject(e);\n }\n const report = (exceptions: TailEvent[\"exceptions\"]) => {\n const event: TailEvent = {\n scriptName: id,\n outcome: exceptions.length ? \"exception\" : \"ok\",\n eventTimestamp: t0,\n event: request ? { request: { url: request.url, method: request.method } } : null,\n logs: l.logs.splice(from),\n exceptions,\n diagnosticsChannelEvents: [],\n };\n for (const t of l.code.tails ?? []) void Promise.resolve(t.tail([event])).catch(() => {});\n };\n Promise.resolve(r).then(\n () => report([]),\n (e) =>\n report([\n {\n name: (e as Error)?.name ?? \"Error\",\n message: String((e as Error)?.message ?? e),\n timestamp: Date.now(),\n },\n ]),\n );\n return r;\n };\n return {\n getDurableObjectClass(name: string) {\n const classesLoaded = () => {\n let p = classCache.get(id);\n if (!p) {\n p = (async () => {\n const code = await getCode();\n return { module: await opts.classes!(id, code), env: code.env ?? {} };\n })();\n classCache.set(id, p);\n }\n return p;\n };\n return classHandle(async () => {\n if (!opts.classes) {\n const iso = (await loaded()).module[ISOLATED as unknown as string] as\n | ((name: string) => IsolatedClass)\n | undefined;\n if (iso) return { isolated: iso(name) };\n }\n const { module, env } = opts.classes ? await classesLoaded() : await loaded();\n const cls = module[name];\n if (typeof cls !== \"function\")\n throw new Error(`Loaded worker \"${id}\" does not export class \"${name}\"`);\n return { cls: cls as DurableObjectClass, env };\n });\n },\n /** Releases the loaded Worker: the id leaves the cache; a later get() loads again. */\n dispose() {\n cache.delete(id);\n },\n getEntrypoint(name = \"default\", options: { props?: unknown } = {}) {\n // Props cross now (workerd serializes them here): a refusal is a rejected promise,\n // so `await` and `assert.rejects` see it.\n try {\n cross(options.props);\n } catch (e) {\n const refused = Promise.reject(e);\n refused.catch(() => {});\n return refused as never;\n }\n const entrypoint: Record<string, unknown> = new Proxy(\n {},\n {\n get(_t, prop) {\n if (prop === REFUSE) return DYNAMIC_ENTRYPOINT;\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n // workerd's `dup()`: this entrypoint holds nothing to release, so it is itself.\n if (prop === \"dup\") return () => entrypoint;\n return (...args: unknown[]) => {\n // Boxed, so awaiting the load does not await the call: calls on its\n // RpcPromise are pipelined.\n const run = loaded().then((l) => {\n const stub = entrypointStub(l.module[name], l.env, options.props, l.exports);\n const request =\n prop === \"fetch\"\n ? new Request(args[0] as RequestInfo, args[1] as RequestInit)\n : undefined;\n return {\n r: traced(l, request, () =>\n stub[prop as string](...(request ? [request] : args)),\n ),\n };\n });\n return rpcPromise(\n run.then((b) => b.r),\n (path, a) => run.then((b) => pipeTo(b.r, path, a)),\n );\n };\n },\n },\n );\n return entrypoint;\n },\n };\n },\n };\n return loader;\n}\n"]}
@@ -18,6 +18,11 @@ export interface ClassHandle {
18
18
  }
19
19
  /** Key of the isolate's class factory on a module facade (see getDurableObjectClass). */
20
20
  export declare const ISOLATED: unique symbol;
21
+ /**
22
+ * On a loaded Worker's module whose isolate can end (`abortIsolate`): registers what to do when
23
+ * it does (the Worker Loader forgets the module, so the next `get()` loads the code again).
24
+ */
25
+ export declare const ON_ABORT: unique symbol;
21
26
  /** A Durable Object class that runs in an isolate: its instances and storage live there. */
22
27
  export interface IsolatedClass {
23
28
  fetch(cellKey: string, req: Request): Promise<Response>;
@@ -38,10 +43,16 @@ export declare const STUB: unique symbol;
38
43
  export declare const REFUSE: unique symbol;
39
44
  /** Answered by a `ctx.exports.X({ props })` stub or class handle: `{ name, props }` (storable). */
40
45
  export declare const EXPORT: unique symbol;
46
+ /**
47
+ * A copy of `v` for a call in one realm, as workerd's RPC makes it: a Request, Response or
48
+ * ReadableStream is passed itself (its body moves with it), Headers are copied, and anything
49
+ * else is structured-cloned.
50
+ */
51
+ export declare function copyInRealm(v: unknown): unknown;
41
52
  /**
42
53
  * What crosses a stub, as in workerd: functions, `RpcTarget`s, stubs and class handles by
43
54
  * reference (`ref` says what stands for one on the far side; in one realm, the value itself),
44
- * arrays and plain objects walked, anything else structured-cloned (`copy`).
55
+ * arrays and plain objects walked, anything else copied (`copy`; in one realm, `copyInRealm`).
45
56
  */
46
57
  export declare function cross<T>(v: T, ref?: (v: object) => unknown, copy?: (v: unknown) => unknown): T;
47
58
  /**
@@ -77,6 +88,15 @@ export declare function asyncStub(call: (method: string, args: unknown[]) => unk
77
88
  * of a plain object receive `(…args, env, ctx)`, as its `fetch` receives `(request, env, ctx)`.
78
89
  */
79
90
  export declare function entrypointStub(target: unknown, env: unknown, props: unknown, exports?: unknown): Record<string, any>;
91
+ /** An event handler of a Worker's default export: `fetch(request, env, ctx)` and the like. */
92
+ export type DefaultHandler = (arg: unknown, env: unknown, ctx: object) => unknown;
93
+ /**
94
+ * The default export's handler for one event (`fetch`, `scheduled`, `queue`), or `undefined`.
95
+ * An object's method is called with `(arg, env, ctx)`. A class (`export default class extends
96
+ * WorkerEntrypoint`) gets a fresh instance per event, built with `(ctx, env)` (`ctx.props` empty),
97
+ * and its method is called with the event's argument alone, as on workerd.
98
+ */
99
+ export declare function defaultHandler(def: unknown, name: string): DefaultHandler | undefined;
80
100
  /**
81
101
  * `ctx.exports`: loopback handles of a Worker's named exports. An entrypoint's (a
82
102
  * WorkerEntrypoint class, or an object with methods) is a stub (`ctx.exports.Greeter.greet()`),
@@ -3,6 +3,11 @@ import { carryWebSocketHeaders } from "../ws/upgrade.js";
3
3
  import { isRpcTarget, isWorkerEntrypoint } from "./durable-object.js";
4
4
  /** Key of the isolate's class factory on a module facade (see getDurableObjectClass). */
5
5
  export const ISOLATED = Symbol.for("cellb.isolated-classes");
6
+ /**
7
+ * On a loaded Worker's module whose isolate can end (`abortIsolate`): registers what to do when
8
+ * it does (the Worker Loader forgets the module, so the next `get()` loads the code again).
9
+ */
10
+ export const ON_ABORT = Symbol.for("cellb.on-abort");
6
11
  export function classHandle(resolve) {
7
12
  return { __cellsClassHandle: true, resolve };
8
13
  }
@@ -17,12 +22,31 @@ export const STUB = Symbol.for("cellb.stub");
17
22
  export const REFUSE = Symbol.for("cellb.refuse");
18
23
  /** Answered by a `ctx.exports.X({ props })` stub or class handle: `{ name, props }` (storable). */
19
24
  export const EXPORT = Symbol.for("cellb.export");
25
+ // The realm's own classes (Worker code may see subclasses of them as its globals).
26
+ const NativeRequest = globalThis.Request;
27
+ const NativeResponse = globalThis.Response;
28
+ const NativeHeaders = globalThis.Headers;
29
+ const NativeReadableStream = globalThis.ReadableStream;
30
+ /**
31
+ * A copy of `v` for a call in one realm, as workerd's RPC makes it: a Request, Response or
32
+ * ReadableStream is passed itself (its body moves with it), Headers are copied, and anything
33
+ * else is structured-cloned.
34
+ */
35
+ export function copyInRealm(v) {
36
+ if (v instanceof NativeHeaders)
37
+ return new Headers(v);
38
+ if (v instanceof NativeRequest ||
39
+ v instanceof NativeResponse ||
40
+ v instanceof NativeReadableStream)
41
+ return v;
42
+ return structuredClone(v);
43
+ }
20
44
  /**
21
45
  * What crosses a stub, as in workerd: functions, `RpcTarget`s, stubs and class handles by
22
46
  * reference (`ref` says what stands for one on the far side; in one realm, the value itself),
23
- * arrays and plain objects walked, anything else structured-cloned (`copy`).
47
+ * arrays and plain objects walked, anything else copied (`copy`; in one realm, `copyInRealm`).
24
48
  */
25
- export function cross(v, ref = (x) => x, copy = structuredClone) {
49
+ export function cross(v, ref = (x) => x, copy = copyInRealm) {
26
50
  if (v === undefined || v === null || (typeof v !== "object" && typeof v !== "function"))
27
51
  return copy(v);
28
52
  const refused = v[REFUSE];
@@ -117,12 +141,15 @@ export function pipeTo(r, path, args) {
117
141
  * `call` returns.
118
142
  */
119
143
  export function asyncStub(call, fetch) {
120
- return new Proxy({}, {
144
+ const stub = new Proxy({}, {
121
145
  get(_t, prop) {
122
146
  if (prop === STUB)
123
147
  return true;
124
148
  if (prop === "then" || typeof prop === "symbol")
125
149
  return undefined;
150
+ // workerd's `stub.dup()`: in one realm, a stub holds nothing to release, so it is itself.
151
+ if (prop === "dup")
152
+ return () => stub;
126
153
  if (prop === "fetch")
127
154
  return (input, init) => {
128
155
  const req = new Request(input, init);
@@ -138,6 +165,7 @@ export function asyncStub(call, fetch) {
138
165
  return (...args) => rpcCall(() => call(String(prop), cross(args)), cross);
139
166
  },
140
167
  });
168
+ return stub;
141
169
  }
142
170
  /**
143
171
  * A stub of a WorkerEntrypoint (or a default export object): a fresh instance per call,
@@ -177,6 +205,24 @@ export function entrypointStub(target, env, props, exports) {
177
205
  : instance.fetch(req, env, objectCtx());
178
206
  });
179
207
  }
208
+ /**
209
+ * The default export's handler for one event (`fetch`, `scheduled`, `queue`), or `undefined`.
210
+ * An object's method is called with `(arg, env, ctx)`. A class (`export default class extends
211
+ * WorkerEntrypoint`) gets a fresh instance per event, built with `(ctx, env)` (`ctx.props` empty),
212
+ * and its method is called with the event's argument alone, as on workerd.
213
+ */
214
+ export function defaultHandler(def, name) {
215
+ if (typeof def === "function") {
216
+ if (typeof def.prototype?.[name] !== "function")
217
+ return undefined;
218
+ const Entry = def;
219
+ return (arg, env, ctx) => new Entry({ ...ctx, props: ctx.props ?? {} }, env)[name](arg);
220
+ }
221
+ const method = def?.[name];
222
+ if (typeof method !== "function")
223
+ return undefined;
224
+ return (arg, env, ctx) => method.call(def, arg, env, ctx);
225
+ }
180
226
  /** workerd's refusal of `ctx.exports.<Entrypoint>` passed on without `({ props })`. */
181
227
  const LOOPBACK = 'Could not serialize object of type "LoopbackServiceStub". This type does not support serialization.';
182
228
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"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AAC,IAAI,EAAE,KAAK,CAAC,GAAG,WAAW,CAAC,KAAK,EAAE,IAAI,CAAsB,CAAC;YACpE,OAAQ,OAAO,CAAC,IAAI,CAAwC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAC1E,CAAC;KACF,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { deserialize, type HostObjects, serialize } from \"../v8/serialize.js\";\nimport { carryWebSocketHeaders } from \"../ws/upgrade.js\";\nimport { isRpcTarget, isWorkerEntrypoint } from \"./durable-object.js\";\nimport type { DurableObjectState } from \"./state.js\";\n\nexport type DurableObjectClass = new (ctx: DurableObjectState, env: any) => any;\n\n/**\n * A class handle — what `worker.getDurableObjectClass(name)` (Worker Loader) and\n * `ctx.exports.App` return, and what `ctx.facets.get(name, () => ({ class }))` accepts.\n * Resolution may be asynchronous (loaded code is compiled on first use).\n */\nexport interface ClassHandle {\n readonly __cellsClassHandle: true;\n resolve(): Promise<\n { cls: DurableObjectClass; env: unknown; props?: unknown } | { isolated: IsolatedClass }\n >;\n}\n\n/** Key of the isolate's class factory on a module facade (see getDurableObjectClass). */\nexport const ISOLATED = Symbol.for(\"cellb.isolated-classes\");\n\n/** A Durable Object class that runs in an isolate: its instances and storage live there. */\nexport interface IsolatedClass {\n fetch(cellKey: string, req: Request): Promise<Response>;\n call(cellKey: string, method: string, args: unknown[]): Promise<unknown>;\n restart(cellKey: string): Promise<void>;\n delete(cellKey: string): Promise<void>;\n /**\n * Tells the isolate which root epoch the facet's log is written under, and the name of the\n * `id` given to `ctx.facets.get` (the facet's `ctx.id.name`; none: the facet's cell key).\n */\n attach?(cellKey: string, epoch?: number, idName?: string): Promise<void>;\n}\n\nexport function classHandle(resolve: ClassHandle[\"resolve\"]): ClassHandle {\n return { __cellsClassHandle: true, resolve };\n}\n\nexport function isClassHandle(v: unknown): v is ClassHandle {\n return (\n !!v &&\n (typeof v === \"object\" || typeof v === \"function\") &&\n (v as ClassHandle).__cellsClassHandle === true\n );\n}\n\n/** Answered `true` by cellb's stubs: they cross by reference. */\nexport const STUB = Symbol.for(\"cellb.stub\");\n/** Answered by a value that may not cross, with workerd's reason. */\nexport const REFUSE = Symbol.for(\"cellb.refuse\");\n/** Answered by a `ctx.exports.X({ props })` stub or class handle: `{ name, props }` (storable). */\nexport const EXPORT = Symbol.for(\"cellb.export\");\n\n/**\n * What crosses a stub, as in workerd: functions, `RpcTarget`s, stubs and class handles by\n * reference (`ref` says what stands for one on the far side; in one realm, the value itself),\n * arrays and plain objects walked, anything else structured-cloned (`copy`).\n */\nexport function cross<T>(\n v: T,\n ref: (v: object) => unknown = (x) => x,\n copy: (v: unknown) => unknown = structuredClone,\n): T {\n if (v === undefined || v === null || (typeof v !== \"object\" && typeof v !== \"function\"))\n return copy(v) as T;\n const refused = (v as Record<symbol, unknown>)[REFUSE];\n if (typeof refused === \"string\") throw new DOMException(refused, \"DataCloneError\");\n if (\n typeof v === \"function\" ||\n isRpcTarget(v) ||\n (v as Record<symbol, unknown>)[STUB] === true ||\n isClassHandle(v)\n )\n return ref(v) as T;\n if (Array.isArray(v)) return v.map((x) => cross(x, ref, copy)) as T;\n if (Object.getPrototypeOf(v) === Object.prototype) {\n const out: Record<string, unknown> = {};\n for (const [k, x] of Object.entries(v)) out[k] = cross(x, ref, copy);\n return out as T;\n }\n return copy(v) as T;\n}\n\n/**\n * A value sent to an object on another node (cells-http, celld's tunnel), checked first: only\n * copies travel between nodes, so a function, `RpcTarget` or stub is refused, not sent as `{}`.\n */\nexport function toAnotherNode<T>(v: T): T {\n cross(\n v,\n () => {\n const e = new DOMException(\n \"Functions, RpcTargets and stubs cannot be sent to another node: they pass by reference only within one runtime.\",\n \"DataCloneError\",\n );\n // An own `name`, so it survives the error's trip back over the link.\n throw Object.defineProperty(e, \"name\", { value: e.name, enumerable: true });\n },\n (x) => x,\n );\n return v;\n}\n\n/** Where a call on an RpcPromise goes: the property path from its result, and the arguments. */\nexport type Pipe = (path: string[], args: unknown[]) => unknown;\n\nconst RPC_PROMISE = Symbol(\"cellb.rpc-promise\");\n\n/**\n * workerd's RpcPromise: what a call on a stub returns. It is awaited as a promise, and used\n * before it settles (promise pipelining): a property read gives the RpcPromise of that path,\n * and a call on a path goes through `pipe` at once, without waiting for `result`.\n */\nexport function rpcPromise(result: Promise<unknown>, pipe: Pipe): any {\n const at = (path: string[]): any => {\n let value: Promise<unknown> | undefined;\n // The result itself is a Promise-like object, not callable (node:assert calls a function\n // given to `rejects`); a property path is callable.\n return new Proxy(path.length ? () => {} : Object.create(Promise.prototype), {\n apply: (_t, _this, args) => rpcCall(() => pipe(path, args)),\n get(_t, prop) {\n if (prop === RPC_PROMISE) return true;\n if (prop === \"then\" || prop === \"catch\" || prop === \"finally\") {\n value ??= result.then((v) => path.reduce((o: any, k) => o[k], v));\n return value[prop].bind(value);\n }\n if (typeof prop === \"symbol\") return undefined;\n return at([...path, prop]);\n },\n });\n };\n return at([]);\n}\n\n/**\n * Runs a call and returns its result as an RpcPromise (`map` applies to the settled value);\n * calls on it go to the result: at once if the result is an RpcPromise itself, else once it\n * settles.\n */\nexport function rpcCall(call: () => unknown, map?: (v: unknown) => unknown): any {\n let r: unknown;\n try {\n r = call();\n } catch (e) {\n r = Promise.reject(e);\n }\n const result = Promise.resolve(r);\n return rpcPromise(map ? result.then(map) : result, (path, args) => pipeTo(r, path, args));\n}\n\n/** Calls `path` of `r` (a value, a promise of one, or an RpcPromise) with `args`. */\nexport function pipeTo(r: unknown, path: string[], args: unknown[]): unknown {\n const callAt = (v: any) => {\n if (!path.length) return v(...args);\n const receiver = path.slice(0, -1).reduce((o, k) => o[k], v);\n return receiver[path[path.length - 1]](...args);\n };\n return (r as Record<symbol, unknown>)?.[RPC_PROMISE]\n ? callAt(r)\n : Promise.resolve(r).then(callAt);\n}\n\n/**\n * A stub over an asynchronously obtained target: `fetch` and JS-RPC methods, arguments\n * and results crossing as between isolates. A method's result is an RpcPromise over what\n * `call` returns.\n */\nexport function asyncStub(\n call: (method: string, args: unknown[]) => unknown,\n fetch: (req: Request) => Promise<Response>,\n): Record<string, any> {\n return new Proxy(\n {},\n {\n get(_t, prop) {\n if (prop === STUB) return true;\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n if (prop === \"fetch\")\n return (input: RequestInfo | URL, init?: RequestInit) => {\n const req = new Request(input as RequestInfo, init);\n // A browser drops `Upgrade` and `Sec-WebSocket-*` from the copy: carried over, so a\n // WebSocket reaches a facet (partyserver forwards its upgrade request as it is).\n const from =\n init?.headers !== undefined\n ? new Headers(init.headers)\n : input instanceof Request\n ? input.headers\n : undefined;\n return fetch(from ? carryWebSocketHeaders(from, req) : req);\n };\n return (...args: unknown[]) => rpcCall(() => call(String(prop), cross(args)), cross);\n },\n },\n );\n}\n\n/**\n * A stub of a WorkerEntrypoint (or a default export object): a fresh instance per call,\n * as workerd creates one per request; `ctx.props` carries copied startup properties. Methods\n * of a plain object receive `(…args, env, ctx)`, as its `fetch` receives `(request, env, ctx)`.\n */\nexport function entrypointStub(\n target: unknown,\n env: unknown,\n props: unknown,\n exports?: unknown,\n): Record<string, any> {\n const objectCtx = () => ({\n waitUntil() {},\n passThroughOnException() {},\n props: cross(props ?? {}),\n });\n const make = () => {\n if (typeof target === \"function\") {\n const ctx = {\n props: cross(props ?? {}),\n exports,\n waitUntil() {},\n passThroughOnException() {},\n };\n return new (target as new (c: unknown, e: unknown) => any)(ctx, env);\n }\n return target as any;\n };\n return asyncStub(\n (method, args) => {\n const instance = make();\n const fn = instance?.[method];\n if (typeof fn !== \"function\")\n throw new TypeError(`The RPC receiver does not implement the method \"${method}\".`);\n return fn.apply(instance, typeof target === \"function\" ? args : [...args, env, objectCtx()]);\n },\n async (req) => {\n const instance = make();\n if (typeof instance?.fetch !== \"function\")\n throw new Error(\"Handler does not export a fetch() function.\");\n return typeof target === \"function\"\n ? instance.fetch(req)\n : instance.fetch(req, env, objectCtx());\n },\n );\n}\n\n/** workerd's refusal of `ctx.exports.<Entrypoint>` passed on without `({ props })`. */\nconst LOOPBACK =\n 'Could not serialize object of type \"LoopbackServiceStub\". This type does not support serialization.';\n\n/**\n * `ctx.exports`: loopback handles of a Worker's named exports. An entrypoint's (a\n * WorkerEntrypoint class, or an object with methods) is a stub (`ctx.exports.Greeter.greet()`),\n * and called with `{ props }` gives one with props; a Durable Object class's is a facet class\n * handle, also callable with `{ props }`.\n */\nexport function ctxExports(worker: Record<string, unknown>, env: unknown): Record<string, unknown> {\n const exports: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(worker)) {\n if (name === \"default\" || !value || (typeof value !== \"function\" && typeof value !== \"object\"))\n continue;\n if (typeof value === \"object\" || isWorkerEntrypoint(value)) {\n const withProps = (o: { props?: unknown } = {}) => {\n const stub = entrypointStub(value, env, o.props, exports);\n return new Proxy(stub, {\n get: (t, prop) => (prop === EXPORT ? { name, props: o.props } : t[prop as string]),\n });\n };\n const stub = withProps();\n exports[name] = new Proxy(withProps, {\n get: (_t, prop) => (prop === REFUSE ? LOOPBACK : stub[prop as string]),\n });\n } else {\n const handle = (o: { props?: unknown } = {}) =>\n Object.assign(\n classHandle(async () => ({ cls: value as DurableObjectClass, env, props: o.props })),\n { [EXPORT]: { name, props: o.props } },\n );\n exports[name] = Object.assign(\n handle,\n classHandle(async () => ({ cls: value as DurableObjectClass, env })),\n );\n }\n }\n return exports;\n}\n\n/**\n * Stubs in Durable Object storage (workerd's `allow_irrevocable_stub_storage`), as V8 host\n * objects: a `ctx.exports.X({ props })` stub or class handle is stored as `[name, props]` and\n * read back as `ctx.exports[name]({ props })`. Other stubs and `RpcTarget`s are refused rather\n * than stored as `{}`.\n */\nexport function storedExports(exports: Record<string, unknown>): HostObjects {\n const host: HostObjects = {\n encode(v) {\n const e = (v as Record<symbol, { name: string; props: unknown } | undefined>)[EXPORT];\n if (e) return serialize([e.name, e.props], host);\n if ((v as Record<symbol, unknown>)[STUB] === true || isRpcTarget(v))\n throw new DOMException(\n \"Only ctx.exports.<name>({ props }) stubs and class handles can be stored.\",\n \"DataCloneError\",\n );\n return undefined;\n },\n decode(bytes) {\n const [name, props] = deserialize(bytes, host) as [string, unknown];\n return (exports[name] as (o: { props: unknown }) => unknown)({ props });\n },\n };\n return host;\n}\n"]}
1
+ {"version":3,"file":"handles.js","sourceRoot":"","sources":["../../src/core/handles.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAoB,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC9E,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAiBtE,yFAAyF;AACzF,MAAM,CAAC,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;AAC7D;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;AAerD,MAAM,UAAU,WAAW,CAAC,OAA+B;IACzD,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AAC/C,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,CAAU;IACtC,OAAO,CACL,CAAC,CAAC,CAAC;QACH,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,UAAU,CAAC;QACjD,CAAiB,CAAC,kBAAkB,KAAK,IAAI,CAC/C,CAAC;AACJ,CAAC;AAED,iEAAiE;AACjE,MAAM,CAAC,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;AAC7C,qEAAqE;AACrE,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AACjD,mGAAmG;AACnG,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AAEjD,mFAAmF;AACnF,MAAM,aAAa,GAAG,UAAU,CAAC,OAA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AC;YACN,MAAM,CAAC,GAAI,CAAkE,CAAC,MAAM,CAAC,CAAC;YACtF,IAAI,CAAC;gBAAE,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,CAAC;YACjD,IAAK,CAA6B,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,WAAW,CAAC,CAAC,CAAC;gBACjE,MAAM,IAAI,YAAY,CACpB,2EAA2E,EAC3E,gBAAgB,CACjB,CAAC;YACJ,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,MAAM,CAAC,KAAK;YACV,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,WAAW,CAAC,KAAK,EAAE,IAAI,CAAsB,CAAC;YACpE,OAAQ,OAAO,CAAC,IAAI,CAAwC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAC1E,CAAC;KACF,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { deserialize, type HostObjects, serialize } from \"../v8/serialize.js\";\nimport { carryWebSocketHeaders } from \"../ws/upgrade.js\";\nimport { isRpcTarget, isWorkerEntrypoint } from \"./durable-object.js\";\nimport type { DurableObjectState } from \"./state.js\";\n\nexport type DurableObjectClass = new (ctx: DurableObjectState, env: any) => any;\n\n/**\n * A class handle — what `worker.getDurableObjectClass(name)` (Worker Loader) and\n * `ctx.exports.App` return, and what `ctx.facets.get(name, () => ({ class }))` accepts.\n * Resolution may be asynchronous (loaded code is compiled on first use).\n */\nexport interface ClassHandle {\n readonly __cellsClassHandle: true;\n resolve(): Promise<\n { cls: DurableObjectClass; env: unknown; props?: unknown } | { isolated: IsolatedClass }\n >;\n}\n\n/** Key of the isolate's class factory on a module facade (see getDurableObjectClass). */\nexport const ISOLATED = Symbol.for(\"cellb.isolated-classes\");\n/**\n * On a loaded Worker's module whose isolate can end (`abortIsolate`): registers what to do when\n * it does (the Worker Loader forgets the module, so the next `get()` loads the code again).\n */\nexport const ON_ABORT = Symbol.for(\"cellb.on-abort\");\n\n/** A Durable Object class that runs in an isolate: its instances and storage live there. */\nexport interface IsolatedClass {\n fetch(cellKey: string, req: Request): Promise<Response>;\n call(cellKey: string, method: string, args: unknown[]): Promise<unknown>;\n restart(cellKey: string): Promise<void>;\n delete(cellKey: string): Promise<void>;\n /**\n * Tells the isolate which root epoch the facet's log is written under, and the name of the\n * `id` given to `ctx.facets.get` (the facet's `ctx.id.name`; none: the facet's cell key).\n */\n attach?(cellKey: string, epoch?: number, idName?: string): Promise<void>;\n}\n\nexport function classHandle(resolve: ClassHandle[\"resolve\"]): ClassHandle {\n return { __cellsClassHandle: true, resolve };\n}\n\nexport function isClassHandle(v: unknown): v is ClassHandle {\n return (\n !!v &&\n (typeof v === \"object\" || typeof v === \"function\") &&\n (v as ClassHandle).__cellsClassHandle === true\n );\n}\n\n/** Answered `true` by cellb's stubs: they cross by reference. */\nexport const STUB = Symbol.for(\"cellb.stub\");\n/** Answered by a value that may not cross, with workerd's reason. */\nexport const REFUSE = Symbol.for(\"cellb.refuse\");\n/** Answered by a `ctx.exports.X({ props })` stub or class handle: `{ name, props }` (storable). */\nexport const EXPORT = Symbol.for(\"cellb.export\");\n\n// The realm's own classes (Worker code may see subclasses of them as its globals).\nconst NativeRequest = globalThis.Request;\nconst NativeResponse = globalThis.Response;\nconst NativeHeaders = globalThis.Headers;\nconst NativeReadableStream = globalThis.ReadableStream;\n\n/**\n * A copy of `v` for a call in one realm, as workerd's RPC makes it: a Request, Response or\n * ReadableStream is passed itself (its body moves with it), Headers are copied, and anything\n * else is structured-cloned.\n */\nexport function copyInRealm(v: unknown): unknown {\n if (v instanceof NativeHeaders) return new Headers(v);\n if (\n v instanceof NativeRequest ||\n v instanceof NativeResponse ||\n v instanceof NativeReadableStream\n )\n return v;\n return structuredClone(v);\n}\n\n/**\n * What crosses a stub, as in workerd: functions, `RpcTarget`s, stubs and class handles by\n * reference (`ref` says what stands for one on the far side; in one realm, the value itself),\n * arrays and plain objects walked, anything else copied (`copy`; in one realm, `copyInRealm`).\n */\nexport function cross<T>(\n v: T,\n ref: (v: object) => unknown = (x) => x,\n copy: (v: unknown) => unknown = copyInRealm,\n): T {\n if (v === undefined || v === null || (typeof v !== \"object\" && typeof v !== \"function\"))\n return copy(v) as T;\n const refused = (v as Record<symbol, unknown>)[REFUSE];\n if (typeof refused === \"string\") throw new DOMException(refused, \"DataCloneError\");\n if (\n typeof v === \"function\" ||\n isRpcTarget(v) ||\n (v as Record<symbol, unknown>)[STUB] === true ||\n isClassHandle(v)\n )\n return ref(v) as T;\n if (Array.isArray(v)) return v.map((x) => cross(x, ref, copy)) as T;\n if (Object.getPrototypeOf(v) === Object.prototype) {\n const out: Record<string, unknown> = {};\n for (const [k, x] of Object.entries(v)) out[k] = cross(x, ref, copy);\n return out as T;\n }\n return copy(v) as T;\n}\n\n/**\n * A value sent to an object on another node (cells-http, celld's tunnel), checked first: only\n * copies travel between nodes, so a function, `RpcTarget` or stub is refused, not sent as `{}`.\n */\nexport function toAnotherNode<T>(v: T): T {\n cross(\n v,\n () => {\n const e = new DOMException(\n \"Functions, RpcTargets and stubs cannot be sent to another node: they pass by reference only within one runtime.\",\n \"DataCloneError\",\n );\n // An own `name`, so it survives the error's trip back over the link.\n throw Object.defineProperty(e, \"name\", { value: e.name, enumerable: true });\n },\n (x) => x,\n );\n return v;\n}\n\n/** Where a call on an RpcPromise goes: the property path from its result, and the arguments. */\nexport type Pipe = (path: string[], args: unknown[]) => unknown;\n\nconst RPC_PROMISE = Symbol(\"cellb.rpc-promise\");\n\n/**\n * workerd's RpcPromise: what a call on a stub returns. It is awaited as a promise, and used\n * before it settles (promise pipelining): a property read gives the RpcPromise of that path,\n * and a call on a path goes through `pipe` at once, without waiting for `result`.\n */\nexport function rpcPromise(result: Promise<unknown>, pipe: Pipe): any {\n const at = (path: string[]): any => {\n let value: Promise<unknown> | undefined;\n // The result itself is a Promise-like object, not callable (node:assert calls a function\n // given to `rejects`); a property path is callable.\n return new Proxy(path.length ? () => {} : Object.create(Promise.prototype), {\n apply: (_t, _this, args) => rpcCall(() => pipe(path, args)),\n get(_t, prop) {\n if (prop === RPC_PROMISE) return true;\n if (prop === \"then\" || prop === \"catch\" || prop === \"finally\") {\n value ??= result.then((v) => path.reduce((o: any, k) => o[k], v));\n return value[prop].bind(value);\n }\n if (typeof prop === \"symbol\") return undefined;\n return at([...path, prop]);\n },\n });\n };\n return at([]);\n}\n\n/**\n * Runs a call and returns its result as an RpcPromise (`map` applies to the settled value);\n * calls on it go to the result: at once if the result is an RpcPromise itself, else once it\n * settles.\n */\nexport function rpcCall(call: () => unknown, map?: (v: unknown) => unknown): any {\n let r: unknown;\n try {\n r = call();\n } catch (e) {\n r = Promise.reject(e);\n }\n const result = Promise.resolve(r);\n return rpcPromise(map ? result.then(map) : result, (path, args) => pipeTo(r, path, args));\n}\n\n/** Calls `path` of `r` (a value, a promise of one, or an RpcPromise) with `args`. */\nexport function pipeTo(r: unknown, path: string[], args: unknown[]): unknown {\n const callAt = (v: any) => {\n if (!path.length) return v(...args);\n const receiver = path.slice(0, -1).reduce((o, k) => o[k], v);\n return receiver[path[path.length - 1]](...args);\n };\n return (r as Record<symbol, unknown>)?.[RPC_PROMISE]\n ? callAt(r)\n : Promise.resolve(r).then(callAt);\n}\n\n/**\n * A stub over an asynchronously obtained target: `fetch` and JS-RPC methods, arguments\n * and results crossing as between isolates. A method's result is an RpcPromise over what\n * `call` returns.\n */\nexport function asyncStub(\n call: (method: string, args: unknown[]) => unknown,\n fetch: (req: Request) => Promise<Response>,\n): Record<string, any> {\n const stub: Record<string, any> = new Proxy(\n {},\n {\n get(_t, prop) {\n if (prop === STUB) return true;\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n // workerd's `stub.dup()`: in one realm, a stub holds nothing to release, so it is itself.\n if (prop === \"dup\") return () => stub;\n if (prop === \"fetch\")\n return (input: RequestInfo | URL, init?: RequestInit) => {\n const req = new Request(input as RequestInfo, init);\n // A browser drops `Upgrade` and `Sec-WebSocket-*` from the copy: carried over, so a\n // WebSocket reaches a facet (partyserver forwards its upgrade request as it is).\n const from =\n init?.headers !== undefined\n ? new Headers(init.headers)\n : input instanceof Request\n ? input.headers\n : undefined;\n return fetch(from ? carryWebSocketHeaders(from, req) : req);\n };\n return (...args: unknown[]) => rpcCall(() => call(String(prop), cross(args)), cross);\n },\n },\n );\n return stub;\n}\n\n/**\n * A stub of a WorkerEntrypoint (or a default export object): a fresh instance per call,\n * as workerd creates one per request; `ctx.props` carries copied startup properties. Methods\n * of a plain object receive `(…args, env, ctx)`, as its `fetch` receives `(request, env, ctx)`.\n */\nexport function entrypointStub(\n target: unknown,\n env: unknown,\n props: unknown,\n exports?: unknown,\n): Record<string, any> {\n const objectCtx = () => ({\n waitUntil() {},\n passThroughOnException() {},\n props: cross(props ?? {}),\n });\n const make = () => {\n if (typeof target === \"function\") {\n const ctx = {\n props: cross(props ?? {}),\n exports,\n waitUntil() {},\n passThroughOnException() {},\n };\n return new (target as new (c: unknown, e: unknown) => any)(ctx, env);\n }\n return target as any;\n };\n return asyncStub(\n (method, args) => {\n const instance = make();\n const fn = instance?.[method];\n if (typeof fn !== \"function\")\n throw new TypeError(`The RPC receiver does not implement the method \"${method}\".`);\n return fn.apply(instance, typeof target === \"function\" ? args : [...args, env, objectCtx()]);\n },\n async (req) => {\n const instance = make();\n if (typeof instance?.fetch !== \"function\")\n throw new Error(\"Handler does not export a fetch() function.\");\n return typeof target === \"function\"\n ? instance.fetch(req)\n : instance.fetch(req, env, objectCtx());\n },\n );\n}\n\n/** An event handler of a Worker's default export: `fetch(request, env, ctx)` and the like. */\nexport type DefaultHandler = (arg: unknown, env: unknown, ctx: object) => unknown;\n\n/**\n * The default export's handler for one event (`fetch`, `scheduled`, `queue`), or `undefined`.\n * An object's method is called with `(arg, env, ctx)`. A class (`export default class extends\n * WorkerEntrypoint`) gets a fresh instance per event, built with `(ctx, env)` (`ctx.props` empty),\n * and its method is called with the event's argument alone, as on workerd.\n */\nexport function defaultHandler(def: unknown, name: string): DefaultHandler | undefined {\n if (typeof def === \"function\") {\n if (typeof def.prototype?.[name] !== \"function\") return undefined;\n const Entry = def as new (ctx: object, env: unknown) => Record<string, (a: unknown) => unknown>;\n return (arg, env, ctx) =>\n new Entry({ ...ctx, props: (ctx as { props?: unknown }).props ?? {} }, env)[name](arg);\n }\n const method = (def as Record<string, unknown> | null | undefined)?.[name];\n if (typeof method !== \"function\") return undefined;\n return (arg, env, ctx) => method.call(def, arg, env, ctx);\n}\n\n/** workerd's refusal of `ctx.exports.<Entrypoint>` passed on without `({ props })`. */\nconst LOOPBACK =\n 'Could not serialize object of type \"LoopbackServiceStub\". This type does not support serialization.';\n\n/**\n * `ctx.exports`: loopback handles of a Worker's named exports. An entrypoint's (a\n * WorkerEntrypoint class, or an object with methods) is a stub (`ctx.exports.Greeter.greet()`),\n * and called with `{ props }` gives one with props; a Durable Object class's is a facet class\n * handle, also callable with `{ props }`.\n */\nexport function ctxExports(worker: Record<string, unknown>, env: unknown): Record<string, unknown> {\n const exports: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(worker)) {\n if (name === \"default\" || !value || (typeof value !== \"function\" && typeof value !== \"object\"))\n continue;\n if (typeof value === \"object\" || isWorkerEntrypoint(value)) {\n const withProps = (o: { props?: unknown } = {}) => {\n const stub = entrypointStub(value, env, o.props, exports);\n return new Proxy(stub, {\n get: (t, prop) => (prop === EXPORT ? { name, props: o.props } : t[prop as string]),\n });\n };\n const stub = withProps();\n exports[name] = new Proxy(withProps, {\n get: (_t, prop) => (prop === REFUSE ? LOOPBACK : stub[prop as string]),\n });\n } else {\n const handle = (o: { props?: unknown } = {}) =>\n Object.assign(\n classHandle(async () => ({ cls: value as DurableObjectClass, env, props: o.props })),\n { [EXPORT]: { name, props: o.props } },\n );\n exports[name] = Object.assign(\n handle,\n classHandle(async () => ({ cls: value as DurableObjectClass, env })),\n );\n }\n }\n return exports;\n}\n\n/**\n * Stubs in Durable Object storage (workerd's `allow_irrevocable_stub_storage`), as V8 host\n * objects: a `ctx.exports.X({ props })` stub or class handle is stored as `[name, props]` and\n * read back as `ctx.exports[name]({ props })`. Other stubs and `RpcTarget`s are refused rather\n * than stored as `{}`.\n */\nexport function storedExports(exports: Record<string, unknown>): HostObjects {\n const host: HostObjects = {\n encode(v) {\n const e = (v as Record<symbol, { name: string; props: unknown } | undefined>)[EXPORT];\n if (e) return serialize([e.name, e.props], host);\n if ((v as Record<symbol, unknown>)[STUB] === true || isRpcTarget(v))\n throw new DOMException(\n \"Only ctx.exports.<name>({ props }) stubs and class handles can be stored.\",\n \"DataCloneError\",\n );\n return undefined;\n },\n decode(bytes) {\n const [name, props] = deserialize(bytes, host) as [string, unknown];\n return (exports[name] as (o: { props: unknown }) => unknown)({ props });\n },\n };\n return host;\n}\n"]}
@@ -129,7 +129,7 @@ function createStub(id, endpoint) {
129
129
  return endpoint().fetch(source ? carryWebSocketHeaders(source, req) : req);
130
130
  },
131
131
  });
132
- return new Proxy(target, {
132
+ const stub = new Proxy(target, {
133
133
  get(t, prop, recv) {
134
134
  if (prop in t)
135
135
  return Reflect.get(t, prop, recv);
@@ -138,5 +138,8 @@ function createStub(id, endpoint) {
138
138
  return (...args) => rpcCall(() => endpoint().call(String(prop), args));
139
139
  },
140
140
  });
141
+ // workerd's `stub.dup()`: a Durable Object stub holds nothing to release, so it is itself.
142
+ Object.defineProperty(target, "dup", { value: () => stub });
143
+ return stub;
141
144
  }
142
145
  //# sourceMappingURL=namespace.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"namespace.js","sourceRoot":"","sources":["../../src/core/namespace.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAwB,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACpF,OAAO,EAAE,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AAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC7E,CAAC;KACF,CAAC,CAAC;IACH,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI;YACf,IAAI,IAAI,IAAI,CAAC;gBAAE,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;YACjD,IAAI,IAAI,KAAK,MAAM,IAAI,OAAO,IAAI,KAAK,QAAQ;gBAAE,OAAO,SAAS,CAAC;YAClE,OAAO,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;QACpF,CAAC;KACF,CAAiC,CAAC;AACrC,CAAC","sourcesContent":["import { carryWebSocketHeaders } from \"../ws/upgrade.js\";\nimport { cross, rpcCall, STUB } from \"./handles.js\";\nimport { type DurableObjectId, idFromName, newUniqueId, validateId } from \"./id.js\";\nimport { closingWith, type ObjectHost } from \"./object-host.js\";\nimport type { DurableObjectState } from \"./state.js\";\n\n/** What a stub talks to: a local ObjectHost or a remote cell host behind a port. */\nexport interface ObjectEndpoint {\n fetch(req: Request): Promise<Response>;\n call(method: string, args: unknown[]): Promise<unknown>;\n /** Present only for in-process objects (enables runInDurableObject). */\n local?: ObjectHost;\n}\n\n/**\n * An in-process object. `ready` (for a cell not open yet): a promise its first events await\n * before the host opens the cell's database (its store is making room), or undefined.\n */\nexport function localEndpoint(\n host: () => ObjectHost,\n ready?: () => Promise<void> | undefined,\n): () => ObjectEndpoint {\n return () => {\n const wait = ready?.();\n if (!wait) return endpointOf(host());\n return {\n get local() {\n return host();\n },\n fetch: async (req) => {\n await wait;\n return endpointOf(host()).fetch(req);\n },\n call: async (method, args) => {\n const copied = cross(args); // the arguments as they are now, as for an open cell\n await wait;\n return deliverCall(host(), method, copied);\n },\n };\n };\n}\n\nfunction endpointOf(h: ObjectHost): ObjectEndpoint {\n return {\n local: h,\n fetch: (req) =>\n h.deliver(async (obj) => {\n if (typeof obj.fetch !== \"function\")\n throw new Error(\"Handler does not export a fetch() function.\");\n let res: Response;\n try {\n const r = await obj.fetch(closingWith(req, h.closing));\n res = r instanceof Response ? r : new Response(String(r)); // a non-Response is sent as text (celld)\n } catch (e) {\n // celld: the stub's fetch() rejects with \"rejected: <name>: <message> [at …]\".\n const err = e as Error;\n throw new Error(`rejected: ${err?.name ?? \"Error\"}: ${err?.message ?? String(e)}`, {\n cause: e,\n });\n }\n // A WebSocket answer to a request that did not ask for one fails (workerd, celld):\n // the stub rejects and the server end sees an abnormal close.\n const ws = (res as { webSocket?: unknown }).webSocket;\n if (res.status === 101 && ws && req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\")\n throw new Error(\n \"rejected: Error: a WebSocket response to a request without Upgrade: websocket\",\n );\n return res;\n }),\n call: async (method, args) => deliverCall(h, method, cross(args)),\n };\n}\n\nasync function deliverCall(h: ObjectHost, method: string, copied: unknown[]): Promise<unknown> {\n const r = await h.deliver((obj) => {\n const m = obj[method];\n if (typeof m !== \"function\") throw new TypeError(`${method} is not a function`); // celld's wording\n return m.apply(obj, copied);\n });\n return cross(r);\n}\n\nexport class DurableObjectNamespace {\n readonly #key: string;\n readonly #endpoint: (id: DurableObjectId) => () => ObjectEndpoint;\n\n constructor(namespaceKey: string, endpoint: (id: DurableObjectId) => () => ObjectEndpoint) {\n this.#key = namespaceKey;\n this.#endpoint = endpoint;\n }\n idFromName(name: string): DurableObjectId {\n return idFromName(this.#key, name);\n }\n newUniqueId(opts?: { jurisdiction?: string }): DurableObjectId {\n if (opts?.jurisdiction != null)\n throw new Error(\"Jurisdiction restrictions are not implemented\");\n return newUniqueId(this.#key);\n }\n idFromString(hex: string): DurableObjectId {\n return validateId(this.#key, hex);\n }\n /** The key ids of this namespace derive from (see id.ts). */\n get namespaceKey(): string {\n return this.#key;\n }\n get(id: DurableObjectId): DurableObjectStub {\n return createStub(id, this.#endpoint(id));\n }\n getByName(name: string): DurableObjectStub {\n return this.get(this.idFromName(name));\n }\n}\n\nexport type DurableObjectStub = {\n readonly id: DurableObjectId;\n readonly name?: string;\n fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;\n} & Record<string, any>;\n\nconst kEndpoint = Symbol(\"cellb.endpoint\");\n\n/**\n * Test hook (same idea as vitest-pool-workers' runInDurableObject): runs `fn`\n * inside a LOCAL object, through the input/output gates, without cloning `fn`.\n */\nexport function runInDurableObject<T>(\n stub: DurableObjectStub,\n fn: (instance: any, state: DurableObjectState) => T | Promise<T>,\n): Promise<T> {\n const ep = (stub as any)[kEndpoint] as (() => ObjectEndpoint) | undefined;\n const local = ep?.().local;\n if (!local) throw new TypeError(\"runInDurableObject needs a stub of an in-process cellb object\");\n return local.deliver(fn);\n}\n\n/** Stub = Proxy: `fetch` → fetch handler, any other property → JS-RPC call (an RpcPromise). */\nfunction createStub(id: DurableObjectId, endpoint: () => ObjectEndpoint): DurableObjectStub {\n const target = { id, name: id.name };\n // Only id and name are own enumerable keys, as in workerd and celld: Object.keys(stub) is\n // [id, name], and two stubs of one object are deep-equal.\n Object.defineProperty(target, kEndpoint, { value: endpoint });\n Object.defineProperty(target, STUB, { value: true });\n Object.defineProperty(target, \"fetch\", {\n value(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const req = new Request(input as any, init);\n // Cloudflare's `cf` request property (RequestInit.cf or Request#cf) is not part of\n // the Fetch standard: re-attach it so objects can read `request.cf`.\n const cf = (init as { cf?: unknown } | undefined)?.cf ?? (input as { cf?: unknown }).cf;\n if (cf !== undefined) Object.defineProperty(req, \"cf\", { value: cf, enumerable: true });\n // Keep a WebSocket upgrade that browsers strip from new Request() (forbidden headers).\n const source = init?.headers\n ? new Headers(init.headers)\n : input instanceof Request\n ? input.headers\n : undefined;\n return endpoint().fetch(source ? carryWebSocketHeaders(source, req) : req);\n },\n });\n return new Proxy(target, {\n get(t, prop, recv) {\n if (prop in t) return Reflect.get(t, prop, recv);\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n return (...args: unknown[]) => rpcCall(() => endpoint().call(String(prop), args));\n },\n }) as unknown as DurableObjectStub;\n}\n"]}
1
+ {"version":3,"file":"namespace.js","sourceRoot":"","sources":["../../src/core/namespace.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAwB,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACpF,OAAO,EAAE,WAAW,EAAmB,MAAM,kBAAkB,CAAC;AAWhE;;;GAGG;AACH,MAAM,UAAU,aAAa,CAC3B,IAAsB,EACtB,KAAuC;IAEvC,OAAO,GAAG,EAAE;QACV,MAAM,IAAI,GAAG,KAAK,EAAE,EAAE,CAAC;QACvB,IAAI,CAAC,IAAI;YAAE,OAAO,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC;QACrC,OAAO;YACL,IAAI,KAAK;gBACP,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YACD,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACnB,MAAM,IAAI,CAAC;gBACX,OAAO,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACvC,CAAC;YACD,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE;gBAC3B,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,qDAAqD;gBACjF,MAAM,IAAI,CAAC;gBACX,OAAO,WAAW,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;YAC7C,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,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ketHeaders } from \"../ws/upgrade.js\";\nimport { cross, rpcCall, STUB } from \"./handles.js\";\nimport { type DurableObjectId, idFromName, newUniqueId, validateId } from \"./id.js\";\nimport { closingWith, type ObjectHost } from \"./object-host.js\";\nimport type { DurableObjectState } from \"./state.js\";\n\n/** What a stub talks to: a local ObjectHost or a remote cell host behind a port. */\nexport interface ObjectEndpoint {\n fetch(req: Request): Promise<Response>;\n call(method: string, args: unknown[]): Promise<unknown>;\n /** Present only for in-process objects (enables runInDurableObject). */\n local?: ObjectHost;\n}\n\n/**\n * An in-process object. `ready` (for a cell not open yet): a promise its first events await\n * before the host opens the cell's database (its store is making room), or undefined.\n */\nexport function localEndpoint(\n host: () => ObjectHost,\n ready?: () => Promise<void> | undefined,\n): () => ObjectEndpoint {\n return () => {\n const wait = ready?.();\n if (!wait) return endpointOf(host());\n return {\n get local() {\n return host();\n },\n fetch: async (req) => {\n await wait;\n return endpointOf(host()).fetch(req);\n },\n call: async (method, args) => {\n const copied = cross(args); // the arguments as they are now, as for an open cell\n await wait;\n return deliverCall(host(), method, copied);\n },\n };\n };\n}\n\nfunction endpointOf(h: ObjectHost): ObjectEndpoint {\n return {\n local: h,\n fetch: (req) =>\n h.deliver(async (obj) => {\n if (typeof obj.fetch !== \"function\")\n throw new Error(\"Handler does not export a fetch() function.\");\n let res: Response;\n try {\n const r = await obj.fetch(closingWith(req, h.closing));\n res = r instanceof Response ? r : new Response(String(r)); // a non-Response is sent as text (celld)\n } catch (e) {\n // celld: the stub's fetch() rejects with \"rejected: <name>: <message> [at …]\".\n const err = e as Error;\n throw new Error(`rejected: ${err?.name ?? \"Error\"}: ${err?.message ?? String(e)}`, {\n cause: e,\n });\n }\n // A WebSocket answer to a request that did not ask for one fails (workerd, celld):\n // the stub rejects and the server end sees an abnormal close.\n const ws = (res as { webSocket?: unknown }).webSocket;\n if (res.status === 101 && ws && req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\")\n throw new Error(\n \"rejected: Error: a WebSocket response to a request without Upgrade: websocket\",\n );\n return res;\n }),\n call: async (method, args) => deliverCall(h, method, cross(args)),\n };\n}\n\nasync function deliverCall(h: ObjectHost, method: string, copied: unknown[]): Promise<unknown> {\n const r = await h.deliver((obj) => {\n const m = obj[method];\n if (typeof m !== \"function\") throw new TypeError(`${method} is not a function`); // celld's wording\n return m.apply(obj, copied);\n });\n return cross(r);\n}\n\nexport class DurableObjectNamespace {\n readonly #key: string;\n readonly #endpoint: (id: DurableObjectId) => () => ObjectEndpoint;\n\n constructor(namespaceKey: string, endpoint: (id: DurableObjectId) => () => ObjectEndpoint) {\n this.#key = namespaceKey;\n this.#endpoint = endpoint;\n }\n idFromName(name: string): DurableObjectId {\n return idFromName(this.#key, name);\n }\n newUniqueId(opts?: { jurisdiction?: string }): DurableObjectId {\n if (opts?.jurisdiction != null)\n throw new Error(\"Jurisdiction restrictions are not implemented\");\n return newUniqueId(this.#key);\n }\n idFromString(hex: string): DurableObjectId {\n return validateId(this.#key, hex);\n }\n /** The key ids of this namespace derive from (see id.ts). */\n get namespaceKey(): string {\n return this.#key;\n }\n get(id: DurableObjectId): DurableObjectStub {\n return createStub(id, this.#endpoint(id));\n }\n getByName(name: string): DurableObjectStub {\n return this.get(this.idFromName(name));\n }\n}\n\nexport type DurableObjectStub = {\n readonly id: DurableObjectId;\n readonly name?: string;\n fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;\n} & Record<string, any>;\n\nconst kEndpoint = Symbol(\"cellb.endpoint\");\n\n/**\n * Test hook (same idea as vitest-pool-workers' runInDurableObject): runs `fn`\n * inside a LOCAL object, through the input/output gates, without cloning `fn`.\n */\nexport function runInDurableObject<T>(\n stub: DurableObjectStub,\n fn: (instance: any, state: DurableObjectState) => T | Promise<T>,\n): Promise<T> {\n const ep = (stub as any)[kEndpoint] as (() => ObjectEndpoint) | undefined;\n const local = ep?.().local;\n if (!local) throw new TypeError(\"runInDurableObject needs a stub of an in-process cellb object\");\n return local.deliver(fn);\n}\n\n/** Stub = Proxy: `fetch` → fetch handler, any other property → JS-RPC call (an RpcPromise). */\nfunction createStub(id: DurableObjectId, endpoint: () => ObjectEndpoint): DurableObjectStub {\n const target = { id, name: id.name };\n // Only id and name are own enumerable keys, as in workerd and celld: Object.keys(stub) is\n // [id, name], and two stubs of one object are deep-equal.\n Object.defineProperty(target, kEndpoint, { value: endpoint });\n Object.defineProperty(target, STUB, { value: true });\n Object.defineProperty(target, \"fetch\", {\n value(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const req = new Request(input as any, init);\n // Cloudflare's `cf` request property (RequestInit.cf or Request#cf) is not part of\n // the Fetch standard: re-attach it so objects can read `request.cf`.\n const cf = (init as { cf?: unknown } | undefined)?.cf ?? (input as { cf?: unknown }).cf;\n if (cf !== undefined) Object.defineProperty(req, \"cf\", { value: cf, enumerable: true });\n // Keep a WebSocket upgrade that browsers strip from new Request() (forbidden headers).\n const source = init?.headers\n ? new Headers(init.headers)\n : input instanceof Request\n ? input.headers\n : undefined;\n return endpoint().fetch(source ? carryWebSocketHeaders(source, req) : req);\n },\n });\n const stub = new Proxy(target, {\n get(t, prop, recv) {\n if (prop in t) return Reflect.get(t, prop, recv);\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n return (...args: unknown[]) => rpcCall(() => endpoint().call(String(prop), args));\n },\n }) as unknown as DurableObjectStub;\n // workerd's `stub.dup()`: a Durable Object stub holds nothing to release, so it is itself.\n Object.defineProperty(target, \"dup\", { value: () => stub });\n return stub;\n}\n"]}
@@ -5,8 +5,16 @@ import { DurableObjectId } from "./id.js";
5
5
  import { type ObjectEndpoint } from "./namespace.js";
6
6
  import { type RejectionHandler } from "./worker-rejections.js";
7
7
  export interface WorkerModule {
8
+ /**
9
+ * An object with handlers (`fetch(req, env, ctx)`), or a class (`export default class extends
10
+ * WorkerEntrypoint`): an instance per request, built with `(ctx, env)`, whose `fetch(req)`
11
+ * answers. A class matches through its `prototype`, so `default.fetch` stays readable.
12
+ */
8
13
  default: {
9
14
  fetch?(req: Request, env: any, ctx: ExecutionContext): Response | Promise<Response>;
15
+ prototype?: {
16
+ fetch?(req: Request): Response | Promise<Response>;
17
+ };
10
18
  };
11
19
  [exportName: string]: unknown;
12
20
  }
@@ -5,7 +5,7 @@ import { takeClientPort } from "../ws/server.js";
5
5
  import { withUpgrade } from "../ws/upgrade.js";
6
6
  import { AlarmScheduler } from "./alarms.js";
7
7
  import { asyncRoot } from "./async-context.js";
8
- import { ctxExports, storedExports } from "./handles.js";
8
+ import { ctxExports, defaultHandler, storedExports } from "./handles.js";
9
9
  import { DurableObjectId, namespaceKey } from "./id.js";
10
10
  import { DurableObjectNamespace, localEndpoint } from "./namespace.js";
11
11
  import { CellOwnedElsewhereError, closingWith, ObjectClosedError, ObjectHost, } from "./object-host.js";
@@ -354,7 +354,7 @@ export function createCellRuntime(opts) {
354
354
  await storage.close?.();
355
355
  },
356
356
  async fetch(req) {
357
- const handler = opts.worker.default?.fetch;
357
+ const handler = defaultHandler(opts.worker.default, "fetch");
358
358
  if (!handler)
359
359
  return new Response("Worker has no fetch handler", { status: 500 });
360
360
  // A closed runtime serves nothing: its cells are closed, or another runtime's now.
@@ -371,7 +371,7 @@ export function createCellRuntime(opts) {
371
371
  if (req.cf === undefined)
372
372
  Object.defineProperty(req, "cf", { value: {}, enumerable: true });
373
373
  try {
374
- const r = await rejections(() => handler.call(opts.worker.default, req, env, ctx));
374
+ const r = await rejections(() => handler(req, env, ctx));
375
375
  // A non-Response is sent as text (celld), not a failure.
376
376
  return r instanceof Response ? r : new Response(String(r));
377
377
  }