@statewalker/cellb 0.1.1 → 0.3.0

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 (81) hide show
  1. package/README.md +51 -25
  2. package/dist/adapters/wasm-sqlite.d.ts +11 -0
  3. package/dist/adapters/wasm-sqlite.js +26 -3
  4. package/dist/adapters/wasm-sqlite.js.map +1 -1
  5. package/dist/bindings/assets.js +2 -2
  6. package/dist/bindings/assets.js.map +1 -1
  7. package/dist/bindings/r2.js +2 -2
  8. package/dist/bindings/r2.js.map +1 -1
  9. package/dist/browser.d.ts +0 -1
  10. package/dist/browser.js +0 -1
  11. package/dist/browser.js.map +1 -1
  12. package/dist/bucket/celld-cells.js +1 -1
  13. package/dist/bucket/celld-cells.js.map +1 -1
  14. package/dist/bucket/s3-object-store.js +1 -1
  15. package/dist/bucket/s3-object-store.js.map +1 -1
  16. package/dist/core/handles.d.ts +5 -2
  17. package/dist/core/handles.js +12 -1
  18. package/dist/core/handles.js.map +1 -1
  19. package/dist/core/id.js +3 -3
  20. package/dist/core/id.js.map +1 -1
  21. package/dist/core/namespace.d.ts +1 -1
  22. package/dist/core/namespace.js +2 -1
  23. package/dist/core/namespace.js.map +1 -1
  24. package/dist/core/object-host.d.ts +23 -0
  25. package/dist/core/object-host.js +87 -6
  26. package/dist/core/object-host.js.map +1 -1
  27. package/dist/core/runtime.d.ts +10 -0
  28. package/dist/core/runtime.js +43 -2
  29. package/dist/core/runtime.js.map +1 -1
  30. package/dist/index.d.ts +2 -1
  31. package/dist/index.js +2 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/isolate/browser.js +1 -1
  34. package/dist/isolate/browser.js.map +1 -1
  35. package/dist/isolate/host.d.ts +5 -1
  36. package/dist/isolate/host.js +29 -2
  37. package/dist/isolate/host.js.map +1 -1
  38. package/dist/isolate/isolate-worker.js +11 -1
  39. package/dist/isolate/isolate-worker.js.map +1 -1
  40. package/dist/isolate/isolate.js +20 -0
  41. package/dist/isolate/isolate.js.map +1 -1
  42. package/dist/isolate/node-entry.js +11 -0
  43. package/dist/isolate/node-entry.js.map +1 -1
  44. package/dist/isolate/protocol.d.ts +5 -0
  45. package/dist/isolate/protocol.js +114 -2
  46. package/dist/isolate/protocol.js.map +1 -1
  47. package/dist/node-compat/crypto.js +3 -3
  48. package/dist/node-compat/crypto.js.map +1 -1
  49. package/dist/peer/celld-peer.d.ts +17 -0
  50. package/dist/peer/celld-peer.js +49 -7
  51. package/dist/peer/celld-peer.js.map +1 -1
  52. package/dist/project/browser-host.js +3 -2
  53. package/dist/project/browser-host.js.map +1 -1
  54. package/dist/project/node-project.js +2 -1
  55. package/dist/project/node-project.js.map +1 -1
  56. package/dist/project/site-loader.d.ts +45 -0
  57. package/dist/project/site-loader.js +97 -0
  58. package/dist/project/site-loader.js.map +1 -0
  59. package/dist/project/site.d.ts +0 -36
  60. package/dist/project/site.js +11 -99
  61. package/dist/project/site.js.map +1 -1
  62. package/dist/project/wrangler.js +10 -0
  63. package/dist/project/wrangler.js.map +1 -1
  64. package/dist/router/cell-router.js +1 -1
  65. package/dist/router/cell-router.js.map +1 -1
  66. package/dist/site.d.ts +1 -0
  67. package/dist/site.js +6 -0
  68. package/dist/site.js.map +1 -0
  69. package/dist/transport/port.d.ts +3 -4
  70. package/dist/transport/port.js +21 -79
  71. package/dist/transport/port.js.map +1 -1
  72. package/dist/ws/client.d.ts +23 -8
  73. package/dist/ws/client.js +50 -189
  74. package/dist/ws/client.js.map +1 -1
  75. package/dist/ws/frames.d.ts +31 -8
  76. package/dist/ws/frames.js +54 -7
  77. package/dist/ws/frames.js.map +1 -1
  78. package/dist/ws/server.d.ts +4 -0
  79. package/dist/ws/server.js +29 -5
  80. package/dist/ws/server.js.map +1 -1
  81. package/package.json +29 -10
