theokit 0.77.2 → 0.77.4
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 +7 -2
- package/dist/{actions-virtual-module-UIX5YWZR.js → actions-virtual-module-CA4YEAL3.js} +3 -3
- package/dist/{actions-virtual-module-V5Q4XVL5.js → actions-virtual-module-QRTV4NHS.js} +2 -2
- package/dist/{agent-WE4WOLKC.js → agent-IBDE65UJ.js} +2 -2
- package/dist/{app-typed-client-6FQB5FQO.js → app-typed-client-ZCLFXBEC.js} +3 -3
- package/dist/{app-typed-client-JCBQGPMP.js → app-typed-client-ZCMCBS45.js} +2 -2
- package/dist/{aws-lambda-XT7ZDJ6B.js → aws-lambda-JXUPC5QM.js} +17 -6
- package/dist/aws-lambda-JXUPC5QM.js.map +1 -0
- package/dist/boot/index.js +3 -3
- package/dist/{build-DSVLRDZ6.js → build-WBQZWGED.js} +6 -6
- package/dist/{bun-PJLDELDT.js → bun-73JZLCKU.js} +16 -5
- package/dist/bun-73JZLCKU.js.map +1 -0
- package/dist/{chunk-EQJF2EH5.js → chunk-DDWF3UUI.js} +32 -1
- package/dist/chunk-DDWF3UUI.js.map +1 -0
- package/dist/{chunk-SEDZI7JF.js → chunk-FCBRWSBH.js} +2 -2
- package/dist/{chunk-BFDEEJOK.js → chunk-GNQKV2NP.js} +1 -1
- package/dist/{chunk-BFDEEJOK.js.map → chunk-GNQKV2NP.js.map} +1 -1
- package/dist/{chunk-KQBY62AE.js → chunk-HWRZUQPE.js} +31 -25
- package/dist/chunk-HWRZUQPE.js.map +1 -0
- package/dist/{chunk-ESSUFQ3H.js → chunk-IBZITTK7.js} +11 -9
- package/dist/chunk-IBZITTK7.js.map +1 -0
- package/dist/{chunk-3TCWOHLY.js → chunk-JZLNZOEL.js} +1 -1
- package/dist/{chunk-G3DDIEYE.js → chunk-MQCXYZEV.js} +4 -2
- package/dist/chunk-MQCXYZEV.js.map +1 -0
- package/dist/{chunk-E22GPCCO.js → chunk-MSSUMKFR.js} +61 -55
- package/dist/chunk-MSSUMKFR.js.map +1 -0
- package/dist/{chunk-XLFDYTWO.js → chunk-N7KDDYDB.js} +5 -3
- package/dist/chunk-N7KDDYDB.js.map +1 -0
- package/dist/{chunk-TODO6J42.js → chunk-PV6IO25S.js} +1 -1
- package/dist/chunk-PV6IO25S.js.map +1 -0
- package/dist/{chunk-N5YHENWJ.js → chunk-SHBPXX5E.js} +2 -2
- package/dist/{chunk-HZAXFD55.js → chunk-VSK5Y4ET.js} +2 -2
- package/dist/{chunk-GNV34JMI.js → chunk-XCPM72D6.js} +2 -2
- package/dist/{chunk-7IPWHWYV.js → chunk-YM6ONZYE.js} +11 -9
- package/dist/chunk-YM6ONZYE.js.map +1 -0
- package/dist/cli/index.js +6 -6
- package/dist/{cloudflare-F7KLBOU4.js → cloudflare-6ONK5HCO.js} +11 -3
- package/dist/cloudflare-6ONK5HCO.js.map +1 -0
- package/dist/{config-support-2TER2BYD.js → config-support-ZJIRVUWZ.js} +10 -5
- package/dist/config-support-ZJIRVUWZ.js.map +1 -0
- package/dist/{deno-deploy-LJ5JQQVR.js → deno-deploy-ZM2UR5ZI.js} +16 -5
- package/dist/deno-deploy-ZM2UR5ZI.js.map +1 -0
- package/dist/{dev-F4ZY7TZX.js → dev-AE7EWSB7.js} +5 -5
- package/dist/{index-C2lcEI-4.d.ts → index-CY_llLI7.d.ts} +4 -1
- package/dist/index.js +4 -4
- package/dist/{internal-api-H3C2ID6N.js → internal-api-JFA4JI3Z.js} +3 -3
- package/dist/{internal-api-5FTPYSEQ.js → internal-api-KQQHFTCG.js} +2 -2
- package/dist/{mcp-H3TNO6YV.js → mcp-UBGNYDMW.js} +2 -2
- package/dist/{netlify-ZPQNREFH.js → netlify-JLTQD3JJ.js} +78 -13
- package/dist/netlify-JLTQD3JJ.js.map +1 -0
- package/dist/{node-3EV3CVWB.js → node-UYRQNJNF.js} +2 -2
- package/dist/{preview-RYN7UI45.js → preview-VMMBMNMM.js} +3 -3
- package/dist/registry-XLKBFOPW.js +34 -0
- package/dist/server/define/index.d.ts +7 -2
- package/dist/server/define/index.js +1 -1
- package/dist/server/http/index.d.ts +2 -1
- package/dist/server/http/index.js +8 -2
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +10 -10
- package/dist/{server-boundary-5ZTBC2KF.js → server-boundary-JA3UOKJS.js} +2 -2
- package/dist/{server-boundary-DTF6ZEUO.js → server-boundary-OJ6YIPQT.js} +3 -3
- package/dist/{start-Y7VVCK6Q.js → start-AE5YCDVS.js} +6 -5
- package/dist/{start-Y7VVCK6Q.js.map → start-AE5YCDVS.js.map} +1 -1
- package/dist/{static-VNN4HYRN.js → static-C7PWUTQO.js} +2 -2
- package/dist/{theo-cloud-243SPOIA.js → theo-cloud-NKZUJO3H.js} +2 -2
- package/dist/{vercel-EXKSZ2OQ.js → vercel-MRZXLOIQ.js} +19 -5
- package/dist/vercel-MRZXLOIQ.js.map +1 -0
- package/dist/vite-plugin/index.js +4 -4
- package/dist/{vite-plugin-LDZJRFKT.js → vite-plugin-JMWUVMP3.js} +4 -4
- package/package.json +3 -3
- package/dist/aws-lambda-XT7ZDJ6B.js.map +0 -1
- package/dist/bun-PJLDELDT.js.map +0 -1
- package/dist/chunk-7IPWHWYV.js.map +0 -1
- package/dist/chunk-E22GPCCO.js.map +0 -1
- package/dist/chunk-EQJF2EH5.js.map +0 -1
- package/dist/chunk-ESSUFQ3H.js.map +0 -1
- package/dist/chunk-G3DDIEYE.js.map +0 -1
- package/dist/chunk-KQBY62AE.js.map +0 -1
- package/dist/chunk-TODO6J42.js.map +0 -1
- package/dist/chunk-XLFDYTWO.js.map +0 -1
- package/dist/cloudflare-F7KLBOU4.js.map +0 -1
- package/dist/config-support-2TER2BYD.js.map +0 -1
- package/dist/deno-deploy-LJ5JQQVR.js.map +0 -1
- package/dist/netlify-ZPQNREFH.js.map +0 -1
- package/dist/registry-3D2KR7UE.js +0 -34
- package/dist/vercel-EXKSZ2OQ.js.map +0 -1
- /package/dist/{actions-virtual-module-UIX5YWZR.js.map → actions-virtual-module-CA4YEAL3.js.map} +0 -0
- /package/dist/{actions-virtual-module-V5Q4XVL5.js.map → actions-virtual-module-QRTV4NHS.js.map} +0 -0
- /package/dist/{agent-WE4WOLKC.js.map → agent-IBDE65UJ.js.map} +0 -0
- /package/dist/{app-typed-client-6FQB5FQO.js.map → app-typed-client-ZCLFXBEC.js.map} +0 -0
- /package/dist/{app-typed-client-JCBQGPMP.js.map → app-typed-client-ZCMCBS45.js.map} +0 -0
- /package/dist/{build-DSVLRDZ6.js.map → build-WBQZWGED.js.map} +0 -0
- /package/dist/{chunk-SEDZI7JF.js.map → chunk-FCBRWSBH.js.map} +0 -0
- /package/dist/{chunk-3TCWOHLY.js.map → chunk-JZLNZOEL.js.map} +0 -0
- /package/dist/{chunk-N5YHENWJ.js.map → chunk-SHBPXX5E.js.map} +0 -0
- /package/dist/{chunk-HZAXFD55.js.map → chunk-VSK5Y4ET.js.map} +0 -0
- /package/dist/{chunk-GNV34JMI.js.map → chunk-XCPM72D6.js.map} +0 -0
- /package/dist/{dev-F4ZY7TZX.js.map → dev-AE7EWSB7.js.map} +0 -0
- /package/dist/{internal-api-H3C2ID6N.js.map → internal-api-JFA4JI3Z.js.map} +0 -0
- /package/dist/{internal-api-5FTPYSEQ.js.map → internal-api-KQQHFTCG.js.map} +0 -0
- /package/dist/{mcp-H3TNO6YV.js.map → mcp-UBGNYDMW.js.map} +0 -0
- /package/dist/{node-3EV3CVWB.js.map → node-UYRQNJNF.js.map} +0 -0
- /package/dist/{preview-RYN7UI45.js.map → preview-VMMBMNMM.js.map} +0 -0
- /package/dist/{registry-3D2KR7UE.js.map → registry-XLKBFOPW.js.map} +0 -0
- /package/dist/{server-boundary-5ZTBC2KF.js.map → server-boundary-JA3UOKJS.js.map} +0 -0
- /package/dist/{server-boundary-DTF6ZEUO.js.map → server-boundary-OJ6YIPQT.js.map} +0 -0
- /package/dist/{static-VNN4HYRN.js.map → static-C7PWUTQO.js.map} +0 -0
- /package/dist/{theo-cloud-243SPOIA.js.map → theo-cloud-NKZUJO3H.js.map} +0 -0
- /package/dist/{vite-plugin-LDZJRFKT.js.map → vite-plugin-JMWUVMP3.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/cloudflare.ts"],"sourcesContent":["import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { parseAssetsMap } from '../core/contracts/module-preloads.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment, type DeployedAgent } from './deployed-agents.js'\nimport { renderBakedRoutes, routeRuntimeLines } from './deployed-baked-routes.js'\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { readDocumentShell } from './deployed-document-shell.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport {\n deployedRateLimitFragment,\n rateLimitCheckFragment,\n type DeployedRateLimitOptions,\n} from './deployed-rate-limit.js'\nimport {\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n type DeployedRuntimeConfigOptions,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders, securityHeadersDeclarations } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\n/**\n * T2.1 — Cloudflare adapter rewritten to consume `theokit/adapters/web-shim`\n * instead of emitting an inline plain-object Request/Response shim. Reduces\n * template from ~50 lines to ~25 and centralizes maintenance.\n */\n\n/**\n * The built `index.html` split into the part before `<div id=\"root\">` and the\n * part after it.\n *\n * Refuses by name when streaming is on and the template is missing, rather than\n * emitting a worker that serves a headless document. A build that cannot produce\n * a correct artifact should say so at build time; the alternative is a deploy\n * that looks successful and serves pages with no stylesheet.\n */\n// `readDocumentShell` moved to `./deployed-document-shell.js` (B-317): the Vercel target needs the\n// same shell, and an adapter importing another adapter is the coupling `deployed-baked-routes.ts`\n// was extracted to avoid.\n\n// Re-exported because this module's tests import it from here, and the move is not their subject.\nexport { readDocumentShell }\n\n/**\n * Read the map `theokit build` emitted, for baking into the worker (B-035).\n *\n * Returns `undefined` — never throws — for an absent or malformed file. A deploy that failed\n * because an optimisation was missing would turn a lost round trip into a broken build, and the\n * worker is correct without it.\n */\nexport function readAssetsMapForBake(path: string): Record<string, string[]> | undefined {\n try {\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- `path` is built by the one caller from a fixed `.theokit/client` layout; this returns `undefined` for anything it cannot read\n return parseAssetsMap(readFileSync(path, 'utf8'))\n } catch {\n return undefined\n }\n}\n\n/**\n * The baked route-to-chunks map, as worker source (B-035).\n *\n * A literal and not a read, for the same reason the document shell is: a Worker has no filesystem\n * at request time. Emitted only when the build produced a map; otherwise the worker carries\n * nothing about preloads and behaves exactly as before.\n *\n * **It emits the DATA and no longer the code.** An earlier revision emitted a hand-written copy of\n * `injectModulePreloads`, justified by a claim that the worker could not import it. That claim was\n * false — `theokit/server` re-exports from `core/contracts/` and the generated worker already\n * imports that subpath — and the copy drifted within a day: a fix for proxy-form request targets\n * landed in the original and not in the duplicate. The worker now imports the real function, which\n * is the shape `adapters/security-headers.ts` established one directory over for exactly this\n * build-half/runtime-half pair.\n */\n/**\n * Whether this worker can preload at all (B-035).\n *\n * ONE predicate, read by the bake, the import and the call. Two conditions for one decision is\n * how the import came to be emitted for a worker that had no map to give it — found at review, in\n * the same change where a copy and its original had already drifted apart.\n *\n * Streaming is required because the other branch serves the document from `env.ASSETS` as a\n * static file and can inject nothing into it.\n */\nfunction preloadsApplyTo(opts: {\n ssrStreaming?: boolean\n assetsMap?: Record<string, string[]>\n}): boolean {\n return opts.ssrStreaming === true && opts.assetsMap !== undefined\n}\n\nfunction renderPreloadSupport(assetsMap: Record<string, string[]> | undefined): string {\n if (assetsMap === undefined) return ''\n return `const __THEO_ASSETS_MAP = ${JSON.stringify(assetsMap)}`\n}\n\n/**\n * The branch that answers a non-API request: streamed SSR, or the static asset the Worker\n * platform serves. Extracted at review — it is the one decision in this emitter with two whole\n * shapes behind it, and keeping it inline pushed the caller past its line budget.\n */\nfunction renderNonApiBranch(\n opts: NonNullable<Parameters<typeof renderCloudflareWorkerEntry>[0]>,\n preloadsApply: boolean,\n): string {\n return opts.ssrStreaming\n ? [\n ` // B-263 — a worker that owns \\`/\\` also receives \\`/robots.txt\\` and \\`/logo.png\\`, because`,\n ` // \\`run_worker_first\\` in wrangler.toml is what stops the asset handler answering the`,\n ` // document before this code runs. Rendering SSR for those would answer a text file with HTML.`,\n ` //`,\n ` // B-331 — the extension is a PRE-FILTER, no longer the decision. It used to decide: a dot in`,\n ` // the last segment meant \"static file\", so \\`/users/john.doe\\`, \\`/v1.2/docs\\` and`,\n ` // \\`/reports/2026.q3\\` were handed to a handler that does not have them, and with`,\n ` // \\`not_found_handling = \"none\"\\` that is a 404 for a page the app renders.`,\n ` //`,\n ` // Now a miss falls through to SSR, so a wrong guess costs one local lookup instead of the`,\n ` // response. Keeping the pre-filter is what keeps that lookup OFF every ordinary page`,\n ` // request: \\`/dashboard\\` never touches the binding.`,\n ` //`,\n ` // Still uncovered, and stated rather than implied: a static file with NO extension, such as`,\n ` // a \\`public/CNAME\\`. The pre-filter never asks for it, so it renders as a document. That`,\n ` // is the pre-existing behaviour and the rarer direction of the two.`,\n ` const lastSegment = url.pathname.slice(url.pathname.lastIndexOf('/') + 1)`,\n ` if (lastSegment.includes('.')) {`,\n ` const staticAssets = env?.ASSETS`,\n ` if (staticAssets === undefined) return notFoundResponse()`,\n ` const hit = await staticAssets.fetch(request)`,\n ` if (hit.status !== 404) return withSecurityHeaders(hit, SECURITY_HEADERS)`,\n ` }`,\n ``,\n ` // T2.3 — streaming SSR for non-API routes`,\n ` // The same primitive \\`theokit start\\` uses, not a second one:`,\n ` // 16 bytes of Web Crypto entropy, base64.`,\n ` const nonce = generateNonce()`,\n ` return withSecurityHeaders(`,\n ` await renderStreamingWeb(request, {`,\n !preloadsApply\n ? ` htmlHead: ${JSON.stringify(opts.htmlHead ?? '')},`\n : ` htmlHead: injectModulePreloads(${JSON.stringify(opts.htmlHead ?? '')}, __THEO_ASSETS_MAP, new URL(request.url).pathname),`,\n ` htmlTail: ${JSON.stringify(opts.htmlTail ?? '')},`,\n ` nonce,`,\n ` }),`,\n ` buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true }, { nonce }),`,\n ` )`,\n ].join('\\n')\n : [\n ` // #412 — the document, served by the worker so it carries the same baseline every`,\n ` // API response carries. It used to return 404 here while wrangler.toml declared a`,\n ` // \\`[site]\\` bucket nothing read, so the page was missing rather than unprotected.`,\n ` const assets = env?.ASSETS`,\n ` // A wrangler.toml that predates this binding has no ASSETS. Reading .fetch off`,\n ` // undefined would turn every page request into a 500; 404 is what this target`,\n ` // answered before, which is the honest fallback rather than a new failure.`,\n ` if (assets === undefined) return notFoundResponse()`,\n ` return withSecurityHeaders(await assets.fetch(request), SECURITY_HEADERS)`,\n ].join('\\n')\n}\n\nexport function renderCloudflareWorkerEntry(\n opts: {\n ssrStreaming?: boolean\n htmlHead?: string\n htmlTail?: string\n /**\n * B-035 — the route-to-chunks map, baked as a literal for the same reason the shell above\n * is: a Worker has no filesystem at request time. Absent when the build produced no map,\n * and then nothing about preloads is emitted at all.\n */\n assetsMap?: Record<string, string[]>\n securityHeaders?: SecurityHeadersConfig\n /**\n * The server routes, scanned on the BUILD machine (#369).\n *\n * A Worker has no filesystem, so the worker used to call `scanServerRoutes` — a `readdirSync` —\n * against a directory that does not exist there, and load each module through `import()` of a\n * file path. Both are baked here instead, which is the road this adapter already takes for the\n * document shell one function away.\n *\n * `filePath` is relative to the project root and is used for two things: the key the executor\n * looks a module up by, and the specifier the static import uses. Paths are emitted relative to\n * `.theokit/cloudflare/`, where the worker is written.\n */\n routes?: readonly { filePath: string; routePath: string; methods?: readonly string[] }[]\n /**\n * The two concerns #410 could not bake (#425), composed from one place so the six targets\n * cannot drift into six spellings. `serialization` is a literal like the security values above;\n * `plugins` is an import, because a closure has no literal.\n */\n runtimeConfigModule?: DeployedRuntimeConfigOptions['runtimeConfigModule']\n serialization?: DeployedRuntimeConfigOptions['serialization']\n /**\n * The app's agents, scanned on the build machine (#367).\n *\n * A different scan from `routes` and served by a different function — which is why a worker\n * that only consulted the route table answered every `/api/agents/<name>` with a 404.\n */\n agents?: readonly DeployedAgent[]\n /** B-185 — the app's `server/context.ts`, project-relative, or absent when it declares none. */\n contextModule?: string\n /** WebSocket route files, scanned on the build machine. Only their presence is used (#369). */\n wsRoutes?: readonly string[]\n } & DeployedServerDirOptions &\n DeployedCsrfOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions = {},\n): string {\n // `/@theo/entry-server` is a VITE virtual id (`vite-plugin/index.ts`), and `adapters/node.ts`\n // resolves it by passing it as the vite build's `input`. This file is not bundled by vite: wrangler\n // hands it to esbuild, which has no such module and fails the build before a request is ever sent —\n // measured 2026-09-26 on the first real `wrangler deploy` this repository attempted (B-263).\n //\n // The same build writes the real thing next door. The worker lands at\n // `.theokit/cloudflare/worker.mjs` and the renderer at `.theokit/server/entry-server.js`, so one\n // directory up is the spelling esbuild can follow.\n const streamingImport = opts.ssrStreaming\n ? `import { renderStreamingWeb } from '../server/entry-server.js'`\n : `// (ssrStreaming off: renderStreamingWeb not imported)`\n // #343 — the document shell is inlined as a build-time literal because a Worker\n // has no filesystem to read `index.html` from at request time. Without it,\n // `renderStreamingWeb` falls back to its empty-string defaults and the response\n // is React output with no `<html>`, no `<head>`, no stylesheet and no client\n // entry — hydration data for a page that cannot hydrate. The streaming\n // assembly was fixed in the generated entry and this, its only caller, was\n // left passing nothing.\n //\n // `JSON.stringify` and not a template literal: the shell contains quotes,\n // angle brackets and a `</script>`, and embedding it naively produces a worker\n // that fails to parse at deploy time rather than here.\n //\n // #410 — this is also the ONE deploy path that renders HTML at request time,\n // so the one that can mint a per-request CSP nonce: `renderStreamingWeb`\n // threads `options.nonce` into `renderToReadableStream` and into the hydration\n // script (`router/entry-server.ts`). Every other response below carries the\n // nonce-less baseline, which is what `buildSecurityHeaders` already does for a\n // prerendered route (EC-4).\n // Only the streaming branch renders HTML at request time; the other serves the document from\n // `env.ASSETS` as a static file and can inject nothing. Baking the map for it would ship the whole\n // route table as dead weight — found at review, where the emitter was measured declaring it with\n // zero call sites.\n const preloadsApply = preloadsApplyTo(opts)\n const preloadSupport = preloadsApply ? renderPreloadSupport(opts.assetsMap) : ''\n\n const nonApiBranch = renderNonApiBranch(opts, preloadsApply)\n\n // CR-006: Workers lack `process.cwd()` and the `node:*` import surface\n // is brittle even under `nodejs_compat`. We use the Web Crypto\n // `crypto.randomUUID()` instead of `node:crypto.randomUUID`, and embed\n // the server directory as a build-time literal instead of resolving via\n // `node:path` at runtime.\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(\n opts.agents === undefined\n ? undefined\n : // B-185 — a Worker has no filesystem, so its identity module is baked exactly like its\n // agents and its routes (ADR 0014). `contextModule` is `undefined` for an app that\n // declares none, and the generator then emits no import for it.\n { kind: 'baked', agents: opts.agents, contextModule: opts.contextModule },\n {\n wrapSecurityHeaders: true,\n // B-185 — bound only when the runtime-config fragment declared the const, which is\n // exactly when a plugins module was emitted. Referencing it otherwise would emit an\n // identifier the entry never declares.\n pluginRunnerExpr:\n opts.runtimeConfigModule === undefined ? undefined : 'await THEO_PLUGIN_RUNNER',\n },\n )\n\n return [\n `// Generated by Theo — Cloudflare Workers Adapter`,\n `//`,\n `// REQUIREMENTS (EC-3):`,\n `// - wrangler.toml MUST include compatibility_flags = [\"nodejs_compat\"]`,\n `// (still required for transitive theokit/server deps, e.g. busboy)`,\n `// - package.json MUST list \"theokit\" in dependencies (not devDependencies)`,\n `// so Wrangler bundles theokit and its transitive deps`,\n `// - Deploy: wrangler deploy`,\n ``,\n // NEVER the `theokit/server` umbrella. It is deprecated (the package prints so on import) and it\n // is what made the first real `wrangler deploy` fail: bisected 2026-09-26 with a worker whose\n // only line was `import { matchRoute } from 'theokit/server'`, and that alone pulled\n // `@swc/core`'s `.node` native addon into the bundle. workerd cannot load a `.node` at any\n // bundler setting, so it is not a flag away from working (B-263).\n //\n // The narrow subpaths were probed the same way and are clean — `wrangler deploy --dry-run`\n // exit 0, zero swc, zero errors for both. Which symbol lives where was read from the modules\n // rather than grepped, since these indexes use `export *`:\n //\n // theokit/server/scan matchRoute, compilePattern\n // theokit/server/http executeRoute, extractTraceIdFromRequest, TRACE_HEADER,\n // createCorsWebHandler, injectModulePreloads\n !preloadsApply\n ? `import { matchRoute, compilePattern } from 'theokit/server/scan'\\nimport { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'`\n : `import { matchRoute, compilePattern } from 'theokit/server/scan'\\nimport { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler, injectModulePreloads } from 'theokit/server/http'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n opts.ssrStreaming\n ? `import { buildSecurityHeaders, generateNonce, withSecurityHeaders } from 'theokit/adapters/security-headers'`\n : `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n `// T3.4 — WS bridge for Cloudflare Workers`,\n `import { createCloudflareWsBridge } from 'theokit/adapters/ws-shim'`,\n // B-027 — only when a limit is declared. `createRateLimiterWeb` is used at module scope by the\n // fragment below and was imported by no target but bun, so an entry that declared a limit threw\n // when it LOADED. `resolveClientIpFromRequest` is the forwarded-header fallback, behind\n // `trustProxy`; the primary source is `cf-connecting-ip`, which the Workers runtime writes.\n ...(opts.rateLimit === undefined\n ? []\n : [\n `import { createRateLimiterWeb } from 'theokit/server/rate-limit'`,\n `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,\n ]),\n streamingImport,\n ``,\n ...runtimeConfig.imports,\n ...agentsFragment.imports,\n ...routeImports,\n ``,\n `// CR-006: server directory is a build-time literal — Workers cannot`,\n `// call process.cwd() and resolving paths at runtime returned '/server'.`,\n `const serverDir = ${serverDirLiteral(opts)}`,\n ``,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries, 'cloudflare'),\n `// #410 — the security baseline \\`theokit start\\` puts on every response, carried`,\n `// here as a literal because a Worker has no theo.config.ts to read. Same`,\n `// function, same input, so the deployed page and the local one cannot`,\n `// disagree about what the configuration means.`,\n preloadSupport,\n ...securityHeadersDeclarations(opts.securityHeaders),\n ``,\n ...deployedCsrfFragment(opts, 'a Worker'),\n ``,\n ...runtimeConfig.declarations,\n ...agentsFragment.declarations,\n ...deployedCorsFragment(opts.cors, 'cloudflare'),\n `// #369 — whether this project declares a WebSocket route, decided at build time. It used`,\n `// to answer it with \\`scanWebSocketRoutes\\`, which is the same readdirSync.`,\n `const HAS_WS_ROUTES = ${String((opts.wsRoutes ?? []).length > 0)}`,\n ``,\n `function notFoundResponse() {`,\n ` return withSecurityHeaders(`,\n ` new Response(`,\n ` JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Route not found' } }),`,\n ` { status: 404, headers: { 'Content-Type': 'application/json' } },`,\n ` ),`,\n ` SECURITY_HEADERS,`,\n ` )`,\n `}`,\n ``,\n ...cloudflareHandleRequestFragment(\n nonApiBranch,\n runtimeConfig.executeRouteSpread,\n agentsFragment.branch,\n agentsFragment.hostBypass,\n opts.rateLimit,\n ),\n ].join('\\n')\n}\n\n/**\n * The Worker's request handler, as generated source.\n *\n * Extracted for the reason `vercel.ts` extracts its own fragments: the emitter is one array\n * literal, so every line the entry gains counts against `max-lines-per-function`, and #410 added\n * the CSRF literal to an emitter already sitting exactly at the ceiling.\n *\n * @param nonApiBranch - what a non-`/api/` request gets, which differs with `ssrStreaming`\n */\nfunction cloudflareHandleRequestFragment(\n nonApiBranch: string,\n runtimeSpread: string,\n agentBranch: readonly string[],\n /** SI-020 — the condition that keeps an agent card path out of the static-asset branch. */\n hostBypass: string,\n /** B-027 — the declared limit, or `undefined`. Passed rather than read: this fragment is a\n * separate function from `renderCloudflareWorkerEntry`, where `opts` is bound. */\n rateLimit: DeployedRateLimitOptions['rateLimit'],\n): string[] {\n return [\n `async function handleRequest(request, url, env) {`,\n ` if (!url.pathname.startsWith('/api/')${hostBypass}) {`,\n nonApiBranch,\n ` }`,\n ``,\n ...agentBranch,\n ``,\n ` const match = matchRoute(url.pathname, routes)`,\n ` if (!match) return notFoundResponse()`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request, { trustedProxy: 'platform' })`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — the run is NOT awaited before the Response is taken. toResponse()`,\n ` // settles as soon as status + headers are known and carries a live body, so`,\n ` // the Worker starts flushing while the handler is still writing. Awaiting`,\n ` // executeRoute() first would re-buffer the whole response here even though`,\n ` // the shim streams; awaiting toResponse() does not — it settles at the head.`,\n ` return withSecurityHeaders(await toResponse(executeRoute({`,\n ` route: match.route, method, params: match.params,`,\n ` req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread}`,\n ` })), SECURITY_HEADERS)`,\n `}`,\n ``,\n ...deployedRateLimitFragment(\n rateLimit,\n 'cloudflare',\n // `cf-connecting-ip` is the RUNTIME's answer and a caller cannot forge it through the edge.\n // A Worker reached directly has none, and then only a declared `trustProxy` produces an\n // address — otherwise `undefined`, which is the named 503 rather than everyone's bucket.\n `request.headers.get('cf-connecting-ip') ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n // `request` alone: the handler binds `(request, env, ctx)` and the header is on the request.\n 'request',\n ),\n ``,\n `export default {`,\n ` async fetch(request, env, ctx) {`,\n ` const url = new URL(request.url)`,\n ``,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router handles`,\n ` // is an OPTIONS the browser never gets a CORS answer to. The WebSocket upgrade above is`,\n ` // deliberately upstream of it — a 101 is not a CORS-governed response.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(rateLimit, ' ', 'request'),\n ``,\n ` // LCR0103 — the upgrade branch sits BELOW the limiter, and the order is the point.`,\n ` // It used to sit above, under the comment \"a 101 carries no document and no script,`,\n ` // so the security baseline does not apply to it\". That is true of the security`,\n ` // HEADERS — a document concern — and false of the limiter, which is a resource`,\n ` // concern: a long-lived socket is the most expensive thing this entry hands out, so`,\n ` // the upgrade is the path that most needs a budget, not the one that may skip it.`,\n ` // T3.4 — Detect WebSocket upgrade and delegate to the CF bridge.`,\n ` // A 101 carries no document and no script, so the security baseline does`,\n ` // not apply to it.`,\n ` if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {`,\n ` if (!HAS_WS_ROUTES) return notFoundResponse()`,\n ` const cfWs = createCloudflareWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` })`,\n ` return cfWs.handle(request)`,\n ` }`,\n ``,\n ` return withCors(request, await handleRequest(request, url, env))`,\n ` },`,\n `}`,\n ]\n}\n\n/** Where the build writes the stub every alias points at, relative to the project root. */\nexport const WORKERS_UNSUPPORTED_STUB_PATH = '.theokit/cloudflare/unsupported-on-workers.mjs'\n\n/** What `absentOptionalPeers` needs to know, injectable so the decision is testable without a tree. */\nexport interface OptionalPeerProject {\n /** The project's own direct dependency names. */\n readonly directDependencies: readonly string[]\n /** The names each dependency declares as `peerDependenciesMeta.<name>.optional === true`. */\n readonly optionalPeersOf: (name: string) => readonly string[]\n /** Whether a name resolves from the project. */\n readonly isInstalled: (name: string) => boolean\n}\n\n/**\n * The optional peer dependencies this project does NOT have, which wrangler will try to resolve.\n *\n * A dependency that reaches an optional backend through `import('better-sqlite3')` leaves a\n * statically resolvable specifier in its dist. `nodejs_compat` does not help — these are npm\n * packages, not builtins — so esbuild fails the whole bundle at BUILD time over a module the code\n * only reaches when a consumer asked for that backend and supplied no override.\n *\n * Measured 2026-09-30 on a fresh `create-theokit` scaffold installed from npm: `wrangler deploy`\n * answered `Could not resolve \"better-sqlite3\"` from `@theokit/sdk/dist/chunk-XZHJYSPB.js:76`, and\n * the scaffold had 28 absent optional peers across four owners.\n *\n * **Derived, never written down.** The first cut of this listed the three names a grep of that dist\n * produced, and was already incomplete — the SDK declares seven optional peers and `@lancedb/lancedb`\n * was not among the three. A list of names here is a second copy of a fact the dependency publishes,\n * and it rots on the release where the dependency adds the eighth.\n *\n * Two filters, both load-bearing:\n *\n * - an INSTALLED optional peer is left alone. The consumer installed it deliberately, and the table\n * shrinks by itself the day they do.\n * - `@types/*` is skipped: a types package never appears in a runtime import graph.\n *\n * Aliasing a module the worker graph never imports is inert — it changes nothing. That is why this\n * does not try to decide which owners are \"server-side\"; that judgement is the hardcoding this\n * design removes.\n *\n * @param project the dependency facts, read from the project or injected by a test\n * @returns the names to alias, in first-seen order, each appearing once\n */\nexport function absentOptionalPeers(project: OptionalPeerProject): string[] {\n const names: string[] = []\n for (const dependency of project.directDependencies) {\n for (const peer of project.optionalPeersOf(dependency)) {\n if (peer.startsWith('@types/')) continue\n if (project.isInstalled(peer)) continue\n if (!names.includes(peer)) names.push(peer)\n }\n }\n return names\n}\n\n/**\n * The module every alias resolves to: it throws when the import is actually reached.\n *\n * Reaching it means the code asked for an optional backend and no override was supplied, which is\n * precisely the condition the calling seam exists for. The message names the module and the remedy,\n * because without it the runtime error is about a path inside `.theokit`.\n *\n * @returns the stub's source\n */\n/**\n * `absentOptionalPeers` against the project on disk.\n *\n * Separated from the decision so the decision stays testable without a `node_modules` tree, which is\n * the same split `unpublished-pins.ts` makes and for the same reason. A dependency whose manifest\n * cannot be read contributes nothing rather than failing the build: an unreadable manifest is a\n * different problem, and a build that refuses over it would refuse over a shape nobody predicted.\n *\n * @param cwd the project root\n * @returns the names to alias, or an empty list when the project's own manifest cannot be read\n */\nexport function absentOptionalPeersOnDisk(cwd: string): string[] {\n const require_ = createRequire(resolve(cwd, 'package.json'))\n const readManifestOf = (name: string): Record<string, unknown> | undefined => {\n try {\n return require_(`${name}/package.json`) as Record<string, unknown>\n } catch {\n return undefined\n }\n }\n\n let own: Record<string, unknown>\n try {\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- the project's own manifest\n own = JSON.parse(readFileSync(resolve(cwd, 'package.json'), 'utf-8')) as Record<string, unknown>\n } catch {\n return []\n }\n\n return absentOptionalPeers({\n directDependencies: Object.keys(own.dependencies ?? {}),\n optionalPeersOf: (name) => {\n const meta = readManifestOf(name)?.peerDependenciesMeta as\n | Record<string, { optional?: boolean }>\n | undefined\n return Object.entries(meta ?? {})\n .filter(([, value]) => value.optional === true)\n .map(([peer]) => peer)\n },\n isInstalled: (name) => readManifestOf(name) !== undefined,\n })\n}\n\nexport function renderWorkersUnsupportedStub(): string {\n return [\n '// Generated by Theo — Cloudflare adapter',\n '//',\n '// Every optional peer dependency this project did not install is aliased here, because',\n '// wrangler resolves a bare dynamic import at BUILD time and a missing one fails the whole',\n '// bundle. Reaching this module means the code asked for an optional backend and no loader',\n '// override was supplied.',\n 'throw new Error(',\n \" 'An optional dependency was imported on Cloudflare Workers and this project did not install \" +\n 'it. Supply a loader override for it, or install it and rebuild — the build regenerates the ' +\n \"[alias] table in wrangler.toml from what is present.',\",\n ')',\n '',\n ].join('\\n')\n}\n\nexport function renderWranglerToml(opts?: {\n ssrStreaming?: boolean\n workersUnsupported?: readonly string[]\n}): string {\n return [\n `# Generated by Theo — Cloudflare Workers`,\n `name = \"theo-app\"`,\n `main = \".theokit/cloudflare/worker.mjs\"`,\n `compatibility_date = \"2025-09-01\"`,\n `compatibility_flags = [\"nodejs_compat\"]`,\n ``,\n `# #412 — \\`[assets]\\` with a BINDING, not the legacy \\`[site]\\` bucket.`,\n `#`,\n `# \\`[site]\\` uploads to KV and is read through \\`kv-asset-handler\\` and a`,\n `# \\`__STATIC_CONTENT\\` binding — neither of which this worker has ever had. So the`,\n `# bucket was declared, uploaded, and consumed by nothing: with ssrStreaming off, a`,\n `# deploy answered 404 for its own page. This binding is what the worker calls.`,\n `[assets]`,\n `directory = \".theokit/client\"`,\n `binding = \"ASSETS\"`,\n `# B-263 — WITHOUT this key Cloudflare's asset handler answers before the worker for any path`,\n `# that matches a file, and \\`.theokit/client/index.html\\` matches \\`/\\`. Measured on the first real`,\n `# deploy: \\`GET /\\` returned 200 with an empty \\`<div id=\"root\">\\` and NONE of the six security`,\n `# headers, while \\`/api/health\\` — a path no file matches — was answered by the worker and carried`,\n `# them. The document was coming off the CDN and the code that renders it never ran.`,\n `#`,\n `# The negation keeps the 300-odd hashed build outputs on the CDN path: \\`true\\` would satisfy the`,\n `# precedence and pay a JS invocation per stylesheet and chunk.`,\n `run_worker_first = [\"/*\", \"!/assets/*\"]`,\n ...(opts?.ssrStreaming === true\n ? [\n `# The worker renders every extension-less path itself, so an asset MISS is a genuine 404.`,\n `# \\`single-page-application\\` here would answer \\`/nope.png\\` with 200 and an HTML body.`,\n `not_found_handling = \"none\"`,\n ]\n : [\n `# A client-routed app asks for /dashboard, which is no file, and with streaming off the`,\n `# worker forwards it to ASSETS rather than rendering it. Without this the asset handler`,\n `# 404s a deep link and the SPA never boots.`,\n `not_found_handling = \"single-page-application\"`,\n ]),\n ``,\n `# B-332 — the [define] \"import.meta.url\" compensation lived here until 2026-09-28.`,\n `#`,\n `# Cloudflare executes the top-level module during validation, so a dependency that resolves a`,\n `# path at load time refused the whole upload (code 10021). The cause was @theokit/sdk, in`,\n `# internal/providers/catalog-loader.ts, fixed upstream and published in 5.9.2 — measured on the`,\n `# published tarball: 0 of 254 executable files resolve a path at module scope.`,\n `#`,\n `# The floor this framework declares is at least 5.9.2, so the versions that needed the compensation`,\n `# cannot be installed. A declared dependency is the honest form of that requirement;`,\n `# substituting a literal for import.meta.url was the form that also covered the NEXT dependency`,\n `# with the same vice, in silence.`,\n ``,\n `# Environment variables are set via wrangler secret or dashboard`,\n `# Example: wrangler secret put DATABASE_URL`,\n // Emitted only when something is absent: an empty `[alias]` reads as a decision nobody made.\n // After `[assets]` on purpose — TOML tables are positional, so these keys must open their own.\n ...((opts?.workersUnsupported ?? []).length === 0\n ? []\n : [\n ``,\n `# Optional peer dependencies this project did not install, derived from every direct`,\n `# dependency's \\`peerDependenciesMeta.<name>.optional\\`. Wrangler resolves a bare dynamic`,\n `# import at BUILD time, so one absent module fails the whole bundle over a code path that`,\n `# only runs when a consumer asked for that backend and supplied no override. Measured`,\n `# 2026-09-30 on a fresh scaffold: \\`Could not resolve \"better-sqlite3\"\\` from`,\n `# @theokit/sdk/dist, before any request existed.`,\n `#`,\n `# Install one of these and rebuild: it leaves this table, because the build derives it from`,\n `# what is present rather than from a list written here.`,\n `[alias]`,\n ...(opts?.workersUnsupported ?? []).map(\n (name) => `\"${name}\" = \"./${WORKERS_UNSUPPORTED_STUB_PATH}\"`,\n ),\n ]),\n ].join('\\n')\n}\n\nexport const cloudflareAdapter: DeployAdapter = {\n // #367 / #369 and `docs/adr/0020`. Wrangler runs esbuild at deploy time, so bundling here\n // twice would be work with no observable effect — validated live 2026-09-26\n // (`records/acceptance/evidence/b263-cloudflare-deploy.txt`). There is still no source tree in\n // a Worker, which is why it bakes.\n readsSourceAtRunTime: false,\n specifiersResolvedBy: 'the-platform',\n name: 'cloudflare',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied: the worker carries `security.headers` as a\n // literal and puts the built baseline on every response it returns, including\n // the streamed SSR document — with a per-request nonce, the only deploy path\n // that can mint one (`adapters/security-headers.ts`).\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('cloudflare', readManifest(cwd))\n\n // 1. Run the standard Node build first (ctx forwarded so nodeAdapter has makeVitePlugins)\n await nodeAdapter.build(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/cloudflare')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time output directory, derived from the project root\n mkdirSync(outputDir, { recursive: true })\n\n // 2. Emit Worker entry (now uses the shared web-shim)\n //\n // The document shell is read HERE, after the Node build produced\n // `.theokit/client/index.html`, and inlined into the worker: a Worker has no\n // filesystem at request time. Split on the root div with the same helper the\n // Node server uses (`ssr-setup.ts`), so the two paths cannot disagree about\n // where the shell ends (#343).\n const shell = readDocumentShell(cwd, config.ssrStreaming)\n // B-035 — the route-to-chunks map, read HERE on the build machine for the same reason the\n // shell above is: a Worker has no filesystem at request time. `nodeAdapter.build` ran\n // first, so the map the Node build emitted is on disk by now. Absent map -> nothing about\n // preloads is emitted, and the worker behaves exactly as it did before.\n const assetsMap = readAssetsMapForBake(resolve(cwd, '.theokit', 'client', 'assets-map.json'))\n\n // #369 — the routes are resolved HERE, on the build machine, for the same reason the document\n // shell above is read here: a Worker has no filesystem at request time, and the worker used to\n // run the scan itself against a directory that does not exist there.\n //\n // The scanner is INJECTED rather than imported: importing it would add an `adapters → server`\n // edge, which is the layering inversion ADR-0001 v3 removed for `vite-plugin` and which\n // `adapters-may-only-depend-on-core-router-services` refuses. An absent scanner emits a worker\n // with no routes rather than falling back to a runtime scan — the fallback IS the defect.\n const scanned = ctx?.scanRoutes?.(config.serverDir) ?? {\n routes: [],\n wsRoutes: [],\n agents: [],\n // B-185 — no provider means no scan, and an app whose context nobody looked for is\n // indistinguishable here from one that has none. Both resolve an anonymous caller, which is\n // the honest answer rather than an invented subject.\n contextModule: undefined,\n }\n\n const pluginsPlan = planDeployedPlugins(config.plugins, 'cloudflare')\n if (pluginsPlan !== undefined) {\n // Beside the worker, so the emitted import is a sibling. Wrangler bundles from here, which is\n // what lets the static import reach the app's own module at all (#425).\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time write under the project's own `.theokit/cloudflare`\n writeFileSync(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time write under the project's own `.theokit/cloudflare`\n writeFileSync(\n resolve(outputDir, 'worker.mjs'),\n renderCloudflareWorkerEntry({\n ssrStreaming: config.ssrStreaming,\n // B-315 — LATENT here, not broken: the routes are baked (#369) so the worker never scans,\n // and a live deploy on 2026-09-26 served every route correctly with the wrong literal. It\n // is still handed to `executeRoute`, so it is one refactor away from mattering.\n serverDir: config.serverDir,\n ...shell,\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n assetsMap,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n routes: scanned.routes,\n // #367 — a Worker has no filesystem, so its agents are decided here like its routes.\n agents: scanned.agents,\n // B-185 — rides beside the agents because it is decided by the same provider, for the same\n // reason: `build.ts` holds `serverDir` and a Worker cannot look for the module itself.\n contextModule: scanned.contextModule,\n wsRoutes: scanned.wsRoutes,\n }),\n )\n\n // 3. Emit the stub every alias resolves to, then wrangler.toml.\n //\n // The stub is written whether or not the table needs it: an alias pointing at a path nothing\n // wrote fails the same way the missing module failed, one layer down, and the file costs nothing.\n const workersUnsupported = absentOptionalPeersOnDisk(cwd)\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time write under the project's own `.theokit/cloudflare`\n writeFileSync(resolve(cwd, WORKERS_UNSUPPORTED_STUB_PATH), renderWorkersUnsupportedStub())\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time write under the project's own `.theokit/cloudflare`\n writeFileSync(\n resolve(cwd, 'wrangler.toml'),\n // B-263 — the toml decides whether the worker or the CDN answers the document, and the two\n // modes need different `not_found_handling`. Passing the flag is what keeps them apart.\n renderWranglerToml({ ssrStreaming: config.ssrStreaming, workersUnsupported }),\n )\n\n if (workersUnsupported.length > 0) {\n // The COUNT on every build, and the names in the file. Printing all 25 of them — measured on a\n // fresh scaffold — buries the rest of the build output in a list nobody reads twice, and the\n // list is already written where a reader can look it up.\n //\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n ` ℹ ${String(workersUnsupported.length)} absent optional peer dependenc${\n workersUnsupported.length === 1 ? 'y' : 'ies'\n } aliased so wrangler can bundle — see [alias] in wrangler.toml`,\n )\n }\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Cloudflare output → .theokit/cloudflare/ + wrangler.toml')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'cloudflare',\n securityHeaders: config.security?.headers,\n // Only the streaming worker renders HTML per request, so only it can put\n // the same nonce on the header and on the script tag it emits.\n mintsNonce: config.ssrStreaming,\n // #412 — either way the worker returns the document now: streamed by\n // `renderStreamingWeb`, or from the ASSETS binding it finally calls.\n documentHeaders: 'handler',\n })}\\n`,\n )\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,cAAc,qBAAqB;AACvD,SAAS,qBAAqB;AAC9B,SAAS,eAAe;AA0DjB,SAAS,qBAAqB,MAAoD;AACvF,MAAI;AAEF,WAAO,eAAe,aAAa,MAAM,MAAM,CAAC;AAAA,EAClD,QAA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AAG,6BAA6B,CAAC;AAGzF;AAAA,MACE,QAAQ,KAAK,eAAe;AAAA;AAAA;AAAA,MAG5B,mBAAmB,EAAE,cAAc,OAAO,cAAc,mBAAmB,CAAC;AAAA,IAC9E;AAEA,QAAI,mBAAmB,SAAS,GAAG;AAMjC,cAAQ;AAAA,QACN,YAAO,OAAO,mBAAmB,MAAM,CAAC,kCACtC,mBAAmB,WAAW,IAAI,MAAM,KAC1C;AAAA,MACF;AAAA,IACF;AAGA,YAAQ,IAAI,0EAAgE;AAE5E,YAAQ;AAAA,MACN,GAAG,gCAAgC;AAAA,QACjC,QAAQ;AAAA,QACR,iBAAiB,OAAO,UAAU;AAAA;AAAA;AAAA,QAGlC,YAAY,OAAO;AAAA;AAAA;AAAA,QAGnB,iBAAiB;AAAA,MACnB,CAAC,CAAC;AAAA;AAAA,IACJ;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/config-support.ts"],"sourcesContent":["/**\n * Which configuration a deploy target's emitted handler actually applies.\n *\n * `theo.config.ts` validates `rateLimit`, `security.cors`, `security.csrf`,\n * `security.disallowed` and `serialization` for every target. Applying them is\n * the handler's job, and the six Web-standards adapters build `executeRoute`'s\n * context from a subset of its fields, so the rest fall back to hard-coded\n * defaults on a deployed app (usetheokit/theokit#410). `security.cors` was read\n * only by the dev server until #409 wired it into `theokit start`; the six Web\n * targets still drop it.\n *\n * This module does not fix that. It makes it **audible at build time**: a\n * config key that is parsed and then dropped is named, with the target that\n * drops it and the next action. Silence was the defect — an operator who\n * declares a rate limit and gets none has no reason to look.\n *\n * It warns rather than refuses, deliberately. Refusing would break every\n * deployment that declares `rateLimit` today, and the real fix — wiring a\n * limiter that needs a per-runtime client address — is not a build away\n * (`docs/program/journeys/j07-rate-limit.md` § Correction measured what it\n * costs). Forcing an operator to delete valid configuration in order to ship\n * would trade a silent gap for a loud one that also loses information.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\nimport { nodeAdapter } from './node.js'\nimport type { ConfigConcern, DeployAdapter } from './types.js'\n\n/**\n * The closed set. A concern belongs here when it is (a) declarable in\n * `theo.config.ts` and (b) applied by a request handler rather than at build\n * time — a build-time key cannot be silently dropped by a runtime.\n */\nexport const CONFIG_CONCERNS = [\n 'rateLimit',\n 'cors',\n 'csrf',\n 'disallowed',\n 'serialization',\n 'plugins',\n 'securityHeaders',\n 'jobs',\n] as const satisfies readonly ConfigConcern[]\n\n/**\n * Does any production target apply this concern?\n *\n * DERIVED from what the `node` adapter declares, rather than listed. This was a hand-maintained\n * `APPLIED_BY_NO_TARGET` set holding `cors`, kept in step with `nodeAdapter.appliesConfig` by a\n * test — and #409, which taught `theokit start` to apply `cors`, emptied it. An empty hardcoded\n * set is not merely redundant: it makes the branch below provably unreachable, which the linter\n * says out loud (`sonarjs/no-empty-collection`).\n *\n * Deriving keeps the branch honest AND reachable: the moment a concern is added that `node` does\n * not apply, the advice stops claiming a target exists for it, with nothing to remember.\n */\nfunction appliedByNoTarget(concern: ConfigConcern): boolean {\n const applied = nodeAdapter.appliesConfig\n if (applied === undefined || applied === 'runtime-not-emitted-here') return true\n return !applied.includes(concern)\n}\n\n/** Where each concern lives in the config, for a message the operator can grep. */\nconst CONFIG_KEY: Record<ConfigConcern, string> = {\n rateLimit: 'rateLimit',\n cors: 'security.cors',\n csrf: 'security.csrf',\n disallowed: 'security.disallowed',\n serialization: 'serialization',\n plugins: 'plugins',\n securityHeaders: 'security.headers',\n jobs: 'jobs.backend',\n}\n\n/** Whether the config declares each concern, one predicate per concern. */\nconst IS_DECLARED: Record<ConfigConcern, (config: TheoConfig) => boolean> = {\n rateLimit: (config) => config.rateLimit !== undefined,\n cors: (config) => config.security?.cors !== undefined,\n // `csrf` carries `.default('strict')` (config/schemas/security.ts:100) and\n // the deployed fallback is also `'strict'` (server/http/execute.ts:144).\n // A config that says `'strict'` therefore gets what it asked for, by\n // coincidence rather than by wiring -- reporting it dropped would be noise\n // over an identical outcome. Only a weaker setting is silently ignored.\n csrf: (config) => config.security?.csrf !== undefined && config.security.csrf !== 'strict',\n disallowed: (config) =>\n config.security?.disallowed !== undefined && config.security.disallowed.routes.length > 0,\n securityHeaders: (config) => config.security?.headers !== undefined,\n // Same shape: `.default('json')` (config/schema.ts:147), and a target with\n // no transformer serializes as JSON. `'json'` is honoured by coincidence;\n // `'superjson'` is the case where the deployed app quietly disagrees with\n // the file.\n serialization: (config) => config.serialization !== 'json',\n plugins: (config) => config.plugins !== undefined && config.plugins.length > 0,\n // A constructed backend (a pool, a map) has no literal a deployed entry could hold, so only\n // `theokit start` wires `ctx.queue` from it (usetheokit/theokit#1009).\n jobs: (config) => config.jobs !== undefined,\n}\n\nfunction isDeclared(config: TheoConfig, concern: ConfigConcern): boolean {\n return IS_DECLARED[concern](config)\n}\n\n/**\n * The concerns this config declares and this adapter does not apply.\n *\n * An adapter that emits no request handler of its own answers\n * `'runtime-not-emitted-here'` and is never reported against: it is not that\n * the configuration is dropped, it is that this build cannot know. Saying\n * nothing is the honest output, and it is a different fact from saying no.\n */\nexport function findUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n): ConfigConcern[] {\n const applied = adapter.appliesConfig ?? []\n if (applied === 'runtime-not-emitted-here') return []\n return CONFIG_CONCERNS.filter(\n (concern) => isDeclared(config, concern) && !applied.includes(concern),\n )\n}\n\n/**\n * The build-time message. Empty string when nothing was dropped, so the caller\n * neither branches nor prints a header over an empty list.\n */\nexport function describeUnappliedConfig(target: string, dropped: readonly ConfigConcern[]): string {\n if (dropped.length === 0) return ''\n const one = dropped.length === 1\n const list = dropped.map((concern) => ` - ${CONFIG_KEY[concern]}`).join('\\n')\n const elsewhere = dropped.filter((concern) => !appliedByNoTarget(concern))\n const nowhere = dropped.filter(appliedByNoTarget)\n\n // The advice has to change with the target, or it degenerates. Building for\n // `node` with only `security.cors` dropped once produced \"deploy to `node`,\n // which applies all of the above except security.cors\" -- an instruction to\n // do what you are already doing, about the one key it then excepts.\n const actions: string[] = []\n if (elsewhere.length > 0 && target !== 'node') {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: build for \\`node\\` and run \\`theokit start\\`,`,\n ` which applies ${elsewhere.length === 1 ? 'it' : 'them'}; or remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n } else if (elsewhere.length > 0) {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n }\n if (nowhere.length > 0) {\n actions.push(\n ` - ${nowhere.map((c) => CONFIG_KEY[c]).join(', ')}: no production target applies ${nowhere.length === 1 ? 'this' : 'these'} today`,\n ` (usetheokit/theokit#409) -- terminate it in front of the app, or remove it.`,\n )\n }\n\n return [\n ` ! ${String(dropped.length)} configuration ${one ? 'key is' : 'keys are'} validated and NOT applied on \\`${target}\\`:`,\n list,\n ` The handler this target emits never reads ${one ? 'it' : 'them'}, so the deployed app`,\n ` behaves as if ${one ? 'the key were' : 'the keys were'} absent.`,\n ` What to do:`,\n ...actions,\n ` Tracked: usetheokit/theokit#410 (deploy targets), usetheokit/theokit#409 (cors).`,\n ].join('\\n')\n}\n\n/**\n * Emit the warning, if there is one. The sink is injected so the behaviour is\n * exercisable without driving a whole build: the alternative was a caller that\n * only a full `theokit build` could reach, which in practice means a caller\n * nothing tests.\n */\nexport function warnUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n target: string,\n log: (message: string) => void,\n): void {\n const dropped = findUnappliedConfig(config, adapter)\n if (dropped.length === 0) return\n log(`\\n${describeUnappliedConfig(target, dropped)}\\n`)\n}\n\n/**\n * A declared rate limit the chosen target cannot enforce.\n *\n * Its own class so a caller can distinguish it from a configuration typo — this is not the build\n * failing to understand the file, it is the build understanding it and refusing the combination.\n */\nexport class UnenforceableRateLimitError extends Error {\n override readonly name = 'UnenforceableRateLimitError'\n constructor(readonly target: string) {\n super(\n [\n `Refusing to build for \\`${target}\\`: theo.config.ts declares a rate limit and this target does not enforce one.`,\n ``,\n ` The config reads as protection the deploy will not have. Nothing at runtime reports the`,\n ` absence, so the first sign is abuse — which is why this refuses rather than warns.`,\n ``,\n ` Two honest ways forward:`,\n ` • build for \\`node\\` and run \\`theokit start\\`, which applies the limit; or`,\n ` • remove \\`rateLimit\\` from theo.config.ts, so the file states what actually runs.`,\n ``,\n ` There is deliberately no flag to keep the key and skip the check: a config that stays`,\n ` while doing nothing is the state this refusal exists to end (usetheokit/theokit#461).`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Refuse a build whose target drops a DECLARED rate limit.\n *\n * Only `rateLimit`, and the narrowness is the design. A dropped `cors` or `serialization` degrades\n * where someone can see it, and `describeUnappliedConfig`'s warning is proportionate for those.\n * `rateLimit` is the one whose absence looks exactly like success, which is the same reasoning\n * `MissingRoutePolicyError` applies to an undeclared route policy: refuse where silence would be\n * read as safety.\n *\n * `'runtime-not-emitted-here'` is not judged. That adapter's runtime is someone else's and this\n * build cannot answer for it; refusing there would be asserting something unmeasured.\n */\n/**\n * Refuse a target that cannot stream when the config says responses stream.\n *\n * Lives here rather than inside an adapter's `build()` because of WHEN it has to run. The refusal was\n * thrown from `buildAwsLambda`, which `runAdapterBuild` reaches a hundred lines after `cleanOutDir` has\n * emptied the output — so a project with `ssrStreaming: true` lost a working build to a refusal about\n * streaming. Measured 2026-09-28: 302 files in `.theokit/client/assets` before, 0 after (B-336).\n *\n * The alternatives are DERIVED from the registry rather than written into the sentence. A hardcoded\n * list was correct when it was written and nothing kept it correct, which is the same class of drift\n * `adapter-streaming-contract.test.ts` now pins.\n */\nexport function assertStreamingSupported(\n config: Pick<TheoConfig, 'ssrStreaming'>,\n adapter: Pick<DeployAdapter, 'streamsResponses' | 'streamingUnsupportedDetail'>,\n target: string,\n streamingTargets?: readonly string[],\n): void {\n if (!config.ssrStreaming) return\n if (adapter.streamsResponses === true) return\n\n const detail =\n adapter.streamingUnsupportedDetail === undefined ? '' : ` ${adapter.streamingUnsupportedDetail}`\n\n // The alternatives are named only when the CALLER could know them. An adapter cannot: asking the\n // registry from inside one closes `adapter -> config-support -> registry -> adapter`, and the Acyclic\n // Dependencies Principle is not negotiable here (`rules/architecture.md`). So the CLI passes the list\n // it already has, and a direct call to an adapter's build gets the same refusal without it.\n const alternatives =\n streamingTargets === undefined || streamingTargets.length === 0\n ? ''\n : ` Build a streaming target instead (${streamingTargets.join(', ')}), or set`\n const orSet = alternatives === '' ? ' Set' : alternatives\n\n throw new Error(\n `[adapter-${target}] ssrStreaming is on, but the ${target} target does not stream responses.` +\n `${detail}${orSet} ssrStreaming: false in theo.config.ts.`,\n )\n}\n\nexport function assertRateLimitEnforceable(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'enforcesRateLimit'>,\n target: string,\n): void {\n if (!isDeclared(config, 'rateLimit')) return\n\n // B-257 — this reads `enforcesRateLimit`, NOT `appliesConfig`. They were one list until now, and\n // `applied.includes('rateLimit')` returned before the throw, so adding that entry to silence the\n // WARNING also switched off this REFUSAL — on a runtime where the limit still cannot hold.\n //\n // **An omitted field REFUSES.** The first cut defaulted to `'not-ours-to-judge'`, which inverted\n // the rule it replaced: `appliesConfig ?? []` did not include `'rateLimit'`, so an adapter that\n // declared nothing was refused; `?? 'not-ours-to-judge'` let it through. Measured on\n // `static.ts`, which declares neither field and is registered at `registry.ts:28` — it went from\n // refusing a declared limit to proceeding with a console warning. `:213-215` refuses exactly that\n // outcome in its own words, and this member is on the EXPORTED `DeployAdapter`, so every\n // third-party adapter inherited the inversion too.\n //\n // Abstaining is a CLAIM about somebody else's runtime, and a claim has to be made rather than\n // inferred from silence.\n const enforces = adapter.enforcesRateLimit ?? 'never'\n\n // An adapter emitting no request handler is not judged. Its runtime is someone else's and this\n // build cannot answer for it; refusing would assert something unmeasured. An ABSTAIN, and the\n // reason it is not spelled `'never'`.\n if (enforces === 'not-ours-to-judge') return\n\n if (enforces === 'always') return\n\n // `'never'`, and the default for an adapter that declared nothing. Refusing here is what the\n // pre-B-257 rule did; reaching the store check below would let an undeclared adapter enforce by\n // accident whenever a config happened to name one.\n if (enforces === 'never') throw new UnenforceableRateLimitError(target)\n\n // `'with-a-store'`: a per-invocation runtime enforces only when the config names a durable\n // counter. Without one the in-process count dies with the invocation, and a limit that forgets is\n // a limit that does not limit — the same class of failure as a shared bucket, by another road.\n if (declaresRateLimitStore(config)) return\n\n throw new UnenforceableRateLimitError(target)\n}\n\n/** Does the declared `rateLimit` name a store the emitted entry could construct? */\nfunction declaresRateLimitStore(config: TheoConfig): boolean {\n const limit = (config as { rateLimit?: { store?: unknown } }).rateLimit\n return typeof limit?.store === 'object' && limit.store !== null\n}\n"],"mappings":";;;;;;;;AAiCO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAcA,SAAS,kBAAkB,SAAiC;AAC1D,QAAM,UAAU,YAAY;AAC5B,MAAI,YAAY,UAAa,YAAY,2BAA4B,QAAO;AAC5E,SAAO,CAAC,QAAQ,SAAS,OAAO;AAClC;AAGA,IAAM,aAA4C;AAAA,EAChD,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,SAAS;AAAA,EACT,iBAAiB;AAAA,EACjB,MAAM;AACR;AAGA,IAAM,cAAsE;AAAA,EAC1E,WAAW,CAAC,WAAW,OAAO,cAAc;AAAA,EAC5C,MAAM,CAAC,WAAW,OAAO,UAAU,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM5C,MAAM,CAAC,WAAW,OAAO,UAAU,SAAS,UAAa,OAAO,SAAS,SAAS;AAAA,EAClF,YAAY,CAAC,WACX,OAAO,UAAU,eAAe,UAAa,OAAO,SAAS,WAAW,OAAO,SAAS;AAAA,EAC1F,iBAAiB,CA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,KACA,sCAAsC,iBAAiB,KAAK,IAAI,CAAC;AACvE,QAAM,QAAQ,iBAAiB,KAAK,SAAS;AAE7C,QAAM,IAAI;AAAA,IACR,YAAY,MAAM,iCAAiC,MAAM,qCACpD,MAAM,GAAG,KAAK;AAAA,EACrB;AACF;AAEO,SAAS,2BACd,QACA,SACA,QACM;AACN,MAAI,CAAC,WAAW,QAAQ,WAAW,EAAG;AAgBtC,QAAM,WAAW,QAAQ,qBAAqB;AAK9C,MAAI,aAAa,oBAAqB;AAEtC,MAAI,aAAa,SAAU;AAK3B,MAAI,aAAa,QAAS,OAAM,IAAI,4BAA4B,MAAM;AAKtE,MAAI,uBAAuB,MAAM,EAAG;AAEpC,QAAM,IAAI,4BAA4B,MAAM;AAC9C;AAGA,SAAS,uBAAuB,QAA6B;AAC3D,QAAM,QAAS,OAA+C;AAC9D,SAAO,OAAO,OAAO,UAAU,YAAY,MAAM,UAAU;AAC7D;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/deno-deploy.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Deno Deploy adapter. Writes to `cwd/.theokit/deno-deploy/`. Build-time.\n */\nimport {\n cpSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment, scannedFromLoaderCache } from './deployed-agents.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport { deployedRateLimitFragment, rateLimitCheckFragment } from './deployed-rate-limit.js'\nimport {\n agentsDirLiteral,\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter, DeployedEntryOptions } from './types.js'\n\nexport interface DenoBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n /** The project's own source texts, whose bare imports the emitted map has to resolve. */\n readProjectSources?: (cwd: string, config: TheoConfig) => string[]\n /** The Deno config already on disk, merged rather than replaced. */\n readDenoConfig?: (cwd: string) => DenoConfig | undefined\n /** Copies the client build to where the entry serves it from. */\n copyClient?: (from: string, to: string) => void\n}\n\n/**\n * The framework imports this entry opens with, as `npm:` specifiers.\n *\n * Extracted from `renderDenoEntry` when adding the configured-directory literal pushed it past the\n * per-function line budget. A cohesive block — every line is one import of the same package family\n * — so lifting it keeps the budget a signal about the renderer rather than about its preamble.\n */\n/**\n * How this entry is deployed, and the one failure whose message names the wrong thing.\n *\n * Extracted for the same reason `FRAMEWORK_IMPORTS` above was: a cohesive block of emitted\n * comment lines that pushed the renderer past its line budget, where the budget is meant to\n * be a signal about the renderer rather than about its preamble.\n */\n/** Where the entry serves the client build from — beside it, inside the upload (#951). */\nexport const DENO_DEPLOY_CLIENT_DIR = 'theokit-deploy/client'\n\n/**\n * The client build, served by the entry itself (#951).\n *\n * Measured 2026-10-03: on a dynamic Deno Deploy app `/`, `/about` and every asset answered this\n * entry's JSON 404, because it returned `notFound()` for each non-API path on the assumption that\n * \"Deno Deploy's static asset handler\" serves them. A dynamic app has no such handler.\n *\n * Served from `theokit-deploy/client`, a copy the build writes, and not from `.theokit/client`.\n * Measured on the platform the same day: the upload honours `.gitignore`, and the scaffold ignores\n * `.theokit/`, so the build output never arrived. Uploading `.theokit` anyway broke every agent\n * route, because its `manifest.json` carries the build machine's absolute paths.\n *\n * `Deno.readFile` rather than `jsr:@std/http`'s `serveDir`: no new specifier for the platform to\n * resolve. An extensionless path is a client route and gets the document; a missing asset stays a\n * 404 so a broken chunk is not answered with HTML. A decoded `..` segment is refused before the\n * path is joined, so nothing outside the build is readable.\n */\nconst CLIENT_SERVER_FRAGMENT: readonly string[] = [\n `const CLIENT_DIR = cwd + '/${DENO_DEPLOY_CLIENT_DIR}'`,\n `const CLIENT_TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.map': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif', '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', '.wasm': 'application/wasm' }`,\n ``,\n `async function readClientFile(path) {`,\n ` try {`,\n ` return await Deno.readFile(CLIENT_DIR + path)`,\n ` } catch (err) {`,\n ` if (err instanceof Deno.errors.NotFound || err?.code === 'EISDIR' || err?.name === 'IsADirectory') return null`,\n ` throw err`,\n ` }`,\n `}`,\n ``,\n `async function serveClient(request, url) {`,\n ` if (request.method !== 'GET' && request.method !== 'HEAD') return notFound()`,\n ` let path`,\n ` try { path = decodeURIComponent(url.pathname) } catch { return notFound() }`,\n ` if (path.split('/').includes('..')) return notFound()`,\n ` if (path.endsWith('/')) path += 'index.html'`,\n ` const dot = path.lastIndexOf('.')`,\n ` const ext = dot > path.lastIndexOf('/') ? path.slice(dot).toLowerCase() : ''`,\n ` const body = await readClientFile(path)`,\n ` if (body !== null) {`,\n ` const headers = { 'Content-Type': CLIENT_TYPES[ext] ?? 'application/octet-stream' }`,\n ` if (path.startsWith('/assets/')) headers['Cache-Control'] = 'public, max-age=31536000, immutable'`,\n ` return new Response(request.method === 'HEAD' ? null : body, { status: 200, headers })`,\n ` }`,\n ` if (ext !== '') return notFound()`,\n ` const document = await readClientFile('/index.html')`,\n ` if (document === null) return notFound()`,\n ` return new Response(request.method === 'HEAD' ? null : document, {`,\n ` status: 200,`,\n ` headers: { 'Content-Type': 'text/html; charset=utf-8' },`,\n ` })`,\n `}`,\n]\n\nconst DEPLOY_INSTRUCTIONS: readonly string[] = [\n `// Deploy from the project root, so the entry finds its own src/server tree:`,\n `// deno deploy --org <org> --app <name> --prod \\\\`,\n `// --ignore node_modules --ignore package.json`,\n `// Both exclusions are load-bearing, and both were isolated on the platform by`,\n `// changing one thing at a time. node_modules: pnpm's is a symlink farm the upload`,\n `// cannot carry, and this entry reaches the framework through npm: specifiers, so`,\n `// it needs none of it. package.json: it is what Deno resolves those specifiers`,\n `// against, so its version ranges bring the minimum-dependency-age policy with`,\n `// them — with the manifest in the upload the revision failed, without it the same`,\n `// directory deployed and served.`,\n `//`,\n `// If a deploy that keeps the manifest fails with \"Could not find npm package`,\n `// <name> matching <range>\",`,\n `// read the rest of that message before changing anything: Deno applies a`,\n `// minimum-dependency-age policy (24h by default) and refuses a version published`,\n `// inside that window, naming the PACKAGE rather than the policy. The range comes`,\n `// from this project's package.json, which the upload carries. It clears by itself;`,\n `// to deploy now, pass --min-dep-age=0 or set minimumDependencyAge in deno.json —`,\n `// both lower a supply-chain protection, which is why nothing here sets it for you.`,\n]\n\nconst FRAMEWORK_IMPORTS: readonly string[] = [\n `// Use npm: specifier so Deno resolves theokit from the user's package.json`,\n `// equivalent (works in both local 'deno run' and Deno Deploy).`,\n // Sub-paths, not the umbrella. `theokit/server` is DEPRECATED by the framework itself with a\n // REMOVAL scheduled, so this entry would stop loading on that release, before a request exists —\n // measured on Deno 2.9.5, where the warning printed on every start. This was the only adapter still\n // on the umbrella; the split below is the mapping four siblings already use and Bun proves by\n // running.\n `import { scanServerRoutes, matchRoute, createProductionLoader, scanWebSocketRoutes } from 'npm:theokit/server/scan'`,\n `import { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'npm:theokit/server/http'`,\n `import { createWebShim } from 'npm:theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'npm:theokit/adapters/security-headers'`,\n `// T3.3 — WS bridge for Deno runtime`,\n `import { createDenoWsBridge } from 'npm:theokit/adapters/ws-shim'`,\n]\n\n/** The target's name, in the five places that spell it. Adding a sixth tripped the duplicate-literal gate. */\n/* The name in the places a gate does NOT read. `assertServicesUnsupported` keeps the literal:\n * `services-other-adapters-reject.test.ts:30` requires each adapter to name ITSELF there, so a\n * copy-paste carrying another adapter's name cannot hide behind a constant. */\nconst TARGET = 'deno-deploy'\n\nexport function renderDenoEntry(port: number, opts: DeployedEntryOptions = {}): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(scannedFromLoaderCache(agentsDirLiteral(opts)), {\n notFound: 'notFound()',\n importPrefix: 'npm:',\n // B-185 — bound only when the runtime-config fragment declared the const, which is\n // exactly when a plugins module was emitted. Referencing it otherwise would emit an\n // identifier the entry never declares.\n pluginRunnerExpr:\n opts.runtimeConfigModule === undefined ? undefined : 'await THEO_PLUGIN_RUNNER',\n })\n return [\n `// Generated by Theo — Deno Deploy Adapter`,\n ...DEPLOY_INSTRUCTIONS,\n `// Requires Deno >= 1.40 (Deno.serve + npm: specifier support)`,\n ``,\n `// Runtime guard`,\n `if (typeof Deno === 'undefined') {`,\n ` throw new Error('TheoDenoDeployAdapter must run inside Deno.')`,\n `}`,\n ``,\n ...FRAMEWORK_IMPORTS,\n ``,\n `const port = Number(Deno.env.get('PORT') ?? '${port}')`,\n `const cwd = Deno.cwd()`,\n `const serverDir = cwd + '/' + ${serverDirLiteral(opts)}`,\n `let routesCache = null`,\n `let wsRoutesCache = null`,\n `let loaderCache = null`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed isolate has no`,\n `// theo.config.ts to read. The document is served by this entry too`,\n `// (usetheokit/theokit#951), so it carries the baseline as well.`,\n ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, TARGET),\n ``,\n ...CLIENT_SERVER_FRAGMENT,\n ``,\n `function notFound() {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'Content-Type': 'application/json' },`,\n ` })`,\n `}`,\n ``,\n // B-027 — `npm:`, like every other specifier this target emits (`:37-43`). A bare one does\n // not resolve on Deno Deploy, and the harness asserts the prefix is here before rewriting it.\n ...(opts.rateLimit === undefined\n ? []\n : [\n `import { createRateLimiterWeb } from 'npm:theokit/server/rate-limit'`,\n `import { resolveClientIpFromRequest } from 'npm:theokit/server/rate-limit'`,\n ``,\n ]),\n ...deployedRateLimitFragment(\n opts.rateLimit,\n TARGET,\n // `info.remoteAddr` is the runtime's own answer. A `UnixAddr` has no `hostname`, so the\n // optional chain is what keeps the read from throwing there rather than a guess.\n `info?.remoteAddr?.hostname ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n 'request, info',\n // B-257 — `npm:`, like every other specifier this target emits. A bare one does not resolve\n // on Deno Deploy, and the durable limiter's import is emitted by the fragment rather than\n // here, so the prefix has to travel with it.\n 'npm:',\n ),\n ``,\n // The serve handler's SECOND parameter is bound here for the first time: `Deno.serve` has\n // always passed it and the emitted entry discarded it.\n `Deno.serve({ port }, async (request, info) => {`,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(opts.rateLimit, ' ', 'request, info'),\n ``,\n ` // LCR0103 — the upgrade branch sits BELOW the limiter, and the order is the point.`,\n ` // It used to sit above, under the comment \"a 101 carries no document and no script,`,\n ` // so the security baseline does not apply to it\". That is true of the security`,\n ` // HEADERS — a document concern — and false of the limiter, which is a resource`,\n ` // concern: a long-lived socket is the most expensive thing this entry hands out, so`,\n ` // the upgrade is the path that most needs a budget, not the one that may skip it.`,\n ` // T3.3 — Detect WebSocket upgrade and delegate to the Deno bridge.`,\n ` // A 101 carries no document and no script, so the security baseline does`,\n ` // not apply to it.`,\n ` if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {`,\n ` if (!wsRoutesCache) wsRoutesCache = scanWebSocketRoutes(serverDir)`,\n ` if (wsRoutesCache.length === 0) return notFound()`,\n ` const denoWs = createDenoWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` }, Deno)`,\n ` return denoWs.handle(request)`,\n ` }`,\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n `})`,\n ``,\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ``,\n ` if (!url.pathname.startsWith('/api/')${agentsFragment.hostBypass}) {`,\n ` return serveClient(request, url)`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ...agentsFragment.branch,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) return notFound()`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — not awaited: toResponse() settles at the headers and carries a`,\n ` // live body, so Deno.serve streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeConfig.executeRouteSpread} }))`,\n `}`,\n ``,\n `console.log('Theo (Deno Deploy) listening on :' + port)`,\n ].join('\\n')\n}\n\nexport async function buildDeno(\n config: TheoConfig,\n cwd: string,\n deps: DenoBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('deno-deploy', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, DENO_DEPLOY_ENTRY_PATH, '..')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const pluginsPlan = planDeployedPlugins(config.plugins, denoDeployAdapter.name)\n const entry = renderDenoEntry(config.port, {\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n // #95 — the configured directories, which `build.ts:210` already threads into the Vite\n // plugins. Without these two lines the literals above fall to their defaults and a project\n // with a custom dir deploys an entry that resolves a directory it does not have.\n serverDir: config.serverDir,\n agentsDir: config.agentsDir,\n })\n const write =\n deps.writeEntry ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n if (pluginsPlan !== undefined) {\n // Beside the entry, so the emitted import is a sibling. Written through the same seam as\n // the entry so a test that captures one captures both (#425).\n write(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n write(resolve(cwd, DENO_DEPLOY_ENTRY_PATH), entry)\n\n copyClientBesideEntry(cwd, deps)\n\n // The import map and `sloppy-imports`, at the upload root. Measured on the platform: a\n // config in a subdirectory failed the revision, so this path is not a preference.\n const readSources = deps.readProjectSources ?? readProjectSourcesFromDisk\n const readConfig = deps.readDenoConfig ?? readDenoConfigFromDisk\n const denoConfig = renderDenoConfig({\n specifiers: bareSpecifiersOf(readSources(cwd, config)),\n existing: readConfig(cwd),\n })\n write(resolve(cwd, DENO_DEPLOY_CONFIG_PATH), `${JSON.stringify(denoConfig, undefined, 2)}\\n`)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `\\n ✓ Deno Deploy output → ${DENO_DEPLOY_ENTRY_PATH} + ${DENO_DEPLOY_CONFIG_PATH} (${\n Object.keys(denoConfig.imports ?? {}).length\n } specifiers mapped)`,\n )\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: TARGET,\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-unmanaged',\n })}\\n`,\n )\n}\n\n/**\n * Where the entry is written, relative to the project root.\n *\n * NOT under `.theokit/`, and that is the whole point: measured against the real platform on\n * 2026-09-30, a dot directory is never uploaded. `./.theokit/deno/probe.ts` failed the\n * revision while the byte-identical file at `./visible/probe.ts` served HTTP 200. An entry\n * the upload cannot see is an entry that cannot run, and the build reported success either\n * way — so nothing short of a deploy could find this.\n *\n * One directory deep, because the upload root has to stay the PROJECT root: the entry scans\n * `<cwd>/src/server` for the project's own route modules, so a deploy rooted anywhere else\n * finds no routes and answers 404 on every path.\n */\nexport const DENO_DEPLOY_ENTRY_PATH = 'theokit-deploy/server.ts'\n\n/** Copy `.theokit/client` to where the entry serves it from. Split out of `buildDeno` for its complexity ceiling. */\nfunction copyClientBesideEntry(cwd: string, deps: DenoBuildDeps): void {\n const copy = deps.copyClient ?? copyClientOnDisk\n copy(resolve(cwd, '.theokit', 'client'), resolve(cwd, DENO_DEPLOY_CLIENT_DIR))\n}\n\n/** Replace the served copy with the current build. No build output means an API-only project. */\nfunction copyClientOnDisk(from: string, to: string): void {\n if (!existsSync(from)) return\n rmSync(to, { recursive: true, force: true })\n cpSync(from, to, { recursive: true })\n}\n\n/** Where the Deno config is written. The upload root, and nowhere else — see below. */\nexport const DENO_DEPLOY_CONFIG_PATH = 'deno.json'\n\n/**\n * The bare specifiers a set of source texts import — the ones needing a registry, in the\n * order they will be emitted.\n *\n * Derived from the project's own sources rather than from `package.json`, because what has\n * to resolve is what is actually imported: a declared dependency nobody imports needs no\n * entry, and a subpath like `theokit/server/define` appears in no manifest at all.\n */\nexport function bareSpecifiersOf(sources: Iterable<string>): string[] {\n const found = new Set<string>()\n for (const source of sources) {\n for (const match of source.matchAll(/(?:from|import)\\s+['\"]([^'\"]+)['\"]/gu)) {\n // `match[1]` and not a guarded read: the capture group is not optional in this pattern,\n // so it participates in every match the loop yields.\n const specifier = match[1]\n // A relative or absolute path resolves on its own; a specifier that already names its\n // registry is not ours to map.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- a regex group's type is wider than this pattern\n if (specifier === undefined) continue\n if (/^(?:[./]|npm:|jsr:|node:|data:|https?:)/u.test(specifier)) continue\n found.add(specifier)\n }\n }\n // An explicit comparator: the emitted map is read in diffs, so its order has to be the\n // same on every machine rather than whatever the default collation is.\n return [...found].sort((a, b) => a.localeCompare(b, 'en'))\n}\n\n/** The shape this adapter reads and writes. Anything else in the file is carried through. */\nexport interface DenoConfig {\n imports?: Record<string, string>\n unstable?: string[]\n [key: string]: unknown\n}\n\n/**\n * The Deno config the platform needs, merged onto whatever the project already wrote.\n *\n * Two measured facts decide its whole content:\n *\n * **Each specifier is mapped exactly, never as a prefix.** The emitted entry imports\n * `npm:theokit/...`; the project's own modules import the bare `theokit/server/define`. A\n * trailing-slash prefix cannot bridge them — Deno refuses `\"theokit/\": \"npm:theokit/\"` with\n * *\"its after-prefix portion could not be URL-parsed relative to the URL prefix\"*, because\n * the part after the prefix is not joinable onto an `npm:` URL. Exact entries resolve; the\n * prefix form fails at the first import, at runtime, with a 500.\n *\n * **`sloppy-imports` is declared.** A generated project's own agent modules import siblings\n * with a `.js` extension against files on disk ending `.ts` — six of them in the default\n * template. Deno refuses that pairing and says so: *\"Maybe change the extension to '.ts' or\n * run with --sloppy-imports\"*.\n */\nexport function renderDenoConfig(opts: {\n specifiers: readonly string[]\n existing?: DenoConfig\n}): DenoConfig {\n const config: DenoConfig = { ...(opts.existing ?? {}) }\n const imports: Record<string, string> = { ...(config.imports ?? {}) }\n for (const specifier of opts.specifiers) imports[specifier] = `npm:${specifier}`\n config.imports = imports\n const unstable = [...(config.unstable ?? [])]\n if (!unstable.includes('sloppy-imports')) unstable.push('sloppy-imports')\n config.unstable = unstable\n return config\n}\n\n/**\n * The project's own TypeScript sources, from the directories the entry scans at runtime.\n *\n * Scoped to those directories plus the config file rather than the whole tree: what the map\n * must resolve is what the DEPLOYED code imports, and a specifier reachable only from a test\n * or a build script never runs on the platform.\n */\nfunction readProjectSourcesFromDisk(cwd: string, config: TheoConfig): string[] {\n // No fallback: `config/schema.ts` gives both a zod `.default()`, so a parsed config always\n // carries them — and the defaults are `server`/`agents`, so the `src/`-prefixed guesses this\n // line used to hold would have read the wrong directories on any project that took them.\n const roots = [config.serverDir, config.agentsDir]\n const texts: string[] = []\n for (const root of roots) {\n const dir = resolve(cwd, root)\n if (!existsSync(dir)) continue\n for (const entry of readdirSync(dir, { recursive: true, withFileTypes: true })) {\n if (!entry.isFile()) continue\n if (!/\\.(?:ts|tsx|mts)$/u.test(entry.name)) continue\n if (/\\.(?:test|spec)\\./u.test(entry.name)) continue\n texts.push(readFileSync(resolve(entry.parentPath, entry.name), 'utf8'))\n }\n }\n const themeConfig = resolve(cwd, 'theo.config.ts')\n if (existsSync(themeConfig)) texts.push(readFileSync(themeConfig, 'utf8'))\n return texts\n}\n\nfunction readDenoConfigFromDisk(cwd: string): DenoConfig | undefined {\n const file = resolve(cwd, DENO_DEPLOY_CONFIG_PATH)\n if (!existsSync(file)) return undefined\n try {\n return JSON.parse(readFileSync(file, 'utf8')) as DenoConfig\n } catch {\n // A config we cannot parse is one we must not overwrite blind: returning undefined would\n // replace whatever the project wrote. Refusing here surfaces it at the write site instead.\n throw new Error(\n `${DENO_DEPLOY_CONFIG_PATH} exists and is not valid JSON. Fix or remove it before building for deno-deploy.`,\n )\n }\n}\n\nexport const denoDeployAdapter: DeployAdapter = {\n // Same as `bun`, plus the runtime compiles the TypeScript it finds — which is why a scan that\n // answered `SyntaxError` on netlify is legitimate here. The last runtime scanner in the fleet.\n readsSourceAtRunTime: true,\n specifiersResolvedBy: 'the-project-at-run-time',\n name: 'deno-deploy',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this isolate returns,\n // the document included, since the entry serves the client build itself\n // (usetheokit/theokit#951).\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n build(config, cwd, ctx) {\n return buildDeno(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AA8CjB,IAAM,yBAAyB;AAmBtC,IAAM,yBAA4C;AAAA,EAChD,8BAA8B,sBAAsB;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,sBAAyC;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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AM,IAAI,EAAG;AAC5C,UAAI,qBAAqB,KAAK,MAAM,IAAI,EAAG;AAC3C,YAAM,KAAK,aAAa,QAAQ,MAAM,YAAY,MAAM,IAAI,GAAG,MAAM,CAAC;AAAA,IACxE;AAAA,EACF;AACA,QAAM,cAAc,QAAQ,KAAK,gBAAgB;AACjD,MAAI,WAAW,WAAW,EAAG,OAAM,KAAK,aAAa,aAAa,MAAM,CAAC;AACzE,SAAO;AACT;AAEA,SAAS,uBAAuB,KAAqC;AACnE,QAAM,OAAO,QAAQ,KAAK,uBAAuB;AACjD,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO;AAC9B,MAAI;AACF,WAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAAA,EAC9C,QAAQ;AAGN,UAAM,IAAI;AAAA,MACR,GAAG,uBAAuB;AAAA,IAC5B;AAAA,EACF;AACF;AAEO,IAAM,oBAAmC;AAAA;AAAA;AAAA,EAG9C,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,EACtB,MAAM;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,cAAc;AAAA,EACd,eAAe,CAAC,mBAAmB,QAAQ,cAAc,QAAQ,iBAAiB,SAAS;AAAA;AAAA,EAE3F,mBAAmB;AAAA,EACnB,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,UAAU,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EACvC;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/netlify.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Netlify deploy adapter. All paths derived from `cwd` and a fixed\n * `.theokit/netlify/` output layout. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport {\n bundleDeployedFunction,\n type BundleDeployedFunctionOptions,\n} from './bundle-deployed-function.js'\nimport { deployedAgentsFragment, JSON_NOT_FOUND_RESPONSE } from './deployed-agents.js'\nimport { renderBakedRoutes, routeRuntimeLines, type BakedRoute } from './deployed-baked-routes.js'\nimport { type DeployedCorsOptions } from './deployed-cors.js'\nimport { type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport { deployedRateLimitFragment, rateLimitCheckFragment } from './deployed-rate-limit.js'\nimport type { DeployedRateLimitOptions } from './deployed-rate-limit.js'\nimport {\n deployedRuntimeConfigFragment,\n type DeployedRuntimeConfigOptions,\n serverDirLiteral,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { buildSecurityHeaders, describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport class NetlifyConflictError extends Error {\n constructor(path: string, currentTo: string) {\n super(\n `netlify.toml has a conflicting redirect: \"${path}\" → \"${currentTo}\". ` +\n `Remove it manually or edit it to point to \"/.netlify/functions/theo\" ` +\n `before running the Netlify adapter again.`,\n )\n this.name = 'NetlifyConflictError'\n }\n}\n\nexport class NetlifyFunctionsConflictError extends Error {\n constructor(key: string, declared: string, required: string) {\n super(\n `netlify.toml declares \\`[functions] ${key} = \"${declared}\"\\`, and this adapter needs ` +\n `\"${required}\". Measured on the Netlify emulator: \\`directory\\` is what makes the generated ` +\n `function discoverable at all (without it the redirect answers \"Function not found\"), and ` +\n `\\`node_bundler = \"none\"\\` is what stops Netlify re-bundling a function theokit already ` +\n `bundled — which produces a SyntaxError. Change the value, or remove the key and let this ` +\n `adapter write it.`,\n )\n this.name = 'NetlifyFunctionsConflictError'\n }\n}\n\nexport interface NetlifyBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeFile?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n readTomlIfExists?: () => string | null\n /**\n * Seam for the bundling step, alongside `runNodeBuild` above.\n *\n * The entry cannot be written as source: it imports `theokit/server/scan` and five sibling\n * sub-paths by bare specifier, and Netlify's own bundler breaks on the result (measured on the\n * emulator — see `the-netlify-function-ships-pre-bundled.test.ts`). Bundling here rather than\n * through `writeFile` is what lets the toml then say `node_bundler = \"none\"`.\n */\n bundleFunction?: (options: BundleDeployedFunctionOptions) => Promise<void>\n}\n\nexport function renderNetlifyFunction(\n opts: { securityHeaders?: SecurityHeadersConfig } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions &\n DeployedServerDirOptions & {\n routes?: readonly BakedRoute[]\n /**\n * The agents, baked at build time — for the same reason the routes are (B-339).\n *\n * Netlify uploads a BUNDLE now, so the runtime scan cannot work here at any value: there is no\n * source tree to read, and `createProductionLoader()` would `import()` a path that was never\n * shipped. Vercel's own comment on this says it best — a fallback \"would preserve a behaviour\n * that is broken by construction: an entry that scans, finds nothing, and answers 404 while\n * looking like it tried.\"\n */\n agents?: readonly { filePath: string; agentPath: string; name: string }[]\n contextModule?: string\n } = {},\n): string {\n // B-338 — the routes are baked, not scanned. The scan was a `readdirSync` over the server directory,\n // and on the Netlify emulator it FOUND `src/server/routes/health.ts` and answered 500\n // `SyntaxError: Unexpected token ')'` — a TypeScript source a plain JS runtime cannot compile. On a real\n // deploy it finds nothing at all, because Netlify uploads the bundled function. The fix B-319 made for\n // Vercel and #369 for Cloudflare, on the fourth target; the emitter is shared and its own docblock says\n // \"the target only supplies what its own error message says\".\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n // B-235. Netlify's handler is `(request, context)` and already RECEIVES a Web `Request`, which\n // is the shape this branch needs — the item filed against it counted `new Request` occurrences\n // and concluded the opposite, measuring how the entry OBTAINS a request rather than whether it\n // has one. It used to take `scannedFromLoaderCache` with Deno as the model — same `loaderCache`,\n // same filesystem `serverDir`. That stopped being right when this target began bundling: the\n // emitted `if (!loaderCache) loaderCache = createProductionLoader()` referenced two names the\n // host no longer declared, which is a ReferenceError on the first /api/agents/<name> request and\n // is what `a-generated-entry-declares-every-identifier.test.ts` was written to catch.\n const agentsFragment = deployedAgentsFragment(\n { kind: 'baked', agents: opts.agents ?? [], contextModule: opts.contextModule },\n {\n // Netlify answers its own 404 inline rather than through a helper, so the fragment is given\n // the expression instead of a call it would have to declare.\n notFound: `new Response('Not Found', { status: 404 })`,\n },\n )\n return [\n `// Generated by Theo — Netlify Functions adapter`,\n `import { resolve } from 'node:path'`,\n `import { matchRoute, compilePattern } from 'theokit/server/scan'\\nimport { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'`,\n ...routeImports,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `const cwd = process.cwd()`,\n // B-338 — was `resolve(cwd, 'server')`, a literal. A project declaring `src/server` got a function\n // scanning a directory that does not exist, and every `/api/*` answered 404 — measured on the Netlify\n // emulator. The FOURTH target with this shape: B-185 (bun, deno), B-235 (agentsDir here), B-315\n // (vercel, aws-lambda, cloudflare), and this file's own call site already names two of them.\n `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries, 'netlify'),\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed function has no`,\n `// theo.config.ts to read. The netlify.toml redirect routes only /api/* here,`,\n `// so this covers the API and not the document Netlify's static host serves`,\n `// (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, 'netlify'),\n ``,\n // B-027 — emitted only when a limit is declared.\n ...(opts.rateLimit === undefined\n ? []\n : [\n // B-338 — the sub-path, not the umbrella. The umbrella re-exports the whole server half and\n // @swc/core's native .node addon is down that graph; the guard against it could not see this\n // adapter, because the shared comment stripper read this file's \"/*\" redirect glob as a\n // comment opener and deleted 36% of it before the sweep looked.\n `import { createRateLimiterWeb } from 'theokit/server/rate-limit'`,\n `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,\n ``,\n ]),\n ...deployedRateLimitFragment(\n opts.rateLimit,\n 'netlify',\n // `context.ip` is the platform's own answer, read from the handler context Netlify passes.\n // The forwarded fallback covers a function shape that carries no context, and returns\n // `undefined` unless a `trustProxy` was declared — which is the named 503, not a shared key.\n `context?.ip ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n // Both names are bound in the OUTER handler, which is where the check runs. Threading\n // `context` into `handleRequest` — which the plan called for — buys nothing: the limiter\n // never runs in there.\n 'request, context',\n ),\n ``,\n `export default async (request, context) => {`,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(opts.rateLimit, ' ', 'request, context'),\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n `}`,\n ``,\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ` if (!url.pathname.startsWith('/api/')${agentsFragment.hostBypass}) {`,\n ` return new Response('Not Found', { status: 404 })`,\n ` }`,\n ``,\n\n ``,\n ...agentsFragment.branch,\n ``,\n ` const match = matchRoute(url.pathname, routes)`,\n ` if (!match) return ${JSON_NOT_FOUND_RESPONSE}`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — the run is not awaited: toResponse() settles at the headers and`,\n ` // carries a live body, so Netlify streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeConfig.executeRouteSpread} }))`,\n `}`,\n ].join('\\n')\n}\n\nconst THEO_REDIRECT_FROM = '/api/*'\nconst THEO_REDIRECT_TO = '/.netlify/functions/theo'\n\n/**\n * TOML merge (EC-2) — non-destructive.\n *\n * We avoid adding a TOML parser dependency by working at the line level. The\n * supported subset is sufficient for the Netlify use case:\n * - detect existing `[[redirects]]` blocks\n * - find a block whose `from = \"...\"` matches our target\n * - error if such a block points elsewhere\n * - otherwise append our block\n *\n * Unknown sections (e.g. `[build]`, `[[headers]]`, `[context.production.environment]`)\n * are preserved as-is.\n */\ninterface NetlifyRedirectBlock {\n startLine: number\n endLine: number\n from?: string\n to?: string\n}\n\nfunction parseRedirectBlocks(lines: readonly string[]): NetlifyRedirectBlock[] {\n const blocks: NetlifyRedirectBlock[] = []\n let current: NetlifyRedirectBlock | null = null\n\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i].trim()\n if (trimmed === '[[redirects]]') {\n if (current) {\n current.endLine = i - 1\n blocks.push(current)\n }\n current = { startLine: i, endLine: i }\n continue\n }\n if (current && /^\\[(\\[|[^[])/.test(trimmed)) {\n // Entering another section — close current.\n current.endLine = i - 1\n blocks.push(current)\n current = null\n }\n if (current) {\n const fromMatch = /^from\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (fromMatch) current.from = fromMatch[1]\n const toMatch = /^to\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (toMatch) current.to = toMatch[1]\n current.endLine = i\n }\n }\n if (current) blocks.push(current)\n return blocks\n}\n\n/**\n * The `[functions]` keys this adapter requires, and why each one is not optional.\n *\n * `directory` — measured on the Netlify emulator 2026-09-29: without it the CLI scans its default\n * `netlify/functions/`, finds nothing, and `/api/*` answers `Function not found...` with a 404. The\n * adapter writes to `.netlify/functions/` deliberately (generated output belongs in an ignored\n * directory, not in the source tree the project commits), so the location has to be declared.\n *\n * `node_bundler` — the entry is already bundled here. Netlify re-bundling it produced\n * `SyntaxError: Invalid left-hand side in assignment`.\n */\nconst THEO_FUNCTIONS_DIR = '.netlify/functions'\nconst THEO_FUNCTION_NAME = 'theo'\nconst THEO_FUNCTIONS_KEYS: readonly (readonly [string, string])[] = [\n ['directory', THEO_FUNCTIONS_DIR],\n ['node_bundler', 'none'],\n]\nconst THEO_FUNCTIONS_TARGET = [\n '[functions]',\n ...THEO_FUNCTIONS_KEYS.map(([key, value]) => ` ${key} = \"${value}\"`),\n].join('\\n')\n\nconst THEO_REDIRECT_TARGET = [\n '[[redirects]]',\n ' from = \"/api/*\"',\n ' to = \"/.netlify/functions/theo\"',\n ' status = 200',\n ' force = true',\n].join('\\n')\n\n/**\n * The client router's fallback: a path that no file and no earlier rule answers gets the document.\n *\n * #949 — measured 2026-10-03 on Netlify production: `GET /about` answered 404 while the same build\n * answered 200 on Vercel and Cloudflare (whose `wrangler.toml` carries `not_found_handling =\n * \"single-page-application\"` for this). Unforced, so a real file such as `/assets/*.js` still wins,\n * and appended after `/api/*` because Netlify applies the first rule that matches.\n */\nconst THEO_SPA_FALLBACK_FROM = '/*'\nconst THEO_SPA_FALLBACK_TARGET = [\n '[[redirects]]',\n ' from = \"/*\"',\n ' to = \"/index.html\"',\n ' status = 200',\n].join('\\n')\n\n/** Append the fallback unless some `/*` rule exists — the project's own wins. */\nfunction withSpaFallback(source: string): string {\n const declared = parseRedirectBlocks(source.split(/\\r?\\n/)).some(\n (b) => b.from === THEO_SPA_FALLBACK_FROM,\n )\n if (declared) return source\n const sep = source.endsWith('\\n') ? '' : '\\n'\n return `${source}${sep}\\n${THEO_SPA_FALLBACK_TARGET}\\n`\n}\n\n/**\n * Marks the block this build owns, so it can be REGENERATED rather than merely not duplicated.\n *\n * Idempotence alone would be the wrong contract here: the block carries configuration, so a\n * `security.headers` change has to reach the file. Leaving an existing block in place — which is\n * what the redirect above correctly does, because its content is fixed — would silently pin the\n * baseline to whatever the first build emitted.\n */\nconst THEO_HEADERS_MARKER = '# Generated by Theo — security baseline (usetheokit/theokit#412)'\n\n/**\n * The `[[headers]]` block telling Netlify's static host the baseline.\n *\n * The emitted function applies these to every response IT returns, and it never returns the HTML\n * document: the `[[redirects]]` block routes only `/api/*`, so the page comes from Netlify's static\n * host and carried none of them. The values come from `buildSecurityHeaders` — the same function\n * the handler calls — rather than being written out here, because two lists of headers that must\n * agree are two lists that eventually do not.\n */\nfunction renderHeadersBlock(securityHeaders: SecurityHeadersConfig | undefined): string {\n const values = buildSecurityHeaders(securityHeaders ?? {}, { production: true })\n return [\n THEO_HEADERS_MARKER,\n '[[headers]]',\n ' for = \"/*\"',\n ' [headers.values]',\n ...Object.entries(values).map(([k, v]) => ` ${k} = ${JSON.stringify(v)}`),\n ].join('\\n')\n}\n\n/**\n * Drop a previously generated block, so the next one replaces it.\n *\n * Bounded by the marker and the next top-level section at column 0 (or EOF) — the shape TOML gives\n * a block. A user's own `[[headers]]` is untouched because it does not carry the marker: their\n * file, their rules, and Netlify applies both.\n */\nfunction withoutGeneratedHeaders(source: string): string {\n const lines = source.split(/\\r?\\n/)\n const start = lines.indexOf(THEO_HEADERS_MARKER)\n if (start < 0) return source\n\n const opensSection = (line: string | undefined): boolean => (line ?? '').startsWith('[')\n\n let end = start + 1\n while (end < lines.length && !opensSection(lines[end])) end += 1\n // The marker line itself opens the block, so `end` now sits on the NEXT section — but the block's\n // own `[[headers]]` is the first `[` after the marker, so step past it before scanning again.\n end += 1\n while (end < lines.length && !opensSection(lines[end])) end += 1\n\n return [...lines.slice(0, start), ...lines.slice(end)].join('\\n').replace(/\\n{3,}/gu, '\\n\\n')\n}\n\n/**\n * Declare the `[functions]` keys this adapter requires, without emitting a second table.\n *\n * A duplicate table is a TOML parse error, so this is not tidiness: a project that already declares\n * `[functions]` for `directory`, `included_files` or `external_node_modules` must keep it and gain\n * one key. Line-level like the rest of this merge, and for the same reason — no TOML parser\n * dependency. `[functions.\"name\"]` is a DIFFERENT table and is left alone, which is why the match\n * is exact rather than a prefix.\n *\n * An explicit conflicting value is refused rather than overwritten, on the same argument\n * `NetlifyConflictError` makes about a `/api/*` redirect pointing elsewhere: it is a deliberate\n * declaration, and silently replacing it breaks their build for a reason nothing states.\n */\n/**\n * Read a TOML scalar exactly as written, with no parser.\n *\n * Neither \"strip the quotes\" nor \"cut at the first #\" is correct alone: TOML allows an inline\n * comment after a value, and a `#` INSIDE a quoted value is legal. Stripping quotes alone read\n * `node_bundler = \"none\" # keep` as `none\" # keep` and refused a legal file; cutting at `#` alone\n * would mangle `directory = \"a#b\"`. Both cases are asserted, in both directions, in\n * `the-netlify-function-ships-pre-bundled.test.ts`.\n */\nfunction readTomlScalar(raw: string): string {\n for (const quote of ['\"', \"'\"]) {\n if (!raw.startsWith(quote)) continue\n const close = raw.indexOf(quote, 1)\n return close < 0 ? raw.slice(1) : raw.slice(1, close)\n }\n const hash = raw.indexOf('#')\n return (hash < 0 ? raw : raw.slice(0, hash)).trim()\n}\n\n/**\n * The value a key carries inside one table's line range, or `null` when the table does not set it.\n *\n * Split rather than matched: the rest of this merge is line-level by design, and a regex with `\\s*`\n * either side of a lazy group backtracks (sonarjs/slow-regex) for no gain here. A commented-out\n * `# node_bundler = …` reads as the key `# node_bundler`, which matches nothing — correct, and free.\n */\nfunction declaredIn(\n lines: readonly string[],\n from: number,\n to: number,\n key: string,\n): string | null {\n for (let i = from; i < to; i += 1) {\n const line = lines[i] ?? ''\n const eq = line.indexOf('=')\n if (eq < 0 || line.slice(0, eq).trim() !== key) continue\n return readTomlScalar(line.slice(eq + 1).trim())\n }\n return null\n}\n\nfunction withFunctionsDeclared(source: string): string {\n const lines = source.split(/\\r?\\n/)\n const at = lines.findIndex((line) => line.trimEnd() === '[functions]')\n\n if (at < 0) {\n const sep = source.endsWith('\\n') ? '' : '\\n'\n return `${source}${sep}\\n${THEO_FUNCTIONS_TARGET}\\n`\n }\n\n let end = at + 1\n while (end < lines.length && !(lines[end] ?? '').startsWith('[')) end += 1\n\n const missing: string[] = []\n for (const [key, required] of THEO_FUNCTIONS_KEYS) {\n const declared = declaredIn(lines, at + 1, end, key)\n if (declared === null) {\n missing.push(` ${key} = \"${required}\"`)\n continue\n }\n if (declared !== required) throw new NetlifyFunctionsConflictError(key, declared, required)\n }\n\n if (missing.length === 0) return source\n return [...lines.slice(0, at + 1), ...missing, ...lines.slice(at + 1)].join('\\n')\n}\n\nexport function mergeNetlifyToml(\n existing: string | null,\n securityHeaders?: SecurityHeadersConfig,\n): string {\n const headersBlock = renderHeadersBlock(securityHeaders)\n\n if (existing === null || existing.trim().length === 0) {\n return withFunctionsDeclared(withSpaFallback(`${THEO_REDIRECT_TARGET}\\n\\n${headersBlock}\\n`))\n }\n\n existing = withoutGeneratedHeaders(existing)\n\n const blocks = parseRedirectBlocks(existing.split(/\\r?\\n/))\n\n // Detect conflict: every `/api/*` block must point at our function.\n for (const b of blocks) {\n if (b.from !== THEO_REDIRECT_FROM) continue\n if (b.to === THEO_REDIRECT_TO) {\n // The redirect is already there. The headers block is regenerated regardless, because it\n // carries configuration and the redirect does not.\n const sep = existing.endsWith('\\n') ? '' : '\\n'\n return withFunctionsDeclared(withSpaFallback(`${existing}${sep}\\n${headersBlock}\\n`))\n }\n throw new NetlifyConflictError(b.from, b.to ?? '(unknown)')\n }\n\n // No conflict — append target block.\n const sep = existing.endsWith('\\n') ? '' : '\\n'\n return withFunctionsDeclared(\n withSpaFallback(`${existing}${sep}\\n${THEO_REDIRECT_TARGET}\\n\\n${headersBlock}\\n`),\n )\n}\n\n/**\n * Resolve the build's effective dependencies once.\n *\n * Extracted when `buildNetlify` crossed the complexity ceiling after B-339 added a fifth seam. The\n * defaults are a separate concern from the build's sequence (SRP), and the sequence is the part a\n * reader comes here to follow.\n */\nfunction resolveNetlifyDeps(\n cwd: string,\n deps: NetlifyBuildDeps,\n): {\n runNodeBuild: NonNullable<NetlifyBuildDeps['runNodeBuild']>\n writeFile: NonNullable<NetlifyBuildDeps['writeFile']>\n ensureDir: NonNullable<NetlifyBuildDeps['ensureDir']>\n readTomlIfExists: NonNullable<NetlifyBuildDeps['readTomlIfExists']>\n bundleFunction: NonNullable<NetlifyBuildDeps['bundleFunction']>\n} {\n return {\n runNodeBuild: deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter),\n writeFile:\n deps.writeFile ??\n ((path, content) => {\n writeFileSync(path, content)\n }),\n ensureDir: deps.ensureDir ?? ((path: string) => mkdirSync(path, { recursive: true })),\n readTomlIfExists:\n deps.readTomlIfExists ??\n (() => {\n const path = resolve(cwd, 'netlify.toml')\n return existsSync(path) ? readFileSync(path, 'utf-8') : null\n }),\n bundleFunction: deps.bundleFunction ?? bundleDeployedFunction,\n }\n}\n\nexport async function buildNetlify(\n config: TheoConfig,\n cwd: string,\n deps: NetlifyBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('netlify', readManifest(cwd))\n\n const { runNodeBuild, writeFile, ensureDir, readTomlIfExists, bundleFunction } =\n resolveNetlifyDeps(cwd, deps)\n\n const merged = mergeNetlifyToml(readTomlIfExists(), config.security?.headers)\n\n await runNodeBuild(config, cwd, ctx)\n\n const scanned = ctx?.scanRoutes?.(config.serverDir)\n\n const fnDir = resolve(cwd, THEO_FUNCTIONS_DIR)\n ensureDir(fnDir)\n // B-339 — bundled, not written as source. The entry imports `theokit/server/scan` and five\n // sibling sub-paths by bare specifier; Netlify's own bundler produced a `ReferenceError` on\n // an identifier that was base64 of the source, and re-bundled an already-bundled file into a\n // `SyntaxError`. Measured on the emulator: bundled here plus `node_bundler = \"none\"` below,\n // `GET /api/health` answers 200. Cloudflare and Vercel already bundle; this was the target\n // shipping raw source and trusting the platform to resolve it.\n await bundleFunction({\n projectRoot: cwd,\n entrySource: renderNetlifyFunction({\n routes: scanned?.routes,\n // B-339 — from the same scan as the routes, for the same reason: this target bundles, so a\n // runtime agents scan has no source tree to read.\n agents: scanned?.agents,\n contextModule: scanned?.contextModule,\n securityHeaders: config.security?.headers,\n // B-235 wired `agentsDir` through to this renderer, and B-339 made it unreadable here: the\n // agents are baked from the BUILD's scan now, so the entry never resolves a directory. An\n // option a renderer accepts and ignores is the defect `rules/foreign-config-surfaces.md` is\n // about, so it is dropped rather than left looking wired. The scan the build performs still\n // honours `config.agentsDir` — that is where the option belongs.\n // B-338 — the same pillar as the comment above, one option over. The sweep in\n // `every-deployed-entry-is-told-its-server-dir.test.ts` could not see this adapter: its\n // population was the adapters that CALL `serverDirLiteral(opts)`, so the one that never\n // adopted it was outside the population the case iterates.\n serverDir: config.serverDir,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n }),\n stagePath: '.theokit/netlify/entry.mjs',\n // A DIRECTORY, not a bare file. The bundler code-splits: this project emitted `theo.mjs` plus\n // 40 chunks under `assets/`, which `theo.mjs` imports. Netlify zips a directory-shaped function\n // whole, so the chunks travel; a bare `theo.mjs` with a sibling `assets/` loads in `netlify dev`\n // (it reads from disk) and would reach a deploy without them. Vercel already uses a dedicated\n // `functions/api.func` for the same reason.\n outDir: resolve(fnDir, THEO_FUNCTION_NAME),\n entryFileName: `${THEO_FUNCTION_NAME}.mjs`,\n })\n\n writeFile(resolve(cwd, 'netlify.toml'), merged)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(`\\n ✓ Netlify output → ${THEO_FUNCTIONS_DIR}/${THEO_FUNCTION_NAME}/ + netlify.toml`)\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'netlify',\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-configured',\n })}\\n`,\n )\n}\n\nexport const netlifyAdapter: DeployAdapter = {\n // B-339 / B-341 / B-343 — measured on the Netlify emulator. Its own bundler turned the raw\n // source into a `ReferenceError`, and re-bundled an already-bundled file into a `SyntaxError`;\n // the toml declares `node_bundler = \"none\"` so the bundle this adapter produces ships intact.\n readsSourceAtRunTime: false,\n specifiersResolvedBy: 'this-adapter',\n name: 'netlify',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this function returns.\n // The document is served by Netlify's static host and does not pass through\n // it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n build(config, cwd, ctx) {\n return buildNetlify(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AA4BjB,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAAY,MAAc,WAAmB;AAC3C;AAAA,MACE,6CAA6C,IAAI,aAAQ,SAAS;AAAA,IAGpE;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,YAAY,KAAa,UAAkB,UAAkB;AAC3D;AAAA,MACE,uCAAuC,GAAG,OAAO,QAAQ,gCACnD,QAAQ;AAAA,IAKhB;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAkBO,SAAS,sBACd,OAiBM,CAAC,GACC;AAOR,QAAM,EAAE,cAAc,oBAAoB,kBAAkB,IAAI;AAAA,IAC9D,KAAK,UAAU,CAAC;AAAA,EAClB;AACA,QAAM,gBAAgB,8BAA8B,IAAI;AASxD,QAAM,iBAAiB;AAAA,IACrB,EAAE,MAAM,SA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AQ;AAAA,IACN,GAAG,gCAAgC;AAAA,MACjC,QAAQ;AAAA,MACR,iBAAiB,OAAO,UAAU;AAAA,MAClC,YAAY;AAAA,MACZ,iBAAiB;AAAA,IACnB,CAAC,CAAC;AAAA;AAAA,EACJ;AACF;AAEO,IAAM,iBAAgC;AAAA;AAAA;AAAA;AAAA,EAI3C,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,EACtB,MAAM;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,eAAe,CAAC,mBAAmB,QAAQ,cAAc,QAAQ,eAAe;AAAA;AAAA,EAEhF,mBAAmB;AAAA,EACnB,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,aAAa,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EAC1C;AACF;","names":["sep"]}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import "tsx/esm";
|
|
3
|
-
import {
|
|
4
|
-
VALID_TARGETS
|
|
5
|
-
} from "./chunk-TODO6J42.js";
|
|
6
|
-
|
|
7
|
-
// src/adapters/registry.ts
|
|
8
|
-
var adapterRegistry = {
|
|
9
|
-
node: async () => (await import("./node-3EV3CVWB.js")).nodeAdapter,
|
|
10
|
-
vercel: async () => (await import("./vercel-EXKSZ2OQ.js")).vercelAdapter,
|
|
11
|
-
cloudflare: async () => (await import("./cloudflare-F7KLBOU4.js")).cloudflareAdapter,
|
|
12
|
-
static: async () => (await import("./static-VNN4HYRN.js")).staticAdapter,
|
|
13
|
-
bun: async () => (await import("./bun-PJLDELDT.js")).bunAdapter,
|
|
14
|
-
"deno-deploy": async () => (await import("./deno-deploy-LJ5JQQVR.js")).denoDeployAdapter,
|
|
15
|
-
netlify: async () => (await import("./netlify-ZPQNREFH.js")).netlifyAdapter,
|
|
16
|
-
"aws-lambda": async () => (await import("./aws-lambda-XT7ZDJ6B.js")).awsLambdaAdapter,
|
|
17
|
-
"theo-cloud": async () => (await import("./theo-cloud-243SPOIA.js")).theoCloudAdapter
|
|
18
|
-
};
|
|
19
|
-
async function resolveAdapter(target) {
|
|
20
|
-
const factory = adapterRegistry[target];
|
|
21
|
-
return factory();
|
|
22
|
-
}
|
|
23
|
-
async function streamingTargets() {
|
|
24
|
-
const out = [];
|
|
25
|
-
for (const target of VALID_TARGETS) {
|
|
26
|
-
if ((await resolveAdapter(target)).streamsResponses === true) out.push(target);
|
|
27
|
-
}
|
|
28
|
-
return out;
|
|
29
|
-
}
|
|
30
|
-
export {
|
|
31
|
-
resolveAdapter,
|
|
32
|
-
streamingTargets
|
|
33
|
-
};
|
|
34
|
-
//# sourceMappingURL=registry-3D2KR7UE.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/vercel.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Vercel deploy adapter. All paths derived from `cwd` and a fixed\n * `.theokit/vercel/` output layout. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, writeFileSync, cpSync } from 'node:fs'\nimport { basename, resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport {\n bundleDeployedFunction,\n type BundleDeployedFunctionOptions,\n} from './bundle-deployed-function.js'\nimport { deployedAgentsFragment, JSON_NOT_FOUND_RESPONSE } from './deployed-agents.js'\nimport { renderBakedRoutes, routeRuntimeLines, type BakedRoute } from './deployed-baked-routes.js'\nimport { readDocumentShell } from './deployed-document-shell.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport {\n deployedRateLimitFragment,\n rateLimitCheckFragment,\n type DeployedRateLimitOptions,\n} from './deployed-rate-limit.js'\nimport { deployedRuntimeConfigFragment, serverDirLiteral } from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { buildSecurityHeaders, describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter, DeployedEntryOptions } from './types.js'\n\n/**\n * T2.2 — Vercel adapter rewritten to consume `theokit/adapters/web-shim`\n * instead of emitting an inline plain-object Request/Response shim and\n * lazy-importing internal `theo-server/` paths.\n */\n\n// Generated-code fragments — extracted so the parent emitter stays under the\n// max-lines-per-function ceiling.\n/** The exported function Vercel invokes: one security-header call, then the drain. */\nfunction vercelHandlerFragment(\n /** B-027 — passed, not read: this is a separate function from the parent emitter. */\n rateLimit: DeployedRateLimitOptions['rateLimit'],\n): string[] {\n return [\n // B-027 — only when a limit is declared. `createRateLimiterWeb` is used at module scope by\n // the fragment; `resolveClientIpFromRequest` reads the forwarded headers behind `trustProxy`.\n ...(rateLimit === undefined\n ? []\n : [\n `import { createRateLimiterWeb } from 'theokit/server/rate-limit'`,\n `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,\n ]),\n ...deployedRateLimitFragment(\n rateLimit,\n 'vercel',\n // The handler builds a real Web `Request` at the top — `corsRequest` — so the exported Web\n // resolver applies directly and nothing new has to parse a header. The plan expected a Node\n // sibling here on the ground that this handler \"has no Web Request\"; reading the emitted code\n // refuted that. With no `trustProxy` declared the resolver returns `undefined`, which is the\n // named 503: on this platform the socket address is always the platform's proxy, so a\n // fallback to it would be one shared bucket wearing a client's clothes.\n `resolveClientIpFromRequest(corsRequest, TRUST_PROXY)`,\n 'corsRequest',\n ),\n ...(rateLimit === undefined\n ? []\n : [\n ``,\n `/**`,\n ` * Write a small, known response and finish.`,\n ` *`,\n ` * Not the drain below: that one exists to stream an arbitrary route response chunk by`,\n ` * chunk, honouring backpressure. A 429 or a 503 is a short JSON literal, so reusing the`,\n ` * streaming path would buy nothing and duplicating it would be worse.`,\n ` */`,\n `async function sendSmall(res, response) {`,\n ` const h = {}`,\n ` response.headers.forEach((v, k) => { h[k] = v })`,\n ` res.writeHead(response.status, h)`,\n ` res.end(await response.text())`,\n `}`,\n ]),\n ``,\n `export default async function handler(nodeReq, nodeRes) {`,\n ` // #409 — CORS reads only the method and the \\`origin\\` / \\`access-control-request-method\\``,\n ` // headers, so this carries exactly those and no body. It is deliberately NOT the routing`,\n ` // Request: that one drains the request stream, and only after a route matched — building it`,\n ` // here would drain the body of every static path too.`,\n ` const corsHeaders = new Headers()`,\n ` for (const [k, v] of Object.entries(nodeReq.headers ?? {})) {`,\n ` if (typeof v === 'string') corsHeaders.set(k, v)`,\n ` }`,\n ` const corsRequest = new Request(`,\n ` new URL(nodeReq.url ?? '/', 'http://' + (nodeReq.headers?.host ?? 'localhost')),`,\n ` { method: (nodeReq.method ?? 'GET').toUpperCase(), headers: corsHeaders },`,\n ` )`,\n ``,\n ` // The preflight is answered BEFORE anything routes: an OPTIONS the router handles is an`,\n ` // OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(corsRequest)`,\n ...rateLimitCheckFragment(\n rateLimit,\n ' ',\n 'corsRequest',\n // This handler returns NOTHING — it drains into `nodeRes`. A bare `return <Response>` would\n // answer the caller with nothing at all.\n 'return sendSmall(nodeRes, withCors(corsRequest, withSecurityHeaders(rateLimited(limit), SECURITY_HEADERS)))',\n 'return sendSmall(nodeRes, withCors(corsRequest, withSecurityHeaders(unnamedCaller(), SECURITY_HEADERS)))',\n ),\n ` const webResponse = preflight !== null`,\n ` ? withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ` : withCors(corsRequest, withSecurityHeaders(await routeRequest(nodeReq), SECURITY_HEADERS))`,\n ``,\n ` // \\`outHeaders\\`, not \\`headers\\`: this used to live in the same scope as the`,\n ` // request-side \\`const headers\\` below, which made the whole module a`,\n ` // SyntaxError — every Vercel build between #382 and #411 emitted a function`,\n ` // that could not be loaded.`,\n ` const outHeaders = {}`,\n ` webResponse.headers.forEach((v, k) => { outHeaders[k] = v })`,\n ` nodeRes.writeHead(webResponse.status, outHeaders)`,\n ` if (typeof nodeRes.flushHeaders === 'function') nodeRes.flushHeaders()`,\n ``,\n ` // #382 — this used to materialize the entire body as a string and hand`,\n ` // it to a single end(), which re-buffered the whole response inside the`,\n ` // function even after the shim was fixed. Drain chunk by chunk instead,`,\n ` // honouring Node backpressure so a slow client cannot grow the queue.`,\n ` if (webResponse.body === null) {`,\n ` nodeRes.end()`,\n ` return`,\n ` }`,\n ` const reader = webResponse.body.getReader()`,\n ` try {`,\n ` for (;;) {`,\n ` const { done, value } = await reader.read()`,\n ` if (done) break`,\n ` if (nodeRes.write(value) === false) {`,\n ` await new Promise((resolveDrain) => {`,\n ` const finish = () => {`,\n ` nodeRes.off('drain', finish)`,\n ` nodeRes.off('close', finish)`,\n ` nodeRes.off('error', finish)`,\n ` resolveDrain()`,\n ` }`,\n ` nodeRes.once('drain', finish)`,\n ` nodeRes.once('close', finish)`,\n ` nodeRes.once('error', finish)`,\n ` })`,\n ` }`,\n ` }`,\n ` nodeRes.end()`,\n ` } catch (streamErr) {`,\n ` // The handler failed after the head went out. Destroying the socket is`,\n ` // the only signal left that the body is incomplete — ending normally`,\n ` // would report a truncated response as a complete one (ADR-0002).`,\n ` nodeRes.destroy(streamErr)`,\n ` } finally {`,\n ` reader.releaseLock()`,\n ` }`,\n `}`,\n ``,\n ]\n}\n\n// Generated-code fragments — extracted so the parent emitter stays under the\n// max-lines-per-function ceiling.\n/** Everything that decides WHAT the response is, as a Web Response for every outcome. */\nfunction vercelRouteRequestFragment(\n runtimeSpread: string,\n agentsBranch: readonly string[],\n agentsHostBypass: string,\n /**\n * The document shell, when this function renders one (B-317).\n *\n * Its PRESENCE is the signal rather than a separate boolean: a shell with no renderer and a\n * renderer with no shell are both states this cannot be in, and a flag beside the data would\n * allow them.\n */\n document?: { htmlHead?: string; htmlTail?: string },\n): string[] {\n return [\n `async function routeRequest(nodeReq) {`,\n ` const url = new URL(nodeReq.url ?? '/', 'http://' + (nodeReq.headers?.host ?? 'localhost'))`,\n ``,\n // B-317 — emitted only when this function does NOT render the document. With a document branch\n // every path is legitimate: `/api/*` is a route and everything else is a page, so refusing\n // non-`/api` paths here would make that branch unreachable — which is exactly what it did, and\n // the first version of the fix shipped it: the branch was present, asserted present, and never\n // entered. `/` answered this 9-byte `Not Found` instead of a document.\n ...(document === undefined\n ? [\n ` if (!url.pathname.startsWith('/api/')${agentsHostBypass}) {`,\n ` return new Response('Not Found', {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'text/plain; charset=utf-8' },`,\n ` })`,\n ` }`,\n ]\n : []),\n ``,\n ``,\n // B-235 — the Node-to-Web conversion is hoisted ABOVE the agents branch, which names\n // `request` like every other host's, and an agent path never reaches a route match. The\n // rename from `webRequest` is what lets this target share the one fragment instead of a\n // fourth near-copy of it.\n //\n // The body is therefore drained before `matchRoute` rather than after, so an unmatched POST\n // now has its body read. That is a real change and the safer direction: an unconsumed Node\n // request socket is what keeps a connection open, and the drain already happened for every\n // request that matched.\n ` // Convert Node-style req to a Web Request — for the agents branch and for the shim`,\n ` const headers = new Headers()`,\n ` for (const [k, v] of Object.entries(nodeReq.headers ?? {})) {`,\n ` if (typeof v === 'string') headers.set(k, v)`,\n ` }`,\n ` let body`,\n ` const method = (nodeReq.method ?? 'GET').toUpperCase()`,\n ` if (method !== 'GET' && method !== 'HEAD') {`,\n ` const chunks = []`,\n ` await new Promise((resolveProm, rejectProm) => {`,\n ` nodeReq.on('data', (c) => chunks.push(c))`,\n ` nodeReq.on('end', () => resolveProm())`,\n ` nodeReq.on('error', rejectProm)`,\n ` })`,\n ` body = Buffer.concat(chunks)`,\n ` }`,\n ` const request = new Request(url.toString(), { method, headers, body })`,\n ``,\n ...agentsBranch,\n ``,\n ` const match = matchRoute(url.pathname, routes)`,\n ...(document !== undefined\n ? [\n ` if (!match) {`,\n ` // B-317 — a path with no matching file arrives here because config.json routes it to this`,\n ` // function. Before this branch it answered a JSON 404, so the config sent every page to the`,\n ` // static shell instead and an SSR project was served an empty \\`<div id=\"root\">\\` while the`,\n ` // build announced SSR.`,\n ` //`,\n ` // Only OUTSIDE \\`/api/\\`: a path under it that matches no route is a routing miss and owes a`,\n ` // JSON 404, not a document. Rendering one there would answer a fetch with HTML.`,\n ` if (!url.pathname.startsWith('/api/')) {`,\n ` const nonce = generateNonce()`,\n ` return withSecurityHeaders(`,\n ` await renderStreamingWeb(request, {`,\n ` htmlHead: ${JSON.stringify(document.htmlHead ?? '')},`,\n ` htmlTail: ${JSON.stringify(document.htmlTail ?? '')},`,\n ` nonce,`,\n ` }),`,\n ` buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true }, { nonce }),`,\n ` )`,\n ` }`,\n ` return ${JSON_NOT_FOUND_RESPONSE}`,\n ` }`,\n ]\n : [` if (!match) return ${JSON_NOT_FOUND_RESPONSE}`]),\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` // #382 — executeRoute() is NOT awaited before the Response is taken:`,\n ` // toResponse() settles at the headers and carries a live body.`,\n ` return toResponse(executeRoute({`,\n ` route: match.route, method, params: match.params,`,\n ` req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread}`,\n ` }))`,\n `}`,\n ]\n}\n\nexport function renderVercelFunctionEntry(\n opts: DeployedEntryOptions & {\n /**\n * The routes, scanned on the BUILD machine (B-319).\n *\n * Build Output API v3 uploads a `.func` directory as it is, so the emitted entry's runtime\n * `scanServerRoutes` was a `readdirSync` against a directory that is not there — measured on a\n * deployed function: every `/api/*` answered its own JSON 404. Baked here for the reason\n * Cloudflare bakes (#369), through the same emitter, so the two cannot drift.\n */\n routes?: readonly BakedRoute[]\n /** The agents, for the same reason and from the same scan. */\n agents?: readonly { filePath: string; agentPath: string; name: string }[]\n /**\n * Whether this function renders the DOCUMENT as well as the routes (B-317).\n *\n * `renderVercelConfigJson` sends a path with no matching file here when it is on, and Vercel's\n * `{ handle: 'filesystem' }` has already served every real file — so the branch below needs no\n * asset fallthrough, unlike the Cloudflare worker's, which owns `/` and therefore also receives\n * `/robots.txt`.\n */\n ssr?: boolean\n /** The document up to `<div id=\"root\">`, read from the built client shell. */\n htmlHead?: string\n /** The document from `<div id=\"root\">` on. */\n htmlTail?: string\n /** The app's identity module, when it has one. */\n contextModule?: string\n } = {},\n): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n // B-235. This is the target the item's evidence was right about in form and wrong about in\n // consequence: the handler IS Node-shaped, and it already converts to a Web `Request` before\n // handing anything to the shim. Threading `nodeReq` through twelve sites says how the entry\n // RECEIVES a request, not whether it can produce the one this branch needs.\n // B-319 — ALWAYS baked, with no scan fallback. This platform uploads only what the build\n // bundled, so `scanAgents` cannot work here at any value: there is no source tree to read. A\n // fallback would preserve a behaviour that is broken by construction — an entry that scans, finds\n // nothing, and answers 404 while looking like it tried. With nothing baked the agents fragment is\n // empty, `/api/agents/<name>` falls through to the route matcher, and the 404 is honest.\n const agentsFragment = deployedAgentsFragment(\n { kind: 'baked', agents: opts.agents ?? [], contextModule: opts.contextModule },\n { notFound: JSON_NOT_FOUND_RESPONSE },\n )\n return [\n `// Generated by Theo — Vercel Functions adapter`,\n `// Environment variables are resolved at RUNTIME, not build time.`,\n ``,\n `import { resolve } from 'node:path'`,\n `import { matchRoute, compilePattern } from 'theokit/server/scan'\\nimport { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'`,\n ...routeImports,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n opts.ssr === true\n ? `import { buildSecurityHeaders, generateNonce, withSecurityHeaders } from 'theokit/adapters/security-headers'`\n : `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ...(opts.ssr === true\n ? [`import { renderStreamingWeb } from '../server/entry-server.js'`]\n : []),\n ``,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries, 'vercel'),\n // B-318 / B-319 — `const cwd` used to be declared here, because the agents fragment emitted\n // `scanAgents(cwd, …)` and this was the one of its four callers that never declared the name.\n // B-319 then removed the scan entirely from this target — there is no source tree to read on a\n // platform that uploads only its bundle — so the declaration became dead code. The pairing is\n // still enforced for the three adapters that DO scan, by\n // `tests/unit/a-generated-entry-declares-every-name-it-uses.test.ts`.\n `const serverDir = resolve(process.cwd(), ${serverDirLiteral(opts)})`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed function has no`,\n `// theo.config.ts to read. config.json routes only /api/* here, so this`,\n `// covers the API and not the document Vercel's static host serves`,\n `// (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, 'vercel'),\n ``,\n `// Vercel Functions invoke this default export with a (req, res) pair`,\n `// (Node IncomingMessage-style). \\`routeRequest\\` produces a Web Response for`,\n `// every outcome — including the two 404s — so the security baseline is`,\n `// applied at ONE place and no branch can be added that skips it.`,\n ...vercelHandlerFragment(opts.rateLimit),\n ``,\n ...vercelRouteRequestFragment(\n runtimeConfig.executeRouteSpread,\n agentsFragment.branch,\n agentsFragment.hostBypass,\n opts.ssr === true ? { htmlHead: opts.htmlHead, htmlTail: opts.htmlTail } : undefined,\n ),\n ].join('\\n')\n}\n\nexport interface VercelRoutingRule {\n src?: string\n dest?: string\n handle?: string\n /** Build Output API v3 — response headers this rule adds. */\n headers?: Record<string, string>\n /**\n * Keep routing after this rule matches.\n *\n * Load-bearing for the header rule: without it a matching rule TERMINATES routing in Build\n * Output v3, so every request would receive the headers and no content.\n */\n continue?: boolean\n}\n\n/**\n * The routing table, plus the security baseline for the responses this build does NOT serve.\n *\n * The emitted function applies the baseline to every response IT returns — and it never returns the\n * HTML document: `{ handle: 'filesystem' }` hands the page to Vercel's static host, so the JSON was\n * protected and the page it renders in was not (usetheokit/theokit#412).\n *\n * The values come from `buildSecurityHeaders`, the same function the handler calls, rather than\n * being written out here. Two lists of headers that must agree are two lists that eventually do\n * not.\n *\n * Order matters twice: the header rule sits FIRST, because a rule after `handle: 'filesystem'`\n * never runs for a static file, and it carries `continue: true`, because a matching rule otherwise\n * ends routing and the request would get headers with no body.\n *\n * What this does NOT prove: that a deployed page carries them. That needs a deployment, and this\n * repository deploys to no Vercel project from CI. The emitted configuration is verifiable; the\n * platform honouring it is not, and the difference is stated rather than glossed.\n */\nexport function renderVercelConfigJson(\n securityHeaders?: SecurityHeadersConfig,\n opts: {\n /**\n * Whether a path with no matching file reaches the function instead of the static shell.\n *\n * A SECOND parameter rather than a field on the first, and the reason is a trap: the first is\n * `SecurityHeadersConfig`, which is all-optional, so `renderVercelConfigJson({ ssr: true })`\n * compiles, passes the flag as a headers object and does nothing. A bag in the position of another\n * all-optional bag is accepted by the type system and ignored by the code (B-317).\n */\n ssr?: boolean\n } = {},\n): {\n version: number\n routes: VercelRoutingRule[]\n} {\n return {\n version: 3,\n routes: [\n {\n src: '/(.*)',\n headers: buildSecurityHeaders(securityHeaders ?? {}, { production: true }),\n continue: true,\n },\n { src: '/api/(.*)', dest: '/api' },\n { handle: 'filesystem' },\n // B-317 — where a path with no matching file goes. `{ handle: 'filesystem' }` above still\n // serves every real file, so this is reached only by a page request: to the function when the\n // project renders one, and to the static shell when it does not. It sent every page to the shell\n // regardless, so an SSR project was served an empty `<div id=\"root\">` while the build announced\n // SSR.\n { src: '/(.*)', dest: opts.ssr === true ? '/api' : '/index.html' },\n ],\n }\n}\n\nexport function renderVercelVcConfigJson(): {\n runtime: string\n handler: string\n launcherType: string\n shouldAddHelpers: boolean\n supportsResponseStreaming: boolean\n} {\n return {\n runtime: 'nodejs22.x',\n handler: 'index.mjs',\n launcherType: 'Nodejs',\n shouldAddHelpers: true,\n // #382 — Build Output API v3 opt-in. Without it the platform buffers the\n // function's response no matter how the handler writes it, so the emitted\n // chunk-by-chunk drain above would never reach the client. We cannot\n // verify the platform side from here; see the streaming note in\n // `adapters/web-shim.ts` and the adapter's `streamsResponses` flag.\n supportsResponseStreaming: true,\n }\n}\n\n/**\n * Whether a file from the client build belongs in `.vercel/output/static`.\n *\n * With `ssr: true` the shell does NOT, and the reason is the routing layer rather than the file:\n * Vercel's `{ handle: 'filesystem' }` satisfies a directory path with the `index.html` inside it, so\n * `/` is a REAL FILE whenever the build copied one — and the SSR route below the handler is never\n * reached. Measured on the first real deploy of this adapter, 2026-09-29: `GET /` answered 200 with\n * 694 bytes and `<div id=\"root\">` carrying zero, while the build announced `(SSR)`.\n *\n * B-317 already made the last route point at the function when `ssr` is on, and its comment states\n * the premise that made that sufficient — *\"`{ handle: 'filesystem' }` above still serves every real\n * file, so this is reached only by a page request\"*. That premise is false for a path the platform\n * resolves to an `index.html`. This closes the half B-317 could not see without a deployment.\n *\n * **The basename is the mechanism, not a heuristic.** It is what the platform uses to satisfy a\n * directory path, so it is what shadows a page route, at any depth. `foo.html` is served at the\n * explicit `/foo.html`, which no page route claims, and dropping it would take a document the\n * project meant to publish.\n *\n * Directories always pass: `cpSync`'s filter is asked about them too, and refusing one prunes the\n * whole subtree — refusing `assets/` would turn one empty page into a site with no stylesheet.\n */\nexport function shouldCopyIntoStatic(source: string, ssr: boolean): boolean {\n if (!ssr) return true\n return basename(source) !== 'index.html'\n}\n\nexport interface VercelBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n bundleFunction?: (options: BundleDeployedFunctionOptions) => Promise<void>\n}\n\n/**\n * The Vercel build, as a function with a dependency seam — the shape `buildNetlify` and\n * `buildAwsLambda` already have.\n *\n * It was inline on the adapter object until B-346, and nothing could drive it: measured, NO test\n * ran it to completion, so `buildVercel` carried zero coverage while a defect shipped inside it and\n * reached a live deployment. The seam is what lets a test assert the wiring — that the copy is\n * handed the filter that withholds the shell — without a client bundle.\n */\n/**\n * The injectable seam's defaults, in one place.\n *\n * The same shape `resolveNetlifyDeps` and `resolveAwsLambdaDeps` already have, and here for the same\n * reason plus one measured one: the two `??` defaults lived inside `buildVercel`, which put it at a\n * complexity of 16 against a maximum of 15. The body was unchanged from the method it was extracted\n * from — 14 — so the seam that made the copy testable is what crossed the line. Moving the defaults\n * out is the convention this file was not following, not a contortion to satisfy the counter.\n */\nfunction resolveVercelDeps(deps: VercelBuildDeps): {\n runNodeBuild: NonNullable<VercelBuildDeps['runNodeBuild']>\n bundleFunction: NonNullable<VercelBuildDeps['bundleFunction']>\n} {\n return {\n runNodeBuild: deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter),\n bundleFunction: deps.bundleFunction ?? bundleDeployedFunction,\n }\n}\n\nexport async function buildVercel(\n config: TheoConfig,\n cwd: string,\n deps: VercelBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n const { runNodeBuild, bundleFunction } = resolveVercelDeps(deps)\n\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n // Per 2026-05-27 owner decision, polyglot is wired via `node` (local\n // docker-compose harness) + `theo-cloud` (Wave 3). Vercel adapter\n // wire-up is deferred to a fresh ADR with demand evidence.\n assertServicesUnsupported('vercel', readManifest(cwd))\n\n // 1. Run the standard Node build first (ctx forwarded so nodeAdapter has makeVitePlugins)\n await runNodeBuild(config, cwd, ctx)\n\n const clientDir = resolve(cwd, '.theokit/client')\n const outputDir = resolve(cwd, '.vercel/output')\n\n // 2. Create .vercel/output structure\n mkdirSync(resolve(outputDir, 'static'), { recursive: true })\n mkdirSync(resolve(outputDir, 'functions/api.func'), { recursive: true })\n\n // 3. Copy static assets\n if (existsSync(clientDir)) {\n // B-346 — the shell is withheld when this project renders its own document. See\n // `shouldCopyIntoStatic`: shipping it makes `/` a real file, and the SSR route never runs.\n cpSync(clientDir, resolve(outputDir, 'static'), {\n recursive: true,\n filter: (source) => shouldCopyIntoStatic(source, config.ssr),\n })\n }\n\n // B-319 — the routes, agents and identity module are resolved HERE, on the build machine, for\n // the reason #369 gives for Cloudflare: Build Output API v3 uploads the `.func` directory as it\n // is, so a runtime `scanServerRoutes` reads a directory that is not there. Measured on a\n // deployed function — every `/api/*` answered its own JSON 404 with the route files present in\n // the project. An absent provider bakes nothing and the entry falls back to the scan, which is\n // what it did before.\n const scanned = ctx?.scanRoutes?.(config.serverDir)\n\n // 4. Emit the serverless function, BUNDLED.\n //\n // B-316 / ADR 0020 — Build Output API v3 uploads a `.func` directory as it is: nothing installs\n // dependencies for it and nothing bundles it. Writing the rendered entry straight out produced a\n // function that could not start, measured on this repository's own scaffold:\n //\n // cp -a .vercel/output/functions/api.func/. /tmp/fn/ && cd /tmp/fn\n // node -e \"import('./index.mjs')\"\n // -> ERR_MODULE_NOT_FOUND: Cannot find package 'theokit'\n //\n // The staged entry goes inside the project root because a specifier resolves relative to the\n // importing file — an entry in `/tmp` makes rollup resolve `theokit/server/scan` from `/tmp`.\n await bundleFunction({\n projectRoot: cwd,\n entrySource: renderVercelFunctionEntry({\n // B-317 — the three options the renderer honoured and no build passed, which is the shape\n // B-185, B-235, B-312 and B-315 each fixed one target at a time. The shell is read here\n // rather than in the renderer because reading a file is the build's job, not a string\n // emitter's.\n ssr: config.ssr,\n ...readDocumentShell(cwd, config.ssr),\n routes: scanned?.routes,\n agents: scanned?.agents,\n contextModule: scanned?.contextModule,\n securityHeaders: config.security?.headers,\n // B-315 — the option existed, the renderer honoured it, and this build never passed\n // it, so a project declaring `src/server` got a deployed entry resolving `server`.\n // The fourth occurrence of that exact shape: B-185 (bun, deno), B-235 (`agentsDir`\n // here), B-312 (the build's agents scan). Measured on the emitted Vercel function.\n serverDir: config.serverDir,\n // B-235 — pillar (a): the option existed and no build passed it, so a project with a\n // configured agents directory got the default `agents` on this target. Same defect\n // B-185 fixed for bun and deno, one target over.\n agentsDir: config.agentsDir,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n }),\n stagePath: '.theokit/vercel/entry.mjs',\n outDir: resolve(outputDir, 'functions/api.func'),\n entryFileName: 'index.mjs',\n })\n\n // 5. Emit .vc-config.json\n writeFileSync(\n resolve(outputDir, 'functions/api.func/.vc-config.json'),\n JSON.stringify(renderVercelVcConfigJson(), null, 2),\n )\n\n // 6. Emit config.json (routing)\n writeFileSync(\n resolve(outputDir, 'config.json'),\n JSON.stringify(renderVercelConfigJson(config.security?.headers, { ssr: config.ssr }), null, 2),\n )\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Vercel output → .vercel/output/')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'vercel',\n securityHeaders: config.security?.headers,\n // Derived, and it was a literal `false` for the hours between B-317 shipping and B-334. The\n // function B-317 emits calls `generateNonce()` and feeds the value to both `renderStreamingWeb`\n // and `buildSecurityHeaders`, so the deployment DID mint one while the build told the operator\n // it did not — and the printed advice was to move inline scripts out to work around a\n // restriction that was no longer there.\n mintsNonce: config.ssr,\n documentHeaders: 'platform-configured',\n })}\\n`,\n )\n}\n\nexport const vercelAdapter: DeployAdapter = {\n // B-316 / B-319 — Build Output API v3 uploads the `.func` directory as it is: nothing\n // installs and nothing bundles. Driven 2026-09-29 from a directory with no `node_modules`:\n // 200 with the trace header and the CSP (`records/acceptance/evidence/b263-vercel-function-driven-locally.txt`).\n readsSourceAtRunTime: false,\n specifiersResolvedBy: 'this-adapter',\n name: 'vercel',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this function returns.\n // The document is served from `.vercel/output/static` and does not pass\n // through it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\n return buildVercel(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,eAAe,cAAc;AAC7D,SAAS,UAAU,eAAe;AAkClC,SAAS,sBAEP,WACU;AACV,SAAO;AAAA;AAAA;AAAA,IAGL,GAAI,cAAc,SACd,CAAC,IACD;AAAA,MACE;AAAA,MACA;AAAA,IACF;AAAA,IACJ,GAAG;AAAA,MACD;AAAA,MACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOA;AAAA,MACA;AAAA,IACF;AAAA,IACA,GAAI,cAAc,SACd,CAAC,IACD;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,MACD;AAAA,MACA;AAAA,MACA;AAAA;AAAA;AAAA,MAGA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA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O,IAAM,gBAA+B;AAAA;AAAA;AAAA;AAAA,EAI1C,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,EACtB,MAAM;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,eAAe,CAAC,mBAAmB,QAAQ,cAAc,QAAQ,eAAe;AAAA;AAAA,EAEhF,mBAAmB;AAAA,EAEnB,MAAM,MAAM,QAAoB,KAAa,KAA0C;AACrF,WAAO,YAAY,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EACzC;AACF;","names":[]}
|
/package/dist/{actions-virtual-module-UIX5YWZR.js.map → actions-virtual-module-CA4YEAL3.js.map}
RENAMED
|
File without changes
|
/package/dist/{actions-virtual-module-V5Q4XVL5.js.map → actions-virtual-module-QRTV4NHS.js.map}
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|