theokit 0.63.0 → 0.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/{aws-lambda-2R77AV5F.js → aws-lambda-AN6CEBXO.js} +5 -4
  2. package/dist/aws-lambda-AN6CEBXO.js.map +1 -0
  3. package/dist/{build-CZAM7K6J.js → build-RF2NLRHS.js} +2 -2
  4. package/dist/{bun-DJ6QEFIP.js → bun-3FFL7CS4.js} +5 -4
  5. package/dist/bun-3FFL7CS4.js.map +1 -0
  6. package/dist/{chunk-HIYBU6NH.js → chunk-EW5IG7GA.js} +49 -15
  7. package/dist/chunk-EW5IG7GA.js.map +1 -0
  8. package/dist/{chunk-VPX3MS5D.js → chunk-PALZUV6E.js} +5 -1
  9. package/dist/chunk-PALZUV6E.js.map +1 -0
  10. package/dist/cli/index.js +2 -2
  11. package/dist/{cloudflare-UYKOO6EP.js → cloudflare-VIQX4FVC.js} +5 -4
  12. package/dist/cloudflare-VIQX4FVC.js.map +1 -0
  13. package/dist/{deno-deploy-W2JWCYPT.js → deno-deploy-PTO7IE4G.js} +2 -2
  14. package/dist/{netlify-BJQGPMGY.js → netlify-3VSNVURQ.js} +2 -2
  15. package/dist/{preview-3TLURUAL.js → preview-F6SR2JAQ.js} +2 -2
  16. package/dist/{registry-PAJOMMVV.js → registry-RZHBBLIF.js} +7 -7
  17. package/dist/server/index.js +1 -1
  18. package/dist/server/webhook/index.js +1 -1
  19. package/dist/{vercel-BEDGUVXX.js → vercel-BZ35DF3B.js} +5 -4
  20. package/dist/vercel-BZ35DF3B.js.map +1 -0
  21. package/package.json +1 -1
  22. package/dist/aws-lambda-2R77AV5F.js.map +0 -1
  23. package/dist/bun-DJ6QEFIP.js.map +0 -1
  24. package/dist/chunk-HIYBU6NH.js.map +0 -1
  25. package/dist/chunk-VPX3MS5D.js.map +0 -1
  26. package/dist/cloudflare-UYKOO6EP.js.map +0 -1
  27. package/dist/vercel-BEDGUVXX.js.map +0 -1
  28. /package/dist/{build-CZAM7K6J.js.map → build-RF2NLRHS.js.map} +0 -0
  29. /package/dist/{deno-deploy-W2JWCYPT.js.map → deno-deploy-PTO7IE4G.js.map} +0 -0
  30. /package/dist/{netlify-BJQGPMGY.js.map → netlify-3VSNVURQ.js.map} +0 -0
  31. /package/dist/{preview-3TLURUAL.js.map → preview-F6SR2JAQ.js.map} +0 -0
  32. /package/dist/{registry-PAJOMMVV.js.map → registry-RZHBBLIF.js.map} +0 -0
@@ -6,8 +6,9 @@ import {
6
6
  deployedRuntimeConfigFragment,
7
7
  deployedTraceFragment,
8
8
  describeDeployedSecurityHeaders,
9
- renderSecurityHeadersConfigLiteral
10
- } from "./chunk-VPX3MS5D.js";
9
+ renderSecurityHeadersConfigLiteral,
10
+ serverDirLiteral
11
+ } from "./chunk-PALZUV6E.js";
11
12
  import {
12
13
  nodeAdapter
13
14
  } from "./chunk-KI4DOTN4.js";
@@ -156,7 +157,7 @@ function renderAwsLambdaEntry(opts = {}) {
156
157
  `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,
157
158
  ``,
158
159
  `const cwd = process.cwd()`,
159
- `const serverDir = resolve(cwd, 'server')`,
160
+ `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,
160
161
  `let routesCache = null`,
161
162
  `let loaderCache = null`,
162
163
  ``,
@@ -258,4 +259,4 @@ export {
258
259
  renderAwsLambdaEntry,
259
260
  responseToLambdaResultV2
260
261
  };
261
- //# sourceMappingURL=aws-lambda-2R77AV5F.js.map
262
+ //# sourceMappingURL=aws-lambda-AN6CEBXO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/aws-lambda.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * AWS Lambda adapter. Writes to `cwd/.theokit/lambda/`. Build-time tool.\n */\nimport { mkdirSync, 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 { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.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 {\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport interface AwsLambdaBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\nexport interface RequestShape {\n method: string\n path: string\n headers: Record<string, string>\n body?: string\n}\n\nexport interface LambdaResultV2 {\n statusCode: number\n headers: Record<string, string>\n body: string\n isBase64Encoded: boolean\n}\n\nconst BINARY_CONTENT_TYPES = [\n 'application/octet-stream',\n 'application/pdf',\n 'application/zip',\n 'image/',\n 'audio/',\n 'video/',\n]\n\nfunction isBinaryContentType(contentType: string | undefined): boolean {\n if (!contentType) return false\n const ct = contentType.toLowerCase()\n return BINARY_CONTENT_TYPES.some((prefix) => ct.startsWith(prefix))\n}\n\ninterface APIGatewayProxyEventV2 {\n version: string\n requestContext: {\n http: { method: string; path: string }\n }\n headers?: Record<string, string | undefined>\n body?: string\n isBase64Encoded?: boolean\n}\n\nexport function eventV2ToRequestShape(event: APIGatewayProxyEventV2): RequestShape {\n const headers: Record<string, string> = {}\n for (const [k, v] of Object.entries(event.headers ?? {})) {\n if (v !== undefined) headers[k] = v\n }\n let body: string | undefined = event.body\n if (body !== undefined && event.isBase64Encoded) {\n body = Buffer.from(body, 'base64').toString('utf-8')\n }\n return {\n method: event.requestContext.http.method,\n path: event.requestContext.http.path,\n headers,\n body,\n }\n}\n\nexport function responseToLambdaResultV2(\n statusCode: number,\n headers: Record<string, string>,\n body: string,\n): LambdaResultV2 {\n const isBinary = isBinaryContentType(headers['content-type'])\n return {\n statusCode,\n headers,\n body: isBinary ? Buffer.from(body, 'binary').toString('base64') : body,\n isBase64Encoded: isBinary,\n }\n}\n\n// Generated-code fragments — extracted so the parent emitter stays under the\n// max-lines-per-function ceiling.\n/** The v2 result conversion, the handler, and the routing that feeds them. */\nfunction awsLambdaHandlerFragment(runtimeSpread: string): string[] {\n return [\n `// #382 — this target is DELISTED for response streaming, by construction.`,\n `// The Lambda v2 result object below carries \\`body\\` as a string, so the`,\n `// response cannot exist until the run has finished, no matter how the`,\n `// framework's shim writes it. Streaming here would require`,\n `// \\`awslambda.streamifyResponse\\` plus a Function URL in RESPONSE_STREAM`,\n `// invoke mode — neither of which this adapter emits, and which would break`,\n `// every API Gateway deployment of it. Rather than degrade in silence, a`,\n `// response that is unambiguously a stream is named in the logs below.`,\n `async function responseToV2Result(response, routePath) {`,\n ` const headers = {}`,\n ` response.headers.forEach((v, k) => { headers[k] = v })`,\n ` const ct = headers['content-type'] ?? ''`,\n ` if (ct.includes('text/event-stream')) {`,\n ` console.warn(`,\n ` '[theo][aws-lambda] ' + routePath + ' returned a streaming response (' + ct + '), ' +`,\n ` 'but the aws-lambda target buffers it whole and delivers it when the run ends. ' +`,\n ` 'This target is delisted for streaming (theokit#382). Deploy streaming routes to ' +`,\n ` 'cloudflare, vercel, netlify, bun, deno-deploy or node.'`,\n ` )`,\n ` }`,\n ` const isBinary = /^application\\\\/(octet-stream|pdf|zip)|^(image|audio|video)\\\\//.test(ct)`,\n ` if (isBinary) {`,\n ` const buf = Buffer.from(await response.arrayBuffer())`,\n ` return {`,\n ` statusCode: response.status,`,\n ` headers,`,\n ` body: buf.toString('base64'),`,\n ` isBase64Encoded: true,`,\n ` }`,\n ` }`,\n ` return {`,\n ` statusCode: response.status,`,\n ` headers,`,\n ` body: await response.text(),`,\n ` isBase64Encoded: false,`,\n ` }`,\n `}`,\n ``,\n `// Every outcome — including both 404s — is produced as a Web Response by`,\n `// routeRequest, so the security baseline is applied at ONE place and the`,\n `// v2 result object is built from headers that already carry it.`,\n `export const handler = async (event) => {`,\n ` const path = event.requestContext?.http?.path ?? '/'`,\n ` // #409 — the same event, read as a Web Request so the CORS matcher can see the method and`,\n ` // the \\`origin\\` header. \\`eventV2ToRequest\\` reads a body already present in the event, so`,\n ` // unlike the Node targets there is no stream to drain twice.`,\n ` const corsRequest = eventV2ToRequest(event)`,\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 ` const response = preflight !== null`,\n ` ? withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ` : withCors(corsRequest, withSecurityHeaders(await routeRequest(event, path), SECURITY_HEADERS))`,\n ` return responseToV2Result(response, path)`,\n `}`,\n ``,\n `async function routeRequest(event, path) {`,\n ` if (!path.startsWith('/api/')) {`,\n ` return new Response(`,\n ` 'Static assets must be served from CloudFront or a separate static host.',`,\n ` { status: 404, headers: { 'content-type': 'text/plain' } },`,\n ` )`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ` const match = matchRoute(path, routesCache)`,\n ` if (!match) {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'application/json' },`,\n ` })`,\n ` }`,\n ``,\n ` const request = eventV2ToRequest(event)`,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,\n `}`,\n ]\n}\n\nexport function renderAwsLambdaEntry(\n opts: { securityHeaders?: SecurityHeadersConfig } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedServerDirOptions &\n DeployedCorsOptions = {},\n): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n return [\n `// Generated by Theo — AWS Lambda Adapter`,\n `// Use with API Gateway HTTP API v2 (default).`,\n ``,\n `import { resolve } from 'node:path'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `const cwd = process.cwd()`,\n `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,\n `let routesCache = 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 function has no`,\n `// theo.config.ts to read. Non-API paths 404 here and the document is served`,\n `// from CloudFront or another static host, so this covers the API and not the`,\n `// page (usetheokit/theokit#412).`,\n `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ``,\n ...runtimeConfig.imports,\n ...runtimeConfig.declarations,\n ...deployedCsrfFragment(opts),\n ``,\n ...deployedCorsFragment(opts.cors, 'aws-lambda'),\n ``,\n `function eventV2ToRequest(event) {`,\n ` const method = event.requestContext?.http?.method ?? 'GET'`,\n ` const path = event.requestContext?.http?.path ?? '/'`,\n ` const host = event.headers?.host ?? 'lambda'`,\n ` const qs = event.rawQueryString ? '?' + event.rawQueryString : ''`,\n ` const url = 'https://' + host + path + qs`,\n ` const headers = new Headers()`,\n ` for (const [k, v] of Object.entries(event.headers ?? {})) {`,\n ` if (v !== undefined) headers.set(k, String(v))`,\n ` }`,\n ` let body = event.body`,\n ` if (body && event.isBase64Encoded) {`,\n ` body = Buffer.from(body, 'base64')`,\n ` }`,\n ` return new Request(url, {`,\n ` method,`,\n ` headers,`,\n ` body: method === 'GET' || method === 'HEAD' ? undefined : body,`,\n ` })`,\n `}`,\n ``,\n ...awsLambdaHandlerFragment(runtimeConfig.executeRouteSpread),\n ].join('\\n')\n}\n\nexport async function buildAwsLambda(\n config: TheoConfig,\n cwd: string,\n deps: AwsLambdaBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('aws-lambda', readManifest(cwd))\n\n // #382 — refuse by name rather than build something that cannot do what was\n // asked. `ssrStreaming` is the config's declaration that responses stream,\n // and this target is delisted for that (see `awsLambdaAdapter.streamsResponses`).\n if (config.ssrStreaming) {\n throw new Error(\n '[adapter-aws-lambda] ssrStreaming is on, but the aws-lambda target does not stream ' +\n 'responses: the Lambda v2 result object carries the body as a string, so nothing can ' +\n 'leave the function before the run ends. Response streaming would need ' +\n 'awslambda.streamifyResponse plus a Function URL in RESPONSE_STREAM invoke mode, which ' +\n 'this adapter does not emit. Build a streaming target instead (cloudflare, vercel, ' +\n 'netlify, bun, deno-deploy, node), or set ssrStreaming: false in theo.config.ts.',\n )\n }\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/aws')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const entry = renderAwsLambdaEntry({\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 })\n const write =\n deps.writeEntry ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n write(resolve(outputDir, 'handler.mjs'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ AWS Lambda output → .theokit/aws/handler.mjs')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'aws-lambda',\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-unmanaged',\n })}\\n`,\n )\n}\n\nexport const awsLambdaAdapter: DeployAdapter = {\n name: 'aws-lambda',\n // #382 — delisted for streaming, deliberately. See DeployAdapter.\n streamsResponses: false,\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 comes from CloudFront or another static host and does not pass\n // through it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n build(config, cwd, ctx) {\n return buildAwsLambda(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;AA0CxB,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,oBAAoB,aAA0C;AACrE,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,KAAK,YAAY,YAAY;AACnC,SAAO,qBAAqB,KAAK,CAAC,WAAW,GAAG,WAAW,MAAM,CAAC;AACpE;AAYO,SAAS,sBAAsB,OAA6C;AACjF,QAAM,UAAkC,CAAC;AACzC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,MAAM,WAAW,CAAC,CAAC,GAAG;AACxD,QAAI,MAAM,OAAW,SAAQ,CAAC,IAAI;AAAA,EACpC;AACA,MAAI,OAA2B,MAAM;AAC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BAAgB,YAAY,MAAM,KAAK,WAAW;AAC5E,QAAM,aAAa,QAAQ,KAAK,GAAG;AAEnC,QAAM,YAAY,QAAQ,KAAK,cAAc;AAC7C,QAAM,YAAY,KAAK,cAAc,CAAC,MAAc,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;AACpF,YAAU,SAAS;AAEnB,QAAM,QAAQ,qBAAqB;AAAA,IACjC,iBAAiB,OAAO,UAAU;AAAA,IAClC,MAAM,OAAO,UAAU;AAAA,IACvB,YAAY,OAAO,UAAU;AAAA,IAC7B,MAAM,OAAO,UAAU;AAAA;AAAA,IAEvB,eAAe,OAAO;AAAA,EACxB,CAAC;AACD,QAAM,QACJ,KAAK,eACJ,CAAC,GAAG,MAAM;AACT,kBAAc,GAAG,CAAC;AAAA,EACpB;AACF,QAAM,QAAQ,WAAW,aAAa,GAAG,KAAK;AAG9C,UAAQ,IAAI,8DAAoD;AAEhE,UAAQ;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,mBAAkC;AAAA,EAC7C,MAAM;AAAA;AAAA,EAEN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,eAAe,CAAC,mBAAmB,QAAQ,cAAc,QAAQ,eAAe;AAAA,EAChF,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,eAAe,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EAC5C;AACF;","names":[]}
@@ -603,7 +603,7 @@ async function runAdapterBuild(target, config, cwd) {
603
603
  };
604
604
  }
605
605
  };
606
- const { resolveAdapter } = await import("./registry-PAJOMMVV.js");
606
+ const { resolveAdapter } = await import("./registry-RZHBBLIF.js");
607
607
  const adapter = await resolveAdapter(target);
608
608
  const { warnUnappliedConfig, assertRateLimitEnforceable } = await import("./config-support-O4REYSK5.js");
609
609
  assertRateLimitEnforceable(config, adapter, target);
@@ -676,4 +676,4 @@ function relativize3(absPath, root) {
676
676
  export {
677
677
  buildCommand
678
678
  };
679
- //# sourceMappingURL=build-CZAM7K6J.js.map
679
+ //# sourceMappingURL=build-RF2NLRHS.js.map
@@ -10,8 +10,9 @@ import {
10
10
  deployedRuntimeConfigFragment,
11
11
  deployedTraceFragment,
12
12
  describeDeployedSecurityHeaders,
13
- renderSecurityHeadersConfigLiteral
14
- } from "./chunk-VPX3MS5D.js";
13
+ renderSecurityHeadersConfigLiteral,
14
+ serverDirLiteral
15
+ } from "./chunk-PALZUV6E.js";
15
16
  import {
16
17
  nodeAdapter
17
18
  } from "./chunk-KI4DOTN4.js";