@@ -0,0 +1,45 @@
1
+ import { type ModuleLoader, type WorkerCode } from "../bindings/worker-loader.js";
2
+ /**
3
+ * The runtime side of a project site (`createProjectSite`, in `@statewalker/cellb/site`): the
4
+ * registry its `~deps` proxies read, and the Worker Loader that uploads code to it. Nothing here
5
+ * compiles code, so the browser host and the isolates import this module without pulling in
6
+ * webrun-modules (and lightningcss-wasm) — only projects that build a site do.
7
+ */
8
+ export declare const LOADED_CONSOLES = "__cellsLoadedConsoles";
9
+ /** What `cloudflare:workers` exports on a site (`env` and `exports` are a project's own). */
10
+ export declare const WORKERS_MODULE_NAMES: string[];
11
+ /**
12
+ * The registry the `~deps` proxies read, for the realm that runs the Worker code. The project
13
+ * and the Workers it loads share this realm's registry, but not their proxies: each has its own
14
+ * module server, so a proxy of loaded code is a module under `<site>loaded/`. A proxy reads the
15
+ * registry while it is evaluated, so the caller on the stack tells whose it is: loaded code gets
16
+ * `workersModule` (`env` and `exports` empty), the project `projectWorkersModule` (its own).
17
+ */
18
+ export declare function workersHostRegistry(entries: {
19
+ /** nodejs_compat: "node:buffer" → module namespace, and the Buffer/process globals. */
20
+ node?: Record<string, unknown>;
21
+ workersModule: object;
22
+ /** With `loadedPrefix` (`<site>loaded/`): the project's own `cloudflare:workers`. */
23
+ projectWorkersModule?: object;
24
+ loadedPrefix?: string;
25
+ emailModule?: unknown;
26
+ Request: unknown;
27
+ Response: unknown;
28
+ WebSocketPair: unknown;
29
+ caches: unknown;
30
+ HTMLRewriter: unknown;
31
+ WebSocketRequestResponsePair?: unknown;
32
+ WebSocket?: unknown;
33
+ }): void;
34
+ export declare const ESM_HEADER = "x-cellb-esm";
35
+ /**
36
+ * Stores one module of loaded code on the site (PUT /loaded-src/<id>/<name>). Source goes
37
+ * through webrun-modules; a text, json or wasm entry is stored as the ESM that wraps it.
38
+ */
39
+ export declare function putLoadedModule(url: string, m: WorkerCode["modules"][string]): Promise<Response>;
40
+ /**
41
+ * Worker Loader over the site: `LOADER.get(id, () => code)` uploads the modules to
42
+ * `/loaded-src/<id>/…` and imports `/loaded/<id>/~/<main>` — compiled by webrun-modules and
43
+ * fetched by the browser like any other module. Works in pages, workers and ServiceWorkers.
44
+ */
45
+ export declare function siteModuleLoader(baseUrl: string): ModuleLoader;
@@ -0,0 +1,97 @@
1
+ import { moduleText, outboundFetch, } from "../bindings/worker-loader.js";
2
+ import { WORKERS_GLOBAL_NAMES } from "./workers-global-names.js";
3
+ /**
4
+ * The runtime side of a project site (`createProjectSite`, in `@statewalker/cellb/site`): the
5
+ * registry its `~deps` proxies read, and the Worker Loader that uploads code to it. Nothing here
6
+ * compiles code, so the browser host and the isolates import this module without pulling in
7
+ * webrun-modules (and lightningcss-wasm) — only projects that build a site do.
8
+ */
9
+ export const LOADED_CONSOLES = "__cellsLoadedConsoles";
10
+ /** What `cloudflare:workers` exports on a site (`env` and `exports` are a project's own). */
11
+ export const WORKERS_MODULE_NAMES = [
12
+ "DurableObject",
13
+ "WorkerEntrypoint",
14
+ "WorkflowEntrypoint",
15
+ "RpcTarget",
16
+ "env",
17
+ "exports",
18
+ "waitUntil",
19
+ ];
20
+ /**
21
+ * The registry the `~deps` proxies read, for the realm that runs the Worker code. The project
22
+ * and the Workers it loads share this realm's registry, but not their proxies: each has its own
23
+ * module server, so a proxy of loaded code is a module under `<site>loaded/`. A proxy reads the
24
+ * registry while it is evaluated, so the caller on the stack tells whose it is: loaded code gets
25
+ * `workersModule` (`env` and `exports` empty), the project `projectWorkersModule` (its own).
26
+ */
27
+ export function workersHostRegistry(entries) {
28
+ const map = new Map([
29
+ ["cloudflare:workers", { env: {}, exports: {}, waitUntil: () => { }, ...entries.workersModule }],
30
+ ["cloudflare:email", entries.emailModule],
31
+ ...WORKERS_GLOBAL_NAMES.map((n) => [n, entries[n]]),
32
+ ...Object.entries(entries.node ?? {}),
33
+ ]);
34
+ const { projectWorkersModule: project, loadedPrefix } = entries;
35
+ globalThis.__webrunHostRegistry = {
36
+ get: (k) => k === "cloudflare:workers" && project && loadedPrefix
37
+ ? (new Error().stack ?? "").includes(loadedPrefix)
38
+ ? map.get(k)
39
+ : project
40
+ : map.get(k),
41
+ has: (k) => map.has(k),
42
+ set: (k, v) => void map.set(k, v),
43
+ };
44
+ }
45
+ export const ESM_HEADER = "x-cellb-esm";
46
+ /**
47
+ * Stores one module of loaded code on the site (PUT /loaded-src/<id>/<name>). Source goes
48
+ * through webrun-modules; a text, json or wasm entry is stored as the ESM that wraps it.
49
+ */
50
+ export function putLoadedModule(url, m) {
51
+ const wrapped = typeof m === "object" && !("js" in m) && !("esModule" in m);
52
+ return fetch(url, {
53
+ method: "PUT",
54
+ body: moduleText(m),
55
+ headers: wrapped ? { [ESM_HEADER]: "1" } : {},
56
+ });
57
+ }
58
+ /**
59
+ * Worker Loader over the site: `LOADER.get(id, () => code)` uploads the modules to
60
+ * `/loaded-src/<id>/…` and imports `/loaded/<id>/~/<main>` — compiled by webrun-modules and
61
+ * fetched by the browser like any other module. Works in pages, workers and ServiceWorkers.
62
+ */
63
+ export function siteModuleLoader(baseUrl) {
64
+ const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
65
+ return async (id, code, logs) => {
66
+ const dir = encodeURIComponent(id);
67
+ for (const [name, m] of Object.entries(code.modules)) {
68
+ const res = await putLoadedModule(`${base}loaded-src/${dir}/${name}`, m);
69
+ if (!res.ok)
70
+ throw new Error(`Worker Loader: cannot store ${id}/${name}: ${res.status}`);
71
+ }
72
+ const outbound = outboundFetch(code);
73
+ if (outbound) {
74
+ const g = globalThis;
75
+ g.__cellsLoadedOutbound ??= {};
76
+ g.__cellsLoadedOutbound[id] = outbound;
77
+ }
78
+ if (logs) {
79
+ const g = globalThis;
80
+ g[LOADED_CONSOLES] ??= {};
81
+ const real = globalThis.console;
82
+ const wrap = (level) => (...args) => {
83
+ logs(level, args);
84
+ real[level](...args);
85
+ };
86
+ g[LOADED_CONSOLES][id] = Object.assign(Object.create(real), {
87
+ log: wrap("log"),
88
+ info: wrap("info"),
89
+ warn: wrap("warn"),
90
+ error: wrap("error"),
91
+ debug: wrap("debug"),
92
+ });
93
+ }
94
+ return (await import(/* @vite-ignore */ `${base}loaded/${dir}/~/${code.mainModule}`));
95
+ };
96
+ }
97
+ //# sourceMappingURL=site-loader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-loader.js","sourceRoot":"","sources":["../../src/project/site-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,UAAU,EACV,aAAa,GAEd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,uBAAuB,CAAC;AAEvD,6FAA6F;AAC7F,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,eAAe;IACf,kBAAkB;IAClB,oBAAoB;IACpB,WAAW;IACX,KAAK;IACL,SAAS;IACT,WAAW;CACZ,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAenC;IACC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAkB;QACnC,CAAC,oBAAoB,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,GAAG,EAAE,GAAE,CAAC,EAAE,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;QAC/F,CAAC,kBAAkB,EAAE,OAAO,CAAC,WAAW,CAAC;QACzC,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAU,CAAC;QAC5D,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC;KACtC,CAAC,CAAC;IACH,MAAM,EAAE,oBAAoB,EAAE,OAAO,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;IAC/D,UAAsC,CAAC,oBAAoB,GAAG;QAC7D,GAAG,EAAE,CAAC,CAAS,EAAE,EAAE,CACjB,CAAC,KAAK,oBAAoB,IAAI,OAAO,IAAI,YAAY;YACnD,CAAC,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC,KAA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E,IAAI,CAAC,OAAO,CAAC;gBACpB,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC;aACrB,CAAC,CAAC;QACL,CAAC;QACD,OAAO,CAAC,MAAM,MAAM,CAAC,kBAAkB,CAAC,GAAG,IAAI,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC,CAGnF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n type WorkerCode,\n} from \"../bindings/worker-loader.js\";\nimport { WORKERS_GLOBAL_NAMES } from \"./workers-global-names.js\";\n\n/**\n * The runtime side of a project site (`createProjectSite`, in `@statewalker/cellb/site`): the\n * registry its `~deps` proxies read, and the Worker Loader that uploads code to it. Nothing here\n * compiles code, so the browser host and the isolates import this module without pulling in\n * webrun-modules (and lightningcss-wasm) — only projects that build a site do.\n */\nexport const LOADED_CONSOLES = \"__cellsLoadedConsoles\";\n\n/** What `cloudflare:workers` exports on a site (`env` and `exports` are a project's own). */\nexport const WORKERS_MODULE_NAMES = [\n \"DurableObject\",\n \"WorkerEntrypoint\",\n \"WorkflowEntrypoint\",\n \"RpcTarget\",\n \"env\",\n \"exports\",\n \"waitUntil\",\n];\n\n/**\n * The registry the `~deps` proxies read, for the realm that runs the Worker code. The project\n * and the Workers it loads share this realm's registry, but not their proxies: each has its own\n * module server, so a proxy of loaded code is a module under `<site>loaded/`. A proxy reads the\n * registry while it is evaluated, so the caller on the stack tells whose it is: loaded code gets\n * `workersModule` (`env` and `exports` empty), the project `projectWorkersModule` (its own).\n */\nexport function workersHostRegistry(entries: {\n /** nodejs_compat: \"node:buffer\" → module namespace, and the Buffer/process globals. */\n node?: Record<string, unknown>;\n workersModule: object;\n /** With `loadedPrefix` (`<site>loaded/`): the project's own `cloudflare:workers`. */\n projectWorkersModule?: object;\n loadedPrefix?: string;\n emailModule?: unknown;\n Request: unknown;\n Response: unknown;\n WebSocketPair: unknown;\n caches: unknown;\n HTMLRewriter: unknown;\n WebSocketRequestResponsePair?: unknown;\n WebSocket?: unknown;\n}): void {\n const map = new Map<string, unknown>([\n [\"cloudflare:workers\", { env: {}, exports: {}, waitUntil: () => {}, ...entries.workersModule }],\n [\"cloudflare:email\", entries.emailModule],\n ...WORKERS_GLOBAL_NAMES.map((n) => [n, entries[n]] as const),\n ...Object.entries(entries.node ?? {}),\n ]);\n const { projectWorkersModule: project, loadedPrefix } = entries;\n (globalThis as Record<string, unknown>).__webrunHostRegistry = {\n get: (k: string) =>\n k === \"cloudflare:workers\" && project && loadedPrefix\n ? (new Error().stack ?? \"\").includes(loadedPrefix)\n ? map.get(k)\n : project\n : map.get(k),\n has: (k: string) => map.has(k),\n set: (k: string, v: unknown) => void map.set(k, v),\n };\n}\n\nexport const ESM_HEADER = \"x-cellb-esm\";\n\n/**\n * Stores one module of loaded code on the site (PUT /loaded-src/<id>/<name>). Source goes\n * through webrun-modules; a text, json or wasm entry is stored as the ESM that wraps it.\n */\nexport function putLoadedModule(url: string, m: WorkerCode[\"modules\"][string]): Promise<Response> {\n const wrapped = typeof m === \"object\" && !(\"js\" in m) && !(\"esModule\" in m);\n return fetch(url, {\n method: \"PUT\",\n body: moduleText(m),\n headers: wrapped ? { [ESM_HEADER]: \"1\" } : {},\n });\n}\n\n/**\n * Worker Loader over the site: `LOADER.get(id, () => code)` uploads the modules to\n * `/loaded-src/<id>/…` and imports `/loaded/<id>/~/<main>` — compiled by webrun-modules and\n * fetched by the browser like any other module. Works in pages, workers and ServiceWorkers.\n */\nexport function siteModuleLoader(baseUrl: string): ModuleLoader {\n const base = baseUrl.endsWith(\"/\") ? baseUrl : `${baseUrl}/`;\n return async (id: string, code: WorkerCode, logs?: LogSink) => {\n const dir = encodeURIComponent(id);\n for (const [name, m] of Object.entries(code.modules)) {\n const res = await putLoadedModule(`${base}loaded-src/${dir}/${name}`, m);\n if (!res.ok) throw new Error(`Worker Loader: cannot store ${id}/${name}: ${res.status}`);\n }\n const outbound = outboundFetch(code);\n if (outbound) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsLoadedOutbound ??= {};\n (g.__cellsLoadedOutbound as Record<string, unknown>)[id] = outbound;\n }\n if (logs) {\n const g = globalThis as Record<string, unknown>;\n g[LOADED_CONSOLES] ??= {};\n const real = globalThis.console;\n const wrap =\n (level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\") =>\n (...args: unknown[]) => {\n logs(level, args);\n real[level](...args);\n };\n (g[LOADED_CONSOLES] as Record<string, unknown>)[id] = Object.assign(Object.create(real), {\n log: wrap(\"log\"),\n info: wrap(\"info\"),\n warn: wrap(\"warn\"),\n error: wrap(\"error\"),\n debug: wrap(\"debug\"),\n });\n }\n return (await import(/* @vite-ignore */ `${base}loaded/${dir}/~/${code.mainModule}`)) as Record<\n string,\n unknown\n >;\n };\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  import { type FilesApi } from "@statewalker/webrun-files";
2
2
  import { type SiteHandler } from "@statewalker/webrun-site-builder";
3
- import { type ModuleLoader, type WorkerCode } from "../bindings/worker-loader.js";
4
3
  /**
5
4
  * A project served by an in-browser "HTTP server" (webrun-site-builder handler, hosted in a
6
5
  * ServiceWorker by webrun-site-host): the browser's own module loader then fetches the
@@ -16,7 +15,6 @@ import { type ModuleLoader, type WorkerCode } from "../bindings/worker-loader.js
16
15
  * that imports the code (see `workersHostRegistry`). Each loaded Worker gets its own module
17
16
  * server whose `console` proxy selects that Worker's console (Tail Workers).
18
17
  */
19
- export declare const LOADED_CONSOLES = "__cellsLoadedConsoles";
20
18
  export declare function createProjectSite(opts: {
21
19
  projectFiles: FilesApi;
22
20
  /**
@@ -38,37 +36,3 @@ export declare function createProjectSite(opts: {
38
36
  */
39
37
  nodeModules?: Record<string, unknown>;
40
38
  }): SiteHandler;
41
- /**
42
- * The registry the `~deps` proxies read, for the realm that runs the Worker code. The project
43
- * and the Workers it loads share this realm's registry, but not their proxies: each has its own
44
- * module server, so a proxy of loaded code is a module under `<site>loaded/`. A proxy reads the
45
- * registry while it is evaluated, so the caller on the stack tells whose it is: loaded code gets
46
- * `workersModule` (`env` and `exports` empty), the project `projectWorkersModule` (its own).
47
- */
48
- export declare function workersHostRegistry(entries: {
49
- /** nodejs_compat: "node:buffer" → module namespace, and the Buffer/process globals. */
50
- node?: Record<string, unknown>;
51
- workersModule: object;
52
- /** With `loadedPrefix` (`<site>loaded/`): the project's own `cloudflare:workers`. */
53
- projectWorkersModule?: object;
54
- loadedPrefix?: string;
55
- emailModule?: unknown;
56
- Request: unknown;
57
- Response: unknown;
58
- WebSocketPair: unknown;
59
- caches: unknown;
60
- HTMLRewriter: unknown;
61
- WebSocketRequestResponsePair?: unknown;
62
- WebSocket?: unknown;
63
- }): void;
64
- /**
65
- * Stores one module of loaded code on the site (PUT /loaded-src/<id>/<name>). Source goes
66
- * through webrun-modules; a text, json or wasm entry is stored as the ESM that wraps it.
67
- */
68
- export declare function putLoadedModule(url: string, m: WorkerCode["modules"][string]): Promise<Response>;
69
- /**
70
- * Worker Loader over the site: `LOADER.get(id, () => code)` uploads the modules to
71
- * `/loaded-src/<id>/…` and imports `/loaded/<id>/~/<main>` — compiled by webrun-modules and
72
- * fetched by the browser like any other module. Works in pages, workers and ServiceWorkers.
73
- */
74
- export declare function siteModuleLoader(baseUrl: string): ModuleLoader;
@@ -2,12 +2,22 @@ import { readText } from "@statewalker/webrun-files";
2
2
  import { MemFilesApi } from "@statewalker/webrun-files-mem";
3
3
  import { newDefaultTransform, newModuleServer } from "@statewalker/webrun-modules";
4
4
  import { SiteBuilder } from "@statewalker/webrun-site-builder";
5
- import { moduleText, outboundFetch, } from "../bindings/worker-loader.js";
6
5
  import { nativeAsyncContext } from "../core/async-context.js";
7
6
  import { NODE_POLYFILL_FILES, NODE_POLYFILL_PACKAGES } from "../node-compat/modules.js";
8
7
  import { lowerAwait } from "./lower-await.js";
9
8
  import { SCHEDULER_EXPRESSION } from "./scheduler.js";
9
+ import { ESM_HEADER, LOADED_CONSOLES, WORKERS_MODULE_NAMES } from "./site-loader.js";
10
10
  import { WORKERS_GLOBAL_NAMES } from "./workers-global-names.js";
