theokit 0.72.1 → 0.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +2 -0
  2. package/dist/{actions-virtual-module-OHENNMQG.js → actions-virtual-module-J2HYO7QZ.js} +4 -4
  3. package/dist/{actions-virtual-module-EAKYEMGF.js → actions-virtual-module-JV7URROJ.js} +7 -7
  4. package/dist/adapters/agent-mount.js +3 -3
  5. package/dist/adapters/security-headers.d.ts +27 -11
  6. package/dist/adapters/security-headers.js +9 -4
  7. package/dist/adapters/security-headers.js.map +1 -1
  8. package/dist/{agent-VJTZ4DQ7.js → agent-GU6JIEFJ.js} +3 -3
  9. package/dist/{app-typed-client-ILLQYTXP.js → app-typed-client-EOA3A2AR.js} +5 -5
  10. package/dist/{app-typed-client-ILLQYTXP.js.map → app-typed-client-EOA3A2AR.js.map} +1 -1
  11. package/dist/{app-typed-client-LHH77QDB.js → app-typed-client-XD4DZBV7.js} +8 -8
  12. package/dist/app-typed-client-XD4DZBV7.js.map +1 -0
  13. package/dist/{aws-lambda-7AZNJGWU.js → aws-lambda-ZYSPTD3O.js} +61 -27
  14. package/dist/aws-lambda-ZYSPTD3O.js.map +1 -0
  15. package/dist/{build-23QF5FNQ.js → build-6FVZKORI.js} +81 -74
  16. package/dist/build-6FVZKORI.js.map +1 -0
  17. package/dist/{bun-NKVHOFSJ.js → bun-I7YM3RDB.js} +82 -21
  18. package/dist/bun-I7YM3RDB.js.map +1 -0
  19. package/dist/{chunk-WBB3MEEN.js → chunk-2NG5T77O.js} +47 -12
  20. package/dist/{chunk-WBB3MEEN.js.map → chunk-2NG5T77O.js.map} +1 -1
  21. package/dist/{chunk-NO6HA4FG.js → chunk-4WP7A7RX.js} +41 -35
  22. package/dist/chunk-4WP7A7RX.js.map +1 -0
  23. package/dist/chunk-4X43VTST.js +31 -0
  24. package/dist/chunk-4X43VTST.js.map +1 -0
  25. package/dist/{chunk-FHQP23Z5.js → chunk-6R5F5YF2.js} +17 -14
  26. package/dist/chunk-6R5F5YF2.js.map +1 -0
  27. package/dist/chunk-72RSCKMW.js +53 -0
  28. package/dist/chunk-72RSCKMW.js.map +1 -0
  29. package/dist/{chunk-V5SSTT3C.js → chunk-C43AHOHI.js} +1 -1
  30. package/dist/chunk-C43AHOHI.js.map +1 -0
  31. package/dist/{chunk-C5CAL3DX.js → chunk-EQJF2EH5.js} +8 -7
  32. package/dist/chunk-EQJF2EH5.js.map +1 -0
  33. package/dist/{chunk-QD5X56I3.js → chunk-FNJVSFEC.js} +1 -1
  34. package/dist/chunk-FNJVSFEC.js.map +1 -0
  35. package/dist/{chunk-6U67SO5U.js → chunk-HK57MPSZ.js} +2 -2
  36. package/dist/{chunk-R7G2B2WH.js → chunk-HKF6YNY4.js} +17 -14
  37. package/dist/{chunk-R7G2B2WH.js.map → chunk-HKF6YNY4.js.map} +1 -1
  38. package/dist/chunk-IJQQNHL7.js +34 -0
  39. package/dist/chunk-IJQQNHL7.js.map +1 -0
  40. package/dist/{chunk-RE2WE7CD.js → chunk-LOOOB46A.js} +2 -2
  41. package/dist/{chunk-PEL3MJLM.js → chunk-MX63AWEK.js} +1 -1
  42. package/dist/{chunk-PEL3MJLM.js.map → chunk-MX63AWEK.js.map} +1 -1
  43. package/dist/chunk-NPQ5A3RU.js +53 -0
  44. package/dist/chunk-NPQ5A3RU.js.map +1 -0
  45. package/dist/{chunk-DKX7LF5Q.js → chunk-ODYLKWRT.js} +3 -3
  46. package/dist/{chunk-L6UHMWXU.js → chunk-QAS5SKZP.js} +3 -3
  47. package/dist/chunk-QAS5SKZP.js.map +1 -0
  48. package/dist/{chunk-4EQEJ4PH.js → chunk-RFZ263XP.js} +68 -23
  49. package/dist/chunk-RFZ263XP.js.map +1 -0
  50. package/dist/{chunk-XLSJWKSP.js → chunk-S5QN3O22.js} +66 -21
  51. package/dist/{chunk-XLSJWKSP.js.map → chunk-S5QN3O22.js.map} +1 -1
  52. package/dist/{chunk-E2RC367T.js → chunk-SHIXTMQE.js} +49 -14
  53. package/dist/{chunk-E2RC367T.js.map → chunk-SHIXTMQE.js.map} +1 -1
  54. package/dist/{chunk-G7U7FQVC.js → chunk-UFBBFP75.js} +13 -3
  55. package/dist/chunk-UFBBFP75.js.map +1 -0
  56. package/dist/{chunk-4CIHLTSI.js → chunk-V7ISZGNS.js} +45 -39
  57. package/dist/chunk-V7ISZGNS.js.map +1 -0
  58. package/dist/{chunk-RCFD5W5V.js → chunk-WR5B2XNT.js} +6 -6
  59. package/dist/chunk-WR5B2XNT.js.map +1 -0
  60. package/dist/{chunk-IB5VIXLR.js → chunk-XLFDYTWO.js} +2 -2
  61. package/dist/cli/index.js +8 -8
  62. package/dist/client/index.d.ts +18 -1
  63. package/dist/client/index.js +15 -1
  64. package/dist/client/index.js.map +1 -1
  65. package/dist/{cloudflare-4M4XVNUH.js → cloudflare-AMH4TJNL.js} +104 -82
  66. package/dist/cloudflare-AMH4TJNL.js.map +1 -0
  67. package/dist/{config-support-SB5NDQZB.js → config-support-MOZYHRWG.js} +13 -2
  68. package/dist/{config-support-SB5NDQZB.js.map → config-support-MOZYHRWG.js.map} +1 -1
  69. package/dist/{deno-deploy-IVACZ62D.js → deno-deploy-6H354VRA.js} +17 -7
  70. package/dist/deno-deploy-6H354VRA.js.map +1 -0
  71. package/dist/{dev-JDJWMRLH.js → dev-HJUD6X3R.js} +9 -9
  72. package/dist/{dev-emit-7KZFUA7M.js → dev-emit-T3X6RR7M.js} +5 -5
  73. package/dist/{dev-emit-7KZFUA7M.js.map → dev-emit-T3X6RR7M.js.map} +1 -1
  74. package/dist/{dev-emit-JPJJFBXL.js → dev-emit-ZK5GCHXN.js} +6 -6
  75. package/dist/dev-emit-ZK5GCHXN.js.map +1 -0
  76. package/dist/index.js +5 -5
  77. package/dist/{internal-api-VDYOXOT7.js → internal-api-GKPJYL3G.js} +7 -7
  78. package/dist/{internal-api-6XNLCNI5.js → internal-api-ZUBUYGCQ.js} +4 -4
  79. package/dist/{mcp-WJNCTM7M.js → mcp-MVKDWZEQ.js} +3 -3
  80. package/dist/{netlify-3HEWV375.js → netlify-ALPCTQFO.js} +158 -48
  81. package/dist/netlify-ALPCTQFO.js.map +1 -0
  82. package/dist/{node-QUGTW6XV.js → node-4HQO6KKZ.js} +2 -2
  83. package/dist/{observability-bootstrap-FP6LMMJE.js → observability-bootstrap-DOWRMADT.js} +2 -2
  84. package/dist/{openapi-Q53YOBIU.js → openapi-C4UX2SFV.js} +5 -5
  85. package/dist/openapi-C4UX2SFV.js.map +1 -0
  86. package/dist/{preview-BARW75PN.js → preview-5HUID27O.js} +3 -3
  87. package/dist/registry-OMLCP4AS.js +34 -0
  88. package/dist/registry-OMLCP4AS.js.map +1 -0
  89. package/dist/{routes-FDF4SLOB.js → routes-3PTNISSO.js} +2 -2
  90. package/dist/server/index.js +2 -2
  91. package/dist/server/scan/index.d.ts +38 -2
  92. package/dist/server/scan/index.js +2 -2
  93. package/dist/{server-boundary-AO6EELRF.js → server-boundary-QCJNECJP.js} +7 -7
  94. package/dist/{server-boundary-E5GFVPLB.js → server-boundary-RTRPHX5I.js} +4 -4
  95. package/dist/{start-4JTYXQQJ.js → start-EREUCSN6.js} +10 -10
  96. package/dist/{static-NQPLPAB6.js → static-7LP7LPGN.js} +2 -2
  97. package/dist/{vercel-5PMYEEKF.js → vercel-VLR52RXT.js} +173 -73
  98. package/dist/vercel-VLR52RXT.js.map +1 -0
  99. package/dist/vite-plugin/index.js +5 -5
  100. package/dist/{vite-plugin-3ON45MQE.js → vite-plugin-JVGI6QUO.js} +9 -9
  101. package/package.json +4 -4
  102. package/dist/app-typed-client-LHH77QDB.js.map +0 -1
  103. package/dist/aws-lambda-7AZNJGWU.js.map +0 -1
  104. package/dist/build-23QF5FNQ.js.map +0 -1
  105. package/dist/bun-NKVHOFSJ.js.map +0 -1
  106. package/dist/chunk-4CIHLTSI.js.map +0 -1
  107. package/dist/chunk-4EQEJ4PH.js.map +0 -1
  108. package/dist/chunk-C5CAL3DX.js.map +0 -1
  109. package/dist/chunk-FHQP23Z5.js.map +0 -1
  110. package/dist/chunk-G7U7FQVC.js.map +0 -1
  111. package/dist/chunk-L6UHMWXU.js.map +0 -1
  112. package/dist/chunk-NO6HA4FG.js.map +0 -1
  113. package/dist/chunk-QD5X56I3.js.map +0 -1
  114. package/dist/chunk-RCFD5W5V.js.map +0 -1
  115. package/dist/chunk-V5SSTT3C.js.map +0 -1
  116. package/dist/cloudflare-4M4XVNUH.js.map +0 -1
  117. package/dist/deno-deploy-IVACZ62D.js.map +0 -1
  118. package/dist/dev-emit-JPJJFBXL.js.map +0 -1
  119. package/dist/netlify-3HEWV375.js.map +0 -1
  120. package/dist/openapi-Q53YOBIU.js.map +0 -1
  121. package/dist/registry-SDBODRU6.js +0 -23
  122. package/dist/registry-SDBODRU6.js.map +0 -1
  123. package/dist/vercel-5PMYEEKF.js.map +0 -1
  124. /package/dist/{actions-virtual-module-OHENNMQG.js.map → actions-virtual-module-J2HYO7QZ.js.map} +0 -0
  125. /package/dist/{actions-virtual-module-EAKYEMGF.js.map → actions-virtual-module-JV7URROJ.js.map} +0 -0
  126. /package/dist/{agent-VJTZ4DQ7.js.map → agent-GU6JIEFJ.js.map} +0 -0
  127. /package/dist/{chunk-6U67SO5U.js.map → chunk-HK57MPSZ.js.map} +0 -0
  128. /package/dist/{chunk-RE2WE7CD.js.map → chunk-LOOOB46A.js.map} +0 -0
  129. /package/dist/{chunk-DKX7LF5Q.js.map → chunk-ODYLKWRT.js.map} +0 -0
  130. /package/dist/{chunk-IB5VIXLR.js.map → chunk-XLFDYTWO.js.map} +0 -0
  131. /package/dist/{dev-JDJWMRLH.js.map → dev-HJUD6X3R.js.map} +0 -0
  132. /package/dist/{internal-api-VDYOXOT7.js.map → internal-api-GKPJYL3G.js.map} +0 -0
  133. /package/dist/{internal-api-6XNLCNI5.js.map → internal-api-ZUBUYGCQ.js.map} +0 -0
  134. /package/dist/{mcp-WJNCTM7M.js.map → mcp-MVKDWZEQ.js.map} +0 -0
  135. /package/dist/{node-QUGTW6XV.js.map → node-4HQO6KKZ.js.map} +0 -0
  136. /package/dist/{observability-bootstrap-FP6LMMJE.js.map → observability-bootstrap-DOWRMADT.js.map} +0 -0
  137. /package/dist/{preview-BARW75PN.js.map → preview-5HUID27O.js.map} +0 -0
  138. /package/dist/{routes-FDF4SLOB.js.map → routes-3PTNISSO.js.map} +0 -0
  139. /package/dist/{server-boundary-AO6EELRF.js.map → server-boundary-QCJNECJP.js.map} +0 -0
  140. /package/dist/{server-boundary-E5GFVPLB.js.map → server-boundary-RTRPHX5I.js.map} +0 -0
  141. /package/dist/{start-4JTYXQQJ.js.map → start-EREUCSN6.js.map} +0 -0
  142. /package/dist/{static-NQPLPAB6.js.map → static-7LP7LPGN.js.map} +0 -0
  143. /package/dist/{vite-plugin-3ON45MQE.js.map → vite-plugin-JVGI6QUO.js.map} +0 -0