@@ -168,7 +169,7 @@ function renderBunEntry(port, opts = {}) {
168
169
  ``,
169
170
  `const cwd = process.cwd()`,
170
171
  `const clientDir = resolve(cwd, '.theokit/client')`,
171
- `const serverDir = resolve(cwd, 'server')`,
172
+ `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,
172
173
  `const port = process.env.PORT ? Number(process.env.PORT) : ${port}`,
173
174
  ``,
174
175
  `// #410 \u2014 the security baseline \`theokit start\` puts on every response,`,
@@ -343,4 +344,4 @@ export {
343
344
  bunAdapter,
344
345
  renderBunEntry
345
346
  };
346
- //# sourceMappingURL=bun-DJ6QEFIP.js.map
347
+ //# sourceMappingURL=bun-3FFL7CS4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/bun.ts","../src/adapters/deployed-rate-limit.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Bun deploy adapter. Writes to `cwd/.theokit/bun/`. Build-time.\n */\nimport { mkdirSync, 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 { deployedAgentsFragment } from './deployed-agents.js'\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.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 {\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport interface BunBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\nexport function renderBunEntry(\n port: number,\n opts: {\n ssrStreaming?: boolean\n securityHeaders?: SecurityHeadersConfig\n } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedServerDirOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions = {},\n): string {\n const streamingComment = opts.ssrStreaming\n ? `// T2.3 — ssrStreaming on; renderStreamingWeb may be consumed by app code`\n : `// (ssrStreaming off)`\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(\n { kind: 'scan', projectRoot: 'cwd', loadModule: 'loadModule' },\n { pathname: 'pathname' },\n )\n return [\n `// Generated by Theo — Bun Adapter`,\n `// Run: bun run .theokit/bun/server.mjs`,\n `// Requires Bun >= 1.1`,\n streamingComment,\n ``,\n `// EC-1: dev-mode guard`,\n `if (process.env.NODE_ENV !== 'production') {`,\n ` console.error('TheoBunAdapter is production-only. Use \\\\'theokit dev\\\\' (Node) for development.')`,\n ` process.exit(1)`,\n `}`,\n ``,\n `// Version check: Bun >= 1.1`,\n `if (typeof Bun === 'undefined') {`,\n ` console.error('TheoBunAdapter must run inside Bun. Got Node.js or unknown runtime.')`,\n ` process.exit(1)`,\n `}`,\n `{`,\n ` const [maj, min] = (Bun.version ?? '0.0').split('.').map(Number)`,\n ` if (maj < 1 || (maj === 1 && min < 1)) {`,\n ` console.error('TheoBunAdapter requires Bun >= 1.1; got ' + Bun.version)`,\n ` process.exit(1)`,\n ` }`,\n `}`,\n ``,\n `import { resolve, join } from 'node:path'`,\n `import { existsSync } from 'node:fs'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler${opts.rateLimit === undefined ? '' : ', createRateLimiterWeb'} } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n `// T3.2 — WS bridge for Bun runtime`,\n `import { createBunWsBridge } from 'theokit/adapters/ws-shim'`,\n `import { scanWebSocketRoutes } from 'theokit/server'`,\n ``,\n `const cwd = process.cwd()`,\n `const clientDir = resolve(cwd, '.theokit/client')`,\n `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,\n `const port = process.env.PORT ? Number(process.env.PORT) : ${port}`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed process has no`,\n `// theo.config.ts to read. Bun is the one Web target whose own handler serves`,\n `// the HTML document (static file + SPA fallback below), so the document gets`,\n `// these headers too -- with a nonce-less CSP, because that HTML was written`,\n `// at build time and carries no nonce on its script tags (EC-4).`,\n `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ``,\n ...runtimeConfig.imports,\n ...agentsFragment.imports,\n ...runtimeConfig.declarations,\n ...agentsFragment.declarations,\n ...deployedCsrfFragment(opts),\n ``,\n ...deployedCorsFragment(opts.cors, 'bun'),\n ``,\n ...deployedRateLimitFragment(opts.rateLimit, 'bun', 'server.requestIP(request)?.address'),\n ``,\n `const routes = existsSync(serverDir) ? scanServerRoutes(serverDir) : []`,\n `const wsRoutes = existsSync(serverDir) ? scanWebSocketRoutes(serverDir) : []`,\n `const loadModule = createProductionLoader()`,\n ``,\n `// Bun WebSocket config — single handler dispatches to first ws route,`,\n `// or a default no-op when none declared. Per-route routing happens above`,\n `// (the upgrade decision is made in fetch handler before Bun.serve hands off).`,\n `const wsBridge = wsRoutes.length > 0`,\n ` ? createBunWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` })`,\n ` : { open: () => {}, message: () => {}, close: () => {} }`,\n ``,\n `function notFoundResponse() {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Route not found' } }), {`,\n ` status: 404,`,\n ` headers: { 'Content-Type': 'application/json' },`,\n ` })`,\n `}`,\n ``,\n `Bun.serve({`,\n ` port,`,\n ` websocket: wsBridge,`,\n ` async fetch(request, server) {`,\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, ' '),\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n ` },`,\n `})`,\n ``,\n ...bunHandleRequestFragment(runtimeConfig.executeRouteSpread, agentsFragment.branch),\n ].join('\\n')\n}\n\n/**\n * The 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 that was already sitting exactly at the ceiling.\n */\nfunction bunHandleRequestFragment(runtimeSpread: string, agentBranch: readonly string[]): string[] {\n return [\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ` const pathname = url.pathname`,\n ``,\n ` // 1) Static assets`,\n ` const staticPath = pathname === '/' ? '/index.html' : pathname`,\n ` const fullStatic = join(clientDir, staticPath)`,\n ` if (existsSync(fullStatic)) {`,\n ` const file = Bun.file(fullStatic)`,\n ` if (await file.exists()) return new Response(file)`,\n ` }`,\n ``,\n ` // 2) API routes through the full executeRoute pipeline via the shim`,\n ` if (pathname.startsWith('/api/')) {`,\n ...agentBranch,\n ``,\n ` const match = matchRoute(pathname, routes)`,\n ` if (!match) return notFoundResponse()`,\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`,\n ` // a live body, so Bun.serve streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,\n ` }`,\n ``,\n ` // 3) SPA fallback`,\n ` const indexPath = join(clientDir, 'index.html')`,\n ` if (existsSync(indexPath)) return new Response(Bun.file(indexPath))`,\n ``,\n ` return notFoundResponse()`,\n `}`,\n ``,\n `console.log('Theo (Bun) listening on http://localhost:' + port)`,\n ]\n}\n\nexport async function buildBun(\n config: TheoConfig,\n cwd: string,\n deps: BunBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('bun', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/bun')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const pluginsPlan = planDeployedPlugins(config.plugins, 'bun')\n const entry = renderBunEntry(config.port, {\n ssrStreaming: config.ssrStreaming,\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 })\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(outputDir, 'server.mjs'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Bun output → .theokit/bun/server.mjs')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'bun',\n securityHeaders: config.security?.headers,\n // No deploy target other than the streamed Cloudflare worker renders HTML\n // at request time, so none of the rest can mint a nonce.\n mintsNonce: false,\n // Bun serves `.theokit/client` itself, so the document DOES pass through\n // the handler these headers are attached to.\n documentHeaders: 'handler',\n })}\\n`,\n )\n}\n\nexport const bunAdapter: DeployAdapter = {\n name: 'bun',\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 entry carries `security.headers` as a\n // literal and puts the built baseline on every response, the served document\n // included.\n servesAgents: true,\n appliesConfig: [\n 'securityHeaders',\n 'csrf',\n 'disallowed',\n 'cors',\n 'serialization',\n 'plugins',\n // #508 — bun is the first Web target to ENFORCE a declared limit rather than refuse the\n // build: `Bun.serve` is long-lived, so the in-process counter survives, and its handler\n // already receives `server`, whose `requestIP` gives the peer address without a header.\n 'rateLimit',\n ],\n build(config, cwd, ctx) {\n return buildBun(config, cwd, {}, ctx)\n },\n}\n","/**\n * The rate limit a deployed entry carries, baked at build time.\n *\n * ## What #508 asked for, and what this answers\n *\n * `theokit build` refuses the six Web-standards targets when `theo.config.ts` declares a\n * `rateLimit` (`UnenforceableRateLimitError`). That refusal is honest and it is not enforcement.\n * The issue names three things standing between the refusal and a working limit: per-runtime\n * caller-address resolution, a refusal that survives where the address cannot be resolved, and\n * storage that outlives one invocation.\n *\n * For `bun` all three already have answers, which is why it is the target that moves first:\n *\n * - **Address** — `Bun.serve`'s handler is `fetch(request, server)`, and `server.requestIP(request)`\n * returns the peer address without depending on a proxy header a client could set.\n * - **Storage** — `Bun.serve` is a long-lived process. `createRateLimiterWeb`'s default\n * `InMemoryStore` therefore behaves exactly as it does under `theokit start`, which is the\n * deployment `node` already ships.\n * - **Refusal** — see below: every shape whose key cannot be resolved in a deployed entry throws\n * at BUILD time rather than degrading.\n *\n * ## Why the other five are not here\n *\n * Cloudflare, AWS Lambda, Netlify and Vercel are per-invocation runtimes: an in-process counter\n * does not survive between requests, so a limiter built on one forgets. A limit that forgets is a\n * limit that does not limit — the same class of failure as the shared bucket, reached by a\n * different road. Deno Deploy evicts isolates for the same reason. Those need an external counter,\n * which is a storage design and not a wiring change, so they keep refusing by name.\n *\n * Being explicit about that boundary is the point. The failure this whole area exists to prevent is\n * a config that reads as protection while protecting nothing.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype RateLimitConfig = NonNullable<TheoConfig['rateLimit']>\n\n/** The rate-limit slice of an adapter's build options, named once like `DeployedCorsOptions`. */\nexport interface DeployedRateLimitOptions {\n rateLimit?: RateLimitConfig\n}\n\n/**\n * Thrown at BUILD time when a declared rate limit cannot be carried into a deployed entry.\n *\n * Distinct from {@link UnenforceableRateLimitError}, and the distinction is not cosmetic: that one\n * means *this target enforces no limit at all*, this one means *this target enforces limits, and\n * cannot carry THIS one*. An operator reading the first looks for another target; an operator\n * reading the second changes the key.\n */\nexport class UnserialisableRateLimitError extends Error {\n override readonly name = 'UnserialisableRateLimitError'\n constructor(\n readonly target: string,\n readonly reason: string,\n ways: readonly string[],\n ) {\n super(\n [\n `Refusing to build for \\`${target}\\`: theo.config.ts declares a rate limit this target cannot carry.`,\n ``,\n ` ${reason}`,\n ``,\n ` Ways forward:`,\n ...ways.map((w) => ` • ${w}`),\n ``,\n ` This refuses rather than dropping the key, because a rate limit that silently does not`,\n ` apply looks exactly like one that does (usetheokit/theokit#461, #508).`,\n ].join('\\n'),\n )\n }\n}\n\n/** The base shape every accepted config narrows to: a window, a ceiling, and an IP key. */\ninterface BakeableRateLimit {\n windowMs: number\n max: number\n}\n\n/**\n * Narrow a declared rate limit to what a deployed entry can actually enforce, or refuse by name.\n *\n * Accepts the base `{ windowMs, max }` and the explicit `keyBy: 'ip'`, which is what the address\n * resolution below can key. Everything else throws:\n *\n * - a **function** `keyBy` has no literal — the same wall `deployed-cors.ts` hits on a callback\n * origin, and refused for the same reason;\n * - `keyBy: 'session' | 'user'` needs a session the deployed entry does not resolve at the point\n * the limit runs, which is before routing;\n * - `routes` needs the matched route, decided after this check. Refusing it is honest today and is\n * the natural next slice.\n */\nfunction bakeableRateLimit(\n rateLimit: RateLimitConfig | undefined,\n target: string,\n): BakeableRateLimit | undefined {\n if (rateLimit === undefined) return undefined\n const cfg = rateLimit as Record<string, unknown>\n\n if (typeof cfg.keyBy === 'function') {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.keyBy` is a function, and a deployed entry has no literal for a closure.',\n [\n \"use `keyBy: 'ip'` (the default), which this target resolves from the connection\",\n 'build for `node` and run `theokit start`, which can call the function',\n ],\n )\n }\n if (cfg.keyBy === 'session' || cfg.keyBy === 'user') {\n throw new UnserialisableRateLimitError(\n target,\n `\\`security.rateLimit.keyBy: '${cfg.keyBy}'\\` needs a resolved session, and the limit runs before routing.`,\n [\n \"use `keyBy: 'ip'`, which is resolvable at that point\",\n 'build for `node` and run `theokit start`',\n ],\n )\n }\n if (cfg.routes !== undefined) {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.routes` needs the matched route, which is decided after the limit runs here.',\n [\n 'declare a single global limit (`windowMs` + `max`)',\n 'build for `node` and run `theokit start`, which applies per-route limits',\n ],\n )\n }\n\n const windowMs = cfg.windowMs\n const max = cfg.max\n if (typeof windowMs !== 'number' || typeof max !== 'number') return undefined\n return { windowMs, max }\n}\n\n/**\n * The generated declarations and helper for a target that keys on the connection's peer address.\n *\n * `addressExpression` is the per-runtime half the issue calls out — the one thing that genuinely\n * differs between targets. Bun passes `server`; a future Deno slice would pass its\n * `ServeHandlerInfo`. Everything else here is shared.\n *\n * Returns `[]` when nothing was declared, so an app without a limit emits no limiter at all rather\n * than an inert one.\n */\nexport function deployedRateLimitFragment(\n rateLimit: RateLimitConfig | undefined,\n target: string,\n addressExpression: string,\n): string[] {\n const baked = bakeableRateLimit(rateLimit, target)\n if (baked === undefined) return []\n return [\n `// #508 — the limit the app declared, carried as a literal because a deployed entry has no`,\n `// theo.config.ts to read. The counter lives in this process, which outlives a request here.`,\n `const RATE_LIMIT = createRateLimiterWeb({ windowMs: ${baked.windowMs}, max: ${baked.max} })`,\n ``,\n `/**`,\n ` * The caller's address, from the connection rather than from a header.`,\n ` *`,\n ` * A header a client can set is a key a client can choose, which makes the bucket theirs to`,\n ` * split. An unresolved address falls back to one shared bucket — rare here, since that only`,\n ` * happens for a connection already gone, and the same fallback \\`theokit start\\` uses.`,\n ` */`,\n `function callerAddress(request, server) {`,\n ` return ${addressExpression} ?? 'unknown'`,\n `}`,\n ``,\n `/** The 429 a limited caller gets, carrying the limiter's own headers. */`,\n `function rateLimited(result) {`,\n ` return new Response(JSON.stringify({ error: { code: 'RATE_LIMITED', message: 'Too many requests' } }), {`,\n ` status: 429,`,\n ` headers: { 'Content-Type': 'application/json', ...result.headers },`,\n ` })`,\n `}`,\n ]\n}\n\n/**\n * The check itself, as generated source, placed inside the runtime's request handler.\n *\n * Extracted for the reason `bun.ts` extracts its other fragments: the emitter is one array literal,\n * so every line the entry gains counts against `max-lines-per-function`, and this one pushed it\n * past the ceiling.\n *\n * Runs AFTER the CORS preflight and BEFORE routing: a limited caller should not reach a handler,\n * and a browser still needs its CORS answer to read the 429 as a 429 rather than as a network\n * failure.\n */\nexport function rateLimitCheckFragment(\n rateLimit: RateLimitConfig | undefined,\n indent: string,\n): string[] {\n if (rateLimit === undefined) return []\n return [\n `${indent}const limit = RATE_LIMIT(callerAddress(request, server))`,\n `${indent}if (limit.limited) {`,\n `${indent} return withCors(request, withSecurityHeaders(rateLimited(limit), SECURITY_HEADERS))`,\n `${indent}}`,\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;;;AC6CjB,IAAM,+BAAN,cAA2C,MAAM;AAAA,EAEtD,YACW,QACA,QACT,MACA;AACA;AAAA,MACE;AAAA,QACE,2BAA2B,MAAM;AAAA,QACjC;AAAA,QACA,KAAK,MAAM;AAAA,QACX;AAAA,QACA;AAAA,QACA,GAAG,KAAK,IAAI,CAAC,MAAM,cAAS,CAAC,EAAE;AAAA,QAC/B;AAAA,QACA;AAAA,QACA;AAAA,MACF,EAAE,KAAK,IAAI;AAAA,IACb;AAhBS;AACA;AAAA,EAgBX;AAAA,EAjBW;AAAA,EACA;AAAA,EAHO,OAAO;AAoB3B;AAqBA,SAAS,kBACP,WACA,QAC+B;AAC/B,MAAI,cAAc,OAAW,QAAO;AACpC,QAAM,MAAM;AAEZ,MAAI,OAAO,IAAI,UAAU,YAAY;AACnC,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,QACE;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,MAAI,IAAI,UAAU,aAAa,IAAI,UAAU,QAAQ;AACnD,UAAM,I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B,eAAe,OAAO;AAAA;AAAA;AAAA;AAAA,IAItB,qBAAqB,aAAa;AAAA,EACpC,CAAC;AACD,QAAM,QACJ,KAAK,eACJ,CAAC,GAAG,MAAM;AACT,kBAAc,GAAG,CAAC;AAAA,EACpB;AACF,MAAI,gBAAgB,QAAW;AAG7B,UAAM,QAAQ,WAAW,kBAAkB,GAAG,YAAY,MAAM;AAAA,EAClE;AACA,QAAM,QAAQ,WAAW,YAAY,GAAG,KAAK;AAG7C,UAAQ,IAAI,sDAA4C;AAExD,UAAQ;AAAA,IACN,GAAG,gCAAgC;AAAA,MACjC,QAAQ;AAAA,MACR,iBAAiB,OAAO,UAAU;AAAA;AAAA;AAAA,MAGlC,YAAY;AAAA;AAAA;AAAA,MAGZ,iBAAiB;AAAA,IACnB,CAAC,CAAC;AAAA;AAAA,EACJ;AACF;AAEO,IAAM,aAA4B;AAAA,EACvC,MAAM;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,cAAc;AAAA,EACd,eAAe;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA,IAIA;AAAA,EACF;AAAA,EACA,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,SAAS,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EACtC;AACF;","names":[]}
@@ -150,6 +150,22 @@ async function dispatchWebhook(def, request) {
150
150
  });
151
151
  }
152
152
 
153
+ // src/server/webhook/providers/configured-secret.ts
154
+ function configuredSecrets(value, option) {
155
+ const secrets = typeof value === "string" ? [value] : value;
156
+ if (secrets.length === 0) return { ok: false, reason: `no ${option} configured` };
157
+ for (let i = 0; i < secrets.length; i++) {
158
+ if (secrets[i].length === 0) {
159
+ const where = typeof value === "string" ? option : `${option}[${i}]`;
160
+ return { ok: false, reason: `${where} is empty` };
161
+ }
162
+ }
163
+ return { ok: true, secrets };
164
+ }
165
+ function refusingVerifier(reason) {
166
+ return () => ({ ok: false, reason });
167
+ }
168
+
153
169
  // src/server/webhook/providers/stripe.ts