11
+ /** webrun-modules' transform, then `lowerAwait` on its output. */
12
+ function loweringTransform() {
13
+ const base = newDefaultTransform(true);
14
+ return {
15
+ async transform(file, rewrite) {
16
+ const r = await base.transform(file, rewrite);
17
+ return { ...r, code: lowerAwait(r.code) };
18
+ },
19
+ };
20
+ }
11
21
  /**
12
22
  * A project served by an in-browser "HTTP server" (webrun-site-builder handler, hosted in a
13
23
  * ServiceWorker by webrun-site-host): the browser's own module loader then fetches the
@@ -23,17 +33,6 @@ import { WORKERS_GLOBAL_NAMES } from "./workers-global-names.js";
23
33
  * that imports the code (see `workersHostRegistry`). Each loaded Worker gets its own module
24
34
  * server whose `console` proxy selects that Worker's console (Tail Workers).
25
35
  */
26
- export const LOADED_CONSOLES = "__cellsLoadedConsoles";
27
- /** webrun-modules' transform, then `lowerAwait` on its output. */
28
- function loweringTransform() {
29
- const base = newDefaultTransform(true);
30
- return {
31
- async transform(file, rewrite) {
32
- const r = await base.transform(file, rewrite);
33
- return { ...r, code: lowerAwait(r.code) };
34
- },
35
- };
36
- }
37
36
  export function createProjectSite(opts) {
38
37
  const host = "globalThis.__webrunHostRegistry.get";
39
38
  // nodejs_compat: node:* and the Buffer/process globals come from the realm's registry too.
@@ -116,91 +115,4 @@ export function createProjectSite(opts) {
116
115
  .setFiles("/src", opts.projectFiles)
117
116
  .build();
118
117
  }
119
- /** What `cloudflare:workers` exports on a site (`env` and `exports` are a project's own). */
120
- const WORKERS_MODULE_NAMES = [
121
- "DurableObject",
122
- "WorkerEntrypoint",
123
- "WorkflowEntrypoint",
124
- "RpcTarget",
125
- "env",
126
- "exports",
127
- "waitUntil",
128
- ];
129
- /**
130
- * The registry the `~deps` proxies read, for the realm that runs the Worker code. The project
131
- * and the Workers it loads share this realm's registry, but not their proxies: each has its own
132
- * module server, so a proxy of loaded code is a module under `<site>loaded/`. A proxy reads the
133
- * registry while it is evaluated, so the caller on the stack tells whose it is: loaded code gets
134
- * `workersModule` (`env` and `exports` empty), the project `projectWorkersModule` (its own).
135
- */
136
- export function workersHostRegistry(entries) {
137
- const map = new Map([
138
- ["cloudflare:workers", { env: {}, exports: {}, waitUntil: () => { }, ...entries.workersModule }],
139
- ["cloudflare:email", entries.emailModule],
140
- ...WORKERS_GLOBAL_NAMES.map((n) => [n, entries[n]]),
141
- ...Object.entries(entries.node ?? {}),
142
- ]);
143
- const { projectWorkersModule: project, loadedPrefix } = entries;
144
- globalThis.__webrunHostRegistry = {
145
- get: (k) => k === "cloudflare:workers" && project && loadedPrefix
146
- ? (new Error().stack ?? "").includes(loadedPrefix)
147
- ? map.get(k)
148
- : project
149
- : map.get(k),
150
- has: (k) => map.has(k),
151
- set: (k, v) => void map.set(k, v),
152
- };
153
- }
154
- const ESM_HEADER = "x-cellb-esm";
155
- /**
156
- * Stores one module of loaded code on the site (PUT /loaded-src/<id>/<name>). Source goes
157
- * through webrun-modules; a text, json or wasm entry is stored as the ESM that wraps it.
158
- */
159
- export function putLoadedModule(url, m) {
160
- const wrapped = typeof m === "object" && !("js" in m) && !("esModule" in m);
161
- return fetch(url, {
162
- method: "PUT",
163
- body: moduleText(m),
164
- headers: wrapped ? { [ESM_HEADER]: "1" } : {},
165
- });
166
- }
167
- /**
168
- * Worker Loader over the site: `LOADER.get(id, () => code)` uploads the modules to
169
- * `/loaded-src/<id>/…` and imports `/loaded/<id>/~/<main>` — compiled by webrun-modules and
170
- * fetched by the browser like any other module. Works in pages, workers and ServiceWorkers.
171
- */
172
- export function siteModuleLoader(baseUrl) {
173
- const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
174
- return async (id, code, logs) => {
175
- const dir = encodeURIComponent(id);
176
- for (const [name, m] of Object.entries(code.modules)) {
177
- const res = await putLoadedModule(`${base}loaded-src/${dir}/${name}`, m);
178
- if (!res.ok)
179
- throw new Error(`Worker Loader: cannot store ${id}/${name}: ${res.status}`);
180
- }
181
- const outbound = outboundFetch(code);
182
- if (outbound) {
183
- const g = globalThis;
184
- g.__cellsLoadedOutbound ??= {};
185
- g.__cellsLoadedOutbound[id] = outbound;
186
- }
187
- if (logs) {
188
- const g = globalThis;
189
- g[LOADED_CONSOLES] ??= {};
190
- const real = globalThis.console;
191
- const wrap = (level) => (...args) => {
192
- logs(level, args);
193
- real[level](...args);
194
- };
195
- g[LOADED_CONSOLES][id] = Object.assign(Object.create(real), {
196
- log: wrap("log"),
197
- info: wrap("info"),
198
- warn: wrap("warn"),
199
- error: wrap("error"),
200
- debug: wrap("debug"),
201
- });
202
- }
203
- return (await import(/* @vite-ignore */ `${base}loaded/${dir}/~/${code.mainModule}`));
204
- };
205
- }
206
118
  //# sourceMappingURL=site.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"site.js","sourceRoot":"","sources":["../../src/project/site.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAkB,MAAM,6BAA6B,CAAC;AACnG,OAAO,EAAE,WAAW,EAAoB,MAAM,kCAAkC,CAAC;AACjF,OAAO,EAGL,UAAU,EACV,aAAa,GAEd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACxF,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,uBAAuB,CAAC;AAEvD,kEAAkE;AAClE,SAAS,iBAAiB;IACxB,MAAM,IAAI,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gBACrB,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;gBAClB,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;YACvB,CAAC,CAAC;YACH,CAAC,CAAC,eAAe,CAA6B,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;gBACvF,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC;gBAChB,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC;gBAClB,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC;gBAClB,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC;gBACpB,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC;aACrB,CAAC,CAAC;QACL,CAAC;QACD,OAAO,CAAC,MAAM,MAAM,CAAC,kBAAkB,CAAC,GAAG,IAAI,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC,CAGnF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { type FilesApi, readText } from \"@statewalker/webrun-files\";\nimport { MemFilesApi } from \"@statewalker/webrun-files-mem\";\nimport { newDefaultTransform, newModuleServer, type Transform } from \"@statewalker/webrun-modules\";\nimport { SiteBuilder, type SiteHandler } from \"@statewalker/webrun-site-builder\";\nimport {\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n type WorkerCode,\n} from \"../bindings/worker-loader.js\";\nimport { nativeAsyncContext } from \"../core/async-context.js\";\nimport { NODE_POLYFILL_FILES, NODE_POLYFILL_PACKAGES } from \"../node-compat/modules.js\";\nimport { lowerAwait } from \"./lower-await.js\";\nimport { SCHEDULER_EXPRESSION } from \"./scheduler.js\";\nimport { WORKERS_GLOBAL_NAMES } from \"./workers-global-names.js\";\n\n/**\n * A project served by an in-browser \"HTTP server\" (webrun-site-builder handler, hosted in a\n * ServiceWorker by webrun-site-host): the browser's own module loader then fetches the\n * Worker code from real URLs — no bundling, no Blob URLs.\n *\n * GET /modules/~/<path> the project's sources compiled to ESM by webrun-modules\n * PUT /loaded-src/<id>/<file> a Worker Loader stores the modules of loaded code\n * GET /loaded/<id>/~/<file> loaded code compiled to ESM by webrun-modules\n * GET /src/<path> raw project files\n *\n * `cloudflare:workers` and the Workers globals (`Response` with status 101, `WebSocketPair`)\n * are webrun-modules `~deps` proxies that read `globalThis.__webrunHostRegistry` in the realm\n * that imports the code (see `workersHostRegistry`). Each loaded Worker gets its own module\n * server whose `console` proxy selects that Worker's console (Tail Workers).\n */\nexport const LOADED_CONSOLES = \"__cellsLoadedConsoles\";\n\n/** webrun-modules' transform, then `lowerAwait` on its output. */\nfunction loweringTransform(): Transform {\n const base = newDefaultTransform(true);\n return {\n async transform(file, rewrite) {\n const r = await base.transform(file, rewrite);\n return { ...r, code: lowerAwait(r.code) };\n },\n };\n}\n\nexport function createProjectSite(opts: {\n projectFiles: FilesApi;\n /**\n * nodejs_compat: serves the `node:*` modules, and (see `lowerAwait`) lowers the modules' awaits\n * to generators so that AsyncLocalStorage stores follow them. It must match the project's flag:\n * without AsyncContext, the browser host makes continuations carry stores for a nodejs_compat\n * project, which awaits that are not lowered would not see.\n */\n nodeCompat?: boolean;\n /**\n * Lower `await` in the modules served. Default: with `nodeCompat`, unless this browser has\n * AsyncContext (the engine then carries the stores through native awaits, as workerd does).\n */\n lowerAwait?: boolean;\n /**\n * The `node:*` registry entries of the realm that runs the code (`nodeRegistryEntries`): a\n * namespace import (`import * as assert from \"node:assert\"`) exports the keys the server\n * sees here, so without them its members are undefined.\n */\n nodeModules?: Record<string, unknown>;\n}): SiteHandler {\n const host = \"globalThis.__webrunHostRegistry.get\";\n // nodejs_compat: node:* and the Buffer/process globals come from the realm's registry too.\n // A namespace import (`import * as cf`) exports the keys the server sees here.\n const provided: Record<string, object> = {\n \"cloudflare:workers\": Object.fromEntries(WORKERS_MODULE_NAMES.map((n) => [n, null])),\n \"cloudflare:email\": { EmailMessage: null },\n };\n if (opts.nodeCompat)\n for (const name of [\n ...Object.keys(NODE_POLYFILL_PACKAGES),\n ...Object.keys(NODE_POLYFILL_FILES),\n ])\n provided[name] = (opts.nodeModules?.[name] as object) ?? {};\n const globals = {\n ...Object.fromEntries(WORKERS_GLOBAL_NAMES.map((n) => [n, `${host}(${JSON.stringify(n)})`])),\n scheduler: SCHEDULER_EXPRESSION,\n ...(opts.nodeCompat ? { Buffer: `${host}(\"Buffer\")`, process: `${host}(\"process\")` } : {}),\n };\n // nodejs_compat without AsyncContext: awaits lowered to generators, so that AsyncLocalStorage\n // stores follow them (the browser host installs the polyfill's continuations for such a project).\n const lower = opts.lowerAwait ?? (!!opts.nodeCompat && !nativeAsyncContext());\n const transform = lower ? loweringTransform() : undefined;\n const modules = newModuleServer({\n cache: new MemFilesApi(),\n project: opts.projectFiles,\n basePath: \"/modules/\",\n target: \"browser\",\n provided,\n globals,\n transform,\n });\n // One module server per loaded Worker: its globals proxy (one per project root in\n // webrun-modules) can then bind `console` to that Worker's own console (Tail Workers).\n // `esm`: modules stored as ESM already (text, json, wasm entries), served as they are: the\n // module server would serve `math.wasm` or `text.txt` by their extension.\n const loaded = new Map<\n string,\n { files: FilesApi; server: ReturnType<typeof newModuleServer>; esm: Set<string> }\n >();\n const loadedFor = (id: string) => {\n let l = loaded.get(id);\n if (!l) {\n const files = new MemFilesApi();\n const server = newModuleServer({\n cache: new MemFilesApi(),\n project: files,\n basePath: `/loaded/${encodeURIComponent(id)}/`,\n target: \"browser\",\n provided,\n transform,\n globals: {\n ...globals,\n console: `(globalThis.${LOADED_CONSOLES}?.[${JSON.stringify(id)}] ?? globalThis.console)`,\n fetch: `(globalThis.__cellsLoadedOutbound?.[${JSON.stringify(id)}] ?? globalThis.fetch)`,\n },\n });\n l = { files, server, esm: new Set() };\n loaded.set(id, l);\n }\n return l;\n };\n return new SiteBuilder()\n .setEndpoint(\"/modules/*\", (req) => modules.fetch(req))\n .setEndpoint(\"/loaded/:id/*\", async (req, env) => {\n const l = loadedFor(decodeURIComponent(String(env.params.id)));\n const path = decodeURIComponent(\n new URL(req.url).pathname.slice(`/loaded/${env.params.id}/~`.length),\n );\n if (!l.esm.has(path)) return l.server.fetch(req);\n return new Response(await readText(l.files, path), {\n headers: { \"content-type\": \"text/javascript\" },\n });\n })\n .setEndpoint(\"/loaded-src/:id/*\", \"PUT\", async (req, env) => {\n const id = decodeURIComponent(String(env.params.id));\n const path = decodeURIComponent(\n new URL(req.url).pathname.slice(`/loaded-src/${env.params.id}`.length),\n );\n const l = loadedFor(id);\n await l.files.write(path, [new Uint8Array(await req.arrayBuffer())]);\n if (req.headers.has(ESM_HEADER)) l.esm.add(path);\n return new Response(null, { status: 204 });\n })\n .setFiles(\"/src\", opts.projectFiles)\n .build();\n}\n\n/** What `cloudflare:workers` exports on a site (`env` and `exports` are a project's own). */\nconst WORKERS_MODULE_NAMES = [\n \"DurableObject\",\n \"WorkerEntrypoint\",\n \"WorkflowEntrypoint\",\n \"RpcTarget\",\n \"env\",\n \"exports\",\n \"waitUntil\",\n];\n\n/**\n * The registry the `~deps` proxies read, for the realm that runs the Worker code. The project\n * and the Workers it loads share this realm's registry, but not their proxies: each has its own\n * module server, so a proxy of loaded code is a module under `<site>loaded/`. A proxy reads the\n * registry while it is evaluated, so the caller on the stack tells whose it is: loaded code gets\n * `workersModule` (`env` and `exports` empty), the project `projectWorkersModule` (its own).\n */\nexport function workersHostRegistry(entries: {\n /** nodejs_compat: \"node:buffer\" → module namespace, and the Buffer/process globals. */\n node?: Record<string, unknown>;\n workersModule: object;\n /** With `loadedPrefix` (`<site>loaded/`): the project's own `cloudflare:workers`. */\n projectWorkersModule?: object;\n loadedPrefix?: string;\n emailModule?: unknown;\n Request: unknown;\n Response: unknown;\n WebSocketPair: unknown;\n caches: unknown;\n HTMLRewriter: unknown;\n WebSocketRequestResponsePair?: unknown;\n WebSocket?: unknown;\n}): void {\n const map = new Map<string, unknown>([\n [\"cloudflare:workers\", { env: {}, exports: {}, waitUntil: () => {}, ...entries.workersModule }],\n [\"cloudflare:email\", entries.emailModule],\n ...WORKERS_GLOBAL_NAMES.map((n) => [n, entries[n]] as const),\n ...Object.entries(entries.node ?? {}),\n ]);\n const { projectWorkersModule: project, loadedPrefix } = entries;\n (globalThis as Record<string, unknown>).__webrunHostRegistry = {\n get: (k: string) =>\n k === \"cloudflare:workers\" && project && loadedPrefix\n ? (new Error().stack ?? \"\").includes(loadedPrefix)\n ? map.get(k)\n : project\n : map.get(k),\n has: (k: string) => map.has(k),\n set: (k: string, v: unknown) => void map.set(k, v),\n };\n}\n\nconst ESM_HEADER = \"x-cellb-esm\";\n\n/**\n * Stores one module of loaded code on the site (PUT /loaded-src/<id>/<name>). Source goes\n * through webrun-modules; a text, json or wasm entry is stored as the ESM that wraps it.\n */\nexport function putLoadedModule(url: string, m: WorkerCode[\"modules\"][string]): Promise<Response> {\n const wrapped = typeof m === \"object\" && !(\"js\" in m) && !(\"esModule\" in m);\n return fetch(url, {\n method: \"PUT\",\n body: moduleText(m),\n headers: wrapped ? { [ESM_HEADER]: \"1\" } : {},\n });\n}\n\n/**\n * Worker Loader over the site: `LOADER.get(id, () => code)` uploads the modules to\n * `/loaded-src/<id>/…` and imports `/loaded/<id>/~/<main>` — compiled by webrun-modules and\n * fetched by the browser like any other module. Works in pages, workers and ServiceWorkers.\n */\nexport function siteModuleLoader(baseUrl: string): ModuleLoader {\n const base = baseUrl.endsWith(\"/\") ? baseUrl : `${baseUrl}/`;\n return async (id: string, code: WorkerCode, logs?: LogSink) => {\n const dir = encodeURIComponent(id);\n for (const [name, m] of Object.entries(code.modules)) {\n const res = await putLoadedModule(`${base}loaded-src/${dir}/${name}`, m);\n if (!res.ok) throw new Error(`Worker Loader: cannot store ${id}/${name}: ${res.status}`);\n }\n const outbound = outboundFetch(code);\n if (outbound) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsLoadedOutbound ??= {};\n (g.__cellsLoadedOutbound as Record<string, unknown>)[id] = outbound;\n }\n if (logs) {\n const g = globalThis as Record<string, unknown>;\n g[LOADED_CONSOLES] ??= {};\n const real = globalThis.console;\n const wrap =\n (level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\") =>\n (...args: unknown[]) => {\n logs(level, args);\n real[level](...args);\n };\n (g[LOADED_CONSOLES] as Record<string, unknown>)[id] = Object.assign(Object.create(real), {\n log: wrap(\"log\"),\n info: wrap(\"info\"),\n warn: wrap(\"warn\"),\n error: wrap(\"error\"),\n debug: wrap(\"debug\"),\n });\n }\n return (await import(/* @vite-ignore */ `${base}loaded/${dir}/~/${code.mainModule}`)) as Record<\n string,\n unknown\n >;\n };\n}\n"]}
1
+ {"version":3,"file":"site.js","sourceRoot":"","sources":["../../src/project/site.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAkB,MAAM,6BAA6B,CAAC;AACnG,OAAO,EAAE,WAAW,EAAoB,MAAM,kCAAkC,CAAC;AACjF,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACxF,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACrF,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE,kEAAkE;AAClE,SAAS,iBAAiB;IACxB,MAAM,IAAI,GAAG,mBAAmB,CAAC,IAAI,CAAC,CAAC;IACvC,OAAO;QACL,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO;YAC3B,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,S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CAAC,QAAQ,CAAC,KAAK,CAAC,eAAe,GAAG,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CACvE,CAAC;QACF,MAAM,CAAC,GAAG,SAAS,CAAC,EAAE,CAAC,CAAC;QACxB,MAAM,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC;QACrE,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;YAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACjD,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;IAC7C,CAAC,CAAC;SACD,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,YAAY,CAAC;SACnC,KAAK,EAAE,CAAC;AACb,CAAC","sourcesContent":["import { type FilesApi, readText } from \"@statewalker/webrun-files\";\nimport { MemFilesApi } from \"@statewalker/webrun-files-mem\";\nimport { newDefaultTransform, newModuleServer, type Transform } from \"@statewalker/webrun-modules\";\nimport { SiteBuilder, type SiteHandler } from \"@statewalker/webrun-site-builder\";\nimport { nativeAsyncContext } from \"../core/async-context.js\";\nimport { NODE_POLYFILL_FILES, NODE_POLYFILL_PACKAGES } from \"../node-compat/modules.js\";\nimport { lowerAwait } from \"./lower-await.js\";\nimport { SCHEDULER_EXPRESSION } from \"./scheduler.js\";\nimport { ESM_HEADER, LOADED_CONSOLES, WORKERS_MODULE_NAMES } from \"./site-loader.js\";\nimport { WORKERS_GLOBAL_NAMES } from \"./workers-global-names.js\";\n\n/** webrun-modules' transform, then `lowerAwait` on its output. */\nfunction loweringTransform(): Transform {\n const base = newDefaultTransform(true);\n return {\n async transform(file, rewrite) {\n const r = await base.transform(file, rewrite);\n return { ...r, code: lowerAwait(r.code) };\n },\n };\n}\n\n/**\n * A project served by an in-browser \"HTTP server\" (webrun-site-builder handler, hosted in a\n * ServiceWorker by webrun-site-host): the browser's own module loader then fetches the\n * Worker code from real URLs — no bundling, no Blob URLs.\n *\n * GET /modules/~/<path> the project's sources compiled to ESM by webrun-modules\n * PUT /loaded-src/<id>/<file> a Worker Loader stores the modules of loaded code\n * GET /loaded/<id>/~/<file> loaded code compiled to ESM by webrun-modules\n * GET /src/<path> raw project files\n *\n * `cloudflare:workers` and the Workers globals (`Response` with status 101, `WebSocketPair`)\n * are webrun-modules `~deps` proxies that read `globalThis.__webrunHostRegistry` in the realm\n * that imports the code (see `workersHostRegistry`). Each loaded Worker gets its own module\n * server whose `console` proxy selects that Worker's console (Tail Workers).\n */\nexport function createProjectSite(opts: {\n projectFiles: FilesApi;\n /**\n * nodejs_compat: serves the `node:*` modules, and (see `lowerAwait`) lowers the modules' awaits\n * to generators so that AsyncLocalStorage stores follow them. It must match the project's flag:\n * without AsyncContext, the browser host makes continuations carry stores for a nodejs_compat\n * project, which awaits that are not lowered would not see.\n */\n nodeCompat?: boolean;\n /**\n * Lower `await` in the modules served. Default: with `nodeCompat`, unless this browser has\n * AsyncContext (the engine then carries the stores through native awaits, as workerd does).\n */\n lowerAwait?: boolean;\n /**\n * The `node:*` registry entries of the realm that runs the code (`nodeRegistryEntries`): a\n * namespace import (`import * as assert from \"node:assert\"`) exports the keys the server\n * sees here, so without them its members are undefined.\n */\n nodeModules?: Record<string, unknown>;\n}): SiteHandler {\n const host = \"globalThis.__webrunHostRegistry.get\";\n // nodejs_compat: node:* and the Buffer/process globals come from the realm's registry too.\n // A namespace import (`import * as cf`) exports the keys the server sees here.\n const provided: Record<string, object> = {\n \"cloudflare:workers\": Object.fromEntries(WORKERS_MODULE_NAMES.map((n) => [n, null])),\n \"cloudflare:email\": { EmailMessage: null },\n };\n if (opts.nodeCompat)\n for (const name of [\n ...Object.keys(NODE_POLYFILL_PACKAGES),\n ...Object.keys(NODE_POLYFILL_FILES),\n ])\n provided[name] = (opts.nodeModules?.[name] as object) ?? {};\n const globals = {\n ...Object.fromEntries(WORKERS_GLOBAL_NAMES.map((n) => [n, `${host}(${JSON.stringify(n)})`])),\n scheduler: SCHEDULER_EXPRESSION,\n ...(opts.nodeCompat ? { Buffer: `${host}(\"Buffer\")`, process: `${host}(\"process\")` } : {}),\n };\n // nodejs_compat without AsyncContext: awaits lowered to generators, so that AsyncLocalStorage\n // stores follow them (the browser host installs the polyfill's continuations for such a project).\n const lower = opts.lowerAwait ?? (!!opts.nodeCompat && !nativeAsyncContext());\n const transform = lower ? loweringTransform() : undefined;\n const modules = newModuleServer({\n cache: new MemFilesApi(),\n project: opts.projectFiles,\n basePath: \"/modules/\",\n target: \"browser\",\n provided,\n globals,\n transform,\n });\n // One module server per loaded Worker: its globals proxy (one per project root in\n // webrun-modules) can then bind `console` to that Worker's own console (Tail Workers).\n // `esm`: modules stored as ESM already (text, json, wasm entries), served as they are: the\n // module server would serve `math.wasm` or `text.txt` by their extension.\n const loaded = new Map<\n string,\n { files: FilesApi; server: ReturnType<typeof newModuleServer>; esm: Set<string> }\n >();\n const loadedFor = (id: string) => {\n let l = loaded.get(id);\n if (!l) {\n const files = new MemFilesApi();\n const server = newModuleServer({\n cache: new MemFilesApi(),\n project: files,\n basePath: `/loaded/${encodeURIComponent(id)}/`,\n target: \"browser\",\n provided,\n transform,\n globals: {\n ...globals,\n console: `(globalThis.${LOADED_CONSOLES}?.[${JSON.stringify(id)}] ?? globalThis.console)`,\n fetch: `(globalThis.__cellsLoadedOutbound?.[${JSON.stringify(id)}] ?? globalThis.fetch)`,\n },\n });\n l = { files, server, esm: new Set() };\n loaded.set(id, l);\n }\n return l;\n };\n return new SiteBuilder()\n .setEndpoint(\"/modules/*\", (req) => modules.fetch(req))\n .setEndpoint(\"/loaded/:id/*\", async (req, env) => {\n const l = loadedFor(decodeURIComponent(String(env.params.id)));\n const path = decodeURIComponent(\n new URL(req.url).pathname.slice(`/loaded/${env.params.id}/~`.length),\n );\n if (!l.esm.has(path)) return l.server.fetch(req);\n return new Response(await readText(l.files, path), {\n headers: { \"content-type\": \"text/javascript\" },\n });\n })\n .setEndpoint(\"/loaded-src/:id/*\", \"PUT\", async (req, env) => {\n const id = decodeURIComponent(String(env.params.id));\n const path = decodeURIComponent(\n new URL(req.url).pathname.slice(`/loaded-src/${env.params.id}`.length),\n );\n const l = loadedFor(id);\n await l.files.write(path, [new Uint8Array(await req.arrayBuffer())]);\n if (req.headers.has(ESM_HEADER)) l.esm.add(path);\n return new Response(null, { status: 204 });\n })\n .setFiles(\"/src\", opts.projectFiles)\n .build();\n}\n"]}
@@ -159,6 +159,16 @@ export function createProjectRuntime(config, module, host) {
159
159
  },
160
160
  };
161
161
  }