@@ -3,9 +3,16 @@ import "tsx/esm";
3
3
  import {
4
4
  parseAssetsMap
5
5
  } from "./chunk-46FM5AFZ.js";
6
+ import {
7
+ readDocumentShell
8
+ } from "./chunk-IJQQNHL7.js";
6
9
  import {
7
10
  planDeployedPlugins
8
- } from "./chunk-V5SSTT3C.js";
11
+ } from "./chunk-C43AHOHI.js";
12
+ import {
13
+ renderBakedRoutes,
14
+ routeRuntimeLines
15
+ } from "./chunk-72RSCKMW.js";
9
16
  import {
10
17
  deployedAgentsFragment,
11
18
  deployedCorsFragment,
@@ -17,13 +24,11 @@ import {
17
24
  rateLimitCheckFragment,
18
25
  securityHeadersDeclarations,
19
26
  serverDirLiteral
20
- } from "./chunk-C5CAL3DX.js";
27
+ } from "./chunk-EQJF2EH5.js";
21
28
  import {
22
29
  nodeAdapter
23
- } from "./chunk-G7U7FQVC.js";
24
- import {
25
- findRootDiv
26
- } from "./chunk-3PWQQWT6.js";
30
+ } from "./chunk-UFBBFP75.js";
31
+ import "./chunk-3PWQQWT6.js";
27
32
  import "./chunk-WSMLSIS5.js";