154
170
  function parseStripeHeader(header) {
155
171
  const parts = header.split(",").map((p) => p.trim());
@@ -199,7 +215,9 @@ var fromHex = (hex) => {
199
215
  };
200
216
  function stripe(opts) {
201
217
  const tolerance = opts.toleranceSeconds ?? 300;
202
- const secrets = Array.isArray(opts.secret) ? opts.secret : [opts.secret];
218
+ const configured = configuredSecrets(opts.secret, "secret");
219
+ if (!configured.ok) return refusingVerifier(configured.reason);
220
+ const { secrets } = configured;
203
221
  return async (req) => {
204
222
  const header = req.headers.get("stripe-signature");
205
223
  if (!header) {
@@ -235,7 +253,10 @@ function stripe(opts) {
235
253
 
236
254
  // src/server/webhook/providers/hmac-sha256.ts
237
255
  function verifyHmacSha256(opts) {
238
- const { header, secrets, decode } = opts;
256
+ const { header, decode } = opts;
257
+ const configured = configuredSecrets(opts.secrets, opts.option);
258
+ if (!configured.ok) return refusingVerifier(configured.reason);
259
+ const { secrets } = configured;
239
260
  return async (req) => {
240
261
  const value = req.headers.get(header);
241
262
  if (!value) return { ok: false, reason: `missing ${header} header` };
@@ -277,13 +298,13 @@ function fromPrefixedHex(value) {
277
298
  }
278
299
  return { ok: true, bytes };
279
300
  }
280
- function verifyHubSignature256(secrets) {
281
- return verifyHmacSha256({ header: HEADER, secrets, decode: fromPrefixedHex });
301
+ function verifyHubSignature256(secrets, option) {
302
+ return verifyHmacSha256({ header: HEADER, secrets, option, decode: fromPrefixedHex });
282
303
  }
283
304
 
284
305
  // src/server/webhook/providers/github.ts
285
306
  function github(opts) {
286
- return verifyHubSignature256(Array.isArray(opts.secret) ? opts.secret : [opts.secret]);
307
+ return verifyHubSignature256(opts.secret, "secret");
287
308
  }
288
309
 
289
310
  // src/server/webhook/providers/slack.ts
@@ -300,7 +321,9 @@ function fromHex2(hex) {
300
321
  }
301
322
  function slack(opts) {
302
323
  const tolerance = opts.toleranceSeconds ?? 300;
303
- const signingSecret = opts.signingSecret;
324
+ const configured = configuredSecrets(opts.signingSecret, "signingSecret");
325
+ if (!configured.ok) return refusingVerifier(configured.reason);
326
+ const signingSecret = configured.secrets[0];
304
327
  return async (req) => {
305
328
  const tsHeader = req.headers.get("x-slack-request-timestamp");
306
329
  const sigHeader = req.headers.get("x-slack-signature");
@@ -354,8 +377,10 @@ function slack(opts) {
354
377
 
355
378
  // src/server/webhook/providers/telegram.ts
356
379
  function telegram(opts) {
380
+ const configured = configuredSecrets(opts.secretToken, "secretToken");
381
+ if (!configured.ok) return refusingVerifier(configured.reason);
357
382
  const enc2 = new TextEncoder();
358
- const expected = enc2.encode(opts.secretToken);
383
+ const expected = enc2.encode(configured.secrets[0]);
359
384
  return (req) => {
360
385
  const header = req.headers.get("x-telegram-bot-api-secret-token");
361
386
  if (!header) {
@@ -379,7 +404,9 @@ function fromHex3(hex) {
379
404
  return bytes;
380
405
  }
381
406
  function discord(opts) {
382
- const keyBytes = fromHex3(opts.publicKey);
407
+ const configured = configuredSecrets(opts.publicKey, "publicKey");
408
+ if (!configured.ok) return refusingVerifier(configured.reason);
409
+ const keyBytes = fromHex3(configured.secrets[0]);
383
410
  return async (req) => {
384
411
  if (!keyBytes) return { ok: false, reason: "malformed public key hex" };
385
412
  const sigHex = req.headers.get("x-signature-ed25519");
@@ -411,13 +438,16 @@ function discord(opts) {
411
438
 
412
439
  // src/server/webhook/providers/whatsapp.ts
413
440
  function whatsapp(opts) {
414
- return verifyHubSignature256(
415
- Array.isArray(opts.appSecret) ? opts.appSecret : [opts.appSecret]
416
- );
441
+ return verifyHubSignature256(opts.appSecret, "appSecret");
417
442
  }
418
443
  function whatsappSubscribe(opts) {
444
+ const configured = configuredSecrets(opts.verifyToken, "verifyToken");
445
+ if (!configured.ok) {
446
+ const { reason } = configured;
447
+ return () => ({ ok: false, reason });
448
+ }
419
449
  const encoder = new TextEncoder();
420
- const expected = encoder.encode(opts.verifyToken);
450
+ const expected = encoder.encode(configured.secrets[0]);
421
451
  return (req) => {
422
452
  const params = new URL(req.url).searchParams;
423
453
  if (params.get("hub.mode") !== "subscribe") {
@@ -454,8 +484,12 @@ function fromBase64(value) {
454
484
  }
455
485
  }
456
486
  function line(options) {
457
- const secrets = typeof options.channelSecret === "string" ? [options.channelSecret] : options.channelSecret;
458
- return verifyHmacSha256({ header: HEADER2, secrets, decode: fromBase64 });
487
+ return verifyHmacSha256({
488
+ header: HEADER2,
489
+ secrets: options.channelSecret,
490
+ option: "channelSecret",
491
+ decode: fromBase64
492
+ });
459
493
  }
460
494
 
461
495
  export {
@@ -474,4 +508,4 @@ export {
474
508
  whatsappSubscribe,
475
509
  line
476
510
  };
477
- //# sourceMappingURL=chunk-HIYBU6NH.js.map
511
+ //# sourceMappingURL=chunk-EW5IG7GA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/webhook/timing-safe-equal.ts","../src/server/webhook/raw-body.ts","../src/server/webhook/define-webhook.ts","../src/server/webhook/providers/configured-secret.ts","../src/server/webhook/providers/stripe.ts","../src/server/webhook/providers/hmac-sha256.ts","../src/server/webhook/providers/hub-signature-256.ts","../src/server/webhook/providers/github.ts","../src/server/webhook/providers/slack.ts","../src/server/webhook/providers/telegram.ts","../src/server/webhook/providers/discord.ts","../src/server/webhook/providers/whatsapp.ts","../src/server/webhook/providers/line.ts"],"mappings":";;;;;;;;;AAqBA,IAAI;AAEJ,SAAS,kBAA8C;AACrD,MAAI,mBAAmB,OAAW,QAAO;AACzC,MAAI;AAIF,UAAM,YAAY,UAAQ,aAAa;AAGvC,qBAAiB,UAAU,mBAAmB;AAAA,EAChD,QAAQ;AACN,qBAAiB;AAAA,EACnB;AACA,SAAO;AACT;AAQO,SAAS,gBAAgB,GAAe,GAAwB;AACrE,MAAI,EAAE,aAAa,eAAe,EAAE,aAAa,aAAa;AAC5D,UAAM,IAAI;AAAA,MACR,qDAAqD,OAAO,CAAC,QAAQ,OAAO,CAAC;AAAA,IAC/E;AAAA,EACF;AA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WAAO,EAAE,IAAI,MAAM,MAAM;AAAA,EAC3B,QAAQ;AACN,WAAO,EAAE,IAAI,OAAO,QAAQ,6BAA6B;AAAA,EAC3D;AACF;AAsBO,SAAS,KAAK,SAAuC;AAC1D,SAAO,iBAAiB;AAAA,IACtB,QAAQA;AAAA,IACR,SAAS,QAAQ;AAAA,IACjB,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AACH;","names":["result","PREFIX","fromHex","enc","enc","fromHex","HEADER"]}
@@ -82,6 +82,9 @@ function deployedCsrfFragment(opts, home = "a deployed function") {
82
82
  }
83
83
 
84
84
  // src/adapters/deployed-runtime-config.ts
85
+ function serverDirLiteral(opts) {
86
+ return JSON.stringify(opts.serverDir ?? "server");
87
+ }
85
88
  var EMPTY = {
86
89
  imports: [],
87
90
  declarations: [],
@@ -180,9 +183,10 @@ function describeDeployedSecurityHeaders(limits) {
180
183
  export {
181
184
  deployedCorsFragment,
182
185
  deployedCsrfFragment,
186
+ serverDirLiteral,
183
187
  deployedRuntimeConfigFragment,
184
188
  deployedTraceFragment,
185
189
  renderSecurityHeadersConfigLiteral,
186
190
  describeDeployedSecurityHeaders
187
191
  };
188
- //# sourceMappingURL=chunk-VPX3MS5D.js.map
192
+ //# sourceMappingURL=chunk-PALZUV6E.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/deployed-cors.ts","../src/adapters/deployed-csrf.ts","../src/adapters/deployed-runtime-config.ts","../src/adapters/deployed-trace.ts","../src/adapters/security-headers.ts"],"sourcesContent":["/**\n * The CORS configuration a deployed entry carries, baked at build time.\n *\n * ## The defect this closes\n *\n * `security.cors` reached exactly one consumer: Vite's `configureServer` hook. So an app that\n * worked cross-origin under `theokit dev` stopped working the moment anything else served it —\n * `theokit start` (fixed separately) and all six Web deploy targets (usetheokit/theokit#409). Same\n * config, same code, no error and no warning; the failure surfaces in a browser as a blocked fetch\n * on the deployed URL, three layers from the key that had quietly stopped being read.\n *\n * The pure half was written twice and called once: `createCorsWebHandler` — the Web mirror — had no\n * caller anywhere in the repository. Nothing here reimplements it.\n *\n * ## A callback origin is REFUSED, not silently dropped\n *\n * `corsSchema.origins` accepts `z.function(...)` alongside the string / RegExp / array shapes. A\n * deployed function has no `theo.config.ts` to read, and there is no literal for a closure — so a\n * build that baked only the serialisable shapes would produce an app whose CORS silently allowed\n * nothing, which is the exact class of failure this issue reports.\n *\n * `rules/three-target-parity.md` § 3 is explicit about the alternative: \"a target that cannot serve\n * a capability refuses by name. Silent degradation is the failure mode this rule exists to\n * prevent.\" So the build throws, naming the target, the key and the two ways forward.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype CorsConfig = NonNullable<NonNullable<TheoConfig['security']>['cors']>\n\n/**\n * The CORS slice of an adapter's build options.\n *\n * Narrow and named once, matching how `securityHeaders` and `DeployedCsrfOptions` already reach the\n * emitters: each renderer receives what it uses, and six signatures name one type instead of six\n * inline shapes that can drift.\n */\nexport interface DeployedCorsOptions {\n cors?: CorsConfig\n}\n\n/**\n * Thrown at BUILD time when the declared CORS cannot be carried to a deployed target.\n *\n * A build error is the point: the alternative is a deploy that looks configured and refuses every\n * cross-origin request, discovered by a browser rather than by the build.\n */\nexport class UnserializableCorsOriginError extends Error {\n constructor(target: string) {\n super(\n `security.cors.origins is a function, and the \\`${target}\\` target cannot carry it: a deployed ` +\n `function has no theo.config.ts to read, and a callback cannot be written into the emitted ` +\n `entry. Replace it with the origin, a RegExp, or an array of either — all of which travel — ` +\n `or build for \\`node\\` and run \\`theokit start\\`, which evaluates the callback at runtime.`,\n )\n this.name = 'UnserializableCorsOriginError'\n }\n}\n\n/** Source text for one origin matcher: a RegExp as a literal, anything else as JSON. */\nfunction renderOrigin(origin: unknown, target: string): string {\n if (typeof origin === 'function') throw new UnserializableCorsOriginError(target)\n if (origin instanceof RegExp) return String(origin)\n if (Array.isArray(origin)) return `[${origin.map((o) => renderOrigin(o, target)).join(', ')}]`\n return JSON.stringify(origin)\n}\n\n/**\n * Source text for the CORS config, or `undefined` when the app declared none.\n *\n * RegExp entries are emitted as regex literals for the reason `deployed-csrf.ts` gives at length:\n * `JSON.stringify` renders a RegExp as `{}`, and `matchesOrigin` checks `instanceof RegExp`, so a\n * JSON-rendered origin would sit in the emitted file looking configured and matching nothing.\n *\n * @throws UnserializableCorsOriginError when `origins` is a callback\n */\nexport function renderDeployedCorsLiteral(cors: CorsConfig | undefined, target: string): string {\n if (cors === undefined) return 'undefined'\n\n const parts = [`origins: ${renderOrigin(cors.origins, target)}`]\n if (cors.methods !== undefined) parts.push(`methods: ${JSON.stringify(cors.methods)}`)\n if (cors.allowedHeaders !== undefined)\n parts.push(`allowedHeaders: ${JSON.stringify(cors.allowedHeaders)}`)\n if (cors.exposedHeaders !== undefined)\n parts.push(`exposedHeaders: ${JSON.stringify(cors.exposedHeaders)}`)\n // Both carry schema defaults, so they are always present and always emitted — unlike the\n // optional fields above, whose absence is a real answer the handler already has one for.\n parts.push(\n `credentials: ${JSON.stringify(cors.credentials)}`,\n `maxAge: ${JSON.stringify(cors.maxAge)}`,\n )\n\n return `{ ${parts.join(', ')} }`\n}\n\n/**\n * The lines that declare the CORS handler in a generated entry.\n *\n * `null` when nothing was declared, which is what \"no cors block\" meant before and still means: no\n * headers, not permissive ones.\n */\nexport function deployedCorsFragment(cors: CorsConfig | undefined, target: string): string[] {\n return [\n `// #409 — the CORS the app declared, carried as a literal because a deployed function has no`,\n `// theo.config.ts to read. \\`null\\` when the app declared none: no headers, not permissive ones.`,\n `const CORS_CONFIG = ${renderDeployedCorsLiteral(cors, target)}`,\n `const CORS_HANDLER = CORS_CONFIG === undefined ? null : createCorsWebHandler(CORS_CONFIG)`,\n ``,\n `/** Answer a preflight before routing — an OPTIONS the router handles never gets a CORS answer. */`,\n `function corsPreflight(request) {`,\n ` return CORS_HANDLER === null ? null : CORS_HANDLER.handlePreflightRequest(request)`,\n `}`,\n ``,\n `/** Put the headers on whatever the app answered, including its 404s — a browser reads a 404`,\n ` * without them as a CORS failure rather than as the 404 it is. */`,\n `function withCors(request, response) {`,\n ` if (CORS_HANDLER !== null) CORS_HANDLER.applyCorsHeaders(request, response.headers)`,\n ` return response`,\n `}`,\n ]\n}\n","/**\n * The CSRF configuration a deployed entry carries, baked at build time.\n *\n * ## The defect this closes\n *\n * The six Web-standards adapter entries built `executeRoute`'s context from an eight-field\n * literal, and neither `csrfMode` nor `disallowed` was among the eight (usetheokit/theokit#410).\n * `executeRoute` defaults an absent mode to `'strict'`, so an app declaring\n * `security: { csrf: 'off' }` — or `'warn'` — got `'strict'` on every deploy target: a `POST` that\n * works under `theokit dev` and `theokit start` answers `403 CSRF_INVALID` on Vercel, naming a\n * mechanism the operator had switched off. The config still validated and the build still\n * succeeded; the behaviour simply changed.\n *\n * The deployed function has no `theo.config.ts` to read, which is why the value is carried as a\n * literal — the same shape `security.headers` already uses (`renderSecurityHeadersConfigLiteral`).\n *\n * ## Why this is not `JSON.stringify`\n *\n * `disallowed.routes` accepts RegExp entries (`config/schemas/security.ts`), and `JSON.stringify`\n * renders a RegExp as `{}`. That is not a formatting problem: `matchDisallowed` checks\n * `p instanceof RegExp`, so a `{}` matches nothing while reading, in the emitted file, as a rule\n * that is present and configured. Reaching for JSON here would reproduce this issue's own defect —\n * configuration that survives validation and quietly stops applying — one layer further down.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype SecurityConfig = NonNullable<TheoConfig['security']>\n\n/**\n * The two slices of `security` that reach `executeRoute`'s context.\n *\n * Narrow rather than the whole block, matching how `securityHeaders` is already passed: each\n * renderer receives what it uses and nothing else, so a headers change cannot reach the CSRF\n * literal and vice versa.\n */\nexport interface DeployedCsrfOptions {\n csrf?: SecurityConfig['csrf']\n disallowed?: SecurityConfig['disallowed']\n}\n\n/**\n * Source text for one route pattern.\n *\n * A RegExp is emitted as a regex literal so it arrives as a RegExp; a string goes through\n * `JSON.stringify`, which is the correct escaper for a JS string literal (quotes, backslashes,\n * control characters, line separators).\n */\nfunction renderRoutePattern(pattern: string | RegExp): string {\n return pattern instanceof RegExp ? String(pattern) : JSON.stringify(pattern)\n}\n\n/**\n * Source text for the CSRF slice of `executeRoute`'s context.\n *\n * Absent values are OMITTED rather than defaulted. `executeRoute` already defaults an absent\n * `csrfMode` to `'strict'`, and writing `'strict'` here would put that default in a second place\n * where the two can disagree — which is the class of drift the whole issue is about.\n *\n * @param security - the declared csrf slices, or `undefined` when the app declared no security block\n */\nexport function renderDeployedCsrfLiteral(security: DeployedCsrfOptions | undefined): string {\n if (security === undefined) return '{}'\n\n const parts: string[] = []\n if (security.csrf !== undefined) parts.push(`csrfMode: ${JSON.stringify(security.csrf)}`)\n\n const { disallowed } = security\n if (disallowed !== undefined) {\n const routes = disallowed.routes.map(renderRoutePattern).join(', ')\n parts.push(\n `disallowed: { routes: [${routes}], behavior: ${JSON.stringify(disallowed.behavior)} }`,\n )\n }\n\n // `{}` and not `{ }` when nothing was declared: the emitted file is read by people, and the\n // two-space version reads as though something was meant to be there.\n return parts.length === 0 ? '{}' : `{ ${parts.join(', ')} }`\n}\n\n/**\n * The lines that declare `CSRF_CONFIG` in a generated entry.\n *\n * One function rather than the same six lines pasted into each of the six adapters: that\n * duplication is how the eight-field context literal came to be wrong in six places at once, and\n * repeating the fix in the same shape would leave the next field with the same six places to be\n * forgotten in. It also keeps the two largest emitters under the `max-lines-per-function` ceiling,\n * which `vercel.ts` already extracts fragments to respect.\n *\n * @param opts - the declared csrf slices, passed straight through from the adapter's build options\n * @param home - what the target has instead of a config file, for the comment's second sentence\n */\nexport function deployedCsrfFragment(\n opts: DeployedCsrfOptions,\n home = 'a deployed function',\n): string[] {\n return [\n `// #410 — the CSRF mode and per-route escalation the app declared. Carried as a`,\n `// literal for the same reason as the headers above: ${home} has no theo.config.ts`,\n `// to read. Absent keys stay absent so executeRoute's own default ('strict') applies,`,\n `// rather than this file becoming a second place it can drift.`,\n `const CSRF_CONFIG = ${renderDeployedCsrfLiteral(opts)}`,\n ]\n}\n","/**\n * The configuration a deployed entry could not apply (usetheokit/theokit#425).\n *\n * ## Why this is not another literal renderer\n *\n * `deployed-csrf.ts` and `deployed-cors.ts` bake their values into the emitted source, which works\n * because `csrf` is an enum and `disallowed` is a `{ routes, behavior }` object — plain data, and a\n * deployed function has no `theo.config.ts` to read.\n *\n * The two concerns left over from #410 turn out to be different from each other, and the difference\n * is the whole design:\n *\n * - **`serialization` is plain data too.** The config field is `z.enum(['json', 'superjson'])`\n * (`config/schema.ts:147`) — a selector, not a transformer. `resolveTransformer` turns it into the\n * functions, and it already ships from `theokit/server`. So this half is a literal like the rest,\n * and the deployed entry resolves it exactly the way `theokit start` does\n * (`cli/commands/start/index.ts:108`), from the same string, through the same function.\n * - **`plugins` genuinely carries functions.** A plugin is constructed in `theo.config.ts` and there\n * is no literal for a closure, so this half needs the entry to import a module instead.\n *\n * ## Static import, not `import()` in the request path\n *\n * The tempting shortcut is `await import('../../theo.config.js')` inside the handler. It trades a\n * silent failure for a louder one on targets with no filesystem, and it moves configuration\n * resolution into every request on the targets that do have one.\n *\n * What this emits instead is a TOP-LEVEL import of a module the build already resolved and wrote\n * beside the entry — the same shape `renderBakedRoutes` uses for route modules (#369): decide on\n * the build machine, emit a static specifier. It is evaluated once at module load, the target's\n * bundler can see through it, and a plugin that needs an API the target lacks fails the build\n * rather than the first request.\n *\n * ## Why each half is optional\n *\n * An app that declares neither concern must produce the entry it produced before this existed.\n * Importing a module the build did not emit fails at load, and spreading an empty object costs an\n * allocation per request for nothing. So an empty request renders to nothing at all, and the\n * caller's `executeRoute` literal is unchanged.\n *\n * The halves are independent on purpose: an app that only picks `superjson` must not be made to\n * carry a plugins module, and an app with plugins and default JSON must not gain a transformer\n * lookup. Coupling them would have made the common case pay for the rare one.\n */\n\n/**\n * The option every Web-standards adapter grows to carry non-serialisable configuration.\n *\n * Composed into each adapter's option type the way `DeployedCsrfOptions` already is, so the six\n * targets cannot drift into six spellings of the same field.\n */\n/**\n * The project's `serverDir`, carried into every generated entrypoint (#RFC server-layout).\n *\n * Separate from the other option groups because it is not a runtime feature toggle: it is the\n * project's own layout, and an adapter that hardcodes `'server'` agrees with the default by\n * COINCIDENCE. The moment a project sets the option — the entire point of it existing — the\n * generated entrypoint resolves a directory that is not there, and only after deploy: the build\n * succeeds, the bundle is written, and routes 404 in production with nothing naming the cause.\n */\nexport interface DeployedServerDirOptions {\n /** Project-relative server directory. Absent ⇒ the schema default, `server`. */\n serverDir?: string\n}\n\n/**\n * The server directory as a quoted TypeScript literal, ready to interpolate into generated source.\n *\n * `JSON.stringify` rather than wrapping in quotes by hand: the value reaches this from user config,\n * so a directory containing a quote or a backslash would otherwise emit a syntax error into\n * somebody else's build — a worse failure than the one this fixes.\n */\nexport function serverDirLiteral(opts: DeployedServerDirOptions): string {\n return JSON.stringify(opts.serverDir ?? 'server')\n}\n\nexport interface DeployedRuntimeConfigOptions {\n /**\n * Specifier of the plugins module the build wrote beside the entry, or `undefined` when the app\n * declares no plugins and the build wrote none.\n */\n runtimeConfigModule?: string\n /**\n * The app's `serialization` selector, carried as a literal.\n *\n * `'json'` and `undefined` both mean the default, and neither emits anything: `executeRoute`\n * already falls back to `JSON.stringify`, and the `x-theo-transformer` header is deliberately\n * absent for the default so a client is told only when there is something to be told.\n */\n serialization?: 'json' | 'superjson'\n}\n\n/** The three places an entry has to grow to carry non-serialisable configuration. */\nexport interface DeployedRuntimeConfigFragment {\n /** Top-level imports. Empty when the build emitted no config module. */\n readonly imports: string[]\n /** Module-scope declarations — evaluated once, at load. Empty when there is nothing to carry. */\n readonly declarations: string[]\n /**\n * Spread into the entry's `executeRoute({ … })` literal, inside an async function.\n *\n * Empty string when there is nothing to carry, so the call site keeps the exact shape it had.\n */\n readonly executeRouteSpread: string\n}\n\nconst EMPTY: DeployedRuntimeConfigFragment = {\n imports: [],\n declarations: [],\n executeRouteSpread: '',\n}\n\n/**\n * What a deployed entry needs in order to apply `config.plugins` and `config.serialization`.\n *\n * @param moduleSpecifier - specifier of the runtime-config module the build emitted beside the\n * entry, or `undefined` when the app declared neither concern and the build emitted none.\n */\nexport function deployedRuntimeConfigFragment(\n options: DeployedRuntimeConfigOptions | undefined,\n): DeployedRuntimeConfigFragment {\n const pluginsModule = options?.runtimeConfigModule\n // 'json' is the default and emits nothing — see `serialization` above.\n const serialization = options?.serialization === 'superjson' ? 'superjson' : undefined\n if (pluginsModule === undefined && serialization === undefined) return EMPTY\n\n const imports: string[] = []\n const declarations: string[] = []\n const spread: string[] = []\n\n if (pluginsModule !== undefined) {\n imports.push(\n `import { createPluginRunnerFromConfig } from 'theokit/server'`,\n `// #425 — the app's own plugins, resolved on the build machine and written beside this entry.`,\n `// A closure has no literal, so this is an import rather than a baked value.`,\n `import theoRuntimeConfig from '${pluginsModule}'`,\n )\n declarations.push(\n `// Built ONCE, at module load. A runner rebuilt per request would re-run every plugin's`,\n `// \\`register\\`, which is where a plugin allocates the state its hooks then read.`,\n `const THEO_PLUGIN_RUNNER = createPluginRunnerFromConfig(theoRuntimeConfig.plugins)`,\n )\n // Awaited, not passed along: `createPluginRunnerFromConfig` is async because `register` is, and\n // a pending promise handed to `executeRoute` is a truthy object with none of the runner's\n // methods — every hook would silently not fire, which is this issue's own defect one layer in.\n spread.push(`pluginRunner: await THEO_PLUGIN_RUNNER`)\n }\n\n if (serialization !== undefined) {\n imports.push(`import { resolveTransformer } from 'theokit/server'`)\n declarations.push(\n `// #425 — a literal, because \\`config.serialization\\` is a SELECTOR and not a transformer.`,\n `// Same string, same function \\`theokit start\\` calls, so the deployed response and the local`,\n `// one cannot disagree about what the app asked for — including the \\`x-theo-transformer\\``,\n `// header, whose absence is what made this a data bug rather than a formatting one.`,\n `const THEO_TRANSFORMER = resolveTransformer('${serialization}')`,\n )\n spread.push(`transformer: THEO_TRANSFORMER`)\n }\n\n return { imports, declarations, executeRouteSpread: `${spread.join(', ')},` }\n}\n","/**\n * The request id a deployed entry uses, and the header it echoes back.\n *\n * ## The defect this closes\n *\n * Every generated entry minted a fresh `randomUUID()` per request and set no correlation header\n * at all on a success path (usetheokit/theokit#410). Both Node paths do the opposite: they resolve\n * an incoming `traceparent` / `x-request-id` through `extractTraceId` and echo the result under\n * both `x-request-id` and `x-trace-id` (`cli/commands/start/request-handler.ts`,\n * `vite-plugin/api-middleware.ts`).\n *\n * The consequence is that a trace crossing into a deployed function starts over. The caller's id\n * is discarded, and the response carries nothing to correlate against — so a request that fails in\n * production cannot be tied to the client that made it, which is the one situation the id exists\n * for.\n *\n * ## Why `setHeader` before the handler, rather than wrapping the response\n *\n * It is what the Node path does, and the shim reproduces Node's semantics exactly: `writeHead`\n * MERGES into the header map rather than replacing it (`web-shim.ts`), so a header set here\n * survives the handler's own `writeHead` and a handler that sets its own id still wins. Wrapping\n * the finished `Response` instead would have to mutate a response whose body is already streaming\n * (#382), and would miss the branches that return before the shim is built.\n */\n\n/**\n * Lines that resolve the request id and echo it, as generated source.\n *\n * @param requestVar - the name the entry gave the Web `Request` in scope\n * @param indent - leading whitespace, so the emitted file stays readable\n */\nexport function deployedTraceFragment(requestVar: string, indent: string): string[] {\n return [\n `${indent}// #410 — honour the caller's trace id instead of minting a new one, and echo it.`,\n `${indent}// \\`extractTraceIdFromRequest\\` validates the caller-controlled \\`x-request-id\\``,\n `${indent}// before trusting it, and falls back to a fresh UUID when neither header is present.`,\n `${indent}const requestId = extractTraceIdFromRequest(${requestVar})`,\n `${indent}res.setHeader('x-request-id', requestId)`,\n `${indent}res.setHeader(TRACE_HEADER, requestId)`,\n ]\n}\n","/**\n * The security headers a deployed target puts on its responses.\n *\n * `theokit start` applies the configured baseline to every response it writes\n * (`cli/commands/start/request-handler.ts`). None of the six Web-standards\n * deploy adapters applied any, so the same page carried a CSP,\n * `X-Frame-Options`, HSTS and `nosniff` under `theokit start` and none of them\n * once deployed (usetheokit/theokit#410, GHSA-87qq-fgcr-384x).\n *\n * This module is the seam that closes that half of the gap. It has two halves\n * and they live together on purpose: the code that writes the literal into a\n * generated entry and the code that reads it at request time have to agree on\n * one shape, and a shape stated in two files drifts.\n *\n * - **Build time** — {@link renderSecurityHeadersConfigLiteral} turns\n * `security.headers` into a JSON literal the adapter inlines. A deployed\n * runtime has no `theo.config.ts` to read, so the configuration travels as\n * data.\n * - **Request time** — the generated entry calls {@link buildSecurityHeaders}\n * on that literal and hands every response to {@link withSecurityHeaders}.\n * The same function `theokit start` calls, on the same input, so the two\n * cannot disagree about what the configuration means.\n *\n * ## The per-request nonce, and where it stops\n *\n * `buildSecurityHeaders` accepts a per-request `nonce` and substitutes it into\n * `script-src`. A nonce cannot survive a build-time literal — it is minted per\n * response — so a target reaches one only if it renders the HTML at request\n * time and can put the same value on the script tags it emits.\n *\n * Exactly one deploy path does: **Cloudflare with `ssrStreaming: true`**, whose\n * worker calls `renderStreamingWeb(request, { nonce })`, and that renderer\n * threads the value into `renderToReadableStream` and into the hydration script\n * (`router/entry-server.ts`). That branch mints a nonce per request and builds\n * its CSP from it. Everything else serves HTML written at build time, or no\n * HTML at all, and carries a **nonce-less CSP** — the same answer\n * `buildSecurityHeaders` already gives a prerendered route (EC-4), for the same\n * reason: a nonce in the header with no nonce on the tag blocks every inline\n * script.\n *\n * That asymmetry is real and is not smoothed over. It is stated in the emitted\n * entry, printed by the build through\n * {@link describeDeployedSecurityHeaders}, and written down in\n * `docs/surfaces/build-adapters.md`.\n */\nimport { generateNonce } from '../core/contracts/nonce.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { buildSecurityHeaders } from '../core/contracts/security-headers.js'\n\n/**\n * Re-exported so a generated entry has ONE import for the whole concern.\n *\n * Reaching it through `theokit/server/security` would work and would also drag\n * that barrel's CSRF surface into a Worker bundle, for a function that is forty\n * lines of string concatenation. It is defined in `core/contracts/`, which is\n * the module every target may import from — `adapters → server` is not an edge\n * in the DAG, and the header policy was never server code.\n */\nexport { buildSecurityHeaders }\n\n/**\n * Re-exported for the same reason, and so the streamed Cloudflare worker mints\n * its nonce with the identical primitive `theokit start` uses\n * (`cli/commands/start/request-handler.ts`) rather than a second, hand-rolled\n * one. It is already runtime-portable: Web Crypto first, with a named error\n * when the runtime has none.\n */\nexport { generateNonce }\n\n/**\n * The `security.headers` block, as a literal a generated entry can carry.\n *\n * `{}` when the app declares none — which is not the same as \"no headers\".\n * `buildSecurityHeaders({})` returns the full default baseline, and `{}` is\n * exactly what `theokit start` passes when `security.headers` is absent\n * (`cli/commands/start/index.ts`). An app with no security block gets the same\n * baseline deployed as it gets locally.\n */\nexport function renderSecurityHeadersConfigLiteral(\n headers: SecurityHeadersConfig | undefined,\n): string {\n return JSON.stringify(headers ?? {})\n}\n\n/**\n * Put the headers on a response, without overruling the handler.\n *\n * `theokit start` sets the baseline BEFORE the route handler runs, so a handler\n * can override it with `res.setHeader` (last write wins, Node convention). On a\n * Web target the response arrives already built, so the equivalent of \"the\n * handler wins\" is to skip a header the response already carries: a route that\n * set its own `Content-Security-Policy` keeps it.\n *\n * Mutates and returns the same `Response` rather than constructing a\n * replacement, because these responses are handed to the runtime while their\n * body is still being written (#382) and re-wrapping the stream is exactly the\n * second buffering point that change removed.\n *\n * Mutation is safe for every response these entries produce: the Fetch spec\n * gives a locally constructed `Response` the `response` header guard, which\n * permits `set` for every name used here. The `immutable` guard belongs to\n * responses that came back from `fetch()`, and none of the six emitted handlers\n * returns one — each builds its response from `createWebShim`, from a `new\n * Response(...)`, or from the SSR renderer. The WebSocket upgrade, which is the\n * one response an adapter gets from its runtime rather than building, is\n * deliberately not routed through here.\n */\nexport function withSecurityHeaders(response: Response, headers: Record<string, string>): Response {\n for (const [key, value] of Object.entries(headers)) {\n if (!response.headers.has(key)) response.headers.set(key, value)\n }\n return response\n}\n\nexport interface DeployedSecurityHeaderLimits {\n target: string\n /** The app's `security.headers` block, or undefined when it declares none. */\n securityHeaders: SecurityHeadersConfig | undefined\n /**\n * Does the emitted handler render HTML at request time and mint a CSP nonce\n * for it? True only for Cloudflare with `ssrStreaming: true`.\n */\n mintsNonce: boolean\n /**\n * Is the HTML document served by a platform static host rather than by the\n * handler this build emits? True wherever the emitted handler answers\n * `/api/*` and returns 404 for everything else.\n */\n /**\n * Who puts the security headers on the HTML DOCUMENT — a different question from who serves it,\n * and the two used to be collapsed into one boolean (usetheokit/theokit#412).\n *\n * - `handler` — this target's own handler returns the document, so it carries the same baseline\n * every API response carries. No caveat.\n * - `platform-configured` — the platform's static host serves the document, AND this build emits\n * the configuration that puts the headers on it (`.vercel/output/config.json`, `netlify.toml`).\n * Still worth stating, because nothing here has seen a deployed response.\n * - `platform-unmanaged` — the platform serves it and this build owns no artifact that could\n * configure it. This is the real remaining gap, and it stays named.\n *\n * The two-value version reported `platform-configured` targets with the same message as\n * `platform-unmanaged` ones, telling an operator to go and do work the build had already done —\n * and a stale limitation reads exactly like a current one.\n */\n documentHeaders: 'handler' | 'platform-configured' | 'platform-unmanaged'\n}\n\n/**\n * What the build tells the operator, once, per target.\n *\n * Silent degradation is the failure mode `rules/three-target-parity.md` exists\n * to prevent. Two things degrade quietly here and both are named rather than\n * discovered in production: a CSP that refuses inline scripts on a deploy while\n * allowing them locally, and an HTML document that never passes through the\n * handler these headers are attached to.\n *\n * The header names are read from the map the entry will actually carry, not\n * from a list written next to it. A configuration that switches HSTS or the CSP\n * off would otherwise be announced as sending them.\n */\nexport function describeDeployedSecurityHeaders(limits: DeployedSecurityHeaderLimits): string {\n const headers = buildSecurityHeaders(limits.securityHeaders ?? {}, { production: true })\n const names = Object.keys(headers)\n if (names.length === 0) {\n return ` ! \\`${limits.target}\\` sends no security headers: the configuration switched every one of them off.`\n }\n\n const lines = [\n ` ✓ security headers on every response \\`${limits.target}\\` returns: ${names.join(', ')}.`,\n ]\n const sendsCsp = names.some((name) => name.startsWith('Content-Security-Policy'))\n if (sendsCsp && !limits.mintsNonce) {\n lines.push(\n ` - The CSP carries no nonce: this target serves HTML written at build time,`,\n ` so there is no per-request value to put on a script tag. An inline`,\n ` <script> is refused by \\`script-src 'self'\\` here, while the same page`,\n ` under \\`theokit start\\` gets a nonce and runs it. Move inline scripts to`,\n ` \\`<script src=\"...\">\\`, or set \\`security.headers.cspMode: 'report-only'\\``,\n ` while you migrate.`,\n )\n }\n if (limits.documentHeaders === 'platform-configured') {\n lines.push(\n ` - The HTML document is served by the platform's static host, and reaches`,\n ` the browser with these headers through config this build emits. That`,\n ` path is not verified by a deploy from here — the values come from the`,\n ` same function the handler uses, but no response has been read back.`,\n )\n }\n if (limits.documentHeaders === 'platform-unmanaged') {\n lines.push(\n ` - The HTML document does NOT pass through this handler — the platform's`,\n ` static host serves it — so these headers reach \\`/api/*\\` responses and`,\n ` not the page. This build emits no artifact that could configure it, so`,\n ` set the document's headers on the platform (usetheokit/theokit#412).`,\n )\n }\n return lines.join('\\n')\n}\n"],"mappings":";;;;;;;AA8CO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,YAAY,QAAgB;AAC1B;AAAA,MACE,kDAAkD,MAAM;AAAA,IAI1D;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAGA,SAAS,aAAa,QAAiB,QAAwB;AAC7D,MAAI,OAAO,WAAW,WAAY,OAAM,IAAI,8BAA8B,MAAM;AAChF,MAAI,kBAAkB,OAAQ,QAAO,OAAO,MAAM;AAClD,MAAI,MAAM,QAAQ,MAAM,EAAG,QAAO,IAAI,OAAO,IAAI,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,EAAE,KAAK,IAAI,CAAC;AAC3F,SAAO,KAAK,UAAU,MAAM;AAC9B;AAWO,SAAS,0BAA0B,MAA8B,QAAwB;AAC9F,MAAI,SAAS,OAAW,QAAO;AAE/B,QAAM,QAAQ,CAAC,YAAY,aAAa,KAAK,SAAS,MAAM,CAAC,EAAE;AAC/D,MAAI,KAAK,YAAY,OAAW,OAAM,KAAK,YAAY,KAAK,UAAU,KAAK,OAAO,CAAC,EAAE;AACrF,MAAI,KAAK,mBAAmB;AAC1B,UAAM,KAAK,mBAAmB,KAAK,UAAU,KAAK,cAAc,CAAC,EAAE;AACrE,MAAI,KAAK,mBAAmB;AAC1B,UAAM,KAAK,mBAAmB,KAA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AE,YAAY,KAAK,CAAC;AACvF,QAAM,QAAQ,OAAO,KAAK,OAAO;AACjC,MAAI,MAAM,WAAW,GAAG;AACtB,WAAO,SAAS,OAAO,MAAM;AAAA,EAC/B;AAEA,QAAM,QAAQ;AAAA,IACZ,iDAA4C,OAAO,MAAM,eAAe,MAAM,KAAK,IAAI,CAAC;AAAA,EAC1F;AACA,QAAM,WAAW,MAAM,KAAK,CAAC,SAAS,KAAK,WAAW,yBAAyB,CAAC;AAChF,MAAI,YAAY,CAAC,OAAO,YAAY;AAClC,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,OAAO,oBAAoB,uBAAuB;AACpD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,OAAO,oBAAoB,sBAAsB;AACnD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
package/dist/cli/index.js CHANGED
@@ -20,7 +20,7 @@ cli.command("dev", "Start development server").option("--port <port>", "Port num
20
20
  });
21
21
  cli.command("build", "Build for production").option("--target <target>", "Deploy target (node, vercel, cloudflare)").action(async (options) => {
22
22
  try {
23
- const { buildCommand } = await import("../build-CZAM7K6J.js");
23
+ const { buildCommand } = await import("../build-RF2NLRHS.js");
24
24
  await buildCommand({ target: options.target });
25
25
  } catch (err) {
26
26
  const msg = err instanceof Error ? err.message : String(err);
@@ -44,7 +44,7 @@ cli.command("start", "Start production server").option("--port <port>", "Port nu
44
44
  });
45
45
  cli.command("preview", "Build for production, then serve it \u2014 one step (B-030)").option("--port <port>", "Port number").option("--target <target>", "Deploy target (node, vercel, cloudflare)").action(async (options) => {
46
46
  try {
47
- const { previewCommand } = await import("../preview-3TLURUAL.js");
47
+ const { previewCommand } = await import("../preview-F6SR2JAQ.js");
48
48
  await previewCommand({
49
49
  port: options.port ? Number(options.port) : void 0,
50
50
  target: options.target
@@ -10,8 +10,9 @@ import {
10
10
  deployedRuntimeConfigFragment,
11
11
  deployedTraceFragment,
12
12
  describeDeployedSecurityHeaders,
13
- renderSecurityHeadersConfigLiteral
14
- } from "./chunk-VPX3MS5D.js";
13
+ renderSecurityHeadersConfigLiteral,
14
+ serverDirLiteral
15
+ } from "./chunk-PALZUV6E.js";
15
16
  import {
16
17
  findRootDiv
17
18
  } from "./chunk-3PWQQWT6.js";
@@ -148,7 +149,7 @@ function renderCloudflareWorkerEntry(opts = {}) {
148
149
  ``,
149
150
  `// CR-006: server directory is a build-time literal \u2014 Workers cannot`,
150
151
  `// call process.cwd() and resolving paths at runtime returned '/server'.`,
151
- `const serverDir = 'server'`,
152
+ `const serverDir = ${serverDirLiteral(opts)}`,
152
153
  ``,
153
154
  ...routeRuntimeLines(routeModuleEntries, routeTableEntries),
154
155
  `// #410 \u2014 the security baseline \`theokit start\` puts on every response, carried`,
@@ -332,4 +333,4 @@ export {
332
333
  renderCloudflareWorkerEntry,
333
334
  renderWranglerToml
334
335
  };
335
- //# sourceMappingURL=cloudflare-UYKOO6EP.js.map
336
+ //# sourceMappingURL=cloudflare-VIQX4FVC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/cloudflare.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Cloudflare deploy adapter. All write paths are under `cwd/.theokit/cloudflare/`\n * and `cwd/wrangler.toml`. 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 { findRootDiv } from '../core/contracts/find-root-div.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 { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.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 {\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} 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 */\nfunction readDocumentShell(\n cwd: string,\n streaming: boolean,\n): { htmlHead?: string; htmlTail?: string } {\n if (!streaming) return {}\n\n const indexPath = resolve(cwd, '.theokit/client/index.html')\n if (!existsSync(indexPath)) {\n throw new Error(\n `[adapter-cloudflare] ssrStreaming is on but ${indexPath} does not exist, so the worker ` +\n `would serve a document with no <head> and no client entry. Run the client build first, ` +\n `or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n const indexHtml = readFileSync(indexPath, 'utf-8')\n const rootDiv = findRootDiv(indexHtml)\n if (rootDiv === undefined) {\n throw new Error(\n `[adapter-cloudflare] ${indexPath} has no <div id=\"root\">, so the streamed document has ` +\n `nowhere to put the app. Add one, or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n return {\n htmlHead: indexHtml.slice(0, rootDiv.insertAt),\n htmlTail: indexHtml.slice(rootDiv.insertAt),\n }\n}\n\n/**\n * The routes, turned into source: static imports, a module map and a literal table (#369).\n *\n * Extracted so the worker renderer stays inside its length budget, and because this is the whole of\n * what changed about how a Worker finds a route — it reads as one idea rather than as three loops\n * inside a hundred lines of template.\n *\n * `../../` because the worker is written to `.theokit/cloudflare/worker.mjs` and `filePath` is\n * relative to the project root. The imports are static so Wrangler's bundler follows them:\n * `wrangler.toml` uploads `.theokit/client` and has never uploaded `server/`, so a module not\n * bundled INTO the worker is not on the platform at all.\n */\nfunction renderBakedRoutes(\n routes: readonly { filePath: string; routePath: string; methods?: readonly string[] }[],\n): { routeImports: string[]; routeModuleEntries: string[]; routeTableEntries: string[] } {\n const routeVar = (index: number): string => `__theoRoute${String(index)}`\n return {\n routeImports: routes.map(\n (route, index) => `import * as ${routeVar(index)} from '../../${route.filePath}'`,\n ),\n routeModuleEntries: routes.map(\n (route, index) => ` ${JSON.stringify(route.filePath)}: ${routeVar(index)},`,\n ),\n routeTableEntries: routes.map(\n (route) =>\n ` { filePath: ${JSON.stringify(route.filePath)}, routePath: ${JSON.stringify(route.routePath)}, ` +\n `methods: ${JSON.stringify([...(route.methods ?? [])])}, ` +\n `...compilePattern(${JSON.stringify(route.routePath)}) },`,\n ),\n }\n}\n\n/**\n * The route-resolution runtime the Worker gets instead of a directory scan (#369).\n *\n * A module map, the literal table, and a loader that refuses anything the build did not bake.\n * Emitted as its own block because it replaces one idea — \"find the routes\" — wholesale.\n */\nfunction routeRuntimeLines(moduleEntries: string[], tableEntries: string[]): string[] {\n return [\n `// #369 — the routes are baked at build time. The Worker used to reach for`,\n `// \\`scanServerRoutes\\` on the server directory — a readdirSync, in a runtime with no`,\n `// filesystem. The pattern is recompiled here from the same routePath the scanner`,\n `// used, so one function decides precedence on every target.`,\n `const ROUTE_MODULES = {`,\n ...moduleEntries,\n `}`,\n ``,\n `const routes = [`,\n ...tableEntries,\n `]`,\n ``,\n `// The executor asks for a module by the path the table names. Anything else was`,\n `// never bundled, and saying so beats returning undefined and failing later on a`,\n `// property access far from the cause.`,\n `async function loadModule(path) {`,\n ` const mod = ROUTE_MODULES[path]`,\n ` if (mod === undefined) {`,\n // No backticks in this message: it is emitted INTO a template literal, and a stray one closes\n // it. That is how #344 shipped a SyntaxError, and the emitted-entry parse gate caught this one\n // before it left the branch.\n \" throw new Error(`Route module '\" +\n '${path}' +\n \"' was not bundled into this Worker. \" +\n 'A Worker has no filesystem, so every route is imported at build time. ' +\n 'Re-run: theokit build --target cloudflare`)',\n ` }`,\n ` return mod`,\n `}`,\n ``,\n ]\n}\n\nexport function renderCloudflareWorkerEntry(\n opts: {\n ssrStreaming?: boolean\n htmlHead?: string\n htmlTail?: 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 /** 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): string {\n const streamingImport = opts.ssrStreaming\n ? `import { renderStreamingWeb } from '/@theo/entry-server'`\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 const nonApiBranch = opts.ssrStreaming\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 ` htmlHead: ${JSON.stringify(opts.htmlHead ?? '')},`,\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 // 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 ? undefined : { kind: 'baked', agents: opts.agents },\n { wrapSecurityHeaders: true },\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 `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\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 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),\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 `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\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 ),\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): string[] {\n return [\n `async function handleRequest(request, url, env) {`,\n ` if (!url.pathname.startsWith('/api/')) {`,\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 `export default {`,\n ` async fetch(request, env, ctx) {`,\n ` const url = new URL(request.url)`,\n ``,\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 ` // #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 ``,\n ` return withCors(request, await handleRequest(request, url, env))`,\n ` },`,\n `}`,\n ]\n}\n\nexport function renderWranglerToml(): 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 `# A client-routed app asks for /dashboard, which is no file. Without this the asset`,\n `# handler 404s a deep link and the SPA never boots.`,\n `not_found_handling = \"single-page-application\"`,\n ``,\n `# Environment variables are set via wrangler secret or dashboard`,\n `# Example: wrangler secret put DATABASE_URL`,\n ].join('\\n')\n}\n\nexport const cloudflareAdapter: DeployAdapter = {\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\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 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\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) ?? { routes: [], wsRoutes: [], agents: [] }\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 writeFileSync(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n\n writeFileSync(\n resolve(outputDir, 'worker.mjs'),\n renderCloudflareWorkerEntry({\n ssrStreaming: config.ssrStreaming,\n ...shell,\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 routes: scanned.routes,\n // #367 — a Worker has no filesystem, so its agents are decided here like its routes.\n agents: scanned.agents,\n wsRoutes: scanned.wsRoutes,\n }),\n )\n\n // 3. Emit wrangler.toml (with nodejs_compat enforced)\n writeFileSync(resolve(cwd, 'wrangler.toml'), renderWranglerToml())\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AAwCxB,SAAS,kBACP,KACA,WAC0C;AAC1C,MAAI,CAAC,UAAW,QAAO,CAAC;AAExB,QAAM,YAAY,QAAQ,KAAK,4BAA4B;AAC3D,MAAI,CAAC,WAAW,SAAS,GAAG;AAC1B,UAAM,IAAI;AAAA,MACR,+CAA+C,SAAS;AAAA,IAG1D;AAAA,EACF;AAEA,QAAM,YAAY,aAAa,WAAW,OAAO;AACjD,QAAM,UAAU,YAAY,SAAS;AACrC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI;AAAA,MACR,wBAAwB,SAAS;AAAA,IAEnC;AAAA,EACF;AAEA,SAAO;AAAA,IACL,UAAU,UAAU,MAAM,GAAG,QAAQ,QAAQ;AAAA,IAC7C,UAAU,UAAU,MAAM,QAAQ,QAAQ;AAAA,EAC5C;AACF;AAcA,SAAS,kBACP,QACuF;AACvF,QAAM,WAAW,CAAC,UAA0B,cAAc,OAAO,KAAK,CAAC;AACvE,SAAO;AAAA,IACL,cAAc,OAAO;AAAA,MACnB,CAAC,OAAO,UAAU,eAAe,SAAS,KAAK,CAAC,gBAAgB,MAAM,QAAQ;AAAA,IAChF;AAAA,IACA,oBAAoB,OAAO;AAAA,MACzB,CAAC,OAAO,UAAU,KAAK,KAAK,UAAU,MAAM,QAAQ,CAAC,KAAK,SAAS,KAAK,CAAC;AAAA,IAC3E;AAAA,IACA,mBAAmB,OAAO;AAAA,MACxB,CAAC,UACC,iBAAiB,KAAK,UAAU,M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a,OAAO,SAAS,KAAK,EAAE,QAAQ,CAAC,GAAG,UAAU,CAAC,GAAG,QAAQ,CAAC,EAAE;AAE9F,UAAM,cAAc,oBAAoB,OAAO,SAAS,YAAY;AACpE,QAAI,gBAAgB,QAAW;AAG7B,oBAAc,QAAQ,WAAW,kBAAkB,GAAG,YAAY,MAAM;AAAA,IAC1E;AAEA;AAAA,MACE,QAAQ,WAAW,YAAY;AAAA,MAC/B,4BAA4B;AAAA,QAC1B,cAAc,OAAO;AAAA,QACrB,GAAG;AAAA,QACH,iBAAiB,OAAO,UAAU;AAAA,QAClC,MAAM,OAAO,UAAU;AAAA,QACvB,YAAY,OAAO,UAAU;AAAA,QAC7B,MAAM,OAAO,UAAU;AAAA;AAAA,QAEvB,eAAe,OAAO;AAAA;AAAA;AAAA;AAAA,QAItB,qBAAqB,aAAa;AAAA,QAClC,QAAQ,QAAQ;AAAA;AAAA,QAEhB,QAAQ,QAAQ;AAAA,QAChB,UAAU,QAAQ;AAAA,MACpB,CAAC;AAAA,IACH;AAGA,kBAAc,QAAQ,KAAK,eAAe,GAAG,mBAAmB,CAAC;AAGjE,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":[]}
@@ -11,7 +11,7 @@ import {
11
11
  deployedTraceFragment,
12
12
  describeDeployedSecurityHeaders,
13
13
  renderSecurityHeadersConfigLiteral
14
- } from "./chunk-VPX3MS5D.js";
14
+ } from "./chunk-PALZUV6E.js";
15
15
  import {
16
16
  nodeAdapter
17
17
  } from "./chunk-KI4DOTN4.js";
@@ -193,4 +193,4 @@ export {
193
193
  denoDeployAdapter,
194
194
  renderDenoEntry
195
195
  };
196
- //# sourceMappingURL=deno-deploy-W2JWCYPT.js.map
196
+ //# sourceMappingURL=deno-deploy-PTO7IE4G.js.map
@@ -7,7 +7,7 @@ import {
7
7
  deployedTraceFragment,
8
8
  describeDeployedSecurityHeaders,
9
9
  renderSecurityHeadersConfigLiteral
10
- } from "./chunk-VPX3MS5D.js";
10
+ } from "./chunk-PALZUV6E.js";
11
11
  import {
12
12
  nodeAdapter
13
13
  } from "./chunk-KI4DOTN4.js";
@@ -242,4 +242,4 @@ export {
242
242
  netlifyAdapter,
243
243
  renderNetlifyFunction
244
244
  };
245
- //# sourceMappingURL=netlify-BJQGPMGY.js.map
245
+ //# sourceMappingURL=netlify-3VSNVURQ.js.map
@@ -4,7 +4,7 @@ import "tsx/esm";
4
4
  // src/cli/commands/preview.ts
5
5
  async function defaultSteps() {
6
6
  const [{ buildCommand }, { startCommand }] = await Promise.all([
7
- import("./build-CZAM7K6J.js"),
7
+ import("./build-RF2NLRHS.js"),
8
8
  import("./start-JEYOON64.js")
9
9
  ]);
10
10
  return {
@@ -20,4 +20,4 @@ async function previewCommand(options = {}, steps) {
20
20
  export {
21
21
  previewCommand
22
22
  };
23
- //# sourceMappingURL=preview-3TLURUAL.js.map
23
+ //# sourceMappingURL=preview-F6SR2JAQ.js.map
@@ -4,13 +4,13 @@ import "tsx/esm";
4
4
  // src/adapters/registry.ts
5
5
  var adapterRegistry = {
6
6
  node: async () => (await import("./node-OSVPYQ3D.js")).nodeAdapter,
7
- vercel: async () => (await import("./vercel-BEDGUVXX.js")).vercelAdapter,
8
- cloudflare: async () => (await import("./cloudflare-UYKOO6EP.js")).cloudflareAdapter,
7
+ vercel: async () => (await import("./vercel-BZ35DF3B.js")).vercelAdapter,
8
+ cloudflare: async () => (await import("./cloudflare-VIQX4FVC.js")).cloudflareAdapter,
9
9
  static: async () => (await import("./static-SVDWIOXJ.js")).staticAdapter,
10
- bun: async () => (await import("./bun-DJ6QEFIP.js")).bunAdapter,
11
- "deno-deploy": async () => (await import("./deno-deploy-W2JWCYPT.js")).denoDeployAdapter,
12
- netlify: async () => (await import("./netlify-BJQGPMGY.js")).netlifyAdapter,
13
- "aws-lambda": async () => (await import("./aws-lambda-2R77AV5F.js")).awsLambdaAdapter,
10
+ bun: async () => (await import("./bun-3FFL7CS4.js")).bunAdapter,
11
+ "deno-deploy": async () => (await import("./deno-deploy-PTO7IE4G.js")).denoDeployAdapter,
12
+ netlify: async () => (await import("./netlify-3VSNVURQ.js")).netlifyAdapter,
13
+ "aws-lambda": async () => (await import("./aws-lambda-AN6CEBXO.js")).awsLambdaAdapter,
14
14
  "theo-cloud": async () => (await import("./theo-cloud-3ET4G5T6.js")).theoCloudAdapter
15
15
  };
16
16
  async function resolveAdapter(target) {
@@ -20,4 +20,4 @@ async function resolveAdapter(target) {
20
20
  export {
21
21
  resolveAdapter
22
22
  };
23
- //# sourceMappingURL=registry-PAJOMMVV.js.map
23
+ //# sourceMappingURL=registry-RZHBBLIF.js.map
@@ -24,7 +24,7 @@ import {
24
24
  timingSafeEqual,
25
25
  whatsapp,
26
26
  whatsappSubscribe
27
- } from "../chunk-HIYBU6NH.js";
27
+ } from "../chunk-EW5IG7GA.js";
28
28
  import {
29
29
  action,
30
30
  defineChannel,
@@ -13,7 +13,7 @@ import {
13
13
  timingSafeEqual,
14
14
  whatsapp,
15
15
  whatsappSubscribe
16
- } from "../../chunk-HIYBU6NH.js";
16
+ } from "../../chunk-EW5IG7GA.js";
17
17
  import "../../chunk-UMNXCU3K.js";
18
18
  import "../../chunk-XTHN6JBX.js";
19
19
  export {
@@ -6,8 +6,9 @@ import {
6
6
  deployedRuntimeConfigFragment,
7
7
  deployedTraceFragment,
8
8
  describeDeployedSecurityHeaders,
9
- renderSecurityHeadersConfigLiteral
10
- } from "./chunk-VPX3MS5D.js";
9
+ renderSecurityHeadersConfigLiteral,
10
+ serverDirLiteral
11
+ } from "./chunk-PALZUV6E.js";
11
12
  import {
12
13
  nodeAdapter
13
14
  } from "./chunk-KI4DOTN4.js";
@@ -160,7 +161,7 @@ function renderVercelFunctionEntry(opts = {}) {
160
161
  `// Cold-start cache`,
161
162
  `let routesCache = null`,
162
163
  `let loaderCache = null`,
163
- `const serverDir = resolve(process.cwd(), 'server')`,
164
+ `const serverDir = resolve(process.cwd(), ${serverDirLiteral(opts)})`,
164
165
  ``,
165
166
  `// #410 \u2014 the security baseline \`theokit start\` puts on every response,`,
166
167
  `// carried here as a literal because the deployed function has no`,
@@ -274,4 +275,4 @@ export {
274
275
  renderVercelVcConfigJson,
275
276
  vercelAdapter
276
277
  };
277
- //# sourceMappingURL=vercel-BEDGUVXX.js.map
278
+ //# sourceMappingURL=vercel-BZ35DF3B.js.map
@@ -0,0 +1 @@
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 { 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 { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.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 {\n buildSecurityHeaders,\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } 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(): string[] {\n return [\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 ` 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(runtimeSpread: string): string[] {\n return [\n `async function routeRequest(nodeReq) {`,\n ` const url = new URL(nodeReq.url ?? '/', 'http://' + (nodeReq.headers?.host ?? 'localhost'))`,\n ``,\n ` if (!url.pathname.startsWith('/api/')) {`,\n ` return new Response('Not Found', {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'text/plain; charset=utf-8' },`,\n ` })`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'application/json' },`,\n ` })`,\n ` }`,\n ``,\n ` // Convert Node-style req to Web Request 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 webRequest = new Request(url.toString(), { method, headers, body })`,\n ``,\n ` const { req, res, toResponse } = createWebShim(webRequest)`,\n ...deployedTraceFragment('webRequest', ' '),\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: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread}`,\n ` }))`,\n `}`,\n ]\n}\n\nexport function renderVercelFunctionEntry(\n opts: { securityHeaders?: SecurityHeadersConfig } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedServerDirOptions &\n DeployedCorsOptions = {},\n): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\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 { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `// Cold-start cache`,\n `let routesCache = null`,\n `let loaderCache = null`,\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 `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ``,\n ...runtimeConfig.imports,\n ...runtimeConfig.declarations,\n ...deployedCsrfFragment(opts),\n ``,\n ...deployedCorsFragment(opts.cors, '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(),\n ``,\n ...vercelRouteRequestFragment(runtimeConfig.executeRouteSpread),\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(securityHeaders?: SecurityHeadersConfig): {\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 { src: '/(.*)', dest: '/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\nexport const vercelAdapter: DeployAdapter = {\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\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\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 nodeAdapter.build(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 cpSync(clientDir, resolve(outputDir, 'static'), { recursive: true })\n }\n\n // 4. Emit serverless function entry (now uses shared web-shim)\n writeFileSync(\n resolve(outputDir, 'functions/api.func/index.mjs'),\n renderVercelFunctionEntry({\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 }),\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), 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 mintsNonce: false,\n documentHeaders: 'platform-configured',\n })}\\n`,\n )\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,eAAe,cAAc;AAC7D,SAAS,eAAe;AAgCxB,SAAS,wBAAkC;AACzC,SAAO;AAAA,IACL;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;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,EACF;AACF;AAKA,SAAS,2BAA2B,eAAiC;AACnE,SAAO;AAAA,IACL;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;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG,sBAAsB,cAAc,IAAI;AAAA,IAC3C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gFAAgF,aAAa;AAAA,IAC7F;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,0BACd,OAGwB,CAAC,GACjB;AACR,QAAM,g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HANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "theokit",
3
- "version": "0.63.0",
3
+ "version": "0.63.1",
4
4
  "description": "The TheoKit web framework — file-based routing, typed server surfaces, the Vite plugin, the CLI and the deploy adapters, around agents served from agents/*.ts.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/aws-lambda.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * AWS Lambda adapter. Writes to `cwd/.theokit/lambda/`. Build-time tool.\n */\nimport { mkdirSync, 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 { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport {\n deployedRuntimeConfigFragment,\n type DeployedRuntimeConfigOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport {\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport interface AwsLambdaBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\nexport interface RequestShape {\n method: string\n path: string\n headers: Record<string, string>\n body?: string\n}\n\nexport interface LambdaResultV2 {\n statusCode: number\n headers: Record<string, string>\n body: string\n isBase64Encoded: boolean\n}\n\nconst BINARY_CONTENT_TYPES = [\n 'application/octet-stream',\n 'application/pdf',\n 'application/zip',\n 'image/',\n 'audio/',\n 'video/',\n]\n\nfunction isBinaryContentType(contentType: string | undefined): boolean {\n if (!contentType) return false\n const ct = contentType.toLowerCase()\n return BINARY_CONTENT_TYPES.some((prefix) => ct.startsWith(prefix))\n}\n\ninterface APIGatewayProxyEventV2 {\n version: string\n requestContext: {\n http: { method: string; path: string }\n }\n headers?: Record<string, string | undefined>\n body?: string\n isBase64Encoded?: boolean\n}\n\nexport function eventV2ToRequestShape(event: APIGatewayProxyEventV2): RequestShape {\n const headers: Record<string, string> = {}\n for (const [k, v] of Object.entries(event.headers ?? {})) {\n if (v !== undefined) headers[k] = v\n }\n let body: string | undefined = event.body\n if (body !== undefined && event.isBase64Encoded) {\n body = Buffer.from(body, 'base64').toString('utf-8')\n }\n return {\n method: event.requestContext.http.method,\n path: event.requestContext.http.path,\n headers,\n body,\n }\n}\n\nexport function responseToLambdaResultV2(\n statusCode: number,\n headers: Record<string, string>,\n body: string,\n): LambdaResultV2 {\n const isBinary = isBinaryContentType(headers['content-type'])\n return {\n statusCode,\n headers,\n body: isBinary ? Buffer.from(body, 'binary').toString('base64') : body,\n isBase64Encoded: isBinary,\n }\n}\n\n// Generated-code fragments — extracted so the parent emitter stays under the\n// max-lines-per-function ceiling.\n/** The v2 result conversion, the handler, and the routing that feeds them. */\nfunction awsLambdaHandlerFragment(runtimeSpread: string): string[] {\n return [\n `// #382 — this target is DELISTED for response streaming, by construction.`,\n `// The Lambda v2 result object below carries \\`body\\` as a string, so the`,\n `// response cannot exist until the run has finished, no matter how the`,\n `// framework's shim writes it. Streaming here would require`,\n `// \\`awslambda.streamifyResponse\\` plus a Function URL in RESPONSE_STREAM`,\n `// invoke mode — neither of which this adapter emits, and which would break`,\n `// every API Gateway deployment of it. Rather than degrade in silence, a`,\n `// response that is unambiguously a stream is named in the logs below.`,\n `async function responseToV2Result(response, routePath) {`,\n ` const headers = {}`,\n ` response.headers.forEach((v, k) => { headers[k] = v })`,\n ` const ct = headers['content-type'] ?? ''`,\n ` if (ct.includes('text/event-stream')) {`,\n ` console.warn(`,\n ` '[theo][aws-lambda] ' + routePath + ' returned a streaming response (' + ct + '), ' +`,\n ` 'but the aws-lambda target buffers it whole and delivers it when the run ends. ' +`,\n ` 'This target is delisted for streaming (theokit#382). Deploy streaming routes to ' +`,\n ` 'cloudflare, vercel, netlify, bun, deno-deploy or node.'`,\n ` )`,\n ` }`,\n ` const isBinary = /^application\\\\/(octet-stream|pdf|zip)|^(image|audio|video)\\\\//.test(ct)`,\n ` if (isBinary) {`,\n ` const buf = Buffer.from(await response.arrayBuffer())`,\n ` return {`,\n ` statusCode: response.status,`,\n ` headers,`,\n ` body: buf.toString('base64'),`,\n ` isBase64Encoded: true,`,\n ` }`,\n ` }`,\n ` return {`,\n ` statusCode: response.status,`,\n ` headers,`,\n ` body: await response.text(),`,\n ` isBase64Encoded: false,`,\n ` }`,\n `}`,\n ``,\n `// Every outcome — including both 404s — is produced as a Web Response by`,\n `// routeRequest, so the security baseline is applied at ONE place and the`,\n `// v2 result object is built from headers that already carry it.`,\n `export const handler = async (event) => {`,\n ` const path = event.requestContext?.http?.path ?? '/'`,\n ` // #409 — the same event, read as a Web Request so the CORS matcher can see the method and`,\n ` // the \\`origin\\` header. \\`eventV2ToRequest\\` reads a body already present in the event, so`,\n ` // unlike the Node targets there is no stream to drain twice.`,\n ` const corsRequest = eventV2ToRequest(event)`,\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 ` const response = preflight !== null`,\n ` ? withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ` : withCors(corsRequest, withSecurityHeaders(await routeRequest(event, path), SECURITY_HEADERS))`,\n ` return responseToV2Result(response, path)`,\n `}`,\n ``,\n `async function routeRequest(event, path) {`,\n ` if (!path.startsWith('/api/')) {`,\n ` return new Response(`,\n ` 'Static assets must be served from CloudFront or a separate static host.',`,\n ` { status: 404, headers: { 'content-type': 'text/plain' } },`,\n ` )`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ` const match = matchRoute(path, routesCache)`,\n ` if (!match) {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'application/json' },`,\n ` })`,\n ` }`,\n ``,\n ` const request = eventV2ToRequest(event)`,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,\n `}`,\n ]\n}\n\nexport function renderAwsLambdaEntry(\n opts: { securityHeaders?: SecurityHeadersConfig } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedCorsOptions = {},\n): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n return [\n `// Generated by Theo — AWS Lambda Adapter`,\n `// Use with API Gateway HTTP API v2 (default).`,\n ``,\n `import { resolve } from 'node:path'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `const cwd = process.cwd()`,\n `const serverDir = resolve(cwd, 'server')`,\n `let routesCache = 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 function has no`,\n `// theo.config.ts to read. Non-API paths 404 here and the document is served`,\n `// from CloudFront or another static host, so this covers the API and not the`,\n `// page (usetheokit/theokit#412).`,\n `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ``,\n ...runtimeConfig.imports,\n ...runtimeConfig.declarations,\n ...deployedCsrfFragment(opts),\n ``,\n ...deployedCorsFragment(opts.cors, 'aws-lambda'),\n ``,\n `function eventV2ToRequest(event) {`,\n ` const method = event.requestContext?.http?.method ?? 'GET'`,\n ` const path = event.requestContext?.http?.path ?? '/'`,\n ` const host = event.headers?.host ?? 'lambda'`,\n ` const qs = event.rawQueryString ? '?' + event.rawQueryString : ''`,\n ` const url = 'https://' + host + path + qs`,\n ` const headers = new Headers()`,\n ` for (const [k, v] of Object.entries(event.headers ?? {})) {`,\n ` if (v !== undefined) headers.set(k, String(v))`,\n ` }`,\n ` let body = event.body`,\n ` if (body && event.isBase64Encoded) {`,\n ` body = Buffer.from(body, 'base64')`,\n ` }`,\n ` return new Request(url, {`,\n ` method,`,\n ` headers,`,\n ` body: method === 'GET' || method === 'HEAD' ? undefined : body,`,\n ` })`,\n `}`,\n ``,\n ...awsLambdaHandlerFragment(runtimeConfig.executeRouteSpread),\n ].join('\\n')\n}\n\nexport async function buildAwsLambda(\n config: TheoConfig,\n cwd: string,\n deps: AwsLambdaBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('aws-lambda', readManifest(cwd))\n\n // #382 — refuse by name rather than build something that cannot do what was\n // asked. `ssrStreaming` is the config's declaration that responses stream,\n // and this target is delisted for that (see `awsLambdaAdapter.streamsResponses`).\n if (config.ssrStreaming) {\n throw new Error(\n '[adapter-aws-lambda] ssrStreaming is on, but the aws-lambda target does not stream ' +\n 'responses: the Lambda v2 result object carries the body as a string, so nothing can ' +\n 'leave the function before the run ends. Response streaming would need ' +\n 'awslambda.streamifyResponse plus a Function URL in RESPONSE_STREAM invoke mode, which ' +\n 'this adapter does not emit. Build a streaming target instead (cloudflare, vercel, ' +\n 'netlify, bun, deno-deploy, node), or set ssrStreaming: false in theo.config.ts.',\n )\n }\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/aws')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const entry = renderAwsLambdaEntry({\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 })\n const write =\n deps.writeEntry ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n write(resolve(outputDir, 'handler.mjs'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ AWS Lambda output → .theokit/aws/handler.mjs')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'aws-lambda',\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-unmanaged',\n })}\\n`,\n )\n}\n\nexport const awsLambdaAdapter: DeployAdapter = {\n name: 'aws-lambda',\n // #382 — delisted for streaming, deliberately. See DeployAdapter.\n streamsResponses: false,\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 comes from CloudFront or another static host and does not pass\n // through it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n build(config, cwd, ctx) {\n return buildAwsLambda(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;AAwCxB,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,oBAA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Q,eAAe;AAAA,EAChF,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,eAAe,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EAC5C;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/bun.ts","../src/adapters/deployed-rate-limit.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Bun deploy adapter. Writes to `cwd/.theokit/bun/`. Build-time.\n */\nimport { mkdirSync, 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 { deployedAgentsFragment } from './deployed-agents.js'\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.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 type DeployedRuntimeConfigOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport {\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport interface BunBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\nexport function renderBunEntry(\n port: number,\n opts: {\n ssrStreaming?: boolean\n securityHeaders?: SecurityHeadersConfig\n } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions = {},\n): string {\n const streamingComment = opts.ssrStreaming\n ? `// T2.3 — ssrStreaming on; renderStreamingWeb may be consumed by app code`\n : `// (ssrStreaming off)`\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(\n { kind: 'scan', projectRoot: 'cwd', loadModule: 'loadModule' },\n { pathname: 'pathname' },\n )\n return [\n `// Generated by Theo — Bun Adapter`,\n `// Run: bun run .theokit/bun/server.mjs`,\n `// Requires Bun >= 1.1`,\n streamingComment,\n ``,\n `// EC-1: dev-mode guard`,\n `if (process.env.NODE_ENV !== 'production') {`,\n ` console.error('TheoBunAdapter is production-only. Use \\\\'theokit dev\\\\' (Node) for development.')`,\n ` process.exit(1)`,\n `}`,\n ``,\n `// Version check: Bun >= 1.1`,\n `if (typeof Bun === 'undefined') {`,\n ` console.error('TheoBunAdapter must run inside Bun. Got Node.js or unknown runtime.')`,\n ` process.exit(1)`,\n `}`,\n `{`,\n ` const [maj, min] = (Bun.version ?? '0.0').split('.').map(Number)`,\n ` if (maj < 1 || (maj === 1 && min < 1)) {`,\n ` console.error('TheoBunAdapter requires Bun >= 1.1; got ' + Bun.version)`,\n ` process.exit(1)`,\n ` }`,\n `}`,\n ``,\n `import { resolve, join } from 'node:path'`,\n `import { existsSync } from 'node:fs'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler${opts.rateLimit === undefined ? '' : ', createRateLimiterWeb'} } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n `// T3.2 — WS bridge for Bun runtime`,\n `import { createBunWsBridge } from 'theokit/adapters/ws-shim'`,\n `import { scanWebSocketRoutes } from 'theokit/server'`,\n ``,\n `const cwd = process.cwd()`,\n `const clientDir = resolve(cwd, '.theokit/client')`,\n `const serverDir = resolve(cwd, 'server')`,\n `const port = process.env.PORT ? Number(process.env.PORT) : ${port}`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed process has no`,\n `// theo.config.ts to read. Bun is the one Web target whose own handler serves`,\n `// the HTML document (static file + SPA fallback below), so the document gets`,\n `// these headers too -- with a nonce-less CSP, because that HTML was written`,\n `// at build time and carries no nonce on its script tags (EC-4).`,\n `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ``,\n ...runtimeConfig.imports,\n ...agentsFragment.imports,\n ...runtimeConfig.declarations,\n ...agentsFragment.declarations,\n ...deployedCsrfFragment(opts),\n ``,\n ...deployedCorsFragment(opts.cors, 'bun'),\n ``,\n ...deployedRateLimitFragment(opts.rateLimit, 'bun', 'server.requestIP(request)?.address'),\n ``,\n `const routes = existsSync(serverDir) ? scanServerRoutes(serverDir) : []`,\n `const wsRoutes = existsSync(serverDir) ? scanWebSocketRoutes(serverDir) : []`,\n `const loadModule = createProductionLoader()`,\n ``,\n `// Bun WebSocket config — single handler dispatches to first ws route,`,\n `// or a default no-op when none declared. Per-route routing happens above`,\n `// (the upgrade decision is made in fetch handler before Bun.serve hands off).`,\n `const wsBridge = wsRoutes.length > 0`,\n ` ? createBunWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` })`,\n ` : { open: () => {}, message: () => {}, close: () => {} }`,\n ``,\n `function notFoundResponse() {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Route not found' } }), {`,\n ` status: 404,`,\n ` headers: { 'Content-Type': 'application/json' },`,\n ` })`,\n `}`,\n ``,\n `Bun.serve({`,\n ` port,`,\n ` websocket: wsBridge,`,\n ` async fetch(request, server) {`,\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, ' '),\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n ` },`,\n `})`,\n ``,\n ...bunHandleRequestFragment(runtimeConfig.executeRouteSpread, agentsFragment.branch),\n ].join('\\n')\n}\n\n/**\n * The 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 that was already sitting exactly at the ceiling.\n */\nfunction bunHandleRequestFragment(runtimeSpread: string, agentBranch: readonly string[]): string[] {\n return [\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ` const pathname = url.pathname`,\n ``,\n ` // 1) Static assets`,\n ` const staticPath = pathname === '/' ? '/index.html' : pathname`,\n ` const fullStatic = join(clientDir, staticPath)`,\n ` if (existsSync(fullStatic)) {`,\n ` const file = Bun.file(fullStatic)`,\n ` if (await file.exists()) return new Response(file)`,\n ` }`,\n ``,\n ` // 2) API routes through the full executeRoute pipeline via the shim`,\n ` if (pathname.startsWith('/api/')) {`,\n ...agentBranch,\n ``,\n ` const match = matchRoute(pathname, routes)`,\n ` if (!match) return notFoundResponse()`,\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`,\n ` // a live body, so Bun.serve streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,\n ` }`,\n ``,\n ` // 3) SPA fallback`,\n ` const indexPath = join(clientDir, 'index.html')`,\n ` if (existsSync(indexPath)) return new Response(Bun.file(indexPath))`,\n ``,\n ` return notFoundResponse()`,\n `}`,\n ``,\n `console.log('Theo (Bun) listening on http://localhost:' + port)`,\n ]\n}\n\nexport async function buildBun(\n config: TheoConfig,\n cwd: string,\n deps: BunBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('bun', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/bun')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const pluginsPlan = planDeployedPlugins(config.plugins, 'bun')\n const entry = renderBunEntry(config.port, {\n ssrStreaming: config.ssrStreaming,\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 })\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(outputDir, 'server.mjs'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Bun output → .theokit/bun/server.mjs')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'bun',\n securityHeaders: config.security?.headers,\n // No deploy target other than the streamed Cloudflare worker renders HTML\n // at request time, so none of the rest can mint a nonce.\n mintsNonce: false,\n // Bun serves `.theokit/client` itself, so the document DOES pass through\n // the handler these headers are attached to.\n documentHeaders: 'handler',\n })}\\n`,\n )\n}\n\nexport const bunAdapter: DeployAdapter = {\n name: 'bun',\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 entry carries `security.headers` as a\n // literal and puts the built baseline on every response, the served document\n // included.\n servesAgents: true,\n appliesConfig: [\n 'securityHeaders',\n 'csrf',\n 'disallowed',\n 'cors',\n 'serialization',\n 'plugins',\n // #508 — bun is the first Web target to ENFORCE a declared limit rather than refuse the\n // build: `Bun.serve` is long-lived, so the in-process counter survives, and its handler\n // already receives `server`, whose `requestIP` gives the peer address without a header.\n 'rateLimit',\n ],\n build(config, cwd, ctx) {\n return buildBun(config, cwd, {}, ctx)\n },\n}\n","/**\n * The rate limit a deployed entry carries, baked at build time.\n *\n * ## What #508 asked for, and what this answers\n *\n * `theokit build` refuses the six Web-standards targets when `theo.config.ts` declares a\n * `rateLimit` (`UnenforceableRateLimitError`). That refusal is honest and it is not enforcement.\n * The issue names three things standing between the refusal and a working limit: per-runtime\n * caller-address resolution, a refusal that survives where the address cannot be resolved, and\n * storage that outlives one invocation.\n *\n * For `bun` all three already have answers, which is why it is the target that moves first:\n *\n * - **Address** — `Bun.serve`'s handler is `fetch(request, server)`, and `server.requestIP(request)`\n * returns the peer address without depending on a proxy header a client could set.\n * - **Storage** — `Bun.serve` is a long-lived process. `createRateLimiterWeb`'s default\n * `InMemoryStore` therefore behaves exactly as it does under `theokit start`, which is the\n * deployment `node` already ships.\n * - **Refusal** — see below: every shape whose key cannot be resolved in a deployed entry throws\n * at BUILD time rather than degrading.\n *\n * ## Why the other five are not here\n *\n * Cloudflare, AWS Lambda, Netlify and Vercel are per-invocation runtimes: an in-process counter\n * does not survive between requests, so a limiter built on one forgets. A limit that forgets is a\n * limit that does not limit — the same class of failure as the shared bucket, reached by a\n * different road. Deno Deploy evicts isolates for the same reason. Those need an external counter,\n * which is a storage design and not a wiring change, so they keep refusing by name.\n *\n * Being explicit about that boundary is the point. The failure this whole area exists to prevent is\n * a config that reads as protection while protecting nothing.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype RateLimitConfig = NonNullable<TheoConfig['rateLimit']>\n\n/** The rate-limit slice of an adapter's build options, named once like `DeployedCorsOptions`. */\nexport interface DeployedRateLimitOptions {\n rateLimit?: RateLimitConfig\n}\n\n/**\n * Thrown at BUILD time when a declared rate limit cannot be carried into a deployed entry.\n *\n * Distinct from {@link UnenforceableRateLimitError}, and the distinction is not cosmetic: that one\n * means *this target enforces no limit at all*, this one means *this target enforces limits, and\n * cannot carry THIS one*. An operator reading the first looks for another target; an operator\n * reading the second changes the key.\n */\nexport class UnserialisableRateLimitError extends Error {\n override readonly name = 'UnserialisableRateLimitError'\n constructor(\n readonly target: string,\n readonly reason: string,\n ways: readonly string[],\n ) {\n super(\n [\n `Refusing to build for \\`${target}\\`: theo.config.ts declares a rate limit this target cannot carry.`,\n ``,\n ` ${reason}`,\n ``,\n ` Ways forward:`,\n ...ways.map((w) => ` • ${w}`),\n ``,\n ` This refuses rather than dropping the key, because a rate limit that silently does not`,\n ` apply looks exactly like one that does (usetheokit/theokit#461, #508).`,\n ].join('\\n'),\n )\n }\n}\n\n/** The base shape every accepted config narrows to: a window, a ceiling, and an IP key. */\ninterface BakeableRateLimit {\n windowMs: number\n max: number\n}\n\n/**\n * Narrow a declared rate limit to what a deployed entry can actually enforce, or refuse by name.\n *\n * Accepts the base `{ windowMs, max }` and the explicit `keyBy: 'ip'`, which is what the address\n * resolution below can key. Everything else throws:\n *\n * - a **function** `keyBy` has no literal — the same wall `deployed-cors.ts` hits on a callback\n * origin, and refused for the same reason;\n * - `keyBy: 'session' | 'user'` needs a session the deployed entry does not resolve at the point\n * the limit runs, which is before routing;\n * - `routes` needs the matched route, decided after this check. Refusing it is honest today and is\n * the natural next slice.\n */\nfunction bakeableRateLimit(\n rateLimit: RateLimitConfig | undefined,\n target: string,\n): BakeableRateLimit | undefined {\n if (rateLimit === undefined) return undefined\n const cfg = rateLimit as Record<string, unknown>\n\n if (typeof cfg.keyBy === 'function') {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.keyBy` is a function, and a deployed entry has no literal for a closure.',\n [\n \"use `keyBy: 'ip'` (the default), which this target resolves from the connection\",\n 'build for `node` and run `theokit start`, which can call the function',\n ],\n )\n }\n if (cfg.keyBy === 'session' || cfg.keyBy === 'user') {\n throw new UnserialisableRateLimitError(\n target,\n `\\`security.rateLimit.keyBy: '${cfg.keyBy}'\\` needs a resolved session, and the limit runs before routing.`,\n [\n \"use `keyBy: 'ip'`, which is resolvable at that point\",\n 'build for `node` and run `theokit start`',\n ],\n )\n }\n if (cfg.routes !== undefined) {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.routes` needs the matched route, which is decided after the limit runs here.',\n [\n 'declare a single global limit (`windowMs` + `max`)',\n 'build for `node` and run `theokit start`, which applies per-route limits',\n ],\n )\n }\n\n const windowMs = cfg.windowMs\n const max = cfg.max\n if (typeof windowMs !== 'number' || typeof max !== 'number') return undefined\n return { windowMs, max }\n}\n\n/**\n * The generated declarations and helper for a target that keys on the connection's peer address.\n *\n * `addressExpression` is the per-runtime half the issue calls out — the one thing that genuinely\n * differs between targets. Bun passes `server`; a future Deno slice would pass its\n * `ServeHandlerInfo`. Everything else here is shared.\n *\n * Returns `[]` when nothing was declared, so an app without a limit emits no limiter at all rather\n * than an inert one.\n */\nexport function deployedRateLimitFragment(\n rateLimit: RateLimitConfig | undefined,\n target: string,\n addressExpression: string,\n): string[] {\n const baked = bakeableRateLimit(rateLimit, target)\n if (baked === undefined) return []\n return [\n `// #508 — the limit the app declared, carried as a literal because a deployed entry has no`,\n `// theo.config.ts to read. The counter lives in this process, which outlives a request here.`,\n `const RATE_LIMIT = createRateLimiterWeb({ windowMs: ${baked.windowMs}, max: ${baked.max} })`,\n ``,\n `/**`,\n ` * The caller's address, from the connection rather than from a header.`,\n ` *`,\n ` * A header a client can set is a key a client can choose, which makes the bucket theirs to`,\n ` * split. An unresolved address falls back to one shared bucket — rare here, since that only`,\n ` * happens for a connection already gone, and the same fallback \\`theokit start\\` uses.`,\n ` */`,\n `function callerAddress(request, server) {`,\n ` return ${addressExpression} ?? 'unknown'`,\n `}`,\n ``,\n `/** The 429 a limited caller gets, carrying the limiter's own headers. */`,\n `function rateLimited(result) {`,\n ` return new Response(JSON.stringify({ error: { code: 'RATE_LIMITED', message: 'Too many requests' } }), {`,\n ` status: 429,`,\n ` headers: { 'Content-Type': 'application/json', ...result.headers },`,\n ` })`,\n `}`,\n ]\n}\n\n/**\n * The check itself, as generated source, placed inside the runtime's request handler.\n *\n * Extracted for the reason `bun.ts` extracts its other fragments: the emitter is one array literal,\n * so every line the entry gains counts against `max-lines-per-function`, and this one pushed it\n * past the ceiling.\n *\n * Runs AFTER the CORS preflight and BEFORE routing: a limited caller should not reach a handler,\n * and a browser still needs its CORS answer to read the 429 as a 429 rather than as a network\n * failure.\n */\nexport function rateLimitCheckFragment(\n rateLimit: RateLimitConfig | undefined,\n indent: string,\n): string[] {\n if (rateLimit === undefined) return []\n return [\n `${indent}const limit = RATE_LIMIT(callerAddress(request, server))`,\n `${indent}if (limit.limited) {`,\n `${indent} return withCors(request, withSecurityHeaders(rateLimited(limit), SECURITY_HEADERS))`,\n `${indent}}`,\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;;;AC6CjB,IAAM,+BAAN,cAA2C,MAAM;AAAA,EAEtD,YACW,QACA,QACT,MACA;AACA;AAAA,MACE;AAAA,QACE,2BAA2B,MAAM;AAAA,QACjC;AAAA,QACA,KAAK,MAAM;AAAA,QACX;AAAA,QACA;AAAA,QACA,GAAG,KAAK,IAAI,CAAC,MAAM,cAAS,CAAC,EAAE;AAAA,QAC/B;AAAA,QACA;AAAA,QACA;AAAA,MACF,EAA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","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/webhook/timing-safe-equal.ts","../src/server/webhook/raw-body.ts","../src/server/webhook/define-webhook.ts","../src/server/webhook/providers/stripe.ts","../src/server/webhook/providers/hmac-sha256.ts","../src/server/webhook/providers/hub-signature-256.ts","../src/server/webhook/providers/github.ts","../src/server/webhook/providers/slack.ts","../src/server/webhook/providers/telegram.ts","../src/server/webhook/providers/discord.ts","../src/server/webhook/providers/whatsapp.ts","../src/server/webhook/providers/line.ts"],"mappings":";;;;;;;;;AAqBA,IAAI;AAEJ,SAAS,kBAA8C;AACrD,MAAI,mBAAmB,OAAW,QAAO;AACzC,MAAI;AAIF,UAAM,YAAY,UAAQ,aAAa;AAGvC,qBAAiB,UAAU,mBAAmB;AAAA,EAChD,QAAQ;AACN,qBAAiB;AAAA,EACnB;AACA,SAAO;AACT;AAQO,SAAS,gBAAgB,GAAe,GAAwB;AACrE,MAAI,EAAE,aAAa,eAAe,EAAE,aAAa,aAAa;AAC5D,UAAM,IAAI;AAAA,MACR,qDAAqD,OAAO,CAAC,QAAQ,OAAO,CAAC;AAAA,IAC/E;AAAA,EACF;AAEA,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,MAAI,EAAE,WAAW,EAAG,QAAO;AAK3B,QAAM,WAAW,gBAAgB;AACjC,MAAI,SAAU,QAAO,SAAS,GAAG,CAAC;AAKlC,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AACjC,YAAQ,EAAE,CAAC,IAAI,EAAE,CAAC;AAAA,EACpB;AACA,SAAO,SAAS;AAClB;;;AClDO,IAAM,yBAAyB;AAmB/B,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAI3C,YACkB,OACA,YAChB;AACA,UAAM,2CAA2C,UAAU,iBAAiB,KAAK,QAAQ;AAHzE;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAAA,EACA;AAAA,EALT,SAAS;AAAA,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ed-runtime-config.ts","../src/adapters/deployed-trace.ts","../src/adapters/security-headers.ts"],"sourcesContent":["/**\n * The CORS configuration a deployed entry carries, baked at build time.\n *\n * ## The defect this closes\n *\n * `security.cors` reached exactly one consumer: Vite's `configureServer` hook. So an app that\n * worked cross-origin under `theokit dev` stopped working the moment anything else served it —\n * `theokit start` (fixed separately) and all six Web deploy targets (usetheokit/theokit#409). Same\n * config, same code, no error and no warning; the failure surfaces in a browser as a blocked fetch\n * on the deployed URL, three layers from the key that had quietly stopped being read.\n *\n * The pure half was written twice and called once: `createCorsWebHandler` — the Web mirror — had no\n * caller anywhere in the repository. Nothing here reimplements it.\n *\n * ## A callback origin is REFUSED, not silently dropped\n *\n * `corsSchema.origins` accepts `z.function(...)` alongside the string / RegExp / array shapes. A\n * deployed function has no `theo.config.ts` to read, and there is no literal for a closure — so a\n * build that baked only the serialisable shapes would produce an app whose CORS silently allowed\n * nothing, which is the exact class of failure this issue reports.\n *\n * `rules/three-target-parity.md` § 3 is explicit about the alternative: \"a target that cannot serve\n * a capability refuses by name. Silent degradation is the failure mode this rule exists to\n * prevent.\" So the build throws, naming the target, the key and the two ways forward.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype CorsConfig = NonNullable<NonNullable<TheoConfig['security']>['cors']>\n\n/**\n * The CORS slice of an adapter's build options.\n *\n * Narrow and named once, matching how `securityHeaders` and `DeployedCsrfOptions` already reach the\n * emitters: each renderer receives what it uses, and six signatures name one type instead of six\n * inline shapes that can drift.\n */\nexport interface DeployedCorsOptions {\n cors?: CorsConfig\n}\n\n/**\n * Thrown at BUILD time when the declared CORS cannot be carried to a deployed target.\n *\n * A build error is the point: the alternative is a deploy that looks configured and refuses every\n * cross-origin request, discovered by a browser rather than by the build.\n */\nexport class UnserializableCorsOriginError extends Error {\n constructor(target: string) {\n super(\n `security.cors.origins is a function, and the \\`${target}\\` target cannot carry it: a deployed ` +\n `function has no theo.config.ts to read, and a callback cannot be written into the emitted ` +\n `entry. Replace it with the origin, a RegExp, or an array of either — all of which travel — ` +\n `or build for \\`node\\` and run \\`theokit start\\`, which evaluates the callback at runtime.`,\n )\n this.name = 'UnserializableCorsOriginError'\n }\n}\n\n/** Source text for one origin matcher: a RegExp as a literal, anything else as JSON. */\nfunction renderOrigin(origin: unknown, target: string): string {\n if (typeof origin === 'function') throw new UnserializableCorsOriginError(target)\n if (origin instanceof RegExp) return String(origin)\n if (Array.isArray(origin)) return `[${origin.map((o) => renderOrigin(o, target)).join(', ')}]`\n return JSON.stringify(origin)\n}\n\n/**\n * Source text for the CORS config, or `undefined` when the app declared none.\n *\n * RegExp entries are emitted as regex literals for the reason `deployed-csrf.ts` gives at length:\n * `JSON.stringify` renders a RegExp as `{}`, and `matchesOrigin` checks `instanceof RegExp`, so a\n * JSON-rendered origin would sit in the emitted file looking configured and matching nothing.\n *\n * @throws UnserializableCorsOriginError when `origins` is a callback\n */\nexport function renderDeployedCorsLiteral(cors: CorsConfig | undefined, target: string): string {\n if (cors === undefined) return 'undefined'\n\n const parts = [`origins: ${renderOrigin(cors.origins, target)}`]\n if (cors.methods !== undefined) parts.push(`methods: ${JSON.stringify(cors.methods)}`)\n if (cors.allowedHeaders !== undefined)\n parts.push(`allowedHeaders: ${JSON.stringify(cors.allowedHeaders)}`)\n if (cors.exposedHeaders !== undefined)\n parts.push(`exposedHeaders: ${JSON.stringify(cors.exposedHeaders)}`)\n // Both carry schema defaults, so they are always present and always emitted — unlike the\n // optional fields above, whose absence is a real answer the handler already has one for.\n parts.push(\n `credentials: ${JSON.stringify(cors.credentials)}`,\n `maxAge: ${JSON.stringify(cors.maxAge)}`,\n )\n\n return `{ ${parts.join(', ')} }`\n}\n\n/**\n * The lines that declare the CORS handler in a generated entry.\n *\n * `null` when nothing was declared, which is what \"no cors block\" meant before and still means: no\n * headers, not permissive ones.\n */\nexport function deployedCorsFragment(cors: CorsConfig | undefined, target: string): string[] {\n return [\n `// #409 — the CORS the app declared, carried as a literal because a deployed function has no`,\n `// theo.config.ts to read. \\`null\\` when the app declared none: no headers, not permissive ones.`,\n `const CORS_CONFIG = ${renderDeployedCorsLiteral(cors, target)}`,\n `const CORS_HANDLER = CORS_CONFIG === undefined ? null : createCorsWebHandler(CORS_CONFIG)`,\n ``,\n `/** Answer a preflight before routing — an OPTIONS the router handles never gets a CORS answer. */`,\n `function corsPreflight(request) {`,\n ` return CORS_HANDLER === null ? null : CORS_HANDLER.handlePreflightRequest(request)`,\n `}`,\n ``,\n `/** Put the headers on whatever the app answered, including its 404s — a browser reads a 404`,\n ` * without them as a CORS failure rather than as the 404 it is. */`,\n `function withCors(request, response) {`,\n ` if (CORS_HANDLER !== null) CORS_HANDLER.applyCorsHeaders(request, response.headers)`,\n ` return response`,\n `}`,\n ]\n}\n","/**\n * The CSRF configuration a deployed entry carries, baked at build time.\n *\n * ## The defect this closes\n *\n * The six Web-standards adapter entries built `executeRoute`'s context from an eight-field\n * literal, and neither `csrfMode` nor `disallowed` was among the eight (usetheokit/theokit#410).\n * `executeRoute` defaults an absent mode to `'strict'`, so an app declaring\n * `security: { csrf: 'off' }` — or `'warn'` — got `'strict'` on every deploy target: a `POST` that\n * works under `theokit dev` and `theokit start` answers `403 CSRF_INVALID` on Vercel, naming a\n * mechanism the operator had switched off. The config still validated and the build still\n * succeeded; the behaviour simply changed.\n *\n * The deployed function has no `theo.config.ts` to read, which is why the value is carried as a\n * literal — the same shape `security.headers` already uses (`renderSecurityHeadersConfigLiteral`).\n *\n * ## Why this is not `JSON.stringify`\n *\n * `disallowed.routes` accepts RegExp entries (`config/schemas/security.ts`), and `JSON.stringify`\n * renders a RegExp as `{}`. That is not a formatting problem: `matchDisallowed` checks\n * `p instanceof RegExp`, so a `{}` matches nothing while reading, in the emitted file, as a rule\n * that is present and configured. Reaching for JSON here would reproduce this issue's own defect —\n * configuration that survives validation and quietly stops applying — one layer further down.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype SecurityConfig = NonNullable<TheoConfig['security']>\n\n/**\n * The two slices of `security` that reach `executeRoute`'s context.\n *\n * Narrow rather than the whole block, matching how `securityHeaders` is already passed: each\n * renderer receives what it uses and nothing else, so a headers change cannot reach the CSRF\n * literal and vice versa.\n */\nexport interface DeployedCsrfOptions {\n csrf?: SecurityConfig['csrf']\n disallowed?: SecurityConfig['disallowed']\n}\n\n/**\n * Source text for one route pattern.\n *\n * A RegExp is emitted as a regex literal so it arrives as a RegExp; a string goes through\n * `JSON.stringify`, which is the correct escaper for a JS string literal (quotes, backslashes,\n * control characters, line separators).\n */\nfunction renderRoutePattern(pattern: string | RegExp): string {\n return pattern instanceof RegExp ? String(pattern) : JSON.stringify(pattern)\n}\n\n/**\n * Source text for the CSRF slice of `executeRoute`'s context.\n *\n * Absent values are OMITTED rather than defaulted. `executeRoute` already defaults an absent\n * `csrfMode` to `'strict'`, and writing `'strict'` here would put that default in a second place\n * where the two can disagree — which is the class of drift the whole issue is about.\n *\n * @param security - the declared csrf slices, or `undefined` when the app declared no security block\n */\nexport function renderDeployedCsrfLiteral(security: DeployedCsrfOptions | undefined): string {\n if (security === undefined) return '{}'\n\n const parts: string[] = []\n if (security.csrf !== undefined) parts.push(`csrfMode: ${JSON.stringify(security.csrf)}`)\n\n const { disallowed } = security\n if (disallowed !== undefined) {\n const routes = disallowed.routes.map(renderRoutePattern).join(', ')\n parts.push(\n `disallowed: { routes: [${routes}], behavior: ${JSON.stringify(disallowed.behavior)} }`,\n )\n }\n\n // `{}` and not `{ }` when nothing was declared: the emitted file is read by people, and the\n // two-space version reads as though something was meant to be there.\n return parts.length === 0 ? '{}' : `{ ${parts.join(', ')} }`\n}\n\n/**\n * The lines that declare `CSRF_CONFIG` in a generated entry.\n *\n * One function rather than the same six lines pasted into each of the six adapters: that\n * duplication is how the eight-field context literal came to be wrong in six places at once, and\n * repeating the fix in the same shape would leave the next field with the same six places to be\n * forgotten in. It also keeps the two largest emitters under the `max-lines-per-function` ceiling,\n * which `vercel.ts` already extracts fragments to respect.\n *\n * @param opts - the declared csrf slices, passed straight through from the adapter's build options\n * @param home - what the target has instead of a config file, for the comment's second sentence\n */\nexport function deployedCsrfFragment(\n opts: DeployedCsrfOptions,\n home = 'a deployed function',\n): string[] {\n return [\n `// #410 — the CSRF mode and per-route escalation the app declared. Carried as a`,\n `// literal for the same reason as the headers above: ${home} has no theo.config.ts`,\n `// to read. Absent keys stay absent so executeRoute's own default ('strict') applies,`,\n `// rather than this file becoming a second place it can drift.`,\n `const CSRF_CONFIG = ${renderDeployedCsrfLiteral(opts)}`,\n ]\n}\n","/**\n * The configuration a deployed entry could not apply (usetheokit/theokit#425).\n *\n * ## Why this is not another literal renderer\n *\n * `deployed-csrf.ts` and `deployed-cors.ts` bake their values into the emitted source, which works\n * because `csrf` is an enum and `disallowed` is a `{ routes, behavior }` object — plain data, and a\n * deployed function has no `theo.config.ts` to read.\n *\n * The two concerns left over from #410 turn out to be different from each other, and the difference\n * is the whole design:\n *\n * - **`serialization` is plain data too.** The config field is `z.enum(['json', 'superjson'])`\n * (`config/schema.ts:147`) — a selector, not a transformer. `resolveTransformer` turns it into the\n * functions, and it already ships from `theokit/server`. So this half is a literal like the rest,\n * and the deployed entry resolves it exactly the way `theokit start` does\n * (`cli/commands/start/index.ts:108`), from the same string, through the same function.\n * - **`plugins` genuinely carries functions.** A plugin is constructed in `theo.config.ts` and there\n * is no literal for a closure, so this half needs the entry to import a module instead.\n *\n * ## Static import, not `import()` in the request path\n *\n * The tempting shortcut is `await import('../../theo.config.js')` inside the handler. It trades a\n * silent failure for a louder one on targets with no filesystem, and it moves configuration\n * resolution into every request on the targets that do have one.\n *\n * What this emits instead is a TOP-LEVEL import of a module the build already resolved and wrote\n * beside the entry — the same shape `renderBakedRoutes` uses for route modules (#369): decide on\n * the build machine, emit a static specifier. It is evaluated once at module load, the target's\n * bundler can see through it, and a plugin that needs an API the target lacks fails the build\n * rather than the first request.\n *\n * ## Why each half is optional\n *\n * An app that declares neither concern must produce the entry it produced before this existed.\n * Importing a module the build did not emit fails at load, and spreading an empty object costs an\n * allocation per request for nothing. So an empty request renders to nothing at all, and the\n * caller's `executeRoute` literal is unchanged.\n *\n * The halves are independent on purpose: an app that only picks `superjson` must not be made to\n * carry a plugins module, and an app with plugins and default JSON must not gain a transformer\n * lookup. Coupling them would have made the common case pay for the rare one.\n */\n\n/**\n * The option every Web-standards adapter grows to carry non-serialisable configuration.\n *\n * Composed into each adapter's option type the way `DeployedCsrfOptions` already is, so the six\n * targets cannot drift into six spellings of the same field.\n */\nexport interface DeployedRuntimeConfigOptions {\n /**\n * Specifier of the plugins module the build wrote beside the entry, or `undefined` when the app\n * declares no plugins and the build wrote none.\n */\n runtimeConfigModule?: string\n /**\n * The app's `serialization` selector, carried as a literal.\n *\n * `'json'` and `undefined` both mean the default, and neither emits anything: `executeRoute`\n * already falls back to `JSON.stringify`, and the `x-theo-transformer` header is deliberately\n * absent for the default so a client is told only when there is something to be told.\n */\n serialization?: 'json' | 'superjson'\n}\n\n/** The three places an entry has to grow to carry non-serialisable configuration. */\nexport interface DeployedRuntimeConfigFragment {\n /** Top-level imports. Empty when the build emitted no config module. */\n readonly imports: string[]\n /** Module-scope declarations — evaluated once, at load. Empty when there is nothing to carry. */\n readonly declarations: string[]\n /**\n * Spread into the entry's `executeRoute({ … })` literal, inside an async function.\n *\n * Empty string when there is nothing to carry, so the call site keeps the exact shape it had.\n */\n readonly executeRouteSpread: string\n}\n\nconst EMPTY: DeployedRuntimeConfigFragment = {\n imports: [],\n declarations: [],\n executeRouteSpread: '',\n}\n\n/**\n * What a deployed entry needs in order to apply `config.plugins` and `config.serialization`.\n *\n * @param moduleSpecifier - specifier of the runtime-config module the build emitted beside the\n * entry, or `undefined` when the app declared neither concern and the build emitted none.\n */\nexport function deployedRuntimeConfigFragment(\n options: DeployedRuntimeConfigOptions | undefined,\n): DeployedRuntimeConfigFragment {\n const pluginsModule = options?.runtimeConfigModule\n // 'json' is the default and emits nothing — see `serialization` above.\n const serialization = options?.serialization === 'superjson' ? 'superjson' : undefined\n if (pluginsModule === undefined && serialization === undefined) return EMPTY\n\n const imports: string[] = []\n const declarations: string[] = []\n const spread: string[] = []\n\n if (pluginsModule !== undefined) {\n imports.push(\n `import { createPluginRunnerFromConfig } from 'theokit/server'`,\n `// #425 — the app's own plugins, resolved on the build machine and written beside this entry.`,\n `// A closure has no literal, so this is an import rather than a baked value.`,\n `import theoRuntimeConfig from '${pluginsModule}'`,\n )\n declarations.push(\n `// Built ONCE, at module load. A runner rebuilt per request would re-run every plugin's`,\n `// \\`register\\`, which is where a plugin allocates the state its hooks then read.`,\n `const THEO_PLUGIN_RUNNER = createPluginRunnerFromConfig(theoRuntimeConfig.plugins)`,\n )\n // Awaited, not passed along: `createPluginRunnerFromConfig` is async because `register` is, and\n // a pending promise handed to `executeRoute` is a truthy object with none of the runner's\n // methods — every hook would silently not fire, which is this issue's own defect one layer in.\n spread.push(`pluginRunner: await THEO_PLUGIN_RUNNER`)\n }\n\n if (serialization !== undefined) {\n imports.push(`import { resolveTransformer } from 'theokit/server'`)\n declarations.push(\n `// #425 — a literal, because \\`config.serialization\\` is a SELECTOR and not a transformer.`,\n `// Same string, same function \\`theokit start\\` calls, so the deployed response and the local`,\n `// one cannot disagree about what the app asked for — including the \\`x-theo-transformer\\``,\n `// header, whose absence is what made this a data bug rather than a formatting one.`,\n `const THEO_TRANSFORMER = resolveTransformer('${serialization}')`,\n )\n spread.push(`transformer: THEO_TRANSFORMER`)\n }\n\n return { imports, declarations, executeRouteSpread: `${spread.join(', ')},` }\n}\n","/**\n * The request id a deployed entry uses, and the header it echoes back.\n *\n * ## The defect this closes\n *\n * Every generated entry minted a fresh `randomUUID()` per request and set no correlation header\n * at all on a success path (usetheokit/theokit#410). Both Node paths do the opposite: they resolve\n * an incoming `traceparent` / `x-request-id` through `extractTraceId` and echo the result under\n * both `x-request-id` and `x-trace-id` (`cli/commands/start/request-handler.ts`,\n * `vite-plugin/api-middleware.ts`).\n *\n * The consequence is that a trace crossing into a deployed function starts over. The caller's id\n * is discarded, and the response carries nothing to correlate against — so a request that fails in\n * production cannot be tied to the client that made it, which is the one situation the id exists\n * for.\n *\n * ## Why `setHeader` before the handler, rather than wrapping the response\n *\n * It is what the Node path does, and the shim reproduces Node's semantics exactly: `writeHead`\n * MERGES into the header map rather than replacing it (`web-shim.ts`), so a header set here\n * survives the handler's own `writeHead` and a handler that sets its own id still wins. Wrapping\n * the finished `Response` instead would have to mutate a response whose body is already streaming\n * (#382), and would miss the branches that return before the shim is built.\n */\n\n/**\n * Lines that resolve the request id and echo it, as generated source.\n *\n * @param requestVar - the name the entry gave the Web `Request` in scope\n * @param indent - leading whitespace, so the emitted file stays readable\n */\nexport function deployedTraceFragment(requestVar: string, indent: string): string[] {\n return [\n `${indent}// #410 — honour the caller's trace id instead of minting a new one, and echo it.`,\n `${indent}// \\`extractTraceIdFromRequest\\` validates the caller-controlled \\`x-request-id\\``,\n `${indent}// before trusting it, and falls back to a fresh UUID when neither header is present.`,\n `${indent}const requestId = extractTraceIdFromRequest(${requestVar})`,\n `${indent}res.setHeader('x-request-id', requestId)`,\n `${indent}res.setHeader(TRACE_HEADER, requestId)`,\n ]\n}\n","/**\n * The security headers a deployed target puts on its responses.\n *\n * `theokit start` applies the configured baseline to every response it writes\n * (`cli/commands/start/request-handler.ts`). None of the six Web-standards\n * deploy adapters applied any, so the same page carried a CSP,\n * `X-Frame-Options`, HSTS and `nosniff` under `theokit start` and none of them\n * once deployed (usetheokit/theokit#410, GHSA-87qq-fgcr-384x).\n *\n * This module is the seam that closes that half of the gap. It has two halves\n * and they live together on purpose: the code that writes the literal into a\n * generated entry and the code that reads it at request time have to agree on\n * one shape, and a shape stated in two files drifts.\n *\n * - **Build time** — {@link renderSecurityHeadersConfigLiteral} turns\n * `security.headers` into a JSON literal the adapter inlines. A deployed\n * runtime has no `theo.config.ts` to read, so the configuration travels as\n * data.\n * - **Request time** — the generated entry calls {@link buildSecurityHeaders}\n * on that literal and hands every response to {@link withSecurityHeaders}.\n * The same function `theokit start` calls, on the same input, so the two\n * cannot disagree about what the configuration means.\n *\n * ## The per-request nonce, and where it stops\n *\n * `buildSecurityHeaders` accepts a per-request `nonce` and substitutes it into\n * `script-src`. A nonce cannot survive a build-time literal — it is minted per\n * response — so a target reaches one only if it renders the HTML at request\n * time and can put the same value on the script tags it emits.\n *\n * Exactly one deploy path does: **Cloudflare with `ssrStreaming: true`**, whose\n * worker calls `renderStreamingWeb(request, { nonce })`, and that renderer\n * threads the value into `renderToReadableStream` and into the hydration script\n * (`router/entry-server.ts`). That branch mints a nonce per request and builds\n * its CSP from it. Everything else serves HTML written at build time, or no\n * HTML at all, and carries a **nonce-less CSP** — the same answer\n * `buildSecurityHeaders` already gives a prerendered route (EC-4), for the same\n * reason: a nonce in the header with no nonce on the tag blocks every inline\n * script.\n *\n * That asymmetry is real and is not smoothed over. It is stated in the emitted\n * entry, printed by the build through\n * {@link describeDeployedSecurityHeaders}, and written down in\n * `docs/surfaces/build-adapters.md`.\n */\nimport { generateNonce } from '../core/contracts/nonce.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { buildSecurityHeaders } from '../core/contracts/security-headers.js'\n\n/**\n * Re-exported so a generated entry has ONE import for the whole concern.\n *\n * Reaching it through `theokit/server/security` would work and would also drag\n * that barrel's CSRF surface into a Worker bundle, for a function that is forty\n * lines of string concatenation. It is defined in `core/contracts/`, which is\n * the module every target may import from — `adapters → server` is not an edge\n * in the DAG, and the header policy was never server code.\n */\nexport { buildSecurityHeaders }\n\n/**\n * Re-exported for the same reason, and so the streamed Cloudflare worker mints\n * its nonce with the identical primitive `theokit start` uses\n * (`cli/commands/start/request-handler.ts`) rather than a second, hand-rolled\n * one. It is already runtime-portable: Web Crypto first, with a named error\n * when the runtime has none.\n */\nexport { generateNonce }\n\n/**\n * The `security.headers` block, as a literal a generated entry can carry.\n *\n * `{}` when the app declares none — which is not the same as \"no headers\".\n * `buildSecurityHeaders({})` returns the full default baseline, and `{}` is\n * exactly what `theokit start` passes when `security.headers` is absent\n * (`cli/commands/start/index.ts`). An app with no security block gets the same\n * baseline deployed as it gets locally.\n */\nexport function renderSecurityHeadersConfigLiteral(\n headers: SecurityHeadersConfig | undefined,\n): string {\n return JSON.stringify(headers ?? {})\n}\n\n/**\n * Put the headers on a response, without overruling the handler.\n *\n * `theokit start` sets the baseline BEFORE the route handler runs, so a handler\n * can override it with `res.setHeader` (last write wins, Node convention). On a\n * Web target the response arrives already built, so the equivalent of \"the\n * handler wins\" is to skip a header the response already carries: a route that\n * set its own `Content-Security-Policy` keeps it.\n *\n * Mutates and returns the same `Response` rather than constructing a\n * replacement, because these responses are handed to the runtime while their\n * body is still being written (#382) and re-wrapping the stream is exactly the\n * second buffering point that change removed.\n *\n * Mutation is safe for every response these entries produce: the Fetch spec\n * gives a locally constructed `Response` the `response` header guard, which\n * permits `set` for every name used here. The `immutable` guard belongs to\n * responses that came back from `fetch()`, and none of the six emitted handlers\n * returns one — each builds its response from `createWebShim`, from a `new\n * Response(...)`, or from the SSR renderer. The WebSocket upgrade, which is the\n * one response an adapter gets from its runtime rather than building, is\n * deliberately not routed through here.\n */\nexport function withSecurityHeaders(response: Response, headers: Record<string, string>): Response {\n for (const [key, value] of Object.entries(headers)) {\n if (!response.headers.has(key)) response.headers.set(key, value)\n }\n return response\n}\n\nexport interface DeployedSecurityHeaderLimits {\n target: string\n /** The app's `security.headers` block, or undefined when it declares none. */\n securityHeaders: SecurityHeadersConfig | undefined\n /**\n * Does the emitted handler render HTML at request time and mint a CSP nonce\n * for it? True only for Cloudflare with `ssrStreaming: true`.\n */\n mintsNonce: boolean\n /**\n * Is the HTML document served by a platform static host rather than by the\n * handler this build emits? True wherever the emitted handler answers\n * `/api/*` and returns 404 for everything else.\n */\n /**\n * Who puts the security headers on the HTML DOCUMENT — a different question from who serves it,\n * and the two used to be collapsed into one boolean (usetheokit/theokit#412).\n *\n * - `handler` — this target's own handler returns the document, so it carries the same baseline\n * every API response carries. No caveat.\n * - `platform-configured` — the platform's static host serves the document, AND this build emits\n * the configuration that puts the headers on it (`.vercel/output/config.json`, `netlify.toml`).\n * Still worth stating, because nothing here has seen a deployed response.\n * - `platform-unmanaged` — the platform serves it and this build owns no artifact that could\n * configure it. This is the real remaining gap, and it stays named.\n *\n * The two-value version reported `platform-configured` targets with the same message as\n * `platform-unmanaged` ones, telling an operator to go and do work the build had already done —\n * and a stale limitation reads exactly like a current one.\n */\n documentHeaders: 'handler' | 'platform-configured' | 'platform-unmanaged'\n}\n\n/**\n * What the build tells the operator, once, per target.\n *\n * Silent degradation is the failure mode `rules/three-target-parity.md` exists\n * to prevent. Two things degrade quietly here and both are named rather than\n * discovered in production: a CSP that refuses inline scripts on a deploy while\n * allowing them locally, and an HTML document that never passes through the\n * handler these headers are attached to.\n *\n * The header names are read from the map the entry will actually carry, not\n * from a list written next to it. A configuration that switches HSTS or the CSP\n * off would otherwise be announced as sending them.\n */\nexport function describeDeployedSecurityHeaders(limits: DeployedSecurityHeaderLimits): string {\n const headers = buildSecurityHeaders(limits.securityHeaders ?? {}, { production: true })\n const names = Object.keys(headers)\n if (names.length === 0) {\n return ` ! \\`${limits.target}\\` sends no security headers: the configuration switched every one of them off.`\n }\n\n const lines = [\n ` ✓ security headers on every response \\`${limits.target}\\` returns: ${names.join(', ')}.`,\n ]\n const sendsCsp = names.some((name) => name.startsWith('Content-Security-Policy'))\n if (sendsCsp && !limits.mintsNonce) {\n lines.push(\n ` - The CSP carries no nonce: this target serves HTML written at build time,`,\n ` so there is no per-request value to put on a script tag. An inline`,\n ` <script> is refused by \\`script-src 'self'\\` here, while the same page`,\n ` under \\`theokit start\\` gets a nonce and runs it. Move inline scripts to`,\n ` \\`<script src=\"...\">\\`, or set \\`security.headers.cspMode: 'report-only'\\``,\n ` while you migrate.`,\n )\n }\n if (limits.documentHeaders === 'platform-configured') {\n lines.push(\n ` - The HTML document is served by the platform's static host, and reaches`,\n ` the browser with these headers through config this build emits. That`,\n ` path is not verified by a deploy from here — the values come from the`,\n ` same function the handler uses, but no response has been read back.`,\n )\n }\n if (limits.documentHeaders === 'platform-unmanaged') {\n lines.push(\n ` - The HTML document does NOT pass through this handler — the platform's`,\n ` static host serves it — so these headers reach \\`/api/*\\` responses and`,\n ` not the page. This build emits no artifact that could configure it, so`,\n ` set the document's headers on the platform (usetheokit/theokit#412).`,\n )\n }\n return lines.join('\\n')\n}\n"],"mappings":";;;;;;;AA8CO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,YAAY,QAAgB;AAC1B;AAAA,MACE,kDAAkD,MAAM;AAAA,IAI1D;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAGA,SAAS,aAAa,QAAiB,QAAwB;AAC7D,MAAI,OAAO,WAAW,WAAY,OAAM,IAAI,8BAA8B,MAAM;AAChF,MAAI,kBAAkB,OAAQ,QAAO,OAAO,MAAM;AAClD,MAAI,MAAM,QAAQ,MAAM,EAAG,QAAO,IAAI,OAAO,IAAI,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,EAAE,KAAK,IAAI,CAAC;AAC3F,SAAO,KAAK,UAAU,MAAM;AAC9B;AAWO,SAAS,0BAA0B,MAA8B,QAAwB;AAC9F,MAAI,SAAS,OAAW,QAAO;AAE/B,QAAM,QAAQ,CAAC,YAAY,aAAa,KAAK,SAAS,MAAM,CAAC,EAAE;AAC/D,MAAI,KAAK,YAAY,OAAW,OAAM,KAAK,YAAY,KAAK,UAAU,KAAK,OAAO,CAAC,EAAE;AACrF,MAAI,KAAK,mBAAmB;AAC1B,UAAM,KAAK,mBAAmB,KAAK,UAAU,KAAK,cAAc,CAAC,EAAE;AACrE,MAAI,KAAK,mBAAmB;AAC1B,UAAM,KAAK,mBAAmB,KAAK,UAAU,KAAK,cAAc,CAAC,EAAE;AAGrE,QAAM;AAAA,IACJ,gBAAgB,KAAK,UAAU,KAAK,WAAW,CAAC;AAAA,IAChD,WAAW,KAAK,UAAU,KAAK,MAAM,CAAC;AAAA,EACxC;AAEA,SAAO,KAAK,MAAM,KAAK,IAAI,CAAC;AAC9B;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AyB,CAAC;AAChF,MAAI,YAAY,CAAC,OAAO,YAAY;AAClC,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,OAAO,oBAAoB,uBAAuB;AACpD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,OAAO,oBAAoB,sBAAsB;AACnD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/cloudflare.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Cloudflare deploy adapter. All write paths are under `cwd/.theokit/cloudflare/`\n * and `cwd/wrangler.toml`. 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 { findRootDiv } from '../core/contracts/find-root-div.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 { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport {\n deployedRuntimeConfigFragment,\n type DeployedRuntimeConfigOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport {\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} 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 */\nfunction readDocumentShell(\n cwd: string,\n streaming: boolean,\n): { htmlHead?: string; htmlTail?: string } {\n if (!streaming) return {}\n\n const indexPath = resolve(cwd, '.theokit/client/index.html')\n if (!existsSync(indexPath)) {\n throw new Error(\n `[adapter-cloudflare] ssrStreaming is on but ${indexPath} does not exist, so the worker ` +\n `would serve a document with no <head> and no client entry. Run the client build first, ` +\n `or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n const indexHtml = readFileSync(indexPath, 'utf-8')\n const rootDiv = findRootDiv(indexHtml)\n if (rootDiv === undefined) {\n throw new Error(\n `[adapter-cloudflare] ${indexPath} has no <div id=\"root\">, so the streamed document has ` +\n `nowhere to put the app. Add one, or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n return {\n htmlHead: indexHtml.slice(0, rootDiv.insertAt),\n htmlTail: indexHtml.slice(rootDiv.insertAt),\n }\n}\n\n/**\n * The routes, turned into source: static imports, a module map and a literal table (#369).\n *\n * Extracted so the worker renderer stays inside its length budget, and because this is the whole of\n * what changed about how a Worker finds a route — it reads as one idea rather than as three loops\n * inside a hundred lines of template.\n *\n * `../../` because the worker is written to `.theokit/cloudflare/worker.mjs` and `filePath` is\n * relative to the project root. The imports are static so Wrangler's bundler follows them:\n * `wrangler.toml` uploads `.theokit/client` and has never uploaded `server/`, so a module not\n * bundled INTO the worker is not on the platform at all.\n */\nfunction renderBakedRoutes(\n routes: readonly { filePath: string; routePath: string; methods?: readonly string[] }[],\n): { routeImports: string[]; routeModuleEntries: string[]; routeTableEntries: string[] } {\n const routeVar = (index: number): string => `__theoRoute${String(index)}`\n return {\n routeImports: routes.map(\n (route, index) => `import * as ${routeVar(index)} from '../../${route.filePath}'`,\n ),\n routeModuleEntries: routes.map(\n (route, index) => ` ${JSON.stringify(route.filePath)}: ${routeVar(index)},`,\n ),\n routeTableEntries: routes.map(\n (route) =>\n ` { filePath: ${JSON.stringify(route.filePath)}, routePath: ${JSON.stringify(route.routePath)}, ` +\n `methods: ${JSON.stringify([...(route.methods ?? [])])}, ` +\n `...compilePattern(${JSON.stringify(route.routePath)}) },`,\n ),\n }\n}\n\n/**\n * The route-resolution runtime the Worker gets instead of a directory scan (#369).\n *\n * A module map, the literal table, and a loader that refuses anything the build did not bake.\n * Emitted as its own block because it replaces one idea — \"find the routes\" — wholesale.\n */\nfunction routeRuntimeLines(moduleEntries: string[], tableEntries: string[]): string[] {\n return [\n `// #369 — the routes are baked at build time. The Worker used to reach for`,\n `// \\`scanServerRoutes\\` on the server directory — a readdirSync, in a runtime with no`,\n `// filesystem. The pattern is recompiled here from the same routePath the scanner`,\n `// used, so one function decides precedence on every target.`,\n `const ROUTE_MODULES = {`,\n ...moduleEntries,\n `}`,\n ``,\n `const routes = [`,\n ...tableEntries,\n `]`,\n ``,\n `// The executor asks for a module by the path the table names. Anything else was`,\n `// never bundled, and saying so beats returning undefined and failing later on a`,\n `// property access far from the cause.`,\n `async function loadModule(path) {`,\n ` const mod = ROUTE_MODULES[path]`,\n ` if (mod === undefined) {`,\n // No backticks in this message: it is emitted INTO a template literal, and a stray one closes\n // it. That is how #344 shipped a SyntaxError, and the emitted-entry parse gate caught this one\n // before it left the branch.\n \" throw new Error(`Route module '\" +\n '${path}' +\n \"' was not bundled into this Worker. \" +\n 'A Worker has no filesystem, so every route is imported at build time. ' +\n 'Re-run: theokit build --target cloudflare`)',\n ` }`,\n ` return mod`,\n `}`,\n ``,\n ]\n}\n\nexport function renderCloudflareWorkerEntry(\n opts: {\n ssrStreaming?: boolean\n htmlHead?: string\n htmlTail?: 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 /** WebSocket route files, scanned on the build machine. Only their presence is used (#369). */\n wsRoutes?: readonly string[]\n } & DeployedCsrfOptions &\n DeployedCorsOptions = {},\n): string {\n const streamingImport = opts.ssrStreaming\n ? `import { renderStreamingWeb } from '/@theo/entry-server'`\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 const nonApiBranch = opts.ssrStreaming\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 ` htmlHead: ${JSON.stringify(opts.htmlHead ?? '')},`,\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 // 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 ? undefined : { kind: 'baked', agents: opts.agents },\n { wrapSecurityHeaders: true },\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 `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\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 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 = 'server'`,\n ``,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries),\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 `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\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 ),\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): string[] {\n return [\n `async function handleRequest(request, url, env) {`,\n ` if (!url.pathname.startsWith('/api/')) {`,\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 `export default {`,\n ` async fetch(request, env, ctx) {`,\n ` const url = new URL(request.url)`,\n ``,\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 ` // #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 ``,\n ` return withCors(request, await handleRequest(request, url, env))`,\n ` },`,\n `}`,\n ]\n}\n\nexport function renderWranglerToml(): 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 `# A client-routed app asks for /dashboard, which is no file. Without this the asset`,\n `# handler 404s a deep link and the SPA never boots.`,\n `not_found_handling = \"single-page-application\"`,\n ``,\n `# Environment variables are set via wrangler secret or dashboard`,\n `# Example: wrangler secret put DATABASE_URL`,\n ].join('\\n')\n}\n\nexport const cloudflareAdapter: DeployAdapter = {\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\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 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\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) ?? { routes: [], wsRoutes: [], agents: [] }\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 writeFileSync(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n\n writeFileSync(\n resolve(outputDir, 'worker.mjs'),\n renderCloudflareWorkerEntry({\n ssrStreaming: config.ssrStreaming,\n ...shell,\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 routes: scanned.routes,\n // #367 — a Worker has no filesystem, so its agents are decided here like its routes.\n agents: scanned.agents,\n wsRoutes: scanned.wsRoutes,\n }),\n )\n\n // 3. Emit wrangler.toml (with nodejs_compat enforced)\n writeFileSync(resolve(cwd, 'wrangler.toml'), renderWranglerToml())\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AAsCxB,SAAS,kBACP,KACA,WAC0C;AAC1C,MAAI,CAAC,UAAW,QAAO,CAAC;AAExB,QAAM,YAAY,QAAQ,KAAK,4BAA4B;AAC3D,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AA;AAAA;AAAA;AAAA,QAItB,qBAAqB,aAAa;AAAA,QAClC,QAAQ,QAAQ;AAAA;AAAA,QAEhB,QAAQ,QAAQ;AAAA,QAChB,UAAU,QAAQ;AAAA,MACpB,CAAC;AAAA,IACH;AAGA,kBAAc,QAAQ,KAAK,eAAe,GAAG,mBAAmB,CAAC;AAGjE,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/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 { 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 { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport {\n deployedRuntimeConfigFragment,\n type DeployedRuntimeConfigOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport {\n buildSecurityHeaders,\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } 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(): string[] {\n return [\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 ` 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(runtimeSpread: string): string[] {\n return [\n `async function routeRequest(nodeReq) {`,\n ` const url = new URL(nodeReq.url ?? '/', 'http://' + (nodeReq.headers?.host ?? 'localhost'))`,\n ``,\n ` if (!url.pathname.startsWith('/api/')) {`,\n ` return new Response('Not Found', {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'text/plain; charset=utf-8' },`,\n ` })`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'application/json' },`,\n ` })`,\n ` }`,\n ``,\n ` // Convert Node-style req to Web Request 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 webRequest = new Request(url.toString(), { method, headers, body })`,\n ``,\n ` const { req, res, toResponse } = createWebShim(webRequest)`,\n ...deployedTraceFragment('webRequest', ' '),\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: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread}`,\n ` }))`,\n `}`,\n ]\n}\n\nexport function renderVercelFunctionEntry(\n opts: { securityHeaders?: SecurityHeadersConfig } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedCorsOptions = {},\n): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\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 { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `// Cold-start cache`,\n `let routesCache = null`,\n `let loaderCache = null`,\n `const serverDir = resolve(process.cwd(), 'server')`,\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 `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ``,\n ...runtimeConfig.imports,\n ...runtimeConfig.declarations,\n ...deployedCsrfFragment(opts),\n ``,\n ...deployedCorsFragment(opts.cors, '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(),\n ``,\n ...vercelRouteRequestFragment(runtimeConfig.executeRouteSpread),\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(securityHeaders?: SecurityHeadersConfig): {\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 { src: '/(.*)', dest: '/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\nexport const vercelAdapter: DeployAdapter = {\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\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\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 nodeAdapter.build(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 cpSync(clientDir, resolve(outputDir, 'static'), { recursive: true })\n }\n\n // 4. Emit serverless function entry (now uses shared web-shim)\n writeFileSync(\n resolve(outputDir, 'functions/api.func/index.mjs'),\n renderVercelFunctionEntry({\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 }),\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), 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 mintsNonce: false,\n documentHeaders: 'platform-configured',\n })}\\n`,\n )\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,eAAe,cAAc;AAC7D,SAAS,eAAe;AA8BxB,SAAS,wBAAkC;AACzC,SAAO;AAAA,IACL;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;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,EACF;AACF;AAKA,SAAS,2BAA2B,eAAiC;AACnE,SAAO;AAAA,IACL;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;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG,sBAAsB,cAAc,IAAI;AAAA,IAC3C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gFAAgF,aAAa;AAAA,IAC7F;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,0BACd,OAEwB,CAAC,GACjB;AACR,QAAM,gBAAg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