@statewalker/cellb 0.1.0 → 0.2.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.
- package/README.md +45 -21
- package/dist/adapters/wasm-sqlite.d.ts +11 -0
- package/dist/adapters/wasm-sqlite.js +26 -3
- package/dist/adapters/wasm-sqlite.js.map +1 -1
- package/dist/bindings/assets.js +2 -2
- package/dist/bindings/assets.js.map +1 -1
- package/dist/bindings/r2.js +2 -2
- package/dist/bindings/r2.js.map +1 -1
- package/dist/browser.d.ts +0 -1
- package/dist/browser.js +0 -1
- package/dist/browser.js.map +1 -1
- package/dist/bucket/celld-cells.js +1 -1
- package/dist/bucket/celld-cells.js.map +1 -1
- package/dist/bucket/s3-object-store.js +1 -1
- package/dist/bucket/s3-object-store.js.map +1 -1
- package/dist/core/handles.d.ts +5 -2
- package/dist/core/handles.js +12 -1
- package/dist/core/handles.js.map +1 -1
- package/dist/core/id.js +3 -3
- package/dist/core/id.js.map +1 -1
- package/dist/core/namespace.d.ts +1 -1
- package/dist/core/namespace.js +2 -1
- package/dist/core/namespace.js.map +1 -1
- package/dist/core/object-host.d.ts +23 -0
- package/dist/core/object-host.js +87 -6
- package/dist/core/object-host.js.map +1 -1
- package/dist/core/runtime.d.ts +10 -0
- package/dist/core/runtime.js +43 -2
- package/dist/core/runtime.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/isolate/browser.js +1 -1
- package/dist/isolate/browser.js.map +1 -1
- package/dist/isolate/host.d.ts +5 -1
- package/dist/isolate/host.js +19 -3
- package/dist/isolate/host.js.map +1 -1
- package/dist/isolate/isolate-worker.js +11 -1
- package/dist/isolate/isolate-worker.js.map +1 -1
- package/dist/isolate/isolate.js +12 -0
- package/dist/isolate/isolate.js.map +1 -1
- package/dist/isolate/node-entry.js +11 -0
- package/dist/isolate/node-entry.js.map +1 -1
- package/dist/isolate/protocol.d.ts +4 -0
- package/dist/isolate/protocol.js +118 -2
- package/dist/isolate/protocol.js.map +1 -1
- package/dist/node-compat/crypto.js +3 -3
- package/dist/node-compat/crypto.js.map +1 -1
- package/dist/project/browser-host.js +3 -2
- package/dist/project/browser-host.js.map +1 -1
- package/dist/project/node-project.js +13 -1
- package/dist/project/node-project.js.map +1 -1
- package/dist/project/site-loader.d.ts +45 -0
- package/dist/project/site-loader.js +97 -0
- package/dist/project/site-loader.js.map +1 -0
- package/dist/project/site.d.ts +0 -36
- package/dist/project/site.js +11 -99
- package/dist/project/site.js.map +1 -1
- package/dist/project/wrangler.js +10 -0
- package/dist/project/wrangler.js.map +1 -1
- package/dist/router/cell-router.js +1 -1
- package/dist/router/cell-router.js.map +1 -1
- package/dist/site.d.ts +1 -0
- package/dist/site.js +6 -0
- package/dist/site.js.map +1 -0
- package/dist/ws/frames.d.ts +14 -0
- package/dist/ws/frames.js +51 -0
- package/dist/ws/frames.js.map +1 -1
- package/dist/ws/server.d.ts +4 -0
- package/dist/ws/server.js +17 -2
- package/dist/ws/server.js.map +1 -1
- package/package.json +25 -5
|
@@ -96,6 +96,17 @@ export async function bundleWorker(entry, logs, outbound, opts = {}) {
|
|
|
96
96
|
mainFields: ["module", "main"],
|
|
97
97
|
target: "es2022",
|
|
98
98
|
logLevel: "silent",
|
|
99
|
+
// nodejs_compat: CommonJS dependencies `require()` Node's built-ins (mime-types requires
|
|
100
|
+
// node:path), as they may under workerd's nodejs_compat. In an ES module bundle esbuild's
|
|
101
|
+
// require shim needs a `require` in scope: vitest's module runner provides one, plain Node
|
|
102
|
+
// does not.
|
|
103
|
+
...(opts.nodeCompat
|
|
104
|
+
? {
|
|
105
|
+
banner: {
|
|
106
|
+
js: 'import { createRequire as __cellbCreateRequire } from "node:module";\nconst require = __cellbCreateRequire(import.meta.url);',
|
|
107
|
+
},
|
|
108
|
+
}
|
|
109
|
+
: {}),
|
|
99
110
|
inject: [
|
|
100
111
|
ownModule(import.meta.dirname, "workers-globals"),
|
|
101
112
|
...(logs ? ["cellb:console"] : []),
|
|
@@ -300,7 +311,8 @@ export function nodeIsolatedLoader(storage) {
|
|
|
300
311
|
}));
|
|
301
312
|
b.onLoad({ filter: /.*/, namespace: "isolate-workers" }, () => ({
|
|
302
313
|
contents: [
|
|
303
|
-
|
|
314
|
+
// cloudflare-workers.js in the published package (dist/), .ts in the sources.
|
|
315
|
+
`export * from ${JSON.stringify(ownModule(import.meta.dirname, "cloudflare-workers"))};`,
|
|
304
316
|
"export const env = globalThis.__cellsProjectScope.env, exports = globalThis.__cellsProjectScope.exports, waitUntil = (p) => globalThis.__cellsProjectScope.waitUntil(p);",
|
|
305
317
|
].join("\n"),
|
|
306
318
|
loader: "js",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-project.js","sourceRoot":"","sources":["../../src/project/node-project.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAGL,UAAU,EACV,aAAa,GACd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,KAAK,cAAc,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC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C3B,IAAI,CAAC,gBAAgB;QAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACtE,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AACD,KAAK,UAAU,iBAAiB;IAC9B,gBAAgB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,gBAAgB,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;IACtF,MAAM,KAAK,CAAC;QACV,WAAW,EAAE,CAAC,SAAS,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,uBAAuB,CAAC,CAAC;QACtE,OAAO,EAAE,gBAAgB;QACzB,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,KAAK;QACb,QAAQ,EAAE,MAAM;QAChB,MAAM,EAAE,QAAQ;QAChB,QAAQ,EAAE,QAAQ;KACnB,CAAC,CAAC;IACH,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED,wFAAwF;AACxF,SAAS,wBAAwB,CAAC,KAAkB;IAClD,MAAM,CAAC,GAAG,UAAqC,CAAC;IAChD,CAAC,CAAC,mBAAmB,GAAG,KAAK,CAAC;IAC9B,CAAC,CAAC,oBAAoB,KAAK,cAAc,CAAC;IAC1C,uEAAuE;IACvE,CAAC,CAAC,kBAAkB,KAAK,IAAI,KAAK,CAChC,EAAE,EACF,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAC5E,CAAC;AACJ,CAAC;AACD,MAAM,cAAc,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC","sourcesContent":["import {\n existsSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { builtinModules, createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { Worker as NodeWorker } from \"node:worker_threads\";\nimport { build } from \"esbuild\";\nimport { applyD1Migrations } from \"../bindings/d1-migrations.js\";\nimport {\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport type { WorkerModule } from \"../core/runtime.js\";\nimport { isolatedModuleLoader } from \"../isolate/host.js\";\nimport type { PortLike } from \"../isolate/protocol.js\";\nimport type { CellStorage } from \"../ports.js\";\nimport * as workersClasses from \"./cloudflare-workers.js\";\nimport { parseJsonc } from \"./jsonc.js\";\nimport { ownModule } from \"./own-module.js\";\nimport { type WorkerScope, workerScope } from \"./worker-scope.js\";\nimport {\n createProjectRuntime,\n loadTimeEnv,\n type ProjectHost,\n type ProjectRuntime,\n type WranglerConfig,\n} from \"./wrangler.js\";\n\n/** Reads `wrangler.jsonc` / `wrangler.json` of a project directory (celld reads the same files). */\nexport function readWranglerConfig(dir: string): WranglerConfig {\n for (const name of [\"wrangler.jsonc\", \"wrangler.json\"]) {\n const p = join(dir, name);\n if (existsSync(p)) return parseJsonc(readFileSync(p, \"utf8\")) as WranglerConfig;\n }\n throw new Error(`no wrangler.jsonc or wrangler.json in ${dir}`);\n}\n\n/** A bare Node.js built-in specifier (\"path\", \"fs/promises\"), not one of a package. */\nconst nodeBuiltinName = new RegExp(\n `^(${builtinModules\n .filter((m) => !m.startsWith(\"_\") && !m.includes(\":\"))\n .map((m) => m.replace(/[/]/g, \"\\\\/\"))\n .join(\"|\")})$`,\n);\n\n/**\n * Node host: bundles `main` with esbuild (as `celld deploy` does) and builds the runtime.\n * `cloudflare:workers` resolves to cellb's module so user classes extend the\n * runtime's own DurableObject / WorkerEntrypoint.\n */\n/** Bundles Worker code (a file, or in-memory modules) with the runtime's module mappings, then imports it. */\nexport async function bundleWorker(\n entry: { path: string } | { modules: Record<string, string>; main: string },\n logs?: LogSink,\n outbound?: typeof fetch,\n opts: { nodeCompat?: boolean; standardBinaryType?: boolean; scope?: WorkerScope } = {},\n): Promise<WorkerModule> {\n // `env` and `exports` of `cloudflare:workers` belong to one Worker: the bundle reads them\n // from its own scope (empty objects for code that has none).\n const scopeKey = opts.scope ? `s${Math.random().toString(36).slice(2)}` : \"\";\n if (opts.scope) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[scopeKey] = opts.scope;\n }\n // Loaded code gets a bundle-local `fetch` (globalOutbound policy)…\n const outboundKey = outbound ? `o${Math.random().toString(36).slice(2)}` : \"\";\n if (outbound) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[outboundKey] = outbound;\n }\n // …and a bundle-local `console` that also feeds its Tail Workers.\n const consoleKey = logs ? `c${Math.random().toString(36).slice(2)}` : \"\";\n if (logs) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\n const registry = g.__cellsConsoles as Record<string, unknown>;\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 registry[consoleKey] = 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 const outDir = mkdtempSync(join(tmpdir(), \"cells-worker-\"));\n const out = join(outDir, \"worker.mjs\");\n const cfWorkers = ownModule(import.meta.dirname, \"cloudflare-workers\");\n // This bundle's `cloudflare:workers`: the runtime's classes plus its own `env` and `exports`.\n // A file of its own, kept out of the bundle so it adds no names to the Worker's scope.\n const workersModule = join(outDir, \"cloudflare-workers.mjs\");\n writeFileSync(\n workersModule,\n [\n `export * from ${JSON.stringify(cfWorkers)};`,\n `const scope = globalThis.__cellsWorkerScopes?.[${JSON.stringify(scopeKey)}];`,\n \"export const env = scope ? scope.env : {};\",\n \"export const exports = scope ? scope.exports : {};\",\n \"export const waitUntil = (p) => scope?.waitUntil(p);\",\n ].join(\"\\n\"),\n );\n const memory = \"modules\" in entry ? entry.modules : undefined;\n await build({\n entryPoints: [\n memory ? `memory:${(entry as { main: string }).main}` : (entry as { path: string }).path,\n ],\n outfile: out,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n // As `celld deploy` resolves packages: workerd's conditions, then `module` and `main` (the\n // neutral platform has no main fields, so a package with only `main` would not resolve).\n conditions: [\"workerd\", \"worker\", \"browser\"],\n mainFields: [\"module\", \"main\"],\n target: \"es2022\",\n logLevel: \"silent\",\n inject: [\n ownModule(import.meta.dirname, \"workers-globals\"),\n ...(logs ? [\"cellb:console\"] : []),\n ...(outbound ? [\"cellb:fetch\"] : []),\n ],\n plugins: [\n {\n name: \"cells-modules\",\n setup(b) {\n b.onResolve({ filter: /^cellb:console$/ }, () => ({\n path: \"console\",\n namespace: \"cells-console\",\n }));\n // nodejs_compat on a Node host: `node:*` are the real Node.js modules.\n if (opts.nodeCompat) {\n b.onResolve({ filter: /^node:/ }, (a) => ({ path: a.path, external: true }));\n // workerd's nodejs_compat also takes the bare names (\"path\", \"fs/promises\").\n b.onResolve({ filter: nodeBuiltinName }, (a) => ({\n path: `node:${a.path}`,\n external: true,\n }));\n }\n b.onResolve({ filter: /^cellb:compat$/ }, () => ({\n path: \"compat\",\n namespace: \"cells-compat\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-compat\" }, () => ({\n contents: `export const standardBinaryType = ${!!opts.standardBinaryType};`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cellb:fetch$/ }, () => ({\n path: \"fetch\",\n namespace: \"cells-fetch\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-fetch\" }, () => ({\n contents: `export const fetch = globalThis.__cellsOutbound[${JSON.stringify(outboundKey)}];`,\n loader: \"js\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-console\" }, () => ({\n contents: `export const console = globalThis.__cellsConsoles[${JSON.stringify(consoleKey)}];`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: workersModule,\n external: true,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n external: true,\n }));\n b.onResolve({ filter: /^cellb:ws$/ }, () => ({\n path: ownModule(import.meta.dirname, \"workers-globals-module\"),\n external: true,\n }));\n if (!memory) return;\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: memory[a.path],\n loader: \"js\",\n }));\n },\n },\n ],\n });\n return (await import(/* @vite-ignore */ out)) as WorkerModule;\n}\n\n/** Worker Loader on Node: compiles `WorkerCode.modules` with esbuild (as celld compiles loaded code). */\nexport const nodeModuleLoader: ModuleLoader = async (_id, code, logs) => {\n const outbound = outboundFetch(code);\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n // `env` and `exports` of the loaded code's `cloudflare:workers` are its own (WorkerCode.env).\n const env = code.env ?? {};\n const scope = workerScope(env);\n const module = (await bundleWorker({ modules, main: code.mainModule }, logs, outbound, {\n scope,\n })) as Record<string, unknown>;\n scope.bind({ env, exports: ctxExports(module, env) });\n return module;\n};\n\nexport async function loadNodeProject(\n dir: string,\n host: Omit<ProjectHost, \"loadModules\"> & Partial<Pick<ProjectHost, \"loadModules\">>,\n): Promise<ProjectRuntime & { config: WranglerConfig }> {\n const config = readWranglerConfig(dir);\n if (!config.main && !config.assets)\n throw new Error(\"wrangler config has neither `main` nor `assets`\");\n const flags = config.compatibility_flags ?? [];\n const nodeCompat = flags.some((f) => f.startsWith(\"nodejs_compat\"));\n const standardBinaryType = flags.includes(\"websocket_standard_binary_type\");\n // The module reads `env` from `cloudflare:workers` while it is evaluated, before the\n // runtime exists: until then the scope holds the configuration's vars (and `ai`).\n const scope = workerScope(loadTimeEnv(config, host.ai));\n // A bundle built elsewhere for cellb (cellbHostModule: webrun-bundler in a browser, say) reads\n // the runtime from globals, as in the browser realm: set them here too, so the same bundle\n // runs on Node. (One such project per process: the globals are the process's.)\n installHostModuleGlobals(scope);\n // As the browser host: nodejs_compat fills process.env with the text vars (from compatibility\n // date 2025-04-01). Node shares its real process with the Worker, so they land there.\n if (\n nodeCompat &&\n !flags.includes(\"nodejs_compat_do_not_populate_process_env\") &&\n (flags.includes(\"nodejs_compat_populate_process_env\") ||\n (config.compatibility_date ?? \"\") >= \"2025-04-01\")\n )\n for (const [k, v] of Object.entries(config.vars ?? {}))\n if (typeof v === \"string\") process.env[k] ??= v;\n const module = config.main\n ? await bundleWorker({ path: resolve(dir, config.main) }, undefined, undefined, {\n nodeCompat,\n standardBinaryType,\n scope,\n })\n : ({ default: {} } as WorkerModule);\n const assetFiles = config.assets?.directory\n ? readAssetDirectory(resolve(dir, config.assets.directory))\n : undefined;\n const project = createProjectRuntime(config, module, {\n loadModules: nodeModuleLoader,\n // own realm, as celld; facets logged like the root's\n isolatedModules: nodeIsolatedLoader(() => host.storage),\n assetFiles,\n ...host,\n });\n scope.bind(project.runtime);\n return { ...project, config };\n}\n\n/** Reads an assets directory into \"/path\" → bytes (what `celld deploy` uploads). */\nexport function readAssetDirectory(root: string): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>();\n const walk = (dir: string, prefix: string) => {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name);\n if (statSync(full).isDirectory()) walk(full, `${prefix}${name}/`);\n else files.set(`${prefix}${name}`, new Uint8Array(readFileSync(full)));\n }\n };\n walk(root, \"/\");\n return files;\n}\n\n/**\n * `celld d1 migrations apply DATABASE` for a Node-hosted project: reads\n * `migrations_dir` (default \"migrations\") of the `d1_databases` entry and applies what is new.\n */\nexport async function applyNodeD1Migrations(\n dir: string,\n runtime: { env: Record<string, unknown> },\n database: string,\n) {\n const config = readWranglerConfig(dir);\n const d1 = config.d1_databases?.find(\n (d) => d.database_name === database || d.binding === database,\n );\n if (!d1) throw new Error(`no d1_databases entry named ${database}`);\n const mdir = resolve(dir, (d1 as { migrations_dir?: string }).migrations_dir ?? \"migrations\");\n const files: [string, string][] = existsSync(mdir)\n ? readdirSync(mdir).map((f) => [f, readFileSync(join(mdir, f), \"utf8\")])\n : [];\n return applyD1Migrations(\n runtime.env[d1.binding] as never,\n files,\n (d1 as { migrations_table?: string }).migrations_table ?? \"d1_migrations\",\n );\n}\n\n/**\n * Loaded Workers in worker threads (one realm each), like celld's isolates. The code is\n * bundled with esbuild (cloudflare:workers bundled in) and imported in the thread from a\n * data: URL; Durable Object classes for facets still load in this realm.\n */\nlet isolateEntry: Promise<string> | undefined;\nexport function nodeIsolatedLoader(storage?: () => CellStorage | undefined): ModuleLoader {\n return isolatedModuleLoader({\n storage,\n spawn: () => {\n const port = new NodeWorker(new URL(`file://${isolateEntryPathSync()}`));\n port.unref(); // an idle isolate never keeps the process alive\n return { port: port as unknown as PortLike, terminate: () => void port.terminate() };\n },\n prepare: async (_id, code) => {\n isolateEntry ??= buildIsolateEntry();\n await isolateEntry;\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n const out = await build({\n entryPoints: [`memory:${code.mainModule}`],\n write: false,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n target: \"es2022\",\n logLevel: \"silent\",\n plugins: [\n {\n name: \"isolate-modules\",\n setup(b) {\n // The loaded Worker is its thread's own: `env` and `exports` are the scope\n // serveIsolate keeps for it.\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: \"cloudflare:workers\",\n namespace: \"isolate-workers\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"isolate-workers\" }, () => ({\n contents: [\n 'export * from \"./cloudflare-workers.ts\";',\n \"export const env = globalThis.__cellsProjectScope.env, exports = globalThis.__cellsProjectScope.exports, waitUntil = (p) => globalThis.__cellsProjectScope.waitUntil(p);\",\n ].join(\"\\n\"),\n loader: \"js\",\n resolveDir: import.meta.dirname,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n }));\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: modules[a.path],\n loader: \"js\",\n }));\n },\n },\n ],\n });\n return { source: out.outputFiles[0].text };\n },\n });\n}\n\nlet isolateEntryFile = \"\";\nfunction isolateEntryPathSync(): string {\n if (!isolateEntryFile) throw new Error(\"isolate entry not built yet\");\n return isolateEntryFile;\n}\nasync function buildIsolateEntry(): Promise<string> {\n isolateEntryFile = join(mkdtempSync(join(tmpdir(), \"cells-isolate-\")), \"isolate.mjs\");\n await build({\n entryPoints: [ownModule(import.meta.dirname, \"../isolate/node-entry\")],\n outfile: isolateEntryFile,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: \"node22\",\n logLevel: \"silent\",\n });\n return isolateEntryFile;\n}\n\n/** The globals `@statewalker/cellb/host-modules` bundles read (see host-modules.ts). */\nfunction installHostModuleGlobals(scope: WorkerScope): void {\n const g = globalThis as Record<string, unknown>;\n g.__cellsProjectScope = scope;\n g.__cellsWorkersModule ??= workersClasses;\n // node:* from Node itself (the browser realm gives cellb's polyfills).\n g.__cellsNodeModules ??= new Proxy(\n {},\n { get: (_t, k) => (typeof k === \"string\" ? requireBuiltin(k) : undefined) },\n );\n}\nconst requireBuiltin = createRequire(import.meta.url);\n"]}
|
|
1
|
+
{"version":3,"file":"node-project.js","sourceRoot":"","sources":["../../src/project/node-project.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAGL,UAAU,EACV,aAAa,GACd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,KAAK,cAAc,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAoB,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EACL,oBAAoB,EACpB,WAAW,GAIZ,MAAM,eAAe,CAAC;AAEvB,oGAAoG;AACpG,MAAM,UAAU,kBAAkB,CAAC,GAAW;IAC5C,KAAK,MAAM,IAAI,IAAI,CAAC,gBAAgB,EAAE,eAAe,CAAC,EAAE,CAAC;QACvD,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAC1B,IAAI,UAAU,CAAC,CAAC,CAAC;YAAE,OAAO,UAA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,CAAC;AACD,KAAK,UAAU,iBAAiB;IAC9B,gBAAgB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,gBAAgB,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;IACtF,MAAM,KAAK,CAAC;QACV,WAAW,EAAE,CAAC,SAAS,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,uBAAuB,CAAC,CAAC;QACtE,OAAO,EAAE,gBAAgB;QACzB,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,KAAK;QACb,QAAQ,EAAE,MAAM;QAChB,MAAM,EAAE,QAAQ;QAChB,QAAQ,EAAE,QAAQ;KACnB,CAAC,CAAC;IACH,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED,wFAAwF;AACxF,SAAS,wBAAwB,CAAC,KAAkB;IAClD,MAAM,CAAC,GAAG,UAAqC,CAAC;IAChD,CAAC,CAAC,mBAAmB,GAAG,KAAK,CAAC;IAC9B,CAAC,CAAC,oBAAoB,KAAK,cAAc,CAAC;IAC1C,uEAAuE;IACvE,CAAC,CAAC,kBAAkB,KAAK,IAAI,KAAK,CAChC,EAAE,EACF,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAC5E,CAAC;AACJ,CAAC;AACD,MAAM,cAAc,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC","sourcesContent":["import {\n existsSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { builtinModules, createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { Worker as NodeWorker } from \"node:worker_threads\";\nimport { build } from \"esbuild\";\nimport { applyD1Migrations } from \"../bindings/d1-migrations.js\";\nimport {\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport type { WorkerModule } from \"../core/runtime.js\";\nimport { isolatedModuleLoader } from \"../isolate/host.js\";\nimport type { PortLike } from \"../isolate/protocol.js\";\nimport type { CellStorage } from \"../ports.js\";\nimport * as workersClasses from \"./cloudflare-workers.js\";\nimport { parseJsonc } from \"./jsonc.js\";\nimport { ownModule } from \"./own-module.js\";\nimport { type WorkerScope, workerScope } from \"./worker-scope.js\";\nimport {\n createProjectRuntime,\n loadTimeEnv,\n type ProjectHost,\n type ProjectRuntime,\n type WranglerConfig,\n} from \"./wrangler.js\";\n\n/** Reads `wrangler.jsonc` / `wrangler.json` of a project directory (celld reads the same files). */\nexport function readWranglerConfig(dir: string): WranglerConfig {\n for (const name of [\"wrangler.jsonc\", \"wrangler.json\"]) {\n const p = join(dir, name);\n if (existsSync(p)) return parseJsonc(readFileSync(p, \"utf8\")) as WranglerConfig;\n }\n throw new Error(`no wrangler.jsonc or wrangler.json in ${dir}`);\n}\n\n/** A bare Node.js built-in specifier (\"path\", \"fs/promises\"), not one of a package. */\nconst nodeBuiltinName = new RegExp(\n `^(${builtinModules\n .filter((m) => !m.startsWith(\"_\") && !m.includes(\":\"))\n .map((m) => m.replace(/[/]/g, \"\\\\/\"))\n .join(\"|\")})$`,\n);\n\n/**\n * Node host: bundles `main` with esbuild (as `celld deploy` does) and builds the runtime.\n * `cloudflare:workers` resolves to cellb's module so user classes extend the\n * runtime's own DurableObject / WorkerEntrypoint.\n */\n/** Bundles Worker code (a file, or in-memory modules) with the runtime's module mappings, then imports it. */\nexport async function bundleWorker(\n entry: { path: string } | { modules: Record<string, string>; main: string },\n logs?: LogSink,\n outbound?: typeof fetch,\n opts: { nodeCompat?: boolean; standardBinaryType?: boolean; scope?: WorkerScope } = {},\n): Promise<WorkerModule> {\n // `env` and `exports` of `cloudflare:workers` belong to one Worker: the bundle reads them\n // from its own scope (empty objects for code that has none).\n const scopeKey = opts.scope ? `s${Math.random().toString(36).slice(2)}` : \"\";\n if (opts.scope) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[scopeKey] = opts.scope;\n }\n // Loaded code gets a bundle-local `fetch` (globalOutbound policy)…\n const outboundKey = outbound ? `o${Math.random().toString(36).slice(2)}` : \"\";\n if (outbound) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[outboundKey] = outbound;\n }\n // …and a bundle-local `console` that also feeds its Tail Workers.\n const consoleKey = logs ? `c${Math.random().toString(36).slice(2)}` : \"\";\n if (logs) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\n const registry = g.__cellsConsoles as Record<string, unknown>;\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 registry[consoleKey] = 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 const outDir = mkdtempSync(join(tmpdir(), \"cells-worker-\"));\n const out = join(outDir, \"worker.mjs\");\n const cfWorkers = ownModule(import.meta.dirname, \"cloudflare-workers\");\n // This bundle's `cloudflare:workers`: the runtime's classes plus its own `env` and `exports`.\n // A file of its own, kept out of the bundle so it adds no names to the Worker's scope.\n const workersModule = join(outDir, \"cloudflare-workers.mjs\");\n writeFileSync(\n workersModule,\n [\n `export * from ${JSON.stringify(cfWorkers)};`,\n `const scope = globalThis.__cellsWorkerScopes?.[${JSON.stringify(scopeKey)}];`,\n \"export const env = scope ? scope.env : {};\",\n \"export const exports = scope ? scope.exports : {};\",\n \"export const waitUntil = (p) => scope?.waitUntil(p);\",\n ].join(\"\\n\"),\n );\n const memory = \"modules\" in entry ? entry.modules : undefined;\n await build({\n entryPoints: [\n memory ? `memory:${(entry as { main: string }).main}` : (entry as { path: string }).path,\n ],\n outfile: out,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n // As `celld deploy` resolves packages: workerd's conditions, then `module` and `main` (the\n // neutral platform has no main fields, so a package with only `main` would not resolve).\n conditions: [\"workerd\", \"worker\", \"browser\"],\n mainFields: [\"module\", \"main\"],\n target: \"es2022\",\n logLevel: \"silent\",\n // nodejs_compat: CommonJS dependencies `require()` Node's built-ins (mime-types requires\n // node:path), as they may under workerd's nodejs_compat. In an ES module bundle esbuild's\n // require shim needs a `require` in scope: vitest's module runner provides one, plain Node\n // does not.\n ...(opts.nodeCompat\n ? {\n banner: {\n js: 'import { createRequire as __cellbCreateRequire } from \"node:module\";\\nconst require = __cellbCreateRequire(import.meta.url);',\n },\n }\n : {}),\n inject: [\n ownModule(import.meta.dirname, \"workers-globals\"),\n ...(logs ? [\"cellb:console\"] : []),\n ...(outbound ? [\"cellb:fetch\"] : []),\n ],\n plugins: [\n {\n name: \"cells-modules\",\n setup(b) {\n b.onResolve({ filter: /^cellb:console$/ }, () => ({\n path: \"console\",\n namespace: \"cells-console\",\n }));\n // nodejs_compat on a Node host: `node:*` are the real Node.js modules.\n if (opts.nodeCompat) {\n b.onResolve({ filter: /^node:/ }, (a) => ({ path: a.path, external: true }));\n // workerd's nodejs_compat also takes the bare names (\"path\", \"fs/promises\").\n b.onResolve({ filter: nodeBuiltinName }, (a) => ({\n path: `node:${a.path}`,\n external: true,\n }));\n }\n b.onResolve({ filter: /^cellb:compat$/ }, () => ({\n path: \"compat\",\n namespace: \"cells-compat\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-compat\" }, () => ({\n contents: `export const standardBinaryType = ${!!opts.standardBinaryType};`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cellb:fetch$/ }, () => ({\n path: \"fetch\",\n namespace: \"cells-fetch\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-fetch\" }, () => ({\n contents: `export const fetch = globalThis.__cellsOutbound[${JSON.stringify(outboundKey)}];`,\n loader: \"js\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-console\" }, () => ({\n contents: `export const console = globalThis.__cellsConsoles[${JSON.stringify(consoleKey)}];`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: workersModule,\n external: true,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n external: true,\n }));\n b.onResolve({ filter: /^cellb:ws$/ }, () => ({\n path: ownModule(import.meta.dirname, \"workers-globals-module\"),\n external: true,\n }));\n if (!memory) return;\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: memory[a.path],\n loader: \"js\",\n }));\n },\n },\n ],\n });\n return (await import(/* @vite-ignore */ out)) as WorkerModule;\n}\n\n/** Worker Loader on Node: compiles `WorkerCode.modules` with esbuild (as celld compiles loaded code). */\nexport const nodeModuleLoader: ModuleLoader = async (_id, code, logs) => {\n const outbound = outboundFetch(code);\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n // `env` and `exports` of the loaded code's `cloudflare:workers` are its own (WorkerCode.env).\n const env = code.env ?? {};\n const scope = workerScope(env);\n const module = (await bundleWorker({ modules, main: code.mainModule }, logs, outbound, {\n scope,\n })) as Record<string, unknown>;\n scope.bind({ env, exports: ctxExports(module, env) });\n return module;\n};\n\nexport async function loadNodeProject(\n dir: string,\n host: Omit<ProjectHost, \"loadModules\"> & Partial<Pick<ProjectHost, \"loadModules\">>,\n): Promise<ProjectRuntime & { config: WranglerConfig }> {\n const config = readWranglerConfig(dir);\n if (!config.main && !config.assets)\n throw new Error(\"wrangler config has neither `main` nor `assets`\");\n const flags = config.compatibility_flags ?? [];\n const nodeCompat = flags.some((f) => f.startsWith(\"nodejs_compat\"));\n const standardBinaryType = flags.includes(\"websocket_standard_binary_type\");\n // The module reads `env` from `cloudflare:workers` while it is evaluated, before the\n // runtime exists: until then the scope holds the configuration's vars (and `ai`).\n const scope = workerScope(loadTimeEnv(config, host.ai));\n // A bundle built elsewhere for cellb (cellbHostModule: webrun-bundler in a browser, say) reads\n // the runtime from globals, as in the browser realm: set them here too, so the same bundle\n // runs on Node. (One such project per process: the globals are the process's.)\n installHostModuleGlobals(scope);\n // As the browser host: nodejs_compat fills process.env with the text vars (from compatibility\n // date 2025-04-01). Node shares its real process with the Worker, so they land there.\n if (\n nodeCompat &&\n !flags.includes(\"nodejs_compat_do_not_populate_process_env\") &&\n (flags.includes(\"nodejs_compat_populate_process_env\") ||\n (config.compatibility_date ?? \"\") >= \"2025-04-01\")\n )\n for (const [k, v] of Object.entries(config.vars ?? {}))\n if (typeof v === \"string\") process.env[k] ??= v;\n const module = config.main\n ? await bundleWorker({ path: resolve(dir, config.main) }, undefined, undefined, {\n nodeCompat,\n standardBinaryType,\n scope,\n })\n : ({ default: {} } as WorkerModule);\n const assetFiles = config.assets?.directory\n ? readAssetDirectory(resolve(dir, config.assets.directory))\n : undefined;\n const project = createProjectRuntime(config, module, {\n loadModules: nodeModuleLoader,\n // own realm, as celld; facets logged like the root's\n isolatedModules: nodeIsolatedLoader(() => host.storage),\n assetFiles,\n ...host,\n });\n scope.bind(project.runtime);\n return { ...project, config };\n}\n\n/** Reads an assets directory into \"/path\" → bytes (what `celld deploy` uploads). */\nexport function readAssetDirectory(root: string): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>();\n const walk = (dir: string, prefix: string) => {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name);\n if (statSync(full).isDirectory()) walk(full, `${prefix}${name}/`);\n else files.set(`${prefix}${name}`, new Uint8Array(readFileSync(full)));\n }\n };\n walk(root, \"/\");\n return files;\n}\n\n/**\n * `celld d1 migrations apply DATABASE` for a Node-hosted project: reads\n * `migrations_dir` (default \"migrations\") of the `d1_databases` entry and applies what is new.\n */\nexport async function applyNodeD1Migrations(\n dir: string,\n runtime: { env: Record<string, unknown> },\n database: string,\n) {\n const config = readWranglerConfig(dir);\n const d1 = config.d1_databases?.find(\n (d) => d.database_name === database || d.binding === database,\n );\n if (!d1) throw new Error(`no d1_databases entry named ${database}`);\n const mdir = resolve(dir, (d1 as { migrations_dir?: string }).migrations_dir ?? \"migrations\");\n const files: [string, string][] = existsSync(mdir)\n ? readdirSync(mdir).map((f) => [f, readFileSync(join(mdir, f), \"utf8\")])\n : [];\n return applyD1Migrations(\n runtime.env[d1.binding] as never,\n files,\n (d1 as { migrations_table?: string }).migrations_table ?? \"d1_migrations\",\n );\n}\n\n/**\n * Loaded Workers in worker threads (one realm each), like celld's isolates. The code is\n * bundled with esbuild (cloudflare:workers bundled in) and imported in the thread from a\n * data: URL; Durable Object classes for facets still load in this realm.\n */\nlet isolateEntry: Promise<string> | undefined;\nexport function nodeIsolatedLoader(storage?: () => CellStorage | undefined): ModuleLoader {\n return isolatedModuleLoader({\n storage,\n spawn: () => {\n const port = new NodeWorker(new URL(`file://${isolateEntryPathSync()}`));\n port.unref(); // an idle isolate never keeps the process alive\n return { port: port as unknown as PortLike, terminate: () => void port.terminate() };\n },\n prepare: async (_id, code) => {\n isolateEntry ??= buildIsolateEntry();\n await isolateEntry;\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n const out = await build({\n entryPoints: [`memory:${code.mainModule}`],\n write: false,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n target: \"es2022\",\n logLevel: \"silent\",\n plugins: [\n {\n name: \"isolate-modules\",\n setup(b) {\n // The loaded Worker is its thread's own: `env` and `exports` are the scope\n // serveIsolate keeps for it.\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: \"cloudflare:workers\",\n namespace: \"isolate-workers\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"isolate-workers\" }, () => ({\n contents: [\n // cloudflare-workers.js in the published package (dist/), .ts in the sources.\n `export * from ${JSON.stringify(ownModule(import.meta.dirname, \"cloudflare-workers\"))};`,\n \"export const env = globalThis.__cellsProjectScope.env, exports = globalThis.__cellsProjectScope.exports, waitUntil = (p) => globalThis.__cellsProjectScope.waitUntil(p);\",\n ].join(\"\\n\"),\n loader: \"js\",\n resolveDir: import.meta.dirname,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n }));\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: modules[a.path],\n loader: \"js\",\n }));\n },\n },\n ],\n });\n return { source: out.outputFiles[0].text };\n },\n });\n}\n\nlet isolateEntryFile = \"\";\nfunction isolateEntryPathSync(): string {\n if (!isolateEntryFile) throw new Error(\"isolate entry not built yet\");\n return isolateEntryFile;\n}\nasync function buildIsolateEntry(): Promise<string> {\n isolateEntryFile = join(mkdtempSync(join(tmpdir(), \"cells-isolate-\")), \"isolate.mjs\");\n await build({\n entryPoints: [ownModule(import.meta.dirname, \"../isolate/node-entry\")],\n outfile: isolateEntryFile,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: \"node22\",\n logLevel: \"silent\",\n });\n return isolateEntryFile;\n}\n\n/** The globals `@statewalker/cellb/host-modules` bundles read (see host-modules.ts). */\nfunction installHostModuleGlobals(scope: WorkerScope): void {\n const g = globalThis as Record<string, unknown>;\n g.__cellsProjectScope = scope;\n g.__cellsWorkersModule ??= workersClasses;\n // node:* from Node itself (the browser realm gives cellb's polyfills).\n g.__cellsNodeModules ??= new Proxy(\n {},\n { get: (_t, k) => (typeof k === \"string\" ? requireBuiltin(k) : undefined) },\n );\n}\nconst requireBuiltin = createRequire(import.meta.url);\n"]}
|
|
@@ -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,O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C,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 {\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"]}
|
package/dist/project/site.d.ts
CHANGED
|
@@ -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;
|
package/dist/project/site.js
CHANGED
|
@@ -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
|
package/dist/project/site.js.map
CHANGED
|
@@ -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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run-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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I,CAAC;YAAE,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACjD,OAAO,IAAI,QAAQ,CAAC,MAAM,QAAQ,CAAC,CAAC,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE;YACjD,OAAO,EAAE,EAAE,cAAc,EAAE,iBAAiB,EAAE;SAC/C,CAAC,CAAC;IACL,CAAC,CAAC;SACD,WAAW,CAAC,mBAAmB,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;QAC1D,MAAM,EAAE,GAAG,kBAAkB,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC;QACrD,MAAM,IAAI,GAAG,kBAAkB,CAC7B,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,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"]}
|