28
33
  import {
29
34
  assertServicesUnsupported,
@@ -31,72 +36,8 @@ import {
31
36
  } from "./chunk-ZNZISJDZ.js";
32
37
 
33
38
  // src/adapters/cloudflare.ts
34
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
39
+ import { mkdirSync, readFileSync, writeFileSync } from "fs";
35
40
  import { resolve } from "path";
36
- function readDocumentShell(cwd, streaming) {
37
- if (!streaming) return {};
38
- const indexPath = resolve(cwd, ".theokit/client/index.html");
39
- if (!existsSync(indexPath)) {
40
- throw new Error(
41
- `[adapter-cloudflare] ssrStreaming is on but ${indexPath} does not exist, so the worker would serve a document with no <head> and no client entry. Run the client build first, or set ssrStreaming: false in theo.config.ts.`
42
- );
43
- }
44
- const indexHtml = readFileSync(indexPath, "utf-8");
45
- const rootDiv = findRootDiv(indexHtml);
46
- if (rootDiv === void 0) {
47
- throw new Error(
48
- `[adapter-cloudflare] ${indexPath} has no <div id="root">, so the streamed document has nowhere to put the app. Add one, or set ssrStreaming: false in theo.config.ts.`
49
- );
50
- }
51
- return {
52
- htmlHead: indexHtml.slice(0, rootDiv.insertAt),
53
- htmlTail: indexHtml.slice(rootDiv.insertAt)
54
- };
55
- }
56
- function renderBakedRoutes(routes) {
57
- const routeVar = (index) => `__theoRoute${String(index)}`;
58
- return {
59
- routeImports: routes.map(
60
- (route, index) => `import * as ${routeVar(index)} from '../../${route.filePath}'`
61
- ),
62
- routeModuleEntries: routes.map(
63
- (route, index) => ` ${JSON.stringify(route.filePath)}: ${routeVar(index)},`
64
- ),
65
- routeTableEntries: routes.map(
66
- (route) => ` { filePath: ${JSON.stringify(route.filePath)}, routePath: ${JSON.stringify(route.routePath)}, methods: ${JSON.stringify([...route.methods ?? []])}, ...compilePattern(${JSON.stringify(route.routePath)}) },`
67
- )
68
- };
69
- }
70
- function routeRuntimeLines(moduleEntries, tableEntries) {
71
- return [
72
- `// #369 \u2014 the routes are baked at build time. The Worker used to reach for`,
73
- `// \`scanServerRoutes\` on the server directory \u2014 a readdirSync, in a runtime with no`,
74
- `// filesystem. The pattern is recompiled here from the same routePath the scanner`,
75
- `// used, so one function decides precedence on every target.`,
76
- `const ROUTE_MODULES = {`,
77
- ...moduleEntries,
78
- `}`,
79
- ``,
80
- `const routes = [`,
81
- ...tableEntries,
82
- `]`,
83
- ``,
84
- `// The executor asks for a module by the path the table names. Anything else was`,
85
- `// never bundled, and saying so beats returning undefined and failing later on a`,
86
- `// property access far from the cause.`,
87
- `async function loadModule(path) {`,
88
- ` const mod = ROUTE_MODULES[path]`,
89
- ` if (mod === undefined) {`,
90
- // No backticks in this message: it is emitted INTO a template literal, and a stray one closes
91
- // it. That is how #344 shipped a SyntaxError, and the emitted-entry parse gate caught this one
92
- // before it left the branch.
93
- " throw new Error(`Route module '${path}' was not bundled into this Worker. A Worker has no filesystem, so every route is imported at build time. Re-run: theokit build --target cloudflare`)",
94
- ` }`,
95
- ` return mod`,
96
- `}`,
97
- ``
98
- ];
99
- }
100
41
  function readAssetsMapForBake(path) {
101
42
  try {
102
43
  return parseAssetsMap(readFileSync(path, "utf8"));
@@ -113,6 +54,30 @@ function renderPreloadSupport(assetsMap) {
113
54
  }
114
55
  function renderNonApiBranch(opts, preloadsApply) {
115
56
  return opts.ssrStreaming ? [
57
+ ` // B-263 \u2014 a worker that owns \`/\` also receives \`/robots.txt\` and \`/logo.png\`, because`,
58
+ ` // \`run_worker_first\` in wrangler.toml is what stops the asset handler answering the`,
59
+ ` // document before this code runs. Rendering SSR for those would answer a text file with HTML.`,
60
+ ` //`,
61
+ ` // B-331 \u2014 the extension is a PRE-FILTER, no longer the decision. It used to decide: a dot in`,
62
+ ` // the last segment meant "static file", so \`/users/john.doe\`, \`/v1.2/docs\` and`,
63
+ ` // \`/reports/2026.q3\` were handed to a handler that does not have them, and with`,
64
+ ` // \`not_found_handling = "none"\` that is a 404 for a page the app renders.`,
65
+ ` //`,
66
+ ` // Now a miss falls through to SSR, so a wrong guess costs one local lookup instead of the`,
67
+ ` // response. Keeping the pre-filter is what keeps that lookup OFF every ordinary page`,
68
+ ` // request: \`/dashboard\` never touches the binding.`,
69
+ ` //`,
70
+ ` // Still uncovered, and stated rather than implied: a static file with NO extension, such as`,
71
+ ` // a \`public/CNAME\`. The pre-filter never asks for it, so it renders as a document. That`,
72
+ ` // is the pre-existing behaviour and the rarer direction of the two.`,
73
+ ` const lastSegment = url.pathname.slice(url.pathname.lastIndexOf('/') + 1)`,
74
+ ` if (lastSegment.includes('.')) {`,
75
+ ` const staticAssets = env?.ASSETS`,
76
+ ` if (staticAssets === undefined) return notFoundResponse()`,
77
+ ` const hit = await staticAssets.fetch(request)`,
78
+ ` if (hit.status !== 404) return withSecurityHeaders(hit, SECURITY_HEADERS)`,
79
+ ` }`,
80
+ ``,
116
81
  ` // T2.3 \u2014 streaming SSR for non-API routes`,
117
82
  ` // The same primitive \`theokit start\` uses, not a second one:`,
118
83
  ` // 16 bytes of Web Crypto entropy, base64.`,
@@ -138,7 +103,7 @@ function renderNonApiBranch(opts, preloadsApply) {
138
103
  ].join("\n");
139
104
  }
140
105
  function renderCloudflareWorkerEntry(opts = {}) {
141
- const streamingImport = opts.ssrStreaming ? `import { renderStreamingWeb } from '/@theo/entry-server'` : `// (ssrStreaming off: renderStreamingWeb not imported)`;
106
+ const streamingImport = opts.ssrStreaming ? `import { renderStreamingWeb } from '../server/entry-server.js'` : `// (ssrStreaming off: renderStreamingWeb not imported)`;
142
107
  const preloadsApply = preloadsApplyTo(opts);
143
108
  const preloadSupport = preloadsApply ? renderPreloadSupport(opts.assetsMap) : "";
144
109
  const nonApiBranch = renderNonApiBranch(opts, preloadsApply);
@@ -171,8 +136,22 @@ function renderCloudflareWorkerEntry(opts = {}) {
171
136
  `// so Wrangler bundles theokit and its transitive deps`,
172
137
  `// - Deploy: wrangler deploy`,
173
138
  ``,
174
- !preloadsApply ? `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'` : `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'
175
- import { injectModulePreloads } from 'theokit/server/http'`,
139
+ // NEVER the `theokit/server` umbrella. It is deprecated (the package prints so on import) and it
140
+ // is what made the first real `wrangler deploy` fail: bisected 2026-09-26 with a worker whose
141
+ // only line was `import { matchRoute } from 'theokit/server'`, and that alone pulled
142
+ // `@swc/core`'s `.node` native addon into the bundle. workerd cannot load a `.node` at any
143
+ // bundler setting, so it is not a flag away from working (B-263).
144
+ //
145
+ // The narrow subpaths were probed the same way and are clean — `wrangler deploy --dry-run`
146
+ // exit 0, zero swc, zero errors for both. Which symbol lives where was read from the modules
147
+ // rather than grepped, since these indexes use `export *`:
148
+ //
149
+ // theokit/server/scan matchRoute, compilePattern
150
+ // theokit/server/http executeRoute, extractTraceIdFromRequest, TRACE_HEADER,
151
+ // createCorsWebHandler, injectModulePreloads
152
+ !preloadsApply ? `import { matchRoute, compilePattern } from 'theokit/server/scan'
153
+ import { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'` : `import { matchRoute, compilePattern } from 'theokit/server/scan'
154
+ import { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler, injectModulePreloads } from 'theokit/server/http'`,
176
155
  `import { createWebShim } from 'theokit/adapters/web-shim'`,
177
156
  opts.ssrStreaming ? `import { buildSecurityHeaders, generateNonce, withSecurityHeaders } from 'theokit/adapters/security-headers'` : `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,
178
157
  `// T3.4 \u2014 WS bridge for Cloudflare Workers`,
@@ -182,7 +161,7 @@ import { injectModulePreloads } from 'theokit/server/http'`,
182
161
  // when it LOADED. `resolveClientIpFromRequest` is the forwarded-header fallback, behind
183
162
  // `trustProxy`; the primary source is `cf-connecting-ip`, which the Workers runtime writes.
184
163
  ...opts.rateLimit === void 0 ? [] : [
185
- `import { createRateLimiterWeb } from 'theokit/server'`,
164
+ `import { createRateLimiterWeb } from 'theokit/server/rate-limit'`,
186
165
  `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`
187
166
  ],
188
167
  streamingImport,
@@ -195,7 +174,7 @@ import { injectModulePreloads } from 'theokit/server/http'`,
195
174
  `// call process.cwd() and resolving paths at runtime returned '/server'.`,
196
175
  `const serverDir = ${serverDirLiteral(opts)}`,
197
176
  ``,
198
- ...routeRuntimeLines(routeModuleEntries, routeTableEntries),
177
+ ...routeRuntimeLines(routeModuleEntries, routeTableEntries, "cloudflare"),
199
178
  `// #410 \u2014 the security baseline \`theokit start\` puts on every response, carried`,
200
179
  `// here as a literal because a Worker has no theo.config.ts to read. Same`,
201
180
  `// function, same input, so the deployed page and the local one cannot`,
@@ -303,7 +282,7 @@ function cloudflareHandleRequestFragment(nonApiBranch, runtimeSpread, agentBranc
303
282
  `}`
304
283
  ];
305
284
  }
306
- function renderWranglerToml() {
285
+ function renderWranglerToml(opts) {
307
286
  return [
308
287
  `# Generated by Theo \u2014 Cloudflare Workers`,
309
288
  `name = "theo-app"`,
@@ -320,15 +299,49 @@ function renderWranglerToml() {
320
299
  `[assets]`,
321
300
  `directory = ".theokit/client"`,
322
301
  `binding = "ASSETS"`,
323
- `# A client-routed app asks for /dashboard, which is no file. Without this the asset`,
324
- `# handler 404s a deep link and the SPA never boots.`,
325
- `not_found_handling = "single-page-application"`,
302
+ `# B-263 \u2014 WITHOUT this key Cloudflare's asset handler answers before the worker for any path`,
303
+ `# that matches a file, and \`.theokit/client/index.html\` matches \`/\`. Measured on the first real`,
304
+ `# deploy: \`GET /\` returned 200 with an empty \`<div id="root">\` and NONE of the six security`,
305
+ `# headers, while \`/api/health\` \u2014 a path no file matches \u2014 was answered by the worker and carried`,
306
+ `# them. The document was coming off the CDN and the code that renders it never ran.`,
307
+ `#`,
308
+ `# The negation keeps the 300-odd hashed build outputs on the CDN path: \`true\` would satisfy the`,
309
+ `# precedence and pay a JS invocation per stylesheet and chunk.`,
310
+ `run_worker_first = ["/*", "!/assets/*"]`,
311
+ ...opts?.ssrStreaming === true ? [
312
+ `# The worker renders every extension-less path itself, so an asset MISS is a genuine 404.`,
313
+ `# \`single-page-application\` here would answer \`/nope.png\` with 200 and an HTML body.`,
314
+ `not_found_handling = "none"`
315
+ ] : [
316
+ `# A client-routed app asks for /dashboard, which is no file, and with streaming off the`,
317
+ `# worker forwards it to ASSETS rather than rendering it. Without this the asset handler`,
318
+ `# 404s a deep link and the SPA never boots.`,
319
+ `not_found_handling = "single-page-application"`
320
+ ],
321
+ ``,
322
+ `# B-332 \u2014 the [define] "import.meta.url" compensation lived here until 2026-09-28.`,
323
+ `#`,
324
+ `# Cloudflare executes the top-level module during validation, so a dependency that resolves a`,
325
+ `# path at load time refused the whole upload (code 10021). The cause was @theokit/sdk, in`,
326
+ `# internal/providers/catalog-loader.ts, fixed upstream and published in 5.9.2 \u2014 measured on the`,
327
+ `# published tarball: 0 of 254 executable files resolve a path at module scope.`,
328
+ `#`,
329
+ `# The floor this framework declares is now ^5.9.2, so the versions that needed the compensation`,
330
+ `# cannot be installed. A declared dependency is the honest form of that requirement;`,
331
+ `# substituting a literal for import.meta.url was the form that also covered the NEXT dependency`,
332
+ `# with the same vice, in silence.`,
326
333
  ``,
327
334
  `# Environment variables are set via wrangler secret or dashboard`,
328
335
  `# Example: wrangler secret put DATABASE_URL`
329
336
  ].join("\n");
330
337
  }
331
338
  var cloudflareAdapter = {
339
+ // #367 / #369 and `docs/adr/0020`. Wrangler runs esbuild at deploy time, so bundling here
340
+ // twice would be work with no observable effect — validated live 2026-09-26
341
+ // (`records/acceptance/evidence/b263-cloudflare-deploy.txt`). There is still no source tree in
342
+ // a Worker, which is why it bakes.
343
+ readsSourceAtRunTime: false,
344
+ specifiersResolvedBy: "the-platform",
332
345
  name: "cloudflare",
333
346
  streamsResponses: true,
334
347
  // #409 / #410 — the generated entry calls `executeRoute` with routes, loader
@@ -369,6 +382,10 @@ var cloudflareAdapter = {
369
382
  resolve(outputDir, "worker.mjs"),
370
383
  renderCloudflareWorkerEntry({
371
384
  ssrStreaming: config.ssrStreaming,
385
+ // B-315 — LATENT here, not broken: the routes are baked (#369) so the worker never scans,
386
+ // and a live deploy on 2026-09-26 served every route correctly with the wrong literal. It
387
+ // is still handed to `executeRoute`, so it is one refactor away from mattering.
388
+ serverDir: config.serverDir,
372
389
  ...shell,
373
390
  securityHeaders: config.security?.headers,
374
391
  csrf: config.security?.csrf,
@@ -390,7 +407,12 @@ var cloudflareAdapter = {
390
407
  wsRoutes: scanned.wsRoutes
391
408
  })
392
409
  );
393
- writeFileSync(resolve(cwd, "wrangler.toml"), renderWranglerToml());
410
+ writeFileSync(
411
+ resolve(cwd, "wrangler.toml"),
412
+ // B-263 — the toml decides whether the worker or the CDN answers the document, and the two
413
+ // modes need different `not_found_handling`. Passing the flag is what keeps them apart.
414
+ renderWranglerToml({ ssrStreaming: config.ssrStreaming })
415
+ );
394
416
  console.log("\n \u2713 Cloudflare output \u2192 .theokit/cloudflare/ + wrangler.toml");
395
417
  console.log(
396
418
  `${describeDeployedSecurityHeaders({
@@ -414,4 +436,4 @@ export {
414
436
  renderCloudflareWorkerEntry,
415
437
  renderWranglerToml
416
438
  };
417
- //# sourceMappingURL=cloudflare-4M4XVNUH.js.map
439
+ //# sourceMappingURL=cloudflare-AMH4TJNL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/cloudflare.ts"],"sourcesContent":["import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { parseAssetsMap } from '../core/contracts/module-preloads.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment, type DeployedAgent } from './deployed-agents.js'\nimport { renderBakedRoutes, routeRuntimeLines } from './deployed-baked-routes.js'\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { readDocumentShell } from './deployed-document-shell.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport {\n deployedRateLimitFragment,\n rateLimitCheckFragment,\n type DeployedRateLimitOptions,\n} from './deployed-rate-limit.js'\nimport {\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n type DeployedRuntimeConfigOptions,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders, securityHeadersDeclarations } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\n/**\n * T2.1 — Cloudflare adapter rewritten to consume `theokit/adapters/web-shim`\n * instead of emitting an inline plain-object Request/Response shim. Reduces\n * template from ~50 lines to ~25 and centralizes maintenance.\n */\n\n/**\n * The built `index.html` split into the part before `<div id=\"root\">` and the\n * part after it.\n *\n * Refuses by name when streaming is on and the template is missing, rather than\n * emitting a worker that serves a headless document. A build that cannot produce\n * a correct artifact should say so at build time; the alternative is a deploy\n * that looks successful and serves pages with no stylesheet.\n */\n// `readDocumentShell` moved to `./deployed-document-shell.js` (B-317): the Vercel target needs the\n// same shell, and an adapter importing another adapter is the coupling `deployed-baked-routes.ts`\n// was extracted to avoid.\n\n// Re-exported because this module's tests import it from here, and the move is not their subject.\nexport { readDocumentShell }\n\n/**\n * Read the map `theokit build` emitted, for baking into the worker (B-035).\n *\n * Returns `undefined` — never throws — for an absent or malformed file. A deploy that failed\n * because an optimisation was missing would turn a lost round trip into a broken build, and the\n * worker is correct without it.\n */\nexport function readAssetsMapForBake(path: string): Record<string, string[]> | undefined {\n try {\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- `path` is built by the one caller from a fixed `.theokit/client` layout; this returns `undefined` for anything it cannot read\n return parseAssetsMap(readFileSync(path, 'utf8'))\n } catch {\n return undefined\n }\n}\n\n/**\n * The baked route-to-chunks map, as worker source (B-035).\n *\n * A literal and not a read, for the same reason the document shell is: a Worker has no filesystem\n * at request time. Emitted only when the build produced a map; otherwise the worker carries\n * nothing about preloads and behaves exactly as before.\n *\n * **It emits the DATA and no longer the code.** An earlier revision emitted a hand-written copy of\n * `injectModulePreloads`, justified by a claim that the worker could not import it. That claim was\n * false — `theokit/server` re-exports from `core/contracts/` and the generated worker already\n * imports that subpath — and the copy drifted within a day: a fix for proxy-form request targets\n * landed in the original and not in the duplicate. The worker now imports the real function, which\n * is the shape `adapters/security-headers.ts` established one directory over for exactly this\n * build-half/runtime-half pair.\n */\n/**\n * Whether this worker can preload at all (B-035).\n *\n * ONE predicate, read by the bake, the import and the call. Two conditions for one decision is\n * how the import came to be emitted for a worker that had no map to give it — found at review, in\n * the same change where a copy and its original had already drifted apart.\n *\n * Streaming is required because the other branch serves the document from `env.ASSETS` as a\n * static file and can inject nothing into it.\n */\nfunction preloadsApplyTo(opts: {\n ssrStreaming?: boolean\n assetsMap?: Record<string, string[]>\n}): boolean {\n return opts.ssrStreaming === true && opts.assetsMap !== undefined\n}\n\nfunction renderPreloadSupport(assetsMap: Record<string, string[]> | undefined): string {\n if (assetsMap === undefined) return ''\n return `const __THEO_ASSETS_MAP = ${JSON.stringify(assetsMap)}`\n}\n\n/**\n * The branch that answers a non-API request: streamed SSR, or the static asset the Worker\n * platform serves. Extracted at review — it is the one decision in this emitter with two whole\n * shapes behind it, and keeping it inline pushed the caller past its line budget.\n */\nfunction renderNonApiBranch(\n opts: NonNullable<Parameters<typeof renderCloudflareWorkerEntry>[0]>,\n preloadsApply: boolean,\n): string {\n return opts.ssrStreaming\n ? [\n ` // B-263 — a worker that owns \\`/\\` also receives \\`/robots.txt\\` and \\`/logo.png\\`, because`,\n ` // \\`run_worker_first\\` in wrangler.toml is what stops the asset handler answering the`,\n ` // document before this code runs. Rendering SSR for those would answer a text file with HTML.`,\n ` //`,\n ` // B-331 — the extension is a PRE-FILTER, no longer the decision. It used to decide: a dot in`,\n ` // the last segment meant \"static file\", so \\`/users/john.doe\\`, \\`/v1.2/docs\\` and`,\n ` // \\`/reports/2026.q3\\` were handed to a handler that does not have them, and with`,\n ` // \\`not_found_handling = \"none\"\\` that is a 404 for a page the app renders.`,\n ` //`,\n ` // Now a miss falls through to SSR, so a wrong guess costs one local lookup instead of the`,\n ` // response. Keeping the pre-filter is what keeps that lookup OFF every ordinary page`,\n ` // request: \\`/dashboard\\` never touches the binding.`,\n ` //`,\n ` // Still uncovered, and stated rather than implied: a static file with NO extension, such as`,\n ` // a \\`public/CNAME\\`. The pre-filter never asks for it, so it renders as a document. That`,\n ` // is the pre-existing behaviour and the rarer direction of the two.`,\n ` const lastSegment = url.pathname.slice(url.pathname.lastIndexOf('/') + 1)`,\n ` if (lastSegment.includes('.')) {`,\n ` const staticAssets = env?.ASSETS`,\n ` if (staticAssets === undefined) return notFoundResponse()`,\n ` const hit = await staticAssets.fetch(request)`,\n ` if (hit.status !== 404) return withSecurityHeaders(hit, SECURITY_HEADERS)`,\n ` }`,\n ``,\n ` // T2.3 — streaming SSR for non-API routes`,\n ` // The same primitive \\`theokit start\\` uses, not a second one:`,\n ` // 16 bytes of Web Crypto entropy, base64.`,\n ` const nonce = generateNonce()`,\n ` return withSecurityHeaders(`,\n ` await renderStreamingWeb(request, {`,\n !preloadsApply\n ? ` htmlHead: ${JSON.stringify(opts.htmlHead ?? '')},`\n : ` htmlHead: injectModulePreloads(${JSON.stringify(opts.htmlHead ?? '')}, __THEO_ASSETS_MAP, new URL(request.url).pathname),`,\n ` htmlTail: ${JSON.stringify(opts.htmlTail ?? '')},`,\n ` nonce,`,\n ` }),`,\n ` buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true }, { nonce }),`,\n ` )`,\n ].join('\\n')\n : [\n ` // #412 — the document, served by the worker so it carries the same baseline every`,\n ` // API response carries. It used to return 404 here while wrangler.toml declared a`,\n ` // \\`[site]\\` bucket nothing read, so the page was missing rather than unprotected.`,\n ` const assets = env?.ASSETS`,\n ` // A wrangler.toml that predates this binding has no ASSETS. Reading .fetch off`,\n ` // undefined would turn every page request into a 500; 404 is what this target`,\n ` // answered before, which is the honest fallback rather than a new failure.`,\n ` if (assets === undefined) return notFoundResponse()`,\n ` return withSecurityHeaders(await assets.fetch(request), SECURITY_HEADERS)`,\n ].join('\\n')\n}\n\nexport function renderCloudflareWorkerEntry(\n opts: {\n ssrStreaming?: boolean\n htmlHead?: string\n htmlTail?: string\n /**\n * B-035 — the route-to-chunks map, baked as a literal for the same reason the shell above\n * is: a Worker has no filesystem at request time. Absent when the build produced no map,\n * and then nothing about preloads is emitted at all.\n */\n assetsMap?: Record<string, string[]>\n securityHeaders?: SecurityHeadersConfig\n /**\n * The server routes, scanned on the BUILD machine (#369).\n *\n * A Worker has no filesystem, so the worker used to call `scanServerRoutes` — a `readdirSync` —\n * against a directory that does not exist there, and load each module through `import()` of a\n * file path. Both are baked here instead, which is the road this adapter already takes for the\n * document shell one function away.\n *\n * `filePath` is relative to the project root and is used for two things: the key the executor\n * looks a module up by, and the specifier the static import uses. Paths are emitted relative to\n * `.theokit/cloudflare/`, where the worker is written.\n */\n routes?: readonly { filePath: string; routePath: string; methods?: readonly string[] }[]\n /**\n * The two concerns #410 could not bake (#425), composed from one place so the six targets\n * cannot drift into six spellings. `serialization` is a literal like the security values above;\n * `plugins` is an import, because a closure has no literal.\n */\n runtimeConfigModule?: DeployedRuntimeConfigOptions['runtimeConfigModule']\n serialization?: DeployedRuntimeConfigOptions['serialization']\n /**\n * The app's agents, scanned on the build machine (#367).\n *\n * A different scan from `routes` and served by a different function — which is why a worker\n * that only consulted the route table answered every `/api/agents/<name>` with a 404.\n */\n agents?: readonly DeployedAgent[]\n /** B-185 — the app's `server/context.ts`, project-relative, or absent when it declares none. */\n contextModule?: string\n /** WebSocket route files, scanned on the build machine. Only their presence is used (#369). */\n wsRoutes?: readonly string[]\n } & DeployedServerDirOptions &\n DeployedCsrfOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions = {},\n): string {\n // `/@theo/entry-server` is a VITE virtual id (`vite-plugin/index.ts`), and `adapters/node.ts`\n // resolves it by passing it as the vite build's `input`. This file is not bundled by vite: wrangler\n // hands it to esbuild, which has no such module and fails the build before a request is ever sent —\n // measured 2026-09-26 on the first real `wrangler deploy` this repository attempted (B-263).\n //\n // The same build writes the real thing next door. The worker lands at\n // `.theokit/cloudflare/worker.mjs` and the renderer at `.theokit/server/entry-server.js`, so one\n // directory up is the spelling esbuild can follow.\n const streamingImport = opts.ssrStreaming\n ? `import { renderStreamingWeb } from '../server/entry-server.js'`\n : `// (ssrStreaming off: renderStreamingWeb not imported)`\n // #343 — the document shell is inlined as a build-time literal because a Worker\n // has no filesystem to read `index.html` from at request time. Without it,\n // `renderStreamingWeb` falls back to its empty-string defaults and the response\n // is React output with no `<html>`, no `<head>`, no stylesheet and no client\n // entry — hydration data for a page that cannot hydrate. The streaming\n // assembly was fixed in the generated entry and this, its only caller, was\n // left passing nothing.\n //\n // `JSON.stringify` and not a template literal: the shell contains quotes,\n // angle brackets and a `</script>`, and embedding it naively produces a worker\n // that fails to parse at deploy time rather than here.\n //\n // #410 — this is also the ONE deploy path that renders HTML at request time,\n // so the one that can mint a per-request CSP nonce: `renderStreamingWeb`\n // threads `options.nonce` into `renderToReadableStream` and into the hydration\n // script (`router/entry-server.ts`). Every other response below carries the\n // nonce-less baseline, which is what `buildSecurityHeaders` already does for a\n // prerendered route (EC-4).\n // Only the streaming branch renders HTML at request time; the other serves the document from\n // `env.ASSETS` as a static file and can inject nothing. Baking the map for it would ship the whole\n // route table as dead weight — found at review, where the emitter was measured declaring it with\n // zero call sites.\n const preloadsApply = preloadsApplyTo(opts)\n const preloadSupport = preloadsApply ? renderPreloadSupport(opts.assetsMap) : ''\n\n const nonApiBranch = renderNonApiBranch(opts, preloadsApply)\n\n // CR-006: Workers lack `process.cwd()` and the `node:*` import surface\n // is brittle even under `nodejs_compat`. We use the Web Crypto\n // `crypto.randomUUID()` instead of `node:crypto.randomUUID`, and embed\n // the server directory as a build-time literal instead of resolving via\n // `node:path` at runtime.\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(\n opts.agents === undefined\n ? undefined\n : // B-185 — a Worker has no filesystem, so its identity module is baked exactly like its\n // agents and its routes (ADR 0014). `contextModule` is `undefined` for an app that\n // declares none, and the generator then emits no import for it.\n { kind: 'baked', agents: opts.agents, contextModule: opts.contextModule },\n {\n wrapSecurityHeaders: true,\n // B-185 — bound only when the runtime-config fragment declared the const, which is\n // exactly when a plugins module was emitted. Referencing it otherwise would emit an\n // identifier the entry never declares.\n pluginRunnerExpr:\n opts.runtimeConfigModule === undefined ? undefined : 'await THEO_PLUGIN_RUNNER',\n },\n )\n\n return [\n `// Generated by Theo — Cloudflare Workers Adapter`,\n `//`,\n `// REQUIREMENTS (EC-3):`,\n `// - wrangler.toml MUST include compatibility_flags = [\"nodejs_compat\"]`,\n `// (still required for transitive theokit/server deps, e.g. busboy)`,\n `// - package.json MUST list \"theokit\" in dependencies (not devDependencies)`,\n `// so Wrangler bundles theokit and its transitive deps`,\n `// - Deploy: wrangler deploy`,\n ``,\n // NEVER the `theokit/server` umbrella. It is deprecated (the package prints so on import) and it\n // is what made the first real `wrangler deploy` fail: bisected 2026-09-26 with a worker whose\n // only line was `import { matchRoute } from 'theokit/server'`, and that alone pulled\n // `@swc/core`'s `.node` native addon into the bundle. workerd cannot load a `.node` at any\n // bundler setting, so it is not a flag away from working (B-263).\n //\n // The narrow subpaths were probed the same way and are clean — `wrangler deploy --dry-run`\n // exit 0, zero swc, zero errors for both. Which symbol lives where was read from the modules\n // rather than grepped, since these indexes use `export *`:\n //\n // theokit/server/scan matchRoute, compilePattern\n // theokit/server/http executeRoute, extractTraceIdFromRequest, TRACE_HEADER,\n // createCorsWebHandler, injectModulePreloads\n !preloadsApply\n ? `import { matchRoute, compilePattern } from 'theokit/server/scan'\\nimport { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'`\n : `import { matchRoute, compilePattern } from 'theokit/server/scan'\\nimport { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler, injectModulePreloads } from 'theokit/server/http'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n opts.ssrStreaming\n ? `import { buildSecurityHeaders, generateNonce, withSecurityHeaders } from 'theokit/adapters/security-headers'`\n : `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n `// T3.4 — WS bridge for Cloudflare Workers`,\n `import { createCloudflareWsBridge } from 'theokit/adapters/ws-shim'`,\n // B-027 — only when a limit is declared. `createRateLimiterWeb` is used at module scope by the\n // fragment below and was imported by no target but bun, so an entry that declared a limit threw\n // when it LOADED. `resolveClientIpFromRequest` is the forwarded-header fallback, behind\n // `trustProxy`; the primary source is `cf-connecting-ip`, which the Workers runtime writes.\n ...(opts.rateLimit === undefined\n ? []\n : [\n `import { createRateLimiterWeb } from 'theokit/server/rate-limit'`,\n `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,\n ]),\n streamingImport,\n ``,\n ...runtimeConfig.imports,\n ...agentsFragment.imports,\n ...routeImports,\n ``,\n `// CR-006: server directory is a build-time literal — Workers cannot`,\n `// call process.cwd() and resolving paths at runtime returned '/server'.`,\n `const serverDir = ${serverDirLiteral(opts)}`,\n ``,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries, 'cloudflare'),\n `// #410 — the security baseline \\`theokit start\\` puts on every response, carried`,\n `// here as a literal because a Worker has no theo.config.ts to read. Same`,\n `// function, same input, so the deployed page and the local one cannot`,\n `// disagree about what the configuration means.`,\n preloadSupport,\n ...securityHeadersDeclarations(opts.securityHeaders),\n ``,\n ...deployedCsrfFragment(opts, 'a Worker'),\n ``,\n ...runtimeConfig.declarations,\n ...agentsFragment.declarations,\n ...deployedCorsFragment(opts.cors, 'cloudflare'),\n `// #369 — whether this project declares a WebSocket route, decided at build time. It used`,\n `// to answer it with \\`scanWebSocketRoutes\\`, which is the same readdirSync.`,\n `const HAS_WS_ROUTES = ${String((opts.wsRoutes ?? []).length > 0)}`,\n ``,\n `function notFoundResponse() {`,\n ` return withSecurityHeaders(`,\n ` new Response(`,\n ` JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Route not found' } }),`,\n ` { status: 404, headers: { 'Content-Type': 'application/json' } },`,\n ` ),`,\n ` SECURITY_HEADERS,`,\n ` )`,\n `}`,\n ``,\n ...cloudflareHandleRequestFragment(\n nonApiBranch,\n runtimeConfig.executeRouteSpread,\n agentsFragment.branch,\n agentsFragment.hostBypass,\n opts.rateLimit,\n ),\n ].join('\\n')\n}\n\n/**\n * The Worker's request handler, as generated source.\n *\n * Extracted for the reason `vercel.ts` extracts its own fragments: the emitter is one array\n * literal, so every line the entry gains counts against `max-lines-per-function`, and #410 added\n * the CSRF literal to an emitter already sitting exactly at the ceiling.\n *\n * @param nonApiBranch - what a non-`/api/` request gets, which differs with `ssrStreaming`\n */\nfunction cloudflareHandleRequestFragment(\n nonApiBranch: string,\n runtimeSpread: string,\n agentBranch: readonly string[],\n /** SI-020 — the condition that keeps an agent card path out of the static-asset branch. */\n hostBypass: string,\n /** B-027 — the declared limit, or `undefined`. Passed rather than read: this fragment is a\n * separate function from `renderCloudflareWorkerEntry`, where `opts` is bound. */\n rateLimit: DeployedRateLimitOptions['rateLimit'],\n): string[] {\n return [\n `async function handleRequest(request, url, env) {`,\n ` if (!url.pathname.startsWith('/api/')${hostBypass}) {`,\n nonApiBranch,\n ` }`,\n ``,\n ...agentBranch,\n ``,\n ` const match = matchRoute(url.pathname, routes)`,\n ` if (!match) return notFoundResponse()`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request, { trustedProxy: 'platform' })`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — the run is NOT awaited before the Response is taken. toResponse()`,\n ` // settles as soon as status + headers are known and carries a live body, so`,\n ` // the Worker starts flushing while the handler is still writing. Awaiting`,\n ` // executeRoute() first would re-buffer the whole response here even though`,\n ` // the shim streams; awaiting toResponse() does not — it settles at the head.`,\n ` return withSecurityHeaders(await toResponse(executeRoute({`,\n ` route: match.route, method, params: match.params,`,\n ` req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread}`,\n ` })), SECURITY_HEADERS)`,\n `}`,\n ``,\n ...deployedRateLimitFragment(\n rateLimit,\n 'cloudflare',\n // `cf-connecting-ip` is the RUNTIME's answer and a caller cannot forge it through the edge.\n // A Worker reached directly has none, and then only a declared `trustProxy` produces an\n // address — otherwise `undefined`, which is the named 503 rather than everyone's bucket.\n `request.headers.get('cf-connecting-ip') ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n // `request` alone: the handler binds `(request, env, ctx)` and the header is on the request.\n 'request',\n ),\n ``,\n `export default {`,\n ` async fetch(request, env, ctx) {`,\n ` const url = new URL(request.url)`,\n ``,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router handles`,\n ` // is an OPTIONS the browser never gets a CORS answer to. The WebSocket upgrade above is`,\n ` // deliberately upstream of it — a 101 is not a CORS-governed response.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(rateLimit, ' ', 'request'),\n ``,\n ` // LCR0103 — the upgrade branch sits BELOW the limiter, and the order is the point.`,\n ` // It used to sit above, under the comment \"a 101 carries no document and no script,`,\n ` // so the security baseline does not apply to it\". That is true of the security`,\n ` // HEADERS — a document concern — and false of the limiter, which is a resource`,\n ` // concern: a long-lived socket is the most expensive thing this entry hands out, so`,\n ` // the upgrade is the path that most needs a budget, not the one that may skip it.`,\n ` // T3.4 — Detect WebSocket upgrade and delegate to the CF bridge.`,\n ` // A 101 carries no document and no script, so the security baseline does`,\n ` // not apply to it.`,\n ` if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {`,\n ` if (!HAS_WS_ROUTES) return notFoundResponse()`,\n ` const cfWs = createCloudflareWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` })`,\n ` return cfWs.handle(request)`,\n ` }`,\n ``,\n ` return withCors(request, await handleRequest(request, url, env))`,\n ` },`,\n `}`,\n ]\n}\n\nexport function renderWranglerToml(opts?: { ssrStreaming?: boolean }): string {\n return [\n `# Generated by Theo — Cloudflare Workers`,\n `name = \"theo-app\"`,\n `main = \".theokit/cloudflare/worker.mjs\"`,\n `compatibility_date = \"2025-09-01\"`,\n `compatibility_flags = [\"nodejs_compat\"]`,\n ``,\n `# #412 — \\`[assets]\\` with a BINDING, not the legacy \\`[site]\\` bucket.`,\n `#`,\n `# \\`[site]\\` uploads to KV and is read through \\`kv-asset-handler\\` and a`,\n `# \\`__STATIC_CONTENT\\` binding — neither of which this worker has ever had. So the`,\n `# bucket was declared, uploaded, and consumed by nothing: with ssrStreaming off, a`,\n `# deploy answered 404 for its own page. This binding is what the worker calls.`,\n `[assets]`,\n `directory = \".theokit/client\"`,\n `binding = \"ASSETS\"`,\n `# B-263 — WITHOUT this key Cloudflare's asset handler answers before the worker for any path`,\n `# that matches a file, and \\`.theokit/client/index.html\\` matches \\`/\\`. Measured on the first real`,\n `# deploy: \\`GET /\\` returned 200 with an empty \\`<div id=\"root\">\\` and NONE of the six security`,\n `# headers, while \\`/api/health\\` — a path no file matches — was answered by the worker and carried`,\n `# them. The document was coming off the CDN and the code that renders it never ran.`,\n `#`,\n `# The negation keeps the 300-odd hashed build outputs on the CDN path: \\`true\\` would satisfy the`,\n `# precedence and pay a JS invocation per stylesheet and chunk.`,\n `run_worker_first = [\"/*\", \"!/assets/*\"]`,\n ...(opts?.ssrStreaming === true\n ? [\n `# The worker renders every extension-less path itself, so an asset MISS is a genuine 404.`,\n `# \\`single-page-application\\` here would answer \\`/nope.png\\` with 200 and an HTML body.`,\n `not_found_handling = \"none\"`,\n ]\n : [\n `# A client-routed app asks for /dashboard, which is no file, and with streaming off the`,\n `# worker forwards it to ASSETS rather than rendering it. Without this the asset handler`,\n `# 404s a deep link and the SPA never boots.`,\n `not_found_handling = \"single-page-application\"`,\n ]),\n ``,\n `# B-332 — the [define] \"import.meta.url\" compensation lived here until 2026-09-28.`,\n `#`,\n `# Cloudflare executes the top-level module during validation, so a dependency that resolves a`,\n `# path at load time refused the whole upload (code 10021). The cause was @theokit/sdk, in`,\n `# internal/providers/catalog-loader.ts, fixed upstream and published in 5.9.2 — measured on the`,\n `# published tarball: 0 of 254 executable files resolve a path at module scope.`,\n `#`,\n `# The floor this framework declares is now ^5.9.2, so the versions that needed the compensation`,\n `# cannot be installed. A declared dependency is the honest form of that requirement;`,\n `# substituting a literal for import.meta.url was the form that also covered the NEXT dependency`,\n `# with the same vice, in silence.`,\n ``,\n `# Environment variables are set via wrangler secret or dashboard`,\n `# Example: wrangler secret put DATABASE_URL`,\n ].join('\\n')\n}\n\nexport const cloudflareAdapter: DeployAdapter = {\n // #367 / #369 and `docs/adr/0020`. Wrangler runs esbuild at deploy time, so bundling here\n // twice would be work with no observable effect — validated live 2026-09-26\n // (`records/acceptance/evidence/b263-cloudflare-deploy.txt`). There is still no source tree in\n // a Worker, which is why it bakes.\n readsSourceAtRunTime: false,\n specifiersResolvedBy: 'the-platform',\n name: 'cloudflare',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied: the worker carries `security.headers` as a\n // literal and puts the built baseline on every response it returns, including\n // the streamed SSR document — with a per-request nonce, the only deploy path\n // that can mint one (`adapters/security-headers.ts`).\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('cloudflare', readManifest(cwd))\n\n // 1. Run the standard Node build first (ctx forwarded so nodeAdapter has makeVitePlugins)\n await nodeAdapter.build(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/cloudflare')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time output directory, derived from the project root\n mkdirSync(outputDir, { recursive: true })\n\n // 2. Emit Worker entry (now uses the shared web-shim)\n //\n // The document shell is read HERE, after the Node build produced\n // `.theokit/client/index.html`, and inlined into the worker: a Worker has no\n // filesystem at request time. Split on the root div with the same helper the\n // Node server uses (`ssr-setup.ts`), so the two paths cannot disagree about\n // where the shell ends (#343).\n const shell = readDocumentShell(cwd, config.ssrStreaming)\n // B-035 — the route-to-chunks map, read HERE on the build machine for the same reason the\n // shell above is: a Worker has no filesystem at request time. `nodeAdapter.build` ran\n // first, so the map the Node build emitted is on disk by now. Absent map -> nothing about\n // preloads is emitted, and the worker behaves exactly as it did before.\n const assetsMap = readAssetsMapForBake(resolve(cwd, '.theokit', 'client', 'assets-map.json'))\n\n // #369 — the routes are resolved HERE, on the build machine, for the same reason the document\n // shell above is read here: a Worker has no filesystem at request time, and the worker used to\n // run the scan itself against a directory that does not exist there.\n //\n // The scanner is INJECTED rather than imported: importing it would add an `adapters → server`\n // edge, which is the layering inversion ADR-0001 v3 removed for `vite-plugin` and which\n // `adapters-may-only-depend-on-core-router-services` refuses. An absent scanner emits a worker\n // with no routes rather than falling back to a runtime scan — the fallback IS the defect.\n const scanned = ctx?.scanRoutes?.(config.serverDir) ?? {\n routes: [],\n wsRoutes: [],\n agents: [],\n // B-185 — no provider means no scan, and an app whose context nobody looked for is\n // indistinguishable here from one that has none. Both resolve an anonymous caller, which is\n // the honest answer rather than an invented subject.\n contextModule: undefined,\n }\n\n const pluginsPlan = planDeployedPlugins(config.plugins, 'cloudflare')\n if (pluginsPlan !== undefined) {\n // Beside the worker, so the emitted import is a sibling. Wrangler bundles from here, which is\n // what lets the static import reach the app's own module at all (#425).\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time write under the project's own `.theokit/cloudflare`\n writeFileSync(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time write under the project's own `.theokit/cloudflare`\n writeFileSync(\n resolve(outputDir, 'worker.mjs'),\n renderCloudflareWorkerEntry({\n ssrStreaming: config.ssrStreaming,\n // B-315 — LATENT here, not broken: the routes are baked (#369) so the worker never scans,\n // and a live deploy on 2026-09-26 served every route correctly with the wrong literal. It\n // is still handed to `executeRoute`, so it is one refactor away from mattering.\n serverDir: config.serverDir,\n ...shell,\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n assetsMap,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n routes: scanned.routes,\n // #367 — a Worker has no filesystem, so its agents are decided here like its routes.\n agents: scanned.agents,\n // B-185 — rides beside the agents because it is decided by the same provider, for the same\n // reason: `build.ts` holds `serverDir` and a Worker cannot look for the module itself.\n contextModule: scanned.contextModule,\n wsRoutes: scanned.wsRoutes,\n }),\n )\n\n // 3. Emit wrangler.toml (with nodejs_compat enforced)\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time write under the project's own `.theokit/cloudflare`\n writeFileSync(\n resolve(cwd, 'wrangler.toml'),\n // B-263 — the toml decides whether the worker or the CDN answers the document, and the two\n // modes need different `not_found_handling`. Passing the flag is what keeps them apart.\n renderWranglerToml({ ssrStreaming: config.ssrStreaming }),\n )\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Cloudflare output → .theokit/cloudflare/ + wrangler.toml')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'cloudflare',\n securityHeaders: config.security?.headers,\n // Only the streaming worker renders HTML per request, so only it can put\n // the same nonce on the header and on the script tag it emits.\n mintsNonce: config.ssrStreaming,\n // #412 — either way the worker returns the document now: streamed by\n // `renderStreamingWeb`, or from the ASSETS binding it finally calls.\n documentHeaders: 'handler',\n })}\\n`,\n )\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,cAAc,qBAAqB;AACvD,SAAS,eAAe;AA0DjB,SAAS,qBAAqB,MAAoD;AACvF,MAAI;AAEF,WAAO,eAAe,aAAa,MAAM,MAAM,CAAC;AAAA,EAClD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AA2BA,SAAS,gBAAgB,MAGb;AACV,SAAO,KAAK,iBAAiB,QAAQ,KAAK,cAAc;AAC1D;AAEA,SAAS,qBAAqB,WAAyD;AACrF,MAAI,cAAc,OAAW,QAAO;AACpC,SAAO,6BAA6B,KAAK,UAAU,SAAS,CAAC;AAC/D;AAOA,SAAS,mBACP,MACA,eACQ;AACR,SAAO,KAAK,eACR;AAAA,IACE;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,CAAC,gBACG,uBAAuB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EA,eAAe,OAAO;AAAA;AAAA;AAAA;AAAA,QAItB,qBAAqB,aAAa;AAAA,QAClC,QAAQ,QAAQ;AAAA;AAAA,QAEhB,QAAQ,QAAQ;AAAA;AAAA;AAAA,QAGhB,eAAe,QAAQ;AAAA,QACvB,UAAU,QAAQ;AAAA,MACpB,CAAC;AAAA,IACH;AAIA;AAAA,MACE,QAAQ,KAAK,eAAe;AAAA;AAAA;AAAA,MAG5B,mBAAmB,EAAE,cAAc,OAAO,aAAa,CAAC;AAAA,IAC1D;AAGA,YAAQ,IAAI,0EAAgE;AAE5E,YAAQ;AAAA,MACN,GAAG,gCAAgC;AAAA,QACjC,QAAQ;AAAA,QACR,iBAAiB,OAAO,UAAU;AAAA;AAAA;AAAA,QAGlC,YAAY,OAAO;AAAA;AAAA;AAAA,QAGnB,iBAAiB;AAAA,MACnB,CAAC,CAAC;AAAA;AAAA,IACJ;AAAA,EACF;AACF;","names":[]}
@@ -2,7 +2,7 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  nodeAdapter
5
- } from "./chunk-G7U7FQVC.js";
5
+ } from "./chunk-UFBBFP75.js";
6
6
  import "./chunk-ZNZISJDZ.js";
7
7
 
8
8
  // src/adapters/config-support.ts
@@ -117,6 +117,16 @@ var UnenforceableRateLimitError = class extends Error {
117
117
  target;
118
118
  name = "UnenforceableRateLimitError";
119
119
  };
120
+ function assertStreamingSupported(config, adapter, target, streamingTargets) {
121
+ if (!config.ssrStreaming) return;
122
+ if (adapter.streamsResponses === true) return;
123
+ const detail = adapter.streamingUnsupportedDetail === void 0 ? "" : ` ${adapter.streamingUnsupportedDetail}`;
124
+ const alternatives = streamingTargets === void 0 || streamingTargets.length === 0 ? "" : ` Build a streaming target instead (${streamingTargets.join(", ")}), or set`;
125
+ const orSet = alternatives === "" ? " Set" : alternatives;
126
+ throw new Error(
127
+ `[adapter-${target}] ssrStreaming is on, but the ${target} target does not stream responses.${detail}${orSet} ssrStreaming: false in theo.config.ts.`
128
+ );
129
+ }
120
130
  function assertRateLimitEnforceable(config, adapter, target) {
121
131
  if (!isDeclared(config, "rateLimit")) return;
122
132
  const enforces = adapter.enforcesRateLimit ?? "never";
@@ -134,8 +144,9 @@ export {
134
144
  CONFIG_CONCERNS,
135
145
  UnenforceableRateLimitError,
136
146
  assertRateLimitEnforceable,
147
+ assertStreamingSupported,
137
148
  describeUnappliedConfig,
138
149
  findUnappliedConfig,
139
150
  warnUnappliedConfig
140
151
  };
141
- //# sourceMappingURL=config-support-SB5NDQZB.js.map
152
+ //# sourceMappingURL=config-support-MOZYHRWG.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapters/config-support.ts"],"sourcesContent":["/**\n * Which configuration a deploy target's emitted handler actually applies.\n *\n * `theo.config.ts` validates `rateLimit`, `security.cors`, `security.csrf`,\n * `security.disallowed` and `serialization` for every target. Applying them is\n * the handler's job, and the six Web-standards adapters build `executeRoute`'s\n * context from a subset of its fields, so the rest fall back to hard-coded\n * defaults on a deployed app (usetheokit/theokit#410). `security.cors` was read\n * only by the dev server until #409 wired it into `theokit start`; the six Web\n * targets still drop it.\n *\n * This module does not fix that. It makes it **audible at build time**: a\n * config key that is parsed and then dropped is named, with the target that\n * drops it and the next action. Silence was the defect — an operator who\n * declares a rate limit and gets none has no reason to look.\n *\n * It warns rather than refuses, deliberately. Refusing would break every\n * deployment that declares `rateLimit` today, and the real fix — wiring a\n * limiter that needs a per-runtime client address — is not a build away\n * (`docs/program/journeys/j07-rate-limit.md` § Correction measured what it\n * costs). Forcing an operator to delete valid configuration in order to ship\n * would trade a silent gap for a loud one that also loses information.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\nimport { nodeAdapter } from './node.js'\nimport type { ConfigConcern, DeployAdapter } from './types.js'\n\n/**\n * The closed set. A concern belongs here when it is (a) declarable in\n * `theo.config.ts` and (b) applied by a request handler rather than at build\n * time — a build-time key cannot be silently dropped by a runtime.\n */\nexport const CONFIG_CONCERNS = [\n 'rateLimit',\n 'cors',\n 'csrf',\n 'disallowed',\n 'serialization',\n 'plugins',\n 'securityHeaders',\n] as const satisfies readonly ConfigConcern[]\n\n/**\n * Does any production target apply this concern?\n *\n * DERIVED from what the `node` adapter declares, rather than listed. This was a hand-maintained\n * `APPLIED_BY_NO_TARGET` set holding `cors`, kept in step with `nodeAdapter.appliesConfig` by a\n * test — and #409, which taught `theokit start` to apply `cors`, emptied it. An empty hardcoded\n * set is not merely redundant: it makes the branch below provably unreachable, which the linter\n * says out loud (`sonarjs/no-empty-collection`).\n *\n * Deriving keeps the branch honest AND reachable: the moment a concern is added that `node` does\n * not apply, the advice stops claiming a target exists for it, with nothing to remember.\n */\nfunction appliedByNoTarget(concern: ConfigConcern): boolean {\n const applied = nodeAdapter.appliesConfig\n if (applied === undefined || applied === 'runtime-not-emitted-here') return true\n return !applied.includes(concern)\n}\n\n/** Where each concern lives in the config, for a message the operator can grep. */\nconst CONFIG_KEY: Record<ConfigConcern, string> = {\n rateLimit: 'rateLimit',\n cors: 'security.cors',\n csrf: 'security.csrf',\n disallowed: 'security.disallowed',\n serialization: 'serialization',\n plugins: 'plugins',\n securityHeaders: 'security.headers',\n}\n\nfunction isDeclared(config: TheoConfig, concern: ConfigConcern): boolean {\n const security = config.security\n switch (concern) {\n case 'rateLimit':\n return config.rateLimit !== undefined\n case 'cors':\n return security?.cors !== undefined\n case 'csrf':\n // `csrf` carries `.default('strict')` (config/schemas/security.ts:100) and\n // the deployed fallback is also `'strict'` (server/http/execute.ts:144).\n // A config that says `'strict'` therefore gets what it asked for, by\n // coincidence rather than by wiring -- reporting it dropped would be noise\n // over an identical outcome. Only a weaker setting is silently ignored.\n return security?.csrf !== undefined && security.csrf !== 'strict'\n case 'disallowed':\n return security?.disallowed !== undefined && security.disallowed.routes.length > 0\n case 'securityHeaders':\n return security?.headers !== undefined\n case 'serialization':\n // Same shape: `.default('json')` (config/schema.ts:147), and a target with\n // no transformer serializes as JSON. `'json'` is honoured by coincidence;\n // `'superjson'` is the case where the deployed app quietly disagrees with\n // the file.\n return config.serialization !== 'json'\n case 'plugins':\n return config.plugins !== undefined && config.plugins.length > 0\n }\n}\n\n/**\n * The concerns this config declares and this adapter does not apply.\n *\n * An adapter that emits no request handler of its own answers\n * `'runtime-not-emitted-here'` and is never reported against: it is not that\n * the configuration is dropped, it is that this build cannot know. Saying\n * nothing is the honest output, and it is a different fact from saying no.\n */\nexport function findUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n): ConfigConcern[] {\n const applied = adapter.appliesConfig ?? []\n if (applied === 'runtime-not-emitted-here') return []\n return CONFIG_CONCERNS.filter(\n (concern) => isDeclared(config, concern) && !applied.includes(concern),\n )\n}\n\n/**\n * The build-time message. Empty string when nothing was dropped, so the caller\n * neither branches nor prints a header over an empty list.\n */\nexport function describeUnappliedConfig(target: string, dropped: readonly ConfigConcern[]): string {\n if (dropped.length === 0) return ''\n const one = dropped.length === 1\n const list = dropped.map((concern) => ` - ${CONFIG_KEY[concern]}`).join('\\n')\n const elsewhere = dropped.filter((concern) => !appliedByNoTarget(concern))\n const nowhere = dropped.filter(appliedByNoTarget)\n\n // The advice has to change with the target, or it degenerates. Building for\n // `node` with only `security.cors` dropped once produced \"deploy to `node`,\n // which applies all of the above except security.cors\" -- an instruction to\n // do what you are already doing, about the one key it then excepts.\n const actions: string[] = []\n if (elsewhere.length > 0 && target !== 'node') {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: build for \\`node\\` and run \\`theokit start\\`,`,\n ` which applies ${elsewhere.length === 1 ? 'it' : 'them'}; or remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n } else if (elsewhere.length > 0) {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n }\n if (nowhere.length > 0) {\n actions.push(\n ` - ${nowhere.map((c) => CONFIG_KEY[c]).join(', ')}: no production target applies ${nowhere.length === 1 ? 'this' : 'these'} today`,\n ` (usetheokit/theokit#409) -- terminate it in front of the app, or remove it.`,\n )\n }\n\n return [\n ` ! ${String(dropped.length)} configuration ${one ? 'key is' : 'keys are'} validated and NOT applied on \\`${target}\\`:`,\n list,\n ` The handler this target emits never reads ${one ? 'it' : 'them'}, so the deployed app`,\n ` behaves as if ${one ? 'the key were' : 'the keys were'} absent.`,\n ` What to do:`,\n ...actions,\n ` Tracked: usetheokit/theokit#410 (deploy targets), usetheokit/theokit#409 (cors).`,\n ].join('\\n')\n}\n\n/**\n * Emit the warning, if there is one. The sink is injected so the behaviour is\n * exercisable without driving a whole build: the alternative was a caller that\n * only a full `theokit build` could reach, which in practice means a caller\n * nothing tests.\n */\nexport function warnUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n target: string,\n log: (message: string) => void,\n): void {\n const dropped = findUnappliedConfig(config, adapter)\n if (dropped.length === 0) return\n log(`\\n${describeUnappliedConfig(target, dropped)}\\n`)\n}\n\n/**\n * A declared rate limit the chosen target cannot enforce.\n *\n * Its own class so a caller can distinguish it from a configuration typo — this is not the build\n * failing to understand the file, it is the build understanding it and refusing the combination.\n */\nexport class UnenforceableRateLimitError extends Error {\n override readonly name = 'UnenforceableRateLimitError'\n constructor(readonly target: string) {\n super(\n [\n `Refusing to build for \\`${target}\\`: theo.config.ts declares a rate limit and this target does not enforce one.`,\n ``,\n ` The config reads as protection the deploy will not have. Nothing at runtime reports the`,\n ` absence, so the first sign is abuse — which is why this refuses rather than warns.`,\n ``,\n ` Two honest ways forward:`,\n ` • build for \\`node\\` and run \\`theokit start\\`, which applies the limit; or`,\n ` • remove \\`rateLimit\\` from theo.config.ts, so the file states what actually runs.`,\n ``,\n ` There is deliberately no flag to keep the key and skip the check: a config that stays`,\n ` while doing nothing is the state this refusal exists to end (usetheokit/theokit#461).`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Refuse a build whose target drops a DECLARED rate limit.\n *\n * Only `rateLimit`, and the narrowness is the design. A dropped `cors` or `serialization` degrades\n * where someone can see it, and `describeUnappliedConfig`'s warning is proportionate for those.\n * `rateLimit` is the one whose absence looks exactly like success, which is the same reasoning\n * `MissingRoutePolicyError` applies to an undeclared route policy: refuse where silence would be\n * read as safety.\n *\n * `'runtime-not-emitted-here'` is not judged. That adapter's runtime is someone else's and this\n * build cannot answer for it; refusing there would be asserting something unmeasured.\n */\nexport function assertRateLimitEnforceable(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'enforcesRateLimit'>,\n target: string,\n): void {\n if (!isDeclared(config, 'rateLimit')) return\n\n // B-257 — this reads `enforcesRateLimit`, NOT `appliesConfig`. They were one list until now, and\n // `applied.includes('rateLimit')` returned before the throw, so adding that entry to silence the\n // WARNING also switched off this REFUSAL — on a runtime where the limit still cannot hold.\n //\n // **An omitted field REFUSES.** The first cut defaulted to `'not-ours-to-judge'`, which inverted\n // the rule it replaced: `appliesConfig ?? []` did not include `'rateLimit'`, so an adapter that\n // declared nothing was refused; `?? 'not-ours-to-judge'` let it through. Measured on\n // `static.ts`, which declares neither field and is registered at `registry.ts:28` — it went from\n // refusing a declared limit to proceeding with a console warning. `:213-215` refuses exactly that\n // outcome in its own words, and this member is on the EXPORTED `DeployAdapter`, so every\n // third-party adapter inherited the inversion too.\n //\n // Abstaining is a CLAIM about somebody else's runtime, and a claim has to be made rather than\n // inferred from silence.\n const enforces = adapter.enforcesRateLimit ?? 'never'\n\n // An adapter emitting no request handler is not judged. Its runtime is someone else's and this\n // build cannot answer for it; refusing would assert something unmeasured. An ABSTAIN, and the\n // reason it is not spelled `'never'`.\n if (enforces === 'not-ours-to-judge') return\n\n if (enforces === 'always') return\n\n // `'never'`, and the default for an adapter that declared nothing. Refusing here is what the\n // pre-B-257 rule did; reaching the store check below would let an undeclared adapter enforce by\n // accident whenever a config happened to name one.\n if (enforces === 'never') throw new UnenforceableRateLimitError(target)\n\n // `'with-a-store'`: a per-invocation runtime enforces only when the config names a durable\n // counter. Without one the in-process count dies with the invocation, and a limit that forgets is\n // a limit that does not limit — the same class of failure as a shared bucket, by another road.\n if (declaresRateLimitStore(config)) return\n\n throw new UnenforceableRateLimitError(target)\n}\n\n/** Does the declared `rateLimit` name a store the emitted entry could construct? */\nfunction declaresRateLimitStore(config: TheoConfig): boolean {\n const limit = (config as { rateLimit?: { store?: unknown } }).rateLimit\n return typeof limit?.store === 'object' && limit.store !== null\n}\n"],"mappings":";;;;;;;;AAiCO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAcA,SAAS,kBAAkB,SAAiC;AAC1D,QAAM,UAAU,YAAY;AAC5B,MAAI,YAAY,UAAa,YAAY,2BAA4B,QAAO;AAC5E,SAAO,CAAC,QAAQ,SAAS,OAAO;AAClC;AAGA,IAAM,aAA4C;AAAA,EAChD,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,SAAS;AAAA,EACT,iBAAiB;AACnB;AAEA,SAAS,WAAW,QAAoB,SAAiC;AACvE,QAAM,WAAW,OAAO;AACxB,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,aAAO,OAAO,cAAc;AAAA,IAC9B,KAAK;AACH,aAAO,UAAU,SAAS;AAAA,IAC5B,KAAK;AAMH,aAAO,UAAU,SAAS,UAAa,SAAS,SAAS;AAAA,IAC3D,KAAK;AACH,aAAO,UAAU,eAAe,UAAa,SAAS,WAAW,OAAO,SAAS;AAAA,IACnF,KAAK;AACH,aAAO,UAAU,YAAY;AAAA,IAC/B,KAAK;AAKH,aAAO,OAAO,kBAAkB;AAAA,IAClC,KAAK;AACH,aAAO,OAAO,YAAY,UAAa,OAAO,QAAQ,SAAS;AAAA,EACnE;AACF;AAUO,SAAS,oBACd,QACA,SACiB;AACjB,QAAM,UAAU,QAAQ,iBAAiB,CAAC;AAC1C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DAAiD,MAAM,OAAO,MAAM;AAAA,IACpE,qBAAqB,MAAM,iBAAiB,eAAe;AAAA,IAC3D;AAAA,IACA,GAAG;AAAA,IACH;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAQO,SAAS,oBACd,QACA,SACA,QACA,KACM;AACN,QAAM,UAAU,oBAAoB,QAAQ,OAAO;AACnD,MAAI,QAAQ,WAAW,EAAG;AAC1B,MAAI;AAAA,EAAK,wBAAwB,QAAQ,OAAO,CAAC;AAAA,CAAI;AACvD;AAQO,IAAM,8BAAN,cAA0C,MAAM;AAAA,EAErD,YAAqB,QAAgB;AACnC;AAAA,MACE;AAAA,QACE,2BAA2B,MAAM;AAAA,QACjC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,EAAE,KAAK,IAAI;AAAA,IACb;AAfmB;AAAA,EAgBrB;AAAA,EAhBqB;AAAA,EADH,OAAO;AAkB3B;AAcO,SAAS,2BACd,QACA,SACA,QACM;AACN,MAAI,CAAC,WAAW,QAAQ,WAAW,EAAG;AAgBtC,QAAM,WAAW,QAAQ,qBAAqB;AAK9C,MAAI,aAAa,oBAAqB;AAEtC,MAAI,aAAa,SAAU;AAK3B,MAAI,aAAa,QAAS,OAAM,IAAI,4BAA4B,MAAM;AAKtE,MAAI,uBAAuB,MAAM,EAAG;AAEpC,QAAM,IAAI,4BAA4B,MAAM;AAC9C;AAGA,SAAS,uBAAuB,QAA6B;AAC3D,QAAM,QAAS,OAA+C;AAC9D,SAAO,OAAO,OAAO,UAAU,YAAY,MAAM,UAAU;AAC7D;","names":[]}
1
+ {"version":3,"sources":["../src/adapters/config-support.ts"],"sourcesContent":["/**\n * Which configuration a deploy target's emitted handler actually applies.\n *\n * `theo.config.ts` validates `rateLimit`, `security.cors`, `security.csrf`,\n * `security.disallowed` and `serialization` for every target. Applying them is\n * the handler's job, and the six Web-standards adapters build `executeRoute`'s\n * context from a subset of its fields, so the rest fall back to hard-coded\n * defaults on a deployed app (usetheokit/theokit#410). `security.cors` was read\n * only by the dev server until #409 wired it into `theokit start`; the six Web\n * targets still drop it.\n *\n * This module does not fix that. It makes it **audible at build time**: a\n * config key that is parsed and then dropped is named, with the target that\n * drops it and the next action. Silence was the defect — an operator who\n * declares a rate limit and gets none has no reason to look.\n *\n * It warns rather than refuses, deliberately. Refusing would break every\n * deployment that declares `rateLimit` today, and the real fix — wiring a\n * limiter that needs a per-runtime client address — is not a build away\n * (`docs/program/journeys/j07-rate-limit.md` § Correction measured what it\n * costs). Forcing an operator to delete valid configuration in order to ship\n * would trade a silent gap for a loud one that also loses information.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\nimport { nodeAdapter } from './node.js'\nimport type { ConfigConcern, DeployAdapter } from './types.js'\n\n/**\n * The closed set. A concern belongs here when it is (a) declarable in\n * `theo.config.ts` and (b) applied by a request handler rather than at build\n * time — a build-time key cannot be silently dropped by a runtime.\n */\nexport const CONFIG_CONCERNS = [\n 'rateLimit',\n 'cors',\n 'csrf',\n 'disallowed',\n 'serialization',\n 'plugins',\n 'securityHeaders',\n] as const satisfies readonly ConfigConcern[]\n\n/**\n * Does any production target apply this concern?\n *\n * DERIVED from what the `node` adapter declares, rather than listed. This was a hand-maintained\n * `APPLIED_BY_NO_TARGET` set holding `cors`, kept in step with `nodeAdapter.appliesConfig` by a\n * test — and #409, which taught `theokit start` to apply `cors`, emptied it. An empty hardcoded\n * set is not merely redundant: it makes the branch below provably unreachable, which the linter\n * says out loud (`sonarjs/no-empty-collection`).\n *\n * Deriving keeps the branch honest AND reachable: the moment a concern is added that `node` does\n * not apply, the advice stops claiming a target exists for it, with nothing to remember.\n */\nfunction appliedByNoTarget(concern: ConfigConcern): boolean {\n const applied = nodeAdapter.appliesConfig\n if (applied === undefined || applied === 'runtime-not-emitted-here') return true\n return !applied.includes(concern)\n}\n\n/** Where each concern lives in the config, for a message the operator can grep. */\nconst CONFIG_KEY: Record<ConfigConcern, string> = {\n rateLimit: 'rateLimit',\n cors: 'security.cors',\n csrf: 'security.csrf',\n disallowed: 'security.disallowed',\n serialization: 'serialization',\n plugins: 'plugins',\n securityHeaders: 'security.headers',\n}\n\nfunction isDeclared(config: TheoConfig, concern: ConfigConcern): boolean {\n const security = config.security\n switch (concern) {\n case 'rateLimit':\n return config.rateLimit !== undefined\n case 'cors':\n return security?.cors !== undefined\n case 'csrf':\n // `csrf` carries `.default('strict')` (config/schemas/security.ts:100) and\n // the deployed fallback is also `'strict'` (server/http/execute.ts:144).\n // A config that says `'strict'` therefore gets what it asked for, by\n // coincidence rather than by wiring -- reporting it dropped would be noise\n // over an identical outcome. Only a weaker setting is silently ignored.\n return security?.csrf !== undefined && security.csrf !== 'strict'\n case 'disallowed':\n return security?.disallowed !== undefined && security.disallowed.routes.length > 0\n case 'securityHeaders':\n return security?.headers !== undefined\n case 'serialization':\n // Same shape: `.default('json')` (config/schema.ts:147), and a target with\n // no transformer serializes as JSON. `'json'` is honoured by coincidence;\n // `'superjson'` is the case where the deployed app quietly disagrees with\n // the file.\n return config.serialization !== 'json'\n case 'plugins':\n return config.plugins !== undefined && config.plugins.length > 0\n }\n}\n\n/**\n * The concerns this config declares and this adapter does not apply.\n *\n * An adapter that emits no request handler of its own answers\n * `'runtime-not-emitted-here'` and is never reported against: it is not that\n * the configuration is dropped, it is that this build cannot know. Saying\n * nothing is the honest output, and it is a different fact from saying no.\n */\nexport function findUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n): ConfigConcern[] {\n const applied = adapter.appliesConfig ?? []\n if (applied === 'runtime-not-emitted-here') return []\n return CONFIG_CONCERNS.filter(\n (concern) => isDeclared(config, concern) && !applied.includes(concern),\n )\n}\n\n/**\n * The build-time message. Empty string when nothing was dropped, so the caller\n * neither branches nor prints a header over an empty list.\n */\nexport function describeUnappliedConfig(target: string, dropped: readonly ConfigConcern[]): string {\n if (dropped.length === 0) return ''\n const one = dropped.length === 1\n const list = dropped.map((concern) => ` - ${CONFIG_KEY[concern]}`).join('\\n')\n const elsewhere = dropped.filter((concern) => !appliedByNoTarget(concern))\n const nowhere = dropped.filter(appliedByNoTarget)\n\n // The advice has to change with the target, or it degenerates. Building for\n // `node` with only `security.cors` dropped once produced \"deploy to `node`,\n // which applies all of the above except security.cors\" -- an instruction to\n // do what you are already doing, about the one key it then excepts.\n const actions: string[] = []\n if (elsewhere.length > 0 && target !== 'node') {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: build for \\`node\\` and run \\`theokit start\\`,`,\n ` which applies ${elsewhere.length === 1 ? 'it' : 'them'}; or remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n } else if (elsewhere.length > 0) {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n }\n if (nowhere.length > 0) {\n actions.push(\n ` - ${nowhere.map((c) => CONFIG_KEY[c]).join(', ')}: no production target applies ${nowhere.length === 1 ? 'this' : 'these'} today`,\n ` (usetheokit/theokit#409) -- terminate it in front of the app, or remove it.`,\n )\n }\n\n return [\n ` ! ${String(dropped.length)} configuration ${one ? 'key is' : 'keys are'} validated and NOT applied on \\`${target}\\`:`,\n list,\n ` The handler this target emits never reads ${one ? 'it' : 'them'}, so the deployed app`,\n ` behaves as if ${one ? 'the key were' : 'the keys were'} absent.`,\n ` What to do:`,\n ...actions,\n ` Tracked: usetheokit/theokit#410 (deploy targets), usetheokit/theokit#409 (cors).`,\n ].join('\\n')\n}\n\n/**\n * Emit the warning, if there is one. The sink is injected so the behaviour is\n * exercisable without driving a whole build: the alternative was a caller that\n * only a full `theokit build` could reach, which in practice means a caller\n * nothing tests.\n */\nexport function warnUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n target: string,\n log: (message: string) => void,\n): void {\n const dropped = findUnappliedConfig(config, adapter)\n if (dropped.length === 0) return\n log(`\\n${describeUnappliedConfig(target, dropped)}\\n`)\n}\n\n/**\n * A declared rate limit the chosen target cannot enforce.\n *\n * Its own class so a caller can distinguish it from a configuration typo — this is not the build\n * failing to understand the file, it is the build understanding it and refusing the combination.\n */\nexport class UnenforceableRateLimitError extends Error {\n override readonly name = 'UnenforceableRateLimitError'\n constructor(readonly target: string) {\n super(\n [\n `Refusing to build for \\`${target}\\`: theo.config.ts declares a rate limit and this target does not enforce one.`,\n ``,\n ` The config reads as protection the deploy will not have. Nothing at runtime reports the`,\n ` absence, so the first sign is abuse — which is why this refuses rather than warns.`,\n ``,\n ` Two honest ways forward:`,\n ` • build for \\`node\\` and run \\`theokit start\\`, which applies the limit; or`,\n ` • remove \\`rateLimit\\` from theo.config.ts, so the file states what actually runs.`,\n ``,\n ` There is deliberately no flag to keep the key and skip the check: a config that stays`,\n ` while doing nothing is the state this refusal exists to end (usetheokit/theokit#461).`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Refuse a build whose target drops a DECLARED rate limit.\n *\n * Only `rateLimit`, and the narrowness is the design. A dropped `cors` or `serialization` degrades\n * where someone can see it, and `describeUnappliedConfig`'s warning is proportionate for those.\n * `rateLimit` is the one whose absence looks exactly like success, which is the same reasoning\n * `MissingRoutePolicyError` applies to an undeclared route policy: refuse where silence would be\n * read as safety.\n *\n * `'runtime-not-emitted-here'` is not judged. That adapter's runtime is someone else's and this\n * build cannot answer for it; refusing there would be asserting something unmeasured.\n */\n/**\n * Refuse a target that cannot stream when the config says responses stream.\n *\n * Lives here rather than inside an adapter's `build()` because of WHEN it has to run. The refusal was\n * thrown from `buildAwsLambda`, which `runAdapterBuild` reaches a hundred lines after `cleanOutDir` has\n * emptied the output — so a project with `ssrStreaming: true` lost a working build to a refusal about\n * streaming. Measured 2026-09-28: 302 files in `.theokit/client/assets` before, 0 after (B-336).\n *\n * The alternatives are DERIVED from the registry rather than written into the sentence. A hardcoded\n * list was correct when it was written and nothing kept it correct, which is the same class of drift\n * `adapter-streaming-contract.test.ts` now pins.\n */\nexport function assertStreamingSupported(\n config: Pick<TheoConfig, 'ssrStreaming'>,\n adapter: Pick<DeployAdapter, 'streamsResponses' | 'streamingUnsupportedDetail'>,\n target: string,\n streamingTargets?: readonly string[],\n): void {\n if (!config.ssrStreaming) return\n if (adapter.streamsResponses === true) return\n\n const detail =\n adapter.streamingUnsupportedDetail === undefined ? '' : ` ${adapter.streamingUnsupportedDetail}`\n\n // The alternatives are named only when the CALLER could know them. An adapter cannot: asking the\n // registry from inside one closes `adapter -> config-support -> registry -> adapter`, and the Acyclic\n // Dependencies Principle is not negotiable here (`rules/architecture.md`). So the CLI passes the list\n // it already has, and a direct call to an adapter's build gets the same refusal without it.\n const alternatives =\n streamingTargets === undefined || streamingTargets.length === 0\n ? ''\n : ` Build a streaming target instead (${streamingTargets.join(', ')}), or set`\n const orSet = alternatives === '' ? ' Set' : alternatives\n\n throw new Error(\n `[adapter-${target}] ssrStreaming is on, but the ${target} target does not stream responses.` +\n `${detail}${orSet} ssrStreaming: false in theo.config.ts.`,\n )\n}\n\nexport function assertRateLimitEnforceable(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'enforcesRateLimit'>,\n target: string,\n): void {\n if (!isDeclared(config, 'rateLimit')) return\n\n // B-257 — this reads `enforcesRateLimit`, NOT `appliesConfig`. They were one list until now, and\n // `applied.includes('rateLimit')` returned before the throw, so adding that entry to silence the\n // WARNING also switched off this REFUSAL — on a runtime where the limit still cannot hold.\n //\n // **An omitted field REFUSES.** The first cut defaulted to `'not-ours-to-judge'`, which inverted\n // the rule it replaced: `appliesConfig ?? []` did not include `'rateLimit'`, so an adapter that\n // declared nothing was refused; `?? 'not-ours-to-judge'` let it through. Measured on\n // `static.ts`, which declares neither field and is registered at `registry.ts:28` — it went from\n // refusing a declared limit to proceeding with a console warning. `:213-215` refuses exactly that\n // outcome in its own words, and this member is on the EXPORTED `DeployAdapter`, so every\n // third-party adapter inherited the inversion too.\n //\n // Abstaining is a CLAIM about somebody else's runtime, and a claim has to be made rather than\n // inferred from silence.\n const enforces = adapter.enforcesRateLimit ?? 'never'\n\n // An adapter emitting no request handler is not judged. Its runtime is someone else's and this\n // build cannot answer for it; refusing would assert something unmeasured. An ABSTAIN, and the\n // reason it is not spelled `'never'`.\n if (enforces === 'not-ours-to-judge') return\n\n if (enforces === 'always') return\n\n // `'never'`, and the default for an adapter that declared nothing. Refusing here is what the\n // pre-B-257 rule did; reaching the store check below would let an undeclared adapter enforce by\n // accident whenever a config happened to name one.\n if (enforces === 'never') throw new UnenforceableRateLimitError(target)\n\n // `'with-a-store'`: a per-invocation runtime enforces only when the config names a durable\n // counter. Without one the in-process count dies with the invocation, and a limit that forgets is\n // a limit that does not limit — the same class of failure as a shared bucket, by another road.\n if (declaresRateLimitStore(config)) return\n\n throw new UnenforceableRateLimitError(target)\n}\n\n/** Does the declared `rateLimit` name a store the emitted entry could construct? */\nfunction declaresRateLimitStore(config: TheoConfig): boolean {\n const limit = (config as { rateLimit?: { store?: unknown } }).rateLimit\n return typeof limit?.store === 'object' && limit.store !== null\n}\n"],"mappings":";;;;;;;;AAiCO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAcA,SAAS,kBAAkB,SAAiC;AAC1D,QAAM,UAAU,YAAY;AAC5B,MAAI,YAAY,UAAa,YAAY,2BAA4B,QAAO;AAC5E,SAAO,CAAC,QAAQ,SAAS,OAAO;AAClC;AAGA,IAAM,aAA4C;AAAA,EAChD,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,SAAS;AAAA,EACT,iBAAiB;AACnB;AAEA,SAAS,WAAW,QAAoB,SAAiC;AACvE,QAAM,WAAW,OAAO;AACxB,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,aAAO,OAAO,cAAc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AAM,eACJ,qBAAqB,UAAa,iBAAiB,WAAW,IAC1D,KACA,sCAAsC,iBAAiB,KAAK,IAAI,CAAC;AACvE,QAAM,QAAQ,iBAAiB,KAAK,SAAS;AAE7C,QAAM,IAAI;AAAA,IACR,YAAY,MAAM,iCAAiC,MAAM,qCACpD,MAAM,GAAG,KAAK;AAAA,EACrB;AACF;AAEO,SAAS,2BACd,QACA,SACA,QACM;AACN,MAAI,CAAC,WAAW,QAAQ,WAAW,EAAG;AAgBtC,QAAM,WAAW,QAAQ,qBAAqB;AAK9C,MAAI,aAAa,oBAAqB;AAEtC,MAAI,aAAa,SAAU;AAK3B,MAAI,aAAa,QAAS,OAAM,IAAI,4BAA4B,MAAM;AAKtE,MAAI,uBAAuB,MAAM,EAAG;AAEpC,QAAM,IAAI,4BAA4B,MAAM;AAC9C;AAGA,SAAS,uBAAuB,QAA6B;AAC3D,QAAM,QAAS,OAA+C;AAC9D,SAAO,OAAO,OAAO,UAAU,YAAY,MAAM,UAAU;AAC7D;","names":[]}
@@ -2,10 +2,10 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  planDeployedPlugins
5
- } from "./chunk-V5SSTT3C.js";
5
+ } from "./chunk-C43AHOHI.js";
6
6
  import {
7
7
  deployedEntryPreamble
8
- } from "./chunk-IB5VIXLR.js";
8
+ } from "./chunk-XLFDYTWO.js";
9
9
  import {
10
10
  agentsDirLiteral,
11
11
  deployedAgentsFragment,
@@ -16,10 +16,10 @@ import {
16
16
  rateLimitCheckFragment,
17
17
  scannedFromLoaderCache,
18
18
  serverDirLiteral
19
- } from "./chunk-C5CAL3DX.js";
19
+ } from "./chunk-EQJF2EH5.js";
20
20
  import {
21
21
  nodeAdapter
22
- } from "./chunk-G7U7FQVC.js";
22
+ } from "./chunk-UFBBFP75.js";
23
23
  import "./chunk-WSMLSIS5.js";
24
24
  import {
25
25
  assertServicesUnsupported,
@@ -32,7 +32,13 @@ import { resolve } from "path";
32
32
  var FRAMEWORK_IMPORTS = [
33
33
  `// Use npm: specifier so Deno resolves theokit from the user's package.json`,
34
34
  `// equivalent (works in both local 'deno run' and Deno Deploy).`,
35
- `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, scanWebSocketRoutes, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'npm:theokit/server'`,
35
+ // Sub-paths, not the umbrella. `theokit/server` is DEPRECATED by the framework itself with a
36
+ // REMOVAL scheduled, so this entry would stop loading on that release, before a request exists —
37
+ // measured on Deno 2.9.5, where the warning printed on every start. This was the only adapter still
38
+ // on the umbrella; the split below is the mapping four siblings already use and Bun proves by
39
+ // running.
40
+ `import { scanServerRoutes, matchRoute, createProductionLoader, scanWebSocketRoutes } from 'npm:theokit/server/scan'`,
41
+ `import { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'npm:theokit/server/http'`,
36
42
  `import { createWebShim } from 'npm:theokit/adapters/web-shim'`,
37
43
  `import { buildSecurityHeaders, withSecurityHeaders } from 'npm:theokit/adapters/security-headers'`,
38
44
  `// T3.3 \u2014 WS bridge for Deno runtime`,
@@ -85,7 +91,7 @@ function renderDenoEntry(port, opts = {}) {
85
91
  // B-027 — `npm:`, like every other specifier this target emits (`:37-43`). A bare one does
86
92
  // not resolve on Deno Deploy, and the harness asserts the prefix is here before rewriting it.
87
93
  ...opts.rateLimit === void 0 ? [] : [
88
- `import { createRateLimiterWeb } from 'npm:theokit/server'`,
94
+ `import { createRateLimiterWeb } from 'npm:theokit/server/rate-limit'`,
89
95
  `import { resolveClientIpFromRequest } from 'npm:theokit/server/rate-limit'`,
90
96
  ``
91
97
  ],
@@ -204,6 +210,10 @@ async function buildDeno(config, cwd, deps = {}, ctx) {
204
210
  );
205
211
  }
206
212
  var denoDeployAdapter = {
213
+ // Same as `bun`, plus the runtime compiles the TypeScript it finds — which is why a scan that
214
+ // answered `SyntaxError` on netlify is legitimate here. The last runtime scanner in the fleet.
215
+ readsSourceAtRunTime: true,
216
+ specifiersResolvedBy: "the-project-at-run-time",
207
217
  name: "deno-deploy",
208
218
  streamsResponses: true,
209
219
  // #409 / #410 — the generated entry calls `executeRoute` with routes, loader
@@ -228,4 +238,4 @@ export {
228
238
  denoDeployAdapter,
229
239
  renderDenoEntry
230
240
  };
231
- //# sourceMappingURL=deno-deploy-IVACZ62D.js.map
241
+ //# sourceMappingURL=deno-deploy-6H354VRA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/deno-deploy.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Deno Deploy adapter. Writes to `cwd/.theokit/deno-deploy/`. Build-time.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment, scannedFromLoaderCache } from './deployed-agents.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport { deployedRateLimitFragment, rateLimitCheckFragment } from './deployed-rate-limit.js'\nimport {\n agentsDirLiteral,\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter, DeployedEntryOptions } from './types.js'\n\nexport interface DenoBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\n/**\n * The framework imports this entry opens with, as `npm:` specifiers.\n *\n * Extracted from `renderDenoEntry` when adding the configured-directory literal pushed it past the\n * per-function line budget. A cohesive block — every line is one import of the same package family\n * — so lifting it keeps the budget a signal about the renderer rather than about its preamble.\n */\nconst FRAMEWORK_IMPORTS: readonly string[] = [\n `// Use npm: specifier so Deno resolves theokit from the user's package.json`,\n `// equivalent (works in both local 'deno run' and Deno Deploy).`,\n // Sub-paths, not the umbrella. `theokit/server` is DEPRECATED by the framework itself with a\n // REMOVAL scheduled, so this entry would stop loading on that release, before a request exists —\n // measured on Deno 2.9.5, where the warning printed on every start. This was the only adapter still\n // on the umbrella; the split below is the mapping four siblings already use and Bun proves by\n // running.\n `import { scanServerRoutes, matchRoute, createProductionLoader, scanWebSocketRoutes } from 'npm:theokit/server/scan'`,\n `import { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'npm:theokit/server/http'`,\n `import { createWebShim } from 'npm:theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'npm:theokit/adapters/security-headers'`,\n `// T3.3 — WS bridge for Deno runtime`,\n `import { createDenoWsBridge } from 'npm:theokit/adapters/ws-shim'`,\n]\n\n/** The target's name, in the five places that spell it. Adding a sixth tripped the duplicate-literal gate. */\n/* The name in the places a gate does NOT read. `assertServicesUnsupported` keeps the literal:\n * `services-other-adapters-reject.test.ts:30` requires each adapter to name ITSELF there, so a\n * copy-paste carrying another adapter's name cannot hide behind a constant. */\nconst TARGET = 'deno-deploy'\n\nexport function renderDenoEntry(port: number, opts: DeployedEntryOptions = {}): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(scannedFromLoaderCache(agentsDirLiteral(opts)), {\n notFound: 'notFound()',\n importPrefix: 'npm:',\n // B-185 — bound only when the runtime-config fragment declared the const, which is\n // exactly when a plugins module was emitted. Referencing it otherwise would emit an\n // identifier the entry never declares.\n pluginRunnerExpr:\n opts.runtimeConfigModule === undefined ? undefined : 'await THEO_PLUGIN_RUNNER',\n })\n return [\n `// Generated by Theo — Deno Deploy Adapter`,\n `// Deploy: deployctl deploy --project=<name> .theokit/deno/server.ts`,\n `// Requires Deno >= 1.40 (Deno.serve + npm: specifier support)`,\n ``,\n `// Runtime guard`,\n `if (typeof Deno === 'undefined') {`,\n ` throw new Error('TheoDenoDeployAdapter must run inside Deno.')`,\n `}`,\n ``,\n ...FRAMEWORK_IMPORTS,\n ``,\n `const port = Number(Deno.env.get('PORT') ?? '${port}')`,\n `const cwd = Deno.cwd()`,\n `const serverDir = cwd + '/' + ${serverDirLiteral(opts)}`,\n `let routesCache = null`,\n `let wsRoutesCache = null`,\n `let loaderCache = null`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed isolate has no`,\n `// theo.config.ts to read. Non-API paths 404 here and are served by Deno`,\n `// Deploy's static asset handler, so this covers the API and not the`,\n `// document (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, TARGET),\n ``,\n `function notFound() {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'Content-Type': 'application/json' },`,\n ` })`,\n `}`,\n ``,\n // B-027 — `npm:`, like every other specifier this target emits (`:37-43`). A bare one does\n // not resolve on Deno Deploy, and the harness asserts the prefix is here before rewriting it.\n ...(opts.rateLimit === undefined\n ? []\n : [\n `import { createRateLimiterWeb } from 'npm:theokit/server/rate-limit'`,\n `import { resolveClientIpFromRequest } from 'npm:theokit/server/rate-limit'`,\n ``,\n ]),\n ...deployedRateLimitFragment(\n opts.rateLimit,\n TARGET,\n // `info.remoteAddr` is the runtime's own answer. A `UnixAddr` has no `hostname`, so the\n // optional chain is what keeps the read from throwing there rather than a guess.\n `info?.remoteAddr?.hostname ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n 'request, info',\n // B-257 — `npm:`, like every other specifier this target emits. A bare one does not resolve\n // on Deno Deploy, and the durable limiter's import is emitted by the fragment rather than\n // here, so the prefix has to travel with it.\n 'npm:',\n ),\n ``,\n // The serve handler's SECOND parameter is bound here for the first time: `Deno.serve` has\n // always passed it and the emitted entry discarded it.\n `Deno.serve({ port }, async (request, info) => {`,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(opts.rateLimit, ' ', 'request, info'),\n ``,\n ` // LCR0103 — the upgrade branch sits BELOW the limiter, and the order is the point.`,\n ` // It used to sit above, under the comment \"a 101 carries no document and no script,`,\n ` // so the security baseline does not apply to it\". That is true of the security`,\n ` // HEADERS — a document concern — and false of the limiter, which is a resource`,\n ` // concern: a long-lived socket is the most expensive thing this entry hands out, so`,\n ` // the upgrade is the path that most needs a budget, not the one that may skip it.`,\n ` // T3.3 — Detect WebSocket upgrade and delegate to the Deno bridge.`,\n ` // A 101 carries no document and no script, so the security baseline does`,\n ` // not apply to it.`,\n ` if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {`,\n ` if (!wsRoutesCache) wsRoutesCache = scanWebSocketRoutes(serverDir)`,\n ` if (wsRoutesCache.length === 0) return notFound()`,\n ` const denoWs = createDenoWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` }, Deno)`,\n ` return denoWs.handle(request)`,\n ` }`,\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n `})`,\n ``,\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ``,\n ` if (!url.pathname.startsWith('/api/')${agentsFragment.hostBypass}) {`,\n ` // Static + SPA fallback are served by Deno Deploy's static asset handler.`,\n ` return notFound()`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ...agentsFragment.branch,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) return notFound()`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — not awaited: toResponse() settles at the headers and carries a`,\n ` // live body, so Deno.serve streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeConfig.executeRouteSpread} }))`,\n `}`,\n ``,\n `console.log('Theo (Deno Deploy) listening on :' + port)`,\n ].join('\\n')\n}\n\nexport async function buildDeno(\n config: TheoConfig,\n cwd: string,\n deps: DenoBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('deno-deploy', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/deno')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const pluginsPlan = planDeployedPlugins(config.plugins, denoDeployAdapter.name)\n const entry = renderDenoEntry(config.port, {\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n // #95 — the configured directories, which `build.ts:210` already threads into the Vite\n // plugins. Without these two lines the literals above fall to their defaults and a project\n // with a custom dir deploys an entry that resolves a directory it does not have.\n serverDir: config.serverDir,\n agentsDir: config.agentsDir,\n })\n const write =\n deps.writeEntry ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n if (pluginsPlan !== undefined) {\n // Beside the entry, so the emitted import is a sibling. Written through the same seam as\n // the entry so a test that captures one captures both (#425).\n write(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n write(resolve(outputDir, 'server.ts'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Deno Deploy output → .theokit/deno/server.ts')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: TARGET,\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-unmanaged',\n })}\\n`,\n )\n}\n\nexport const denoDeployAdapter: DeployAdapter = {\n // Same as `bun`, plus the runtime compiles the TypeScript it finds — which is why a scan that\n // answered `SyntaxError` on netlify is legitimate here. The last runtime scanner in the fleet.\n readsSourceAtRunTime: true,\n specifiersResolvedBy: 'the-project-at-run-time',\n name: 'deno-deploy',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this isolate returns. The\n // document comes from Deno Deploy's static asset handler and does not pass\n // through it (usetheokit/theokit#412).\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n build(config, cwd, ctx) {\n return buildDeno(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;AAgCxB,IAAM,oBAAuC;AAAA,EAC3C;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMA,IAAM,SAAS;AAER,SAAS,gBAAgB,MAAc,OAA6B,CAAC,GAAW;AACrF,QAAM,gBAAgB,8BAA8B,IA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