162
+ // The isolates of loaded Workers end with the runtime (on Node, a worker thread's port would
163
+ // keep the process alive; in a browser, a Dedicated Worker would outlive the runtime).
164
+ const isolated = host.isolatedModules;
165
+ if (config.worker_loaders?.length && isolated?.close) {
166
+ const close = runtime.close.bind(runtime);
167
+ runtime.close = async () => {
168
+ await close();
169
+ await isolated.close?.();
170
+ };
171
+ }
162
172
  for (const l of config.worker_loaders ?? []) {
163
173
  if (!host.loadModules)
164
174
  unsupported.push(`worker_loaders[${l.binding}] (the host provides no module loader)`);
@@ -1 +1 @@
1
- {"version":3,"file":"wrangler.js","sourceRoot":"","sources":["../../src/project/wrangler.ts"],"names":[],"mappings":"AACA,OAAO,EAAsC,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACzF,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,WAAW,EAA4B,MAAM,6BAA6B,CAAC;AACpF,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD,OA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,CAAC,SAAS,CAAC;QAC1C,CAAC;QACD,GAAG,EAAE,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,CAC5B,KAAK,EAAE,CAAC,IAAI,CAAC,8EAA8E,EAAE;YAC3F,CAAC;YACD,CAAC;SACF,CAAC;KACL,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,MAAsB;IACpD,MAAM,EAAE,GAAG,MAAM,CAAC,aAAa,CAAC;IAChC,MAAM,EAAE,GAAG,MAAM,CAAC,YAAY,CAAC;IAC/B,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;QAAE,OAAO,MAAM,CAAC;IAC/E,OAAO;QACL,GAAG,MAAM;QACT,aAAa,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QACnE,YAAY,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAC1B,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,aAAa,IAAI,CAAC,CAAC,OAAO,EAAE,CACxE;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { FilesApi } from \"@statewalker/webrun-files\";\nimport { type AssetFiles, type AssetsConfig, createAssets } from \"../bindings/assets.js\";\nimport { celldKv } from \"../bindings/celld-kv.js\";\nimport { celldQueues, type QueueConsumerConfig } from \"../bindings/celld-queues.js\";\nimport { celldWorkflows } from \"../bindings/celld-workflows.js\";\nimport { startCronTriggers } from \"../bindings/cron.js\";\nimport { r2Bucket, r2BucketOn } from \"../bindings/r2.js\";\nimport { celldR2Backend } from \"../bindings/r2-celld.js\";\nimport { type ModuleLoader, workerLoader } from \"../bindings/worker-loader.js\";\nimport { type WorkersAiOptions, workersAi } from \"../bindings/workers-ai.js\";\nimport { entrypointStub } from \"../core/handles.js\";\nimport type { DurableObjectNamespace } from \"../core/namespace.js\";\nimport {\n type CellRuntime,\n type CellRuntimeOptions,\n createCellRuntime,\n type WorkerModule,\n} from \"../core/runtime.js\";\nimport { splitSqlStatements } from \"../core/sql-split.js\";\nimport { filesApiBlobService } from \"../miniflare-compat/blob-service.js\";\nimport { simulatorFetcher } from \"../miniflare-compat/simulator-fetcher.js\";\nimport { D1DatabaseObject, makeD1Binding } from \"../miniflare-compat/vendored.js\";\nimport { systemClock } from \"../ports.js\";\n\n/** The subset of wrangler.json(c) that celld deploys (and cellb reads). */\nexport interface WranglerConfig {\n name?: string;\n main?: string;\n compatibility_date?: string;\n compatibility_flags?: string[];\n vars?: Record<string, unknown>;\n durable_objects?: { bindings?: { name: string; class_name: string; script_name?: string }[] };\n migrations?: {\n tag: string;\n new_sqlite_classes?: string[];\n new_classes?: string[];\n renamed_classes?: { from: string; to: string }[];\n deleted_classes?: string[];\n }[];\n kv_namespaces?: { binding: string; id?: string }[];\n d1_databases?: { binding: string; database_name?: string; database_id?: string }[];\n r2_buckets?: { binding: string; bucket_name: string }[];\n queues?: {\n producers?: { binding: string; queue: string; delivery_delay?: number }[];\n consumers?: QueueConsumerConfig[];\n };\n workflows?: WorkflowConfig[];\n triggers?: { crons?: string[] };\n assets?: AssetsConfig;\n services?: { binding: string; service: string; entrypoint?: string; props?: unknown }[];\n worker_loaders?: { binding: string }[];\n /** Workers AI: served by the host's OpenAI-compatible endpoint (`ProjectHost.ai`), if any. */\n ai?: { binding: string };\n /** Containers (celld runs them with Docker or Podman): not supported, reported. */\n containers?: { class_name: string; image?: string }[];\n}\n\n/** wrangler `workflows` entries. */\nexport interface WorkflowConfig {\n binding: string;\n name: string;\n class_name: string;\n}\n\n/** Runs the Worker's `queue(batch, env, ctx)` handler for a batch celld's queue cell leased. */\ninterface QueueDispatcher {\n deliver(batch: unknown): Promise<void>;\n}\n\nexport interface ProjectHost\n extends Pick<CellRuntimeOptions, \"openSql\" | \"storage\" | \"clock\" | \"peers\" | \"route\"> {\n /** Files of `assets.directory` (path \"/a/b.html\" → bytes), loaded by the host. */\n assetFiles?: AssetFiles;\n /** Runs each loaded Worker in its own realm (celld isolates); classes still use `loadModules`. */\n isolatedModules?: ModuleLoader;\n /** Compiles code given to a Worker Loader binding (esbuild on Node, webrun-modules in browsers). */\n loadModules?: ModuleLoader;\n /** Blob store of the KV simulator (large values): OPFS in a browser, a directory or S3 on a server. */\n files: FilesApi;\n /** The OpenAI-compatible endpoint behind the `ai` binding; without it the binding is unsupported. */\n ai?: WorkersAiOptions;\n}\n\nexport interface ProjectRuntime {\n runtime: CellRuntime;\n /** Configuration entries cellb does not support yet (reported, not silently ignored). */\n unsupported: string[];\n}\n\n/**\n * What `env` of `cloudflare:workers` holds while the Worker's module is evaluated, before the\n * runtime exists: the vars, and the bindings that need no runtime (`ai`; Flue's entry reads\n * `env.AI` at load).\n */\nexport function loadTimeEnv(\n config: WranglerConfig,\n ai?: WorkersAiOptions,\n): Record<string, unknown> {\n const env: Record<string, unknown> = { ...config.vars };\n if (config.ai && ai) env[config.ai.binding] = workersAi(ai);\n return env;\n}\n\n// Internal bindings carrying the runtime-supplied objects behind KV and D1.\nconst KV_OBJECTS = \"__CELLS_KV_OBJECTS\";\nconst D1_OBJECTS = \"__CELLS_D1_OBJECTS\";\nconst QUEUE_OBJECTS = \"__CELLS_QUEUE_OBJECTS\";\nconst WORKFLOW_OBJECTS = \"__CELLS_WORKFLOW_OBJECTS\";\n\n/**\n * Builds a runtime from a wrangler config and the Worker's module namespace — the same\n * inputs celld deploys. Hosts differ only in `host` (storage) and in how they load `main`.\n */\nexport function createProjectRuntime(\n config: WranglerConfig,\n module: WorkerModule,\n host: ProjectHost,\n): ProjectRuntime {\n config = withResourceIds(config);\n const unsupported: string[] = [];\n const durableObjects: NonNullable<CellRuntimeOptions[\"durableObjects\"]> = {};\n const sqliteClasses = new Set<string>();\n for (const m of config.migrations ?? []) {\n for (const c of m.new_sqlite_classes ?? []) sqliteClasses.add(c);\n for (const c of m.new_classes ?? []) sqliteClasses.add(c); // KV-backed on Cloudflare; SQLite here (superset)\n for (const r of m.renamed_classes ?? [])\n unsupported.push(`migrations.renamed_classes (${r.from} → ${r.to})`);\n }\n for (const c of config.containers ?? [])\n unsupported.push(`containers[${c.class_name}] (cellb runs no containers)`);\n for (const b of config.durable_objects?.bindings ?? []) {\n if (b.script_name) unsupported.push(`durable_objects.bindings[${b.name}].script_name`);\n durableObjects[b.name] = { className: b.class_name };\n }\n const worker: WorkerModule = { ...module };\n let kv: ReturnType<typeof celldKv> | undefined;\n if (config.kv_namespaces?.length) {\n kv = celldKv(host.files);\n worker.__KvNamespace = kv.KvNamespaceCell as never;\n durableObjects[KV_OBJECTS] = { className: \"__KvNamespace\" };\n }\n if (config.d1_databases?.length) {\n worker.__D1Database = D1DatabaseObject;\n durableObjects[D1_OBJECTS] = { className: \"__D1Database\" };\n }\n // Queues: every queue is a cell of a runtime-supplied class (as on celld).\n const consumers = new Map((config.queues?.consumers ?? []).map((c) => [c.queue, c]));\n // celld's own queue code (vendor/celld/queues.js): its queue cell, producer and consumer\n // batch, so a queue's cell (and pending messages) is celld's format.\n let queueDispatcher: QueueDispatcher | undefined;\n let queues: ReturnType<typeof celldQueues> | undefined;\n if (config.queues?.producers?.length || consumers.size) {\n queues = celldQueues({\n namespace: () => runtime.env[QUEUE_OBJECTS] as never,\n consumers: [...consumers.values()],\n compatibilityDate: config.compatibility_date,\n runConsumer: (batch) => queueDispatcher!.deliver(batch as never),\n });\n worker.__Queue = queues.QueueCell as never;\n durableObjects[QUEUE_OBJECTS] = { className: \"__Queue\" };\n }\n // Workflows: every instance is a cell of a runtime-supplied class (as on celld).\n // celld's own workflow code (vendor/celld/workflows.js): its instance cell and binding.\n let workflows: ReturnType<typeof celldWorkflows> | undefined;\n if (config.workflows?.length) {\n workflows = celldWorkflows({\n script: config.name ?? \"worker\",\n workflows: Object.fromEntries(config.workflows.map((w) => [w.name, w.class_name])),\n exports: () => module as Record<string, unknown>,\n env: () => runtime.env,\n namespace: () => runtime.env[WORKFLOW_OBJECTS],\n });\n worker[workflows.className] = workflows.WorkflowCell as never;\n durableObjects[WORKFLOW_OBJECTS] = { className: workflows.className };\n }\n if (config.ai && !host.ai)\n unsupported.push(\n `ai[${config.ai.binding}] (Workers AI: give the host an OpenAI-compatible \\`ai\\`)`,\n );\n for (const s of config.services ?? [])\n if (s.service !== config.name)\n unsupported.push(\n `services[${s.binding}] → \"${s.service}\" (only this script's own entrypoints)`,\n );\n const sqlExtensions: string[] = [];\n let deleteAllPreservesAlarm = false;\n for (const f of config.compatibility_flags ?? []) {\n if (f === \"delete_all_preserves_alarm\") deleteAllPreservesAlarm = true;\n else if (f === \"delete_all_deletes_alarm\")\n continue; // the default\n else if (f === \"sqlite_vec\")\n sqlExtensions.push(\"sqlite_vec\"); // vec0 virtual tables, as on celld\n else if (f === \"nodejs_compat\" || f === \"nodejs_compat_v2\")\n continue; // the host's bundler maps node:*\n else if (f === \"websocket_standard_binary_type\")\n continue; // the host picks the project's WebSocketPair\n else unsupported.push(`compatibility_flags: ${f}`);\n }\n\n const runtime = createCellRuntime({\n worker,\n durableObjects,\n vars: { ...config.vars, MINIFLARE_BLOBS: filesApiBlobService(host.files) },\n openSql: host.openSql,\n sqlExtensions,\n deleteAllPreservesAlarm,\n scriptName: config.name ?? \"worker\",\n // celld's fleet-wide namespaces for the resources several scripts can share.\n namespaceKeys: {\n __KvNamespace: \"cells:v1:kv:__KvNamespace\",\n __D1Database: \"cells:v1:d1:__D1Database\",\n __Queue: \"cells:v1:queue:__Queue\",\n },\n storage: host.storage,\n clock: host.clock,\n peers: host.peers,\n route: host.route,\n });\n const env = runtime.env as Record<string, unknown>;\n if (config.ai && host.ai) env[config.ai.binding] = workersAi(host.ai);\n // KV: celld's own client against celld's own namespace cell (cell name \"<id>/<shard>\").\n for (const ns of config.kv_namespaces ?? [])\n env[ns.binding] = new kv!.KvNamespace(() => env[KV_OBJECTS], `${ns.id}/0`);\n for (const p of config.queues?.producers ?? [])\n env[p.binding] = queues!.producer(p.queue, p.delivery_delay ?? 0);\n if (consumers.size) {\n const handler = (module.default as { queue?: (b: unknown, e: unknown, c: unknown) => unknown })\n .queue;\n if (typeof handler !== \"function\")\n unsupported.push(\"queues.consumers without a queue() handler\");\n queueDispatcher = {\n deliver: async (batch) => {\n const pending: Promise<unknown>[] = [];\n await handler?.call(module.default, batch, env, {\n waitUntil: (p: Promise<unknown>) => pending.push(p),\n passThroughOnException() {},\n });\n await Promise.allSettled(pending);\n },\n };\n }\n for (const l of config.worker_loaders ?? []) {\n if (!host.loadModules)\n unsupported.push(`worker_loaders[${l.binding}] (the host provides no module loader)`);\n else\n env[l.binding] = host.isolatedModules\n ? workerLoader(host.isolatedModules) // facets of loaded code run in the isolate as well\n : workerLoader(host.loadModules);\n }\n // Cron Triggers (validated at load time like `celld deploy` does).\n const crons = config.triggers?.crons ?? [];\n if (crons.length) {\n const scheduled = (\n module.default as { scheduled?: (c: unknown, e: unknown, x: unknown) => unknown }\n ).scheduled;\n if (typeof scheduled !== \"function\")\n unsupported.push(\"triggers.crons without a scheduled() handler\");\n else {\n const db = host.openSql(\"__cellb/cron\");\n const stop = startCronTriggers(\n crons,\n (c, x) => runtime.runEvent(() => scheduled.call(module.default, c, env, x)),\n host.clock ?? systemClock,\n cronState(db),\n );\n const close = runtime.close.bind(runtime);\n runtime.close = async () => {\n stop();\n db.close();\n await close();\n };\n }\n }\n // Static assets: routed before the Worker; `assets.binding` exposes env.ASSETS.\n if (config.assets) {\n const hasWorker = typeof (module.default as { fetch?: unknown })?.fetch === \"function\";\n if (host.assetFiles?.has(\"/.assetsignore\"))\n throw new Error(\n `${config.assets.directory ?? \"assets\"}/.assetsignore is not supported by celld; remove it`,\n );\n const assets = createAssets(host.assetFiles ?? new Map(), config.assets, hasWorker);\n if (config.assets.binding) env[config.assets.binding] = assets.binding;\n const workerFetch = runtime.fetch.bind(runtime);\n runtime.fetch = async (req) =>\n assets.route(req) ??\n (hasWorker ? workerFetch(req) : new Response(\"Not found\", { status: 404 }));\n }\n for (const w of config.workflows ?? []) env[w.binding] = workflows!.binding(w.name);\n // Service bindings to this script's own entrypoints (a celld fleet runs one application):\n // default export or a named WorkerEntrypoint, with fetch() and JS RPC.\n for (const s of config.services ?? []) {\n if (s.service !== config.name) continue;\n const target = s.entrypoint ? module[s.entrypoint] : module.default;\n if (!target)\n unsupported.push(`services[${s.binding}].entrypoint \"${s.entrypoint}\" is not exported`);\n else env[s.binding] = entrypointStub(target, env, s.props);\n }\n // R2 objects live directly in the host's store, as celld keeps them in the fleet bucket.\n // With a celld fleet bucket, R2 objects live in it as celld keeps them; else in the FilesApi.\n for (const r2 of config.r2_buckets ?? [])\n env[r2.binding] = host.storage?.objects\n ? r2BucketOn(celldR2Backend(host.storage.objects, r2.bucket_name), r2.binding)\n : r2Bucket(host.files, `/r2/${r2.bucket_name}`, r2.binding);\n for (const d1 of config.d1_databases ?? [])\n env[d1.binding] = celldExec(\n makeD1Binding({\n fetcher: simulatorFetcher(\n env[D1_OBJECTS] as DurableObjectNamespace,\n d1.database_id as string, // set by withResourceIds\n ) as never,\n }) as D1Like,\n );\n for (const name of [...sqliteClasses])\n if (!Object.values(durableObjects).some((d) => d.className === name)) {\n // A migrated class without a binding is fine (reachable through other code paths only).\n }\n return { runtime, unsupported };\n}\n\ninterface D1Like {\n exec(sql: string): Promise<{ count: number; duration: number }>;\n prepare(sql: string): { run(): Promise<unknown> };\n}\n\n/**\n * `D1Database#exec` as celld implements it: statements are split by SQL syntax.\n * workerd's d1-api.ts splits on NEWLINES (Cloudflare's documented behaviour), so a\n * multi-line `CREATE TABLE` fails there but works on celld — and celld is the\n * reference here (verified on celld 0.6.2 by the d1 example in conformance/).\n */\nfunction celldExec<T extends D1Like>(db: T): T {\n const exec = async (sql: string) => {\n const t0 = Date.now();\n const statements = splitSqlStatements(sql).filter((s) => s.trim());\n for (const statement of statements) {\n if (/^\\s*BEGIN\\b/i.test(statement))\n throw new Error(\n \"D1_EXEC_ERROR: the SQL ends in an incomplete statement, which did not run: terminate the last statement with a semicolon\",\n );\n guard(statement);\n await db.prepare(statement).run();\n }\n return { count: statements.length, duration: Date.now() - t0 };\n };\n return celldD1(db, exec) as T;\n}\n\n/**\n * celld's D1 rules on top of workerd's client (celld docs/services/d1.md, checked by the\n * d1-details project): ATTACH/DETACH and TEMP objects are \"not authorized\", VACUUM is\n * \"authorization denied\"; there is one primary and no replica, so sessions return the\n * bookmark \"celld:primary\" and every result reports served_by_primary/served_by_region\n * \"local\"; a read-only statement reports last_row_id and changes as 0.\n */\nfunction guard(sql: string): void {\n if (/^\\s*(ATTACH|DETACH)\\b/i.test(sql) || /^\\s*CREATE\\s+(TEMP|TEMPORARY)\\b/i.test(sql))\n throw new Error(\"D1_ERROR: not authorized\");\n if (/^\\s*VACUUM\\b/i.test(sql)) throw new Error(\"D1_ERROR: authorization denied\");\n}\n\nfunction celldMeta(r: any): any {\n if (!r?.meta) return r;\n r.meta.served_by_primary = true;\n r.meta.served_by_region = \"local\";\n if (r.meta.changed_db === false) {\n r.meta.last_row_id = 0;\n r.meta.changes = 0;\n }\n return r;\n}\n\nfunction celldStatement(stmt: any): any {\n return new Proxy(stmt, {\n get(t, p, r) {\n const v = Reflect.get(t, p, r);\n if (p === \"bind\") return (...a: unknown[]) => celldStatement(v.apply(t, a));\n if (p === \"run\" || p === \"all\")\n return async (...a: unknown[]) => celldMeta(await v.apply(t, a));\n return typeof v === \"function\" ? v.bind(t) : v;\n },\n });\n}\n\nfunction celldD1(db: any, exec?: (sql: string) => Promise<unknown>): any {\n return new Proxy(db, {\n get(t, p, r) {\n if (p === \"exec\" && exec) return exec;\n const v = Reflect.get(t, p, r);\n if (p === \"prepare\")\n return (sql: string) => {\n guard(sql);\n return celldStatement(v.call(t, sql));\n };\n if (p === \"batch\")\n return async (stmts: unknown[], ...a: unknown[]) =>\n ((await v.call(t, stmts, ...a)) as unknown[]).map(celldMeta);\n if (p === \"withSession\")\n return () => {\n const session = celldD1(t);\n return new Proxy(session, {\n get: (s, q, rr) =>\n q === \"getBookmark\" ? () => \"celld:primary\" : Reflect.get(s, q, rr),\n });\n };\n if (p === \"getBookmark\") return () => \"celld:primary\";\n return typeof v === \"function\" ? v.bind(t) : v;\n },\n });\n}\n\n/** Last fired occurrence per cron expression, in a small SQLite database of the host. */\nfunction cronState(db: ReturnType<ProjectHost[\"openSql\"]>) {\n db.exec(\n \"CREATE TABLE IF NOT EXISTS cron_state (expression TEXT PRIMARY KEY, scheduled_time INTEGER)\",\n [],\n );\n return {\n get: (e: string) => {\n const row = db.exec(\"SELECT scheduled_time FROM cron_state WHERE expression = ?\", [e])\n .rows[0];\n return row ? Number(row[0]) : undefined;\n },\n set: (e: string, t: number) =>\n void db.exec(\"INSERT OR REPLACE INTO cron_state (expression, scheduled_time) VALUES (?, ?)\", [\n e,\n t,\n ]),\n };\n}\n\n/**\n * KV namespaces and D1 databases may omit their ids: wrangler provisions them on deploy, and\n * framework builds (Astro's Cloudflare adapter, for one) emit such entries. A KV namespace\n * then takes its binding name as id; a D1 database its `database_name`, else its binding name.\n * Entries with ids are kept as they are, so storage shared with celld keeps its names.\n */\nexport function withResourceIds(config: WranglerConfig): WranglerConfig {\n const kv = config.kv_namespaces;\n const d1 = config.d1_databases;\n if (!kv?.some((n) => !n.id) && !d1?.some((d) => !d.database_id)) return config;\n return {\n ...config,\n kv_namespaces: kv?.map((n) => (n.id ? n : { ...n, id: n.binding })),\n d1_databases: d1?.map((d) =>\n d.database_id ? d : { ...d, database_id: d.database_name ?? d.binding },\n ),\n };\n}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AAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;QAAE,OAAO,MAAM,CAAC;IAC/E,OAAO;QACL,GAAG,MAAM;QACT,aAAa,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QACnE,YAAY,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAC1B,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,aAAa,IAAI,CAAC,CAAC,OAAO,EAAE,CACxE;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { FilesApi } from \"@statewalker/webrun-files\";\nimport { type AssetFiles, type AssetsConfig, createAssets } from \"../bindings/assets.js\";\nimport { celldKv } from \"../bindings/celld-kv.js\";\nimport { celldQueues, type QueueConsumerConfig } from \"../bindings/celld-queues.js\";\nimport { celldWorkflows } from \"../bindings/celld-workflows.js\";\nimport { startCronTriggers } from \"../bindings/cron.js\";\nimport { r2Bucket, r2BucketOn } from \"../bindings/r2.js\";\nimport { celldR2Backend } from \"../bindings/r2-celld.js\";\nimport { type ModuleLoader, workerLoader } from \"../bindings/worker-loader.js\";\nimport { type WorkersAiOptions, workersAi } from \"../bindings/workers-ai.js\";\nimport { entrypointStub } from \"../core/handles.js\";\nimport type { DurableObjectNamespace } from \"../core/namespace.js\";\nimport {\n type CellRuntime,\n type CellRuntimeOptions,\n createCellRuntime,\n type WorkerModule,\n} from \"../core/runtime.js\";\nimport { splitSqlStatements } from \"../core/sql-split.js\";\nimport { filesApiBlobService } from \"../miniflare-compat/blob-service.js\";\nimport { simulatorFetcher } from \"../miniflare-compat/simulator-fetcher.js\";\nimport { D1DatabaseObject, makeD1Binding } from \"../miniflare-compat/vendored.js\";\nimport { systemClock } from \"../ports.js\";\n\n/** The subset of wrangler.json(c) that celld deploys (and cellb reads). */\nexport interface WranglerConfig {\n name?: string;\n main?: string;\n compatibility_date?: string;\n compatibility_flags?: string[];\n vars?: Record<string, unknown>;\n durable_objects?: { bindings?: { name: string; class_name: string; script_name?: string }[] };\n migrations?: {\n tag: string;\n new_sqlite_classes?: string[];\n new_classes?: string[];\n renamed_classes?: { from: string; to: string }[];\n deleted_classes?: string[];\n }[];\n kv_namespaces?: { binding: string; id?: string }[];\n d1_databases?: { binding: string; database_name?: string; database_id?: string }[];\n r2_buckets?: { binding: string; bucket_name: string }[];\n queues?: {\n producers?: { binding: string; queue: string; delivery_delay?: number }[];\n consumers?: QueueConsumerConfig[];\n };\n workflows?: WorkflowConfig[];\n triggers?: { crons?: string[] };\n assets?: AssetsConfig;\n services?: { binding: string; service: string; entrypoint?: string; props?: unknown }[];\n worker_loaders?: { binding: string }[];\n /** Workers AI: served by the host's OpenAI-compatible endpoint (`ProjectHost.ai`), if any. */\n ai?: { binding: string };\n /** Containers (celld runs them with Docker or Podman): not supported, reported. */\n containers?: { class_name: string; image?: string }[];\n}\n\n/** wrangler `workflows` entries. */\nexport interface WorkflowConfig {\n binding: string;\n name: string;\n class_name: string;\n}\n\n/** Runs the Worker's `queue(batch, env, ctx)` handler for a batch celld's queue cell leased. */\ninterface QueueDispatcher {\n deliver(batch: unknown): Promise<void>;\n}\n\nexport interface ProjectHost\n extends Pick<CellRuntimeOptions, \"openSql\" | \"storage\" | \"clock\" | \"peers\" | \"route\"> {\n /** Files of `assets.directory` (path \"/a/b.html\" → bytes), loaded by the host. */\n assetFiles?: AssetFiles;\n /** Runs each loaded Worker in its own realm (celld isolates); classes still use `loadModules`. */\n isolatedModules?: ModuleLoader;\n /** Compiles code given to a Worker Loader binding (esbuild on Node, webrun-modules in browsers). */\n loadModules?: ModuleLoader;\n /** Blob store of the KV simulator (large values): OPFS in a browser, a directory or S3 on a server. */\n files: FilesApi;\n /** The OpenAI-compatible endpoint behind the `ai` binding; without it the binding is unsupported. */\n ai?: WorkersAiOptions;\n}\n\nexport interface ProjectRuntime {\n runtime: CellRuntime;\n /** Configuration entries cellb does not support yet (reported, not silently ignored). */\n unsupported: string[];\n}\n\n/**\n * What `env` of `cloudflare:workers` holds while the Worker's module is evaluated, before the\n * runtime exists: the vars, and the bindings that need no runtime (`ai`; Flue's entry reads\n * `env.AI` at load).\n */\nexport function loadTimeEnv(\n config: WranglerConfig,\n ai?: WorkersAiOptions,\n): Record<string, unknown> {\n const env: Record<string, unknown> = { ...config.vars };\n if (config.ai && ai) env[config.ai.binding] = workersAi(ai);\n return env;\n}\n\n// Internal bindings carrying the runtime-supplied objects behind KV and D1.\nconst KV_OBJECTS = \"__CELLS_KV_OBJECTS\";\nconst D1_OBJECTS = \"__CELLS_D1_OBJECTS\";\nconst QUEUE_OBJECTS = \"__CELLS_QUEUE_OBJECTS\";\nconst WORKFLOW_OBJECTS = \"__CELLS_WORKFLOW_OBJECTS\";\n\n/**\n * Builds a runtime from a wrangler config and the Worker's module namespace — the same\n * inputs celld deploys. Hosts differ only in `host` (storage) and in how they load `main`.\n */\nexport function createProjectRuntime(\n config: WranglerConfig,\n module: WorkerModule,\n host: ProjectHost,\n): ProjectRuntime {\n config = withResourceIds(config);\n const unsupported: string[] = [];\n const durableObjects: NonNullable<CellRuntimeOptions[\"durableObjects\"]> = {};\n const sqliteClasses = new Set<string>();\n for (const m of config.migrations ?? []) {\n for (const c of m.new_sqlite_classes ?? []) sqliteClasses.add(c);\n for (const c of m.new_classes ?? []) sqliteClasses.add(c); // KV-backed on Cloudflare; SQLite here (superset)\n for (const r of m.renamed_classes ?? [])\n unsupported.push(`migrations.renamed_classes (${r.from} → ${r.to})`);\n }\n for (const c of config.containers ?? [])\n unsupported.push(`containers[${c.class_name}] (cellb runs no containers)`);\n for (const b of config.durable_objects?.bindings ?? []) {\n if (b.script_name) unsupported.push(`durable_objects.bindings[${b.name}].script_name`);\n durableObjects[b.name] = { className: b.class_name };\n }\n const worker: WorkerModule = { ...module };\n let kv: ReturnType<typeof celldKv> | undefined;\n if (config.kv_namespaces?.length) {\n kv = celldKv(host.files);\n worker.__KvNamespace = kv.KvNamespaceCell as never;\n durableObjects[KV_OBJECTS] = { className: \"__KvNamespace\" };\n }\n if (config.d1_databases?.length) {\n worker.__D1Database = D1DatabaseObject;\n durableObjects[D1_OBJECTS] = { className: \"__D1Database\" };\n }\n // Queues: every queue is a cell of a runtime-supplied class (as on celld).\n const consumers = new Map((config.queues?.consumers ?? []).map((c) => [c.queue, c]));\n // celld's own queue code (vendor/celld/queues.js): its queue cell, producer and consumer\n // batch, so a queue's cell (and pending messages) is celld's format.\n let queueDispatcher: QueueDispatcher | undefined;\n let queues: ReturnType<typeof celldQueues> | undefined;\n if (config.queues?.producers?.length || consumers.size) {\n queues = celldQueues({\n namespace: () => runtime.env[QUEUE_OBJECTS] as never,\n consumers: [...consumers.values()],\n compatibilityDate: config.compatibility_date,\n runConsumer: (batch) => queueDispatcher!.deliver(batch as never),\n });\n worker.__Queue = queues.QueueCell as never;\n durableObjects[QUEUE_OBJECTS] = { className: \"__Queue\" };\n }\n // Workflows: every instance is a cell of a runtime-supplied class (as on celld).\n // celld's own workflow code (vendor/celld/workflows.js): its instance cell and binding.\n let workflows: ReturnType<typeof celldWorkflows> | undefined;\n if (config.workflows?.length) {\n workflows = celldWorkflows({\n script: config.name ?? \"worker\",\n workflows: Object.fromEntries(config.workflows.map((w) => [w.name, w.class_name])),\n exports: () => module as Record<string, unknown>,\n env: () => runtime.env,\n namespace: () => runtime.env[WORKFLOW_OBJECTS],\n });\n worker[workflows.className] = workflows.WorkflowCell as never;\n durableObjects[WORKFLOW_OBJECTS] = { className: workflows.className };\n }\n if (config.ai && !host.ai)\n unsupported.push(\n `ai[${config.ai.binding}] (Workers AI: give the host an OpenAI-compatible \\`ai\\`)`,\n );\n for (const s of config.services ?? [])\n if (s.service !== config.name)\n unsupported.push(\n `services[${s.binding}] → \"${s.service}\" (only this script's own entrypoints)`,\n );\n const sqlExtensions: string[] = [];\n let deleteAllPreservesAlarm = false;\n for (const f of config.compatibility_flags ?? []) {\n if (f === \"delete_all_preserves_alarm\") deleteAllPreservesAlarm = true;\n else if (f === \"delete_all_deletes_alarm\")\n continue; // the default\n else if (f === \"sqlite_vec\")\n sqlExtensions.push(\"sqlite_vec\"); // vec0 virtual tables, as on celld\n else if (f === \"nodejs_compat\" || f === \"nodejs_compat_v2\")\n continue; // the host's bundler maps node:*\n else if (f === \"websocket_standard_binary_type\")\n continue; // the host picks the project's WebSocketPair\n else unsupported.push(`compatibility_flags: ${f}`);\n }\n\n const runtime = createCellRuntime({\n worker,\n durableObjects,\n vars: { ...config.vars, MINIFLARE_BLOBS: filesApiBlobService(host.files) },\n openSql: host.openSql,\n sqlExtensions,\n deleteAllPreservesAlarm,\n scriptName: config.name ?? \"worker\",\n // celld's fleet-wide namespaces for the resources several scripts can share.\n namespaceKeys: {\n __KvNamespace: \"cells:v1:kv:__KvNamespace\",\n __D1Database: \"cells:v1:d1:__D1Database\",\n __Queue: \"cells:v1:queue:__Queue\",\n },\n storage: host.storage,\n clock: host.clock,\n peers: host.peers,\n route: host.route,\n });\n const env = runtime.env as Record<string, unknown>;\n if (config.ai && host.ai) env[config.ai.binding] = workersAi(host.ai);\n // KV: celld's own client against celld's own namespace cell (cell name \"<id>/<shard>\").\n for (const ns of config.kv_namespaces ?? [])\n env[ns.binding] = new kv!.KvNamespace(() => env[KV_OBJECTS], `${ns.id}/0`);\n for (const p of config.queues?.producers ?? [])\n env[p.binding] = queues!.producer(p.queue, p.delivery_delay ?? 0);\n if (consumers.size) {\n const handler = (module.default as { queue?: (b: unknown, e: unknown, c: unknown) => unknown })\n .queue;\n if (typeof handler !== \"function\")\n unsupported.push(\"queues.consumers without a queue() handler\");\n queueDispatcher = {\n deliver: async (batch) => {\n const pending: Promise<unknown>[] = [];\n await handler?.call(module.default, batch, env, {\n waitUntil: (p: Promise<unknown>) => pending.push(p),\n passThroughOnException() {},\n });\n await Promise.allSettled(pending);\n },\n };\n }\n // The isolates of loaded Workers end with the runtime (on Node, a worker thread's port would\n // keep the process alive; in a browser, a Dedicated Worker would outlive the runtime).\n const isolated = host.isolatedModules as\n | (ModuleLoader & { close?(): void | Promise<void> })\n | undefined;\n if (config.worker_loaders?.length && isolated?.close) {\n const close = runtime.close.bind(runtime);\n runtime.close = async () => {\n await close();\n await isolated.close?.();\n };\n }\n for (const l of config.worker_loaders ?? []) {\n if (!host.loadModules)\n unsupported.push(`worker_loaders[${l.binding}] (the host provides no module loader)`);\n else\n env[l.binding] = host.isolatedModules\n ? workerLoader(host.isolatedModules) // facets of loaded code run in the isolate as well\n : workerLoader(host.loadModules);\n }\n // Cron Triggers (validated at load time like `celld deploy` does).\n const crons = config.triggers?.crons ?? [];\n if (crons.length) {\n const scheduled = (\n module.default as { scheduled?: (c: unknown, e: unknown, x: unknown) => unknown }\n ).scheduled;\n if (typeof scheduled !== \"function\")\n unsupported.push(\"triggers.crons without a scheduled() handler\");\n else {\n const db = host.openSql(\"__cellb/cron\");\n const stop = startCronTriggers(\n crons,\n (c, x) => runtime.runEvent(() => scheduled.call(module.default, c, env, x)),\n host.clock ?? systemClock,\n cronState(db),\n );\n const close = runtime.close.bind(runtime);\n runtime.close = async () => {\n stop();\n db.close();\n await close();\n };\n }\n }\n // Static assets: routed before the Worker; `assets.binding` exposes env.ASSETS.\n if (config.assets) {\n const hasWorker = typeof (module.default as { fetch?: unknown })?.fetch === \"function\";\n if (host.assetFiles?.has(\"/.assetsignore\"))\n throw new Error(\n `${config.assets.directory ?? \"assets\"}/.assetsignore is not supported by celld; remove it`,\n );\n const assets = createAssets(host.assetFiles ?? new Map(), config.assets, hasWorker);\n if (config.assets.binding) env[config.assets.binding] = assets.binding;\n const workerFetch = runtime.fetch.bind(runtime);\n runtime.fetch = async (req) =>\n assets.route(req) ??\n (hasWorker ? workerFetch(req) : new Response(\"Not found\", { status: 404 }));\n }\n for (const w of config.workflows ?? []) env[w.binding] = workflows!.binding(w.name);\n // Service bindings to this script's own entrypoints (a celld fleet runs one application):\n // default export or a named WorkerEntrypoint, with fetch() and JS RPC.\n for (const s of config.services ?? []) {\n if (s.service !== config.name) continue;\n const target = s.entrypoint ? module[s.entrypoint] : module.default;\n if (!target)\n unsupported.push(`services[${s.binding}].entrypoint \"${s.entrypoint}\" is not exported`);\n else env[s.binding] = entrypointStub(target, env, s.props);\n }\n // R2 objects live directly in the host's store, as celld keeps them in the fleet bucket.\n // With a celld fleet bucket, R2 objects live in it as celld keeps them; else in the FilesApi.\n for (const r2 of config.r2_buckets ?? [])\n env[r2.binding] = host.storage?.objects\n ? r2BucketOn(celldR2Backend(host.storage.objects, r2.bucket_name), r2.binding)\n : r2Bucket(host.files, `/r2/${r2.bucket_name}`, r2.binding);\n for (const d1 of config.d1_databases ?? [])\n env[d1.binding] = celldExec(\n makeD1Binding({\n fetcher: simulatorFetcher(\n env[D1_OBJECTS] as DurableObjectNamespace,\n d1.database_id as string, // set by withResourceIds\n ) as never,\n }) as D1Like,\n );\n for (const name of [...sqliteClasses])\n if (!Object.values(durableObjects).some((d) => d.className === name)) {\n // A migrated class without a binding is fine (reachable through other code paths only).\n }\n return { runtime, unsupported };\n}\n\ninterface D1Like {\n exec(sql: string): Promise<{ count: number; duration: number }>;\n prepare(sql: string): { run(): Promise<unknown> };\n}\n\n/**\n * `D1Database#exec` as celld implements it: statements are split by SQL syntax.\n * workerd's d1-api.ts splits on NEWLINES (Cloudflare's documented behaviour), so a\n * multi-line `CREATE TABLE` fails there but works on celld — and celld is the\n * reference here (verified on celld 0.6.2 by the d1 example in conformance/).\n */\nfunction celldExec<T extends D1Like>(db: T): T {\n const exec = async (sql: string) => {\n const t0 = Date.now();\n const statements = splitSqlStatements(sql).filter((s) => s.trim());\n for (const statement of statements) {\n if (/^\\s*BEGIN\\b/i.test(statement))\n throw new Error(\n \"D1_EXEC_ERROR: the SQL ends in an incomplete statement, which did not run: terminate the last statement with a semicolon\",\n );\n guard(statement);\n await db.prepare(statement).run();\n }\n return { count: statements.length, duration: Date.now() - t0 };\n };\n return celldD1(db, exec) as T;\n}\n\n/**\n * celld's D1 rules on top of workerd's client (celld docs/services/d1.md, checked by the\n * d1-details project): ATTACH/DETACH and TEMP objects are \"not authorized\", VACUUM is\n * \"authorization denied\"; there is one primary and no replica, so sessions return the\n * bookmark \"celld:primary\" and every result reports served_by_primary/served_by_region\n * \"local\"; a read-only statement reports last_row_id and changes as 0.\n */\nfunction guard(sql: string): void {\n if (/^\\s*(ATTACH|DETACH)\\b/i.test(sql) || /^\\s*CREATE\\s+(TEMP|TEMPORARY)\\b/i.test(sql))\n throw new Error(\"D1_ERROR: not authorized\");\n if (/^\\s*VACUUM\\b/i.test(sql)) throw new Error(\"D1_ERROR: authorization denied\");\n}\n\nfunction celldMeta(r: any): any {\n if (!r?.meta) return r;\n r.meta.served_by_primary = true;\n r.meta.served_by_region = \"local\";\n if (r.meta.changed_db === false) {\n r.meta.last_row_id = 0;\n r.meta.changes = 0;\n }\n return r;\n}\n\nfunction celldStatement(stmt: any): any {\n return new Proxy(stmt, {\n get(t, p, r) {\n const v = Reflect.get(t, p, r);\n if (p === \"bind\") return (...a: unknown[]) => celldStatement(v.apply(t, a));\n if (p === \"run\" || p === \"all\")\n return async (...a: unknown[]) => celldMeta(await v.apply(t, a));\n return typeof v === \"function\" ? v.bind(t) : v;\n },\n });\n}\n\nfunction celldD1(db: any, exec?: (sql: string) => Promise<unknown>): any {\n return new Proxy(db, {\n get(t, p, r) {\n if (p === \"exec\" && exec) return exec;\n const v = Reflect.get(t, p, r);\n if (p === \"prepare\")\n return (sql: string) => {\n guard(sql);\n return celldStatement(v.call(t, sql));\n };\n if (p === \"batch\")\n return async (stmts: unknown[], ...a: unknown[]) =>\n ((await v.call(t, stmts, ...a)) as unknown[]).map(celldMeta);\n if (p === \"withSession\")\n return () => {\n const session = celldD1(t);\n return new Proxy(session, {\n get: (s, q, rr) =>\n q === \"getBookmark\" ? () => \"celld:primary\" : Reflect.get(s, q, rr),\n });\n };\n if (p === \"getBookmark\") return () => \"celld:primary\";\n return typeof v === \"function\" ? v.bind(t) : v;\n },\n });\n}\n\n/** Last fired occurrence per cron expression, in a small SQLite database of the host. */\nfunction cronState(db: ReturnType<ProjectHost[\"openSql\"]>) {\n db.exec(\n \"CREATE TABLE IF NOT EXISTS cron_state (expression TEXT PRIMARY KEY, scheduled_time INTEGER)\",\n [],\n );\n return {\n get: (e: string) => {\n const row = db.exec(\"SELECT scheduled_time FROM cron_state WHERE expression = ?\", [e])\n .rows[0];\n return row ? Number(row[0]) : undefined;\n },\n set: (e: string, t: number) =>\n void db.exec(\"INSERT OR REPLACE INTO cron_state (expression, scheduled_time) VALUES (?, ?)\", [\n e,\n t,\n ]),\n };\n}\n\n/**\n * KV namespaces and D1 databases may omit their ids: wrangler provisions them on deploy, and\n * framework builds (Astro's Cloudflare adapter, for one) emit such entries. A KV namespace\n * then takes its binding name as id; a D1 database its `database_name`, else its binding name.\n * Entries with ids are kept as they are, so storage shared with celld keeps its names.\n */\nexport function withResourceIds(config: WranglerConfig): WranglerConfig {\n const kv = config.kv_namespaces;\n const d1 = config.d1_databases;\n if (!kv?.some((n) => !n.id) && !d1?.some((d) => !d.database_id)) return config;\n return {\n ...config,\n kv_namespaces: kv?.map((n) => (n.id ? n : { ...n, id: n.binding })),\n d1_databases: d1?.map((d) =>\n d.database_id ? d : { ...d, database_id: d.database_name ?? d.binding },\n ),\n };\n}\n"]}
@@ -142,7 +142,7 @@ export class CellRouter {
142
142
  lost,
143
143
  ]);
144
144
  if (!res.body)
145
- return done(), res;
145
+ return (done(), res);
146
146
  const { readable, writable } = new TransformStream();
147
147
  res.body.pipeTo(writable, { signal: ac.signal }).then(done, done);
148
148
  return new Response(readable, res);