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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/aws-lambda.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * AWS Lambda adapter. Writes to `cwd/.theokit/lambda/`. Build-time tool.\n */\nimport { mkdirSync } 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 {\n bundleDeployedFunction,\n type BundleDeployedFunctionOptions,\n} from './bundle-deployed-function.js'\nimport { deployedAgentsFragment, JSON_NOT_FOUND_RESPONSE } from './deployed-agents.js'\nimport { renderBakedRoutes, routeRuntimeLines, type BakedRoute } from './deployed-baked-routes.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport {\n deployedRateLimitFragment,\n rateLimitCheckFragment,\n type DeployedRateLimitOptions,\n} from './deployed-rate-limit.js'\nimport { deployedRuntimeConfigFragment, serverDirLiteral } from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter, DeployedEntryOptions } from './types.js'\n\nexport interface AwsLambdaBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n /**\n * Seam for the bundling step, alongside `runNodeBuild`.\n *\n * The entry imports five `theokit/…` sub-paths by bare specifier, and nothing resolves them for\n * an uploaded Lambda: measured 2026-09-29, copying the written handler to a directory with no\n * `node_modules` gave `ERR_MODULE_NOT_FOUND: Cannot find package 'theokit'`. ADR 0020 names this\n * target as needing the same call Vercel got.\n */\n bundleFunction?: (options: BundleDeployedFunctionOptions) => Promise<void>\n /**\n * RETIRED by B-344, kept out rather than left accepting a value nothing reads.\n *\n * The handler is bundled now, so there is no raw write for a caller to intercept. A dep a build\n * accepts and ignores is the same defect as a renderer option it accepts and ignores — see the\n * `agentsDir` note in `netlify.ts`. Nothing in this repository stubbed it.\n */\n ensureDir?: (path: string) => void\n}\n\nexport interface RequestShape {\n method: string\n path: string\n headers: Record<string, string>\n body?: string\n}\n\nexport interface LambdaResultV2 {\n statusCode: number\n headers: Record<string, string>\n body: string\n isBase64Encoded: boolean\n}\n\nconst BINARY_CONTENT_TYPES = [\n 'application/octet-stream',\n 'application/pdf',\n 'application/zip',\n 'image/',\n 'audio/',\n 'video/',\n]\n\nfunction isBinaryContentType(contentType: string | undefined): boolean {\n if (!contentType) return false\n const ct = contentType.toLowerCase()\n return BINARY_CONTENT_TYPES.some((prefix) => ct.startsWith(prefix))\n}\n\ninterface APIGatewayProxyEventV2 {\n version: string\n requestContext: {\n http: { method: string; path: string }\n }\n headers?: Record<string, string | undefined>\n body?: string\n isBase64Encoded?: boolean\n}\n\nexport function eventV2ToRequestShape(event: APIGatewayProxyEventV2): RequestShape {\n const headers: Record<string, string> = {}\n for (const [k, v] of Object.entries(event.headers ?? {})) {\n if (v !== undefined) headers[k] = v\n }\n let body: string | undefined = event.body\n if (body !== undefined && event.isBase64Encoded) {\n body = Buffer.from(body, 'base64').toString('utf-8')\n }\n return {\n method: event.requestContext.http.method,\n path: event.requestContext.http.path,\n headers,\n body,\n }\n}\n\nexport function responseToLambdaResultV2(\n statusCode: number,\n headers: Record<string, string>,\n body: string,\n): LambdaResultV2 {\n const isBinary = isBinaryContentType(headers['content-type'])\n return {\n statusCode,\n headers,\n body: isBinary ? Buffer.from(body, 'binary').toString('base64') : body,\n isBase64Encoded: isBinary,\n }\n}\n\n// Generated-code fragments — extracted so the parent emitter stays under the\n// max-lines-per-function ceiling.\n/** The v2 result conversion, the handler, and the routing that feeds them. */\n/** The target's name, in the five places that spell it — same gate deno-deploy tripped. */\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 = 'aws-lambda'\n\nfunction awsLambdaHandlerFragment(\n runtimeSpread: string,\n agentsBranch: readonly string[],\n agentsHostBypass: string,\n /** B-027 — passed, not read: this is a separate function from the parent emitter. */\n rateLimit: DeployedRateLimitOptions['rateLimit'],\n): string[] {\n return [\n `// #382 — this target is DELISTED for response streaming, by construction.`,\n `// The Lambda v2 result object below carries \\`body\\` as a string, so the`,\n `// response cannot exist until the run has finished, no matter how the`,\n `// framework's shim writes it. Streaming here would require`,\n `// \\`awslambda.streamifyResponse\\` plus a Function URL in RESPONSE_STREAM`,\n `// invoke mode — neither of which this adapter emits, and which would break`,\n `// every API Gateway deployment of it. Rather than degrade in silence, a`,\n `// response that is unambiguously a stream is named in the logs below.`,\n `async function responseToV2Result(response, routePath) {`,\n ` const headers = {}`,\n ` response.headers.forEach((v, k) => { headers[k] = v })`,\n ` const ct = headers['content-type'] ?? ''`,\n ` if (ct.includes('text/event-stream')) {`,\n ` console.warn(`,\n ` '[theo][aws-lambda] ' + routePath + ' returned a streaming response (' + ct + '), ' +`,\n ` 'but the aws-lambda target buffers it whole and delivers it when the run ends. ' +`,\n ` 'This target is delisted for streaming (theokit#382). Deploy streaming routes to ' +`,\n ` 'cloudflare, vercel, netlify, bun, deno-deploy or node.'`,\n ` )`,\n ` }`,\n ` const isBinary = /^application\\\\/(octet-stream|pdf|zip)|^(image|audio|video)\\\\//.test(ct)`,\n ` if (isBinary) {`,\n ` const buf = Buffer.from(await response.arrayBuffer())`,\n ` return {`,\n ` statusCode: response.status,`,\n ` headers,`,\n ` body: buf.toString('base64'),`,\n ` isBase64Encoded: true,`,\n ` }`,\n ` }`,\n ` return {`,\n ` statusCode: response.status,`,\n ` headers,`,\n ` body: await response.text(),`,\n ` isBase64Encoded: false,`,\n ` }`,\n `}`,\n ``,\n `// Every outcome — including both 404s — is produced as a Web Response by`,\n `// routeRequest, so the security baseline is applied at ONE place and the`,\n `// v2 result object is built from headers that already carry it.`,\n ...(rateLimit === undefined\n ? []\n : [\n `import { createRateLimiterWeb } from 'theokit/server/rate-limit'`,\n `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,\n ``,\n ]),\n ...deployedRateLimitFragment(\n rateLimit,\n TARGET,\n // The v2 payload's own answer, with the v1 `identity.sourceIp` beside it: a v1 event carries\n // no `http` object at all, and both reads are optional-chained so neither throws on the\n // other's shape. Same treatment `:153` already gives `requestContext?.http?.path`.\n `event.requestContext?.http?.sourceIp ?? event.requestContext?.identity?.sourceIp ?? resolveClientIpFromRequest(corsRequest, TRUST_PROXY)`,\n // `corsRequest`, not `request`: the Web request this entry builds is named that (`:157`).\n 'corsRequest, event',\n ),\n ``,\n `export const handler = async (event) => {`,\n ` const path = event.requestContext?.http?.path ?? '/'`,\n ` // #409 — the same event, read as a Web Request so the CORS matcher can see the method and`,\n ` // the \\`origin\\` header. \\`eventV2ToRequest\\` reads a body already present in the event, so`,\n ` // unlike the Node targets there is no stream to drain twice.`,\n ` const corsRequest = eventV2ToRequest(event)`,\n ``,\n ` // The preflight is answered BEFORE anything routes: an OPTIONS the router handles is an`,\n ` // OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(corsRequest)`,\n ...rateLimitCheckFragment(\n rateLimit,\n ' ',\n 'corsRequest, event',\n // This handler returns a Lambda v2 RESULT, not a Response. A bare `return <Response>` would\n // hand the runtime an object it does not understand.\n 'return responseToV2Result(withCors(corsRequest, withSecurityHeaders(rateLimited(limit), SECURITY_HEADERS)), path)',\n 'return responseToV2Result(withCors(corsRequest, withSecurityHeaders(unnamedCaller(), SECURITY_HEADERS)), path)',\n ),\n ` const response = preflight !== null`,\n ` ? withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ` : withCors(corsRequest, withSecurityHeaders(await routeRequest(event, path), SECURITY_HEADERS))`,\n ` return responseToV2Result(response, path)`,\n `}`,\n ``,\n `async function routeRequest(event, path) {`,\n ` if (!path.startsWith('/api/')${agentsHostBypass}) {`,\n ` return new Response(`,\n ` 'Static assets must be served from CloudFront or a separate static host.',`,\n ` { status: 404, headers: { 'content-type': 'text/plain' } },`,\n ` )`,\n ` }`,\n ``,\n ``,\n // B-235 — hoisted above the agents branch, which names `request` like every other host's.\n // It was declared below `matchRoute`, and an agent path never reaches a route match. Building\n // it here costs nothing new: the outer handler already built one for the CORS matcher, and\n // `eventV2ToRequest` reads a body the event already carries, so there is no stream to drain\n // twice.\n ` const request = eventV2ToRequest(event)`,\n ``,\n ...agentsBranch,\n ``,\n ` const match = matchRoute(path, routes)`,\n ` if (!match) return ${JSON_NOT_FOUND_RESPONSE}`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,\n `}`,\n ]\n}\n\nexport function renderAwsLambdaEntry(\n opts: DeployedEntryOptions & {\n /**\n * The routes, baked at build time (B-344).\n *\n * The entry used to resolve them with a runtime `scanServerRoutes` — a `readdirSync` over\n * `serverDir`. An uploaded Lambda has no source tree, so every `/api/*` answered its own JSON 404:\n * measured 2026-09-29 by bundling this entry, copying it to a directory with no `node_modules`,\n * importing it and invoking it with a synthetic API Gateway v2 event. Where a tree IS uploaded the\n * route files are TypeScript, which a plain Node runtime cannot compile — the `SyntaxError`\n * Netlify answered with before B-338. The fix #369 made for Cloudflare, B-319 for Vercel and B-338\n * for Netlify, on the fifth target, through the same emitter so the five cannot drift.\n */\n routes?: readonly BakedRoute[]\n /** The agents, for the same reason and from the same scan. */\n agents?: readonly { filePath: string; agentPath: string; name: string }[]\n contextModule?: string\n } = {},\n): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n // B-235. The entry already builds a Web `Request` — `eventV2ToRequest(event)`, for the CORS\n // matcher — so the shape this branch needs was here all along. `path` rather than `url.pathname`\n // because that is the name this host reads the route from.\n // B-344 — baked, for the reason the routes are: an uploaded function has no source tree, so a\n // runtime `scanAgents` finds nothing and `createProductionLoader()` would import a path that was\n // never shipped. Vercel's own note says it best — a fallback \"would preserve a behaviour that is\n // broken by construction: an entry that scans, finds nothing, and answers 404 while looking like it\n // tried.\"\n const agentsFragment = deployedAgentsFragment(\n { kind: 'baked', agents: opts.agents ?? [], contextModule: opts.contextModule },\n {\n pathname: 'path',\n // This entry has no `url` object: `eventV2ToRequest` builds a STRING, in another function.\n // `request` is what routeRequest holds, and it carries the same absolute URL that string was.\n baseUrl: 'new URL(request.url).origin',\n notFound: JSON_NOT_FOUND_RESPONSE,\n },\n )\n return [\n `// Generated by Theo — AWS Lambda Adapter`,\n `// Use with API Gateway HTTP API v2 (default).`,\n ``,\n `import { resolve } from 'node:path'`,\n `import { matchRoute, compilePattern } from 'theokit/server/scan'\\nimport { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'`,\n ...routeImports,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `const cwd = process.cwd()`,\n `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries, TARGET),\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed function has no`,\n `// theo.config.ts to read. Non-API paths 404 here and the document is served`,\n `// from CloudFront or another static host, so this covers the API and not the`,\n `// page (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, 'aws-lambda'),\n ``,\n `function eventV2ToRequest(event) {`,\n ` const method = event.requestContext?.http?.method ?? 'GET'`,\n ` const path = event.requestContext?.http?.path ?? '/'`,\n ` const host = event.headers?.host ?? 'lambda'`,\n ` const qs = event.rawQueryString ? '?' + event.rawQueryString : ''`,\n ` const url = 'https://' + host + path + qs`,\n ` const headers = new Headers()`,\n ` for (const [k, v] of Object.entries(event.headers ?? {})) {`,\n ` if (v !== undefined) headers.set(k, String(v))`,\n ` }`,\n ` let body = event.body`,\n ` if (body && event.isBase64Encoded) {`,\n ` body = Buffer.from(body, 'base64')`,\n ` }`,\n ` return new Request(url, {`,\n ` method,`,\n ` headers,`,\n ` body: method === 'GET' || method === 'HEAD' ? undefined : body,`,\n ` })`,\n `}`,\n ``,\n ...awsLambdaHandlerFragment(\n runtimeConfig.executeRouteSpread,\n agentsFragment.branch,\n agentsFragment.hostBypass,\n opts.rateLimit,\n ),\n ].join('\\n')\n}\n\n/**\n * Resolve the build's effective dependencies once.\n *\n * Extracted when `buildAwsLambda` crossed the complexity ceiling after B-344 added the bundling\n * seam. The defaults are a separate concern from the build's sequence (SRP), and the sequence is\n * the part a reader comes here to follow. Same extraction as `resolveNetlifyDeps`.\n */\nfunction resolveAwsLambdaDeps(deps: AwsLambdaBuildDeps): {\n runNodeBuild: NonNullable<AwsLambdaBuildDeps['runNodeBuild']>\n bundleFunction: NonNullable<AwsLambdaBuildDeps['bundleFunction']>\n ensureDir: NonNullable<AwsLambdaBuildDeps['ensureDir']>\n} {\n return {\n runNodeBuild: deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter),\n bundleFunction: deps.bundleFunction ?? bundleDeployedFunction,\n ensureDir: deps.ensureDir ?? ((path: string) => mkdirSync(path, { recursive: true })),\n }\n}\n\nexport async function buildAwsLambda(\n config: TheoConfig,\n cwd: string,\n deps: AwsLambdaBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n const { runNodeBuild, bundleFunction, ensureDir } = resolveAwsLambdaDeps(deps)\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('aws-lambda', readManifest(cwd))\n\n // #382 — refuse by name rather than build something that cannot do what was\n // asked. `ssrStreaming` is the config's declaration that responses stream,\n // and this target is delisted for that (see `awsLambdaAdapter.streamsResponses`).\n // Kept as a guard for a DIRECT call to this function, which bypasses the CLI. The normal path is\n // refused earlier, before anything is emptied — see `assertStreamingSupported` (B-336). One message,\n // declared in one place, so the two cannot drift apart.\n if (config.ssrStreaming) {\n const { assertStreamingSupported } = await import('./config-support.js')\n assertStreamingSupported(config, awsLambdaAdapter, 'aws-lambda')\n }\n\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/aws')\n ensureDir(outputDir)\n\n // B-344 — scanned on the BUILD machine, like cloudflare, vercel and netlify. An absent scanner\n // emits an entry with NO routes rather than falling back to a runtime scan: that fallback is what\n // answered 404 from a bundle with no source tree.\n const scanned = ctx?.scanRoutes?.(config.serverDir)\n\n const entry = renderAwsLambdaEntry({\n routes: scanned?.routes,\n agents: scanned?.agents,\n contextModule: scanned?.contextModule,\n securityHeaders: config.security?.headers,\n // B-315 — the same shape as the B-235 note below, one option over: this build never passed\n // `serverDir`, so a project declaring `src/server` got an entry resolving `server`.\n serverDir: config.serverDir,\n // B-235 — pillar (a): the option existed and no build passed it, so a project with a\n // configured agents directory got the default `agents` on this target. Same defect\n // B-185 fixed for bun and deno, one target over.\n agentsDir: config.agentsDir,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n })\n // B-344 — bundled, not written as source. Unlike netlify the output goes into the directory\n // itself rather than a subdirectory: Lambda's handler is `<file>.<export>` and the operator zips\n // the directory, so the bundler's chunks travel without a per-function folder. Netlify needed one\n // because its platform treats each file in the functions directory as a separate function.\n await bundleFunction({\n projectRoot: cwd,\n entrySource: entry,\n stagePath: '.theokit/aws/handler.entry.mjs',\n outDir: outputDir,\n entryFileName: 'handler.mjs',\n })\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ AWS Lambda output → .theokit/aws/handler.mjs')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: TARGET,\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-unmanaged',\n })}\\n`,\n )\n}\n\nexport const awsLambdaAdapter: DeployAdapter = {\n // B-342 / B-344 — measured by INVOKING the handler from a directory with no `node_modules`:\n // `ERR_MODULE_NOT_FOUND: Cannot find package 'theokit'` as source, then 404 once bundled but\n // still scanning, then 200 with routes and agents baked.\n readsSourceAtRunTime: false,\n specifiersResolvedBy: 'this-adapter',\n name: TARGET,\n // #382 — delisted for streaming, deliberately. See DeployAdapter.\n streamsResponses: false,\n streamingUnsupportedDetail:\n 'The Lambda v2 result object carries the body as a string, so nothing can leave the function ' +\n 'before the run ends. Response streaming would need awslambda.streamifyResponse plus a Function ' +\n 'URL in RESPONSE_STREAM invoke mode, which this adapter does not emit.',\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this function returns.\n // The document comes from CloudFront or another static host and does not pass\n // through it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n // 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 buildAwsLambda(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,iBAAiB;AAC1B,SAAS,eAAe;AA0DxB,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,oBAAoB,aAA0C;AACrE,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,KAAK,YAAY,YAAY;AACnC,SAAO,qBAAqB,KAAK,CAAC,WAAW,GAAG,WAAW,MAAM,CAAC;AACpE;AAYO,SAAS,sBAAsB,OAA6C;AACjF,QAAM,UAAkC,CAAC;AACzC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,MAAM,WAAW,CAAC,CAAC,GAAG;AACxD,QAAI,MAAM,OAAW,SAAQ,CAAC,IAAI;AAAA,EACpC;AACA,MAAI,OAA2B,MAAM;AACrC,MAAI,SAAS,UAAa,MAAM,iBAAiB;AAC/C,WAAO,OAAO,KAAK,MAAM,QAAQ,EAAE,SAAS,OAAO;AAAA,EACrD;AACA,SAAO;AAAA,IACL,QAAQ,MAAM,eAAe,KAAK;AAAA,IAClC,MAAM,MAAM,eAAe,KAAK;AAAA,IAChC;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,yBACd,YACA,SACA,MACgB;AAChB,QAAM,WAAW,oBAAoB,QAAQ,cAAc,CAAC;AAC5D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,MAAM,WAAW,OAAO,KAAK,MAAM,QAAQ,EAAE,SAAS,QAAQ,IAAI;AAAA,IAClE,iBAAiB;AAAA,EACnB;AACF;AASA,IAAM,SAAS;AAEf,S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;AAEO,IAAM,mBAAkC;AAAA;AAAA;AAAA;AAAA,EAI7C,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,EACtB,MAAM;AAAA;AAAA,EAEN,kBAAkB;AAAA,EAClB,4BACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYF,eAAe,CAAC,mBAAmB,QAAQ,cAAc,QAAQ,eAAe;AAAA;AAAA,EAEhF,mBAAmB;AAAA,EACnB,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,eAAe,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EAC5C;AACF;","names":[]}
@@ -1,16 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
+ import {
4
+ VALID_TARGETS,
5
+ targetRendersDocument
6
+ } from "./chunk-4X43VTST.js";
3
7
  import {
4
8
  describeControllerArtifacts,
5
9
  emitControllerArtifacts
6
- } from "./chunk-RE2WE7CD.js";
10
+ } from "./chunk-LOOOB46A.js";
7
11
  import {
8
12
  validateProjectStructure
9
13
  } from "./chunk-GEQJAFSV.js";
10
14
  import {
11
15
  preflightNodeAndBindings
12
16
  } from "./chunk-KTMQUYED.js";
13
- import "./chunk-QD5X56I3.js";
17
+ import "./chunk-FNJVSFEC.js";
14
18
  import "./chunk-C27VRUVN.js";
15
19
  import "./chunk-7UZZHCRN.js";
16
20
  import {
@@ -20,14 +24,14 @@ import {
20
24
  import {
21
25
  generateManifest,
22
26
  writeManifest as writeManifest2
23
- } from "./chunk-RCFD5W5V.js";
27
+ } from "./chunk-WR5B2XNT.js";
24
28
  import {
25
29
  scanAgents
26
- } from "./chunk-R7G2B2WH.js";
30
+ } from "./chunk-HKF6YNY4.js";
27
31
  import {
28
32
  scanServerRoutes,
29
33
  scanWebSocketRoutes
30
- } from "./chunk-NO6HA4FG.js";
34
+ } from "./chunk-4WP7A7RX.js";
31
35
  import {
32
36
  compareByCodeUnit,
33
37
  walkSourceFiles
@@ -49,21 +53,8 @@ import {
49
53
  import "./chunk-D2R5SJEL.js";
50
54
 
51
55
  // src/cli/commands/build.ts
52
- import { existsSync as existsSync4 } from "fs";
53
- import { dirname as dirname2, join, relative, resolve, sep as sep2 } from "path";
54
-
55
- // src/adapters/types.ts
56
- var VALID_TARGETS = [
57
- "node",
58
- "vercel",
59
- "cloudflare",
60
- "static",
61
- "bun",
62
- "deno-deploy",
63
- "netlify",
64
- "aws-lambda",
65
- "theo-cloud"
66
- ];
56
+ import { existsSync as existsSync5 } from "fs";
57
+ import { resolve as resolve2 } from "path";
67
58
 
68
59
  // src/server/cron/adapter-translators.ts
69
60
  import { existsSync, readFileSync } from "fs";
@@ -472,6 +463,48 @@ async function cleanOutDir(opts) {
472
463
  return { deleted, kept };
473
464
  }
474
465
 
466
+ // src/cli/commands/build-scan-routes.ts
467
+ import { existsSync as existsSync4 } from "fs";
468
+ import { join, relative, resolve, sep as sep2 } from "path";
469
+ function createBuildScanRoutes(projectRoot, config) {
470
+ return (serverDir) => {
471
+ const abs = resolve(projectRoot, serverDir);
472
+ const toProjectRelative = (p) => relative(projectRoot, p).split(sep2).join("/");
473
+ return {
474
+ routes: scanServerRoutes(abs).map((route) => ({
475
+ filePath: toProjectRelative(route.filePath),
476
+ routePath: route.routePath,
477
+ methods: route.methods ?? []
478
+ })),
479
+ wsRoutes: scanWebSocketRoutes(abs).map(
480
+ (ws) => toProjectRelative(typeof ws === "string" ? ws : ws.filePath)
481
+ ),
482
+ // #367 — agents are a DIFFERENT scan served by a DIFFERENT function, which is why no adapter
483
+ // had ever heard of them: the entries route `/api/` through `scanServerRoutes` +
484
+ // `executeRoute` alone, so `/api/agents/<name>` matched nothing and 404'd on every target.
485
+ // Scanned here, beside the routes, because the same inversion argument applies verbatim.
486
+ //
487
+ // B-312 — the root is the PROJECT ROOT, and was `dirname(abs)`. `config.agentsDir` is
488
+ // documented and declared relative to the project root, while `dirname(serverDir)` is the
489
+ // root only when `serverDir` is a direct child of it. The scaffold's own nested layout
490
+ // (`serverDir: 'src/server'`, `agentsDir: 'src/server/agents'`) made the two disagree, and
491
+ // `join()` produced `<root>/src/src/server/agents` — so `scanAgents` returned `[]` and every
492
+ // `/api/agents/*` route 404'd on every scanned target. Measured on a live Cloudflare deploy,
493
+ // 2026-09-26. Every other caller in the tree already passes the project root.
494
+ agents: scanAgents(projectRoot, config.agentsDir).map((agent) => ({
495
+ filePath: toProjectRelative(agent.filePath),
496
+ agentPath: agent.agentPath,
497
+ name: agent.name
498
+ })),
499
+ // B-185 — the identity module, decided here for the same reason the agents are: this provider
500
+ // is handed `serverDir`, and a Worker has no filesystem to look for it on. An app with no
501
+ // `server/context.ts` yields `undefined`, and the generator then emits no import — importing
502
+ // a file that is not there would fail the BUILD rather than one request.
503
+ contextModule: existsSync4(join(abs, "context.ts")) ? toProjectRelative(join(abs, "context.ts")) : void 0
504
+ };
505
+ };
506
+ }
507
+
475
508
  // src/cli/commands/build.ts
476
509
  var CRON_NA_TARGETS = /* @__PURE__ */ new Set(["bun", "netlify", "static"]);
477
510
  var CRON_SUPPORTED_TARGETS = VALID_TARGETS.filter((t) => !CRON_NA_TARGETS.has(t));
@@ -481,14 +514,19 @@ async function buildCommand(options) {
481
514
  loadEnv({ cwd, mode: "production" });
482
515
  const config = await loadConfig(cwd);
483
516
  validateProjectStructure(cwd, config.appDir);
484
- const distDirAbs = resolve(cwd, config.distDir);
485
- await cleanOutDir({ dir: distDirAbs });
486
517
  const target = options?.target ?? "node";
487
518
  if (!VALID_TARGETS.includes(target)) {
488
519
  throw new Error(
489
520
  `Invalid build target "${target}". Available targets: ${VALID_TARGETS.join(", ")}`
490
521
  );
491
522
  }
523
+ const { resolveAdapter, streamingTargets } = await import("./registry-OMLCP4AS.js");
524
+ const adapter = await resolveAdapter(target);
525
+ const { assertRateLimitEnforceable, assertStreamingSupported } = await import("./config-support-MOZYHRWG.js");
526
+ assertRateLimitEnforceable(config, adapter, target);
527
+ assertStreamingSupported(config, adapter, target, await streamingTargets());
528
+ const distDirAbs = resolve2(cwd, config.distDir);
529
+ await cleanOutDir({ dir: distDirAbs });
492
530
  const configAdapters = config.adapters;
493
531
  if (configAdapters && configAdapters.length > 0) {
494
532
  const otherAdapters = configAdapters.filter((a) => a !== target);
@@ -502,7 +540,7 @@ async function buildCommand(options) {
502
540
  console.log(`
503
541
  Building for ${target}...
504
542
  `);
505
- const serverDir = resolve(cwd, config.serverDir);
543
+ const serverDir = resolve2(cwd, config.serverDir);
506
544
  const distDir = distDirAbs;
507
545
  const manifest = generateManifest(serverDir, cwd, config.agentsDir);
508
546
  writeManifest2(manifest, distDir);
@@ -538,9 +576,9 @@ async function buildCommand(options) {
538
576
  });
539
577
  console.log(` \u2713 OpenAPI: ${String(hydrated.length)} ops \u2192 ${devResult.path}`);
540
578
  }
541
- await runAdapterBuild(target, config, cwd);
579
+ await runAdapterBuild(target, config, cwd, adapter);
542
580
  if (config.openapi !== void 0) {
543
- const distOut = resolve(cwd, "dist");
581
+ const distOut = resolve2(cwd, "dist");
544
582
  const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes });
545
583
  const distResult = emitOpenApi({
546
584
  manifest: hydrated,
@@ -548,13 +586,13 @@ async function buildCommand(options) {
548
586
  });
549
587
  console.log(` \u2713 OpenAPI (dist): ${distResult.path}`);
550
588
  }
551
- const ssrNote = config.ssr ? " (SSR)" : "";
589
+ const ssrNote = config.ssr && targetRendersDocument(target) ? " (SSR)" : "";
552
590
  console.log(`
553
591
  \u2713 Build complete \u2192 ${target}${ssrNote}
554
592
  `);
555
593
  }
556
- async function runAdapterBuild(target, config, cwd) {
557
- const { theoPluginAsync } = await import("./vite-plugin-3ON45MQE.js");
594
+ async function runAdapterBuild(target, config, cwd, adapter) {
595
+ const { theoPluginAsync } = await import("./vite-plugin-JVGI6QUO.js");
558
596
  const { default: react } = await import("@vitejs/plugin-react");
559
597
  const ctx = {
560
598
  // `react()` may return Plugin or Plugin[] depending on version; spread the
@@ -576,52 +614,21 @@ async function runAdapterBuild(target, config, cwd) {
576
614
  // `adapters → server` edge that `adapters-may-only-depend-on-core-router-services` refuses. The
577
615
  // CLI already imports both sides, so it composes the scan and hands over the result.
578
616
  //
579
- // Paths are made relative to the project root here, where `cwd` is known: that string is both
580
- // the emitted import specifier and the key the executor looks a module up by, and the scanners
581
- // return absolute paths.
582
- scanRoutes: (serverDir) => {
583
- const abs = resolve(cwd, serverDir);
584
- const toProjectRelative = (p) => relative(cwd, p).split(sep2).join("/");
585
- return {
586
- routes: scanServerRoutes(abs).map((route) => ({
587
- filePath: toProjectRelative(route.filePath),
588
- routePath: route.routePath,
589
- methods: route.methods ?? []
590
- })),
591
- wsRoutes: scanWebSocketRoutes(abs).map(
592
- (ws) => toProjectRelative(typeof ws === "string" ? ws : ws.filePath)
593
- ),
594
- // #367 — agents are a DIFFERENT scan served by a DIFFERENT function, which is why no
595
- // adapter had ever heard of them: the entries route `/api/` through `scanServerRoutes` +
596
- // `executeRoute` alone, so `/api/agents/<name>` matched nothing and 404'd on every target.
597
- // Scanned here, beside the routes, because the same inversion argument applies verbatim.
598
- agents: scanAgents(dirname2(abs), config.agentsDir).map((agent) => ({
599
- filePath: toProjectRelative(agent.filePath),
600
- agentPath: agent.agentPath,
601
- name: agent.name
602
- })),
603
- // B-185 — the identity module, decided here for the same reason the agents are: this
604
- // provider is handed `serverDir`, and a Worker has no filesystem to look for it on. An app
605
- // with no `server/context.ts` yields `undefined`, and the generator then emits no import —
606
- // importing a file that is not there would fail the BUILD rather than one request.
607
- contextModule: existsSync4(join(abs, "context.ts")) ? toProjectRelative(join(abs, "context.ts")) : void 0
608
- };
609
- }
617
+ // A module rather than a closure since B-312: the wrong argument it carried was unreachable from
618
+ // any test while it lived in here, because reaching it meant running the whole build.
619
+ scanRoutes: createBuildScanRoutes(cwd, config)
610
620
  };
611
- const { resolveAdapter } = await import("./registry-SDBODRU6.js");
612
- const adapter = await resolveAdapter(target);
613
- const { warnUnappliedConfig, assertRateLimitEnforceable } = await import("./config-support-SB5NDQZB.js");
614
- assertRateLimitEnforceable(config, adapter, target);
621
+ const { warnUnappliedConfig } = await import("./config-support-MOZYHRWG.js");
615
622
  warnUnappliedConfig(config, adapter, target, (message) => {
616
623
  console.log(message);
617
624
  });
618
625
  await adapter.build(config, cwd, ctx);
619
626
  }
620
627
  async function emitCronArtifacts(opts) {
621
- const cronsDir = resolve(opts.serverDir, "crons");
622
- const agentsSchedulesDir = resolve(opts.cwd, opts.agentsDir, "schedules");
628
+ const cronsDir = resolve2(opts.serverDir, "crons");
629
+ const agentsSchedulesDir = resolve2(opts.cwd, opts.agentsDir, "schedules");
623
630
  const cronNodes = await scanCronDirs([cronsDir, agentsSchedulesDir]);
624
- const manifestPath = resolve(opts.distDir, "crons.json");
631
+ const manifestPath = resolve2(opts.distDir, "crons.json");
625
632
  writeCronManifest(manifestPath, cronNodes, opts.cwd);
626
633
  console.log(` \u2713 Crons: ${cronNodes.length} declared`);
627
634
  if (cronNodes.length === 0) return;
@@ -640,19 +647,19 @@ async function emitCronArtifacts(opts) {
640
647
  try {
641
648
  switch (opts.target) {
642
649
  case "vercel":
643
- translateCronToVercel(resolve(opts.cwd, "vercel.json"), manifestEntries);
650
+ translateCronToVercel(resolve2(opts.cwd, "vercel.json"), manifestEntries);
644
651
  console.log(` \u2713 Cron \u2192 vercel.json crons[] (${cronNodes.length} entries)`);
645
652
  break;
646
653
  case "cloudflare":
647
- translateCronToCloudflare(resolve(opts.cwd, "wrangler.toml"), manifestEntries);
654
+ translateCronToCloudflare(resolve2(opts.cwd, "wrangler.toml"), manifestEntries);
648
655
  console.log(` \u2713 Cron \u2192 wrangler.toml [triggers] (${cronNodes.length})`);
649
656
  break;
650
657
  case "aws-lambda":
651
- translateCronToAws(resolve(opts.cwd, "serverless.yml"), manifestEntries);
658
+ translateCronToAws(resolve2(opts.cwd, "serverless.yml"), manifestEntries);
652
659
  console.log(` \u2713 Cron \u2192 serverless.yml functions (${cronNodes.length})`);
653
660
  break;
654
661
  case "deno-deploy":
655
- translateCronToDeno(resolve(opts.distDir, "crons-entry.ts"), manifestEntries);
662
+ translateCronToDeno(resolve2(opts.distDir, "crons-entry.ts"), manifestEntries);
656
663
  console.log(` \u2713 Cron \u2192 ${opts.distDir}/crons-entry.ts (Deno.cron)`);
657
664
  break;
658
665
  case "node":
@@ -665,9 +672,9 @@ async function emitCronArtifacts(opts) {
665
672
  }
666
673
  }
667
674
  async function emitJobArtifacts(opts) {
668
- const jobsDir = resolve(opts.serverDir, "jobs");
669
- const jobNodes = existsSync4(jobsDir) ? await scanJobs(jobsDir) : [];
670
- const manifestPath = resolve(opts.distDir, "jobs.json");
675
+ const jobsDir = resolve2(opts.serverDir, "jobs");
676
+ const jobNodes = existsSync5(jobsDir) ? await scanJobs(jobsDir) : [];
677
+ const manifestPath = resolve2(opts.distDir, "jobs.json");
671
678
  writeJobManifest(manifestPath, jobNodes, opts.cwd);
672
679
  console.log(` \u2713 Jobs: ${jobNodes.length} declared`);
673
680
  }
@@ -681,4 +688,4 @@ function relativize3(absPath, root) {
681
688
  export {
682
689
  buildCommand
683
690
  };
684
- //# sourceMappingURL=build-23QF5FNQ.js.map
691
+ //# sourceMappingURL=build-6FVZKORI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/build.ts","../src/server/cron/adapter-translators.ts","../src/server/_internal/atomic-write.ts","../src/server/cron/cron-manifest.ts","../src/server/cron/cron-scan.ts","../src/server/jobs/job-manifest.ts","../src/server/jobs/job-scan.ts","../src/cli/cleanup/cleanup.ts","../src/cli/commands/build-scan-routes.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\n// T1.1 (architecture-medium-deferrals) — nodeAdapter no longer static-imported.\n// All adapters dispatch via `adapterRegistry` (lazy-imported within runAdapterBuild).\nimport {\n VALID_TARGETS,\n targetRendersDocument,\n type BuildTarget,\n type AdapterBuildContext,\n type DeployAdapter,\n} from '../../adapters/types.js'\nimport { loadConfig } from '../../config/load-config.js'\nimport { loadEnv } from '../../config/load-env.js'\nimport { validateProjectStructure } from '../../config/validate-structure.js'\nimport {\n ExistingConfigUnparseableError,\n translateCronToAws,\n translateCronToCloudflare,\n translateCronToDeno,\n translateCronToVercel,\n} from '../../server/cron/adapter-translators.js'\nimport { writeCronManifest } from '../../server/cron/cron-manifest.js'\nimport { scanCronDirs } from '../../server/cron/cron-scan.js'\nimport { writeJobManifest } from '../../server/jobs/job-manifest.js'\nimport { scanJobs } from '../../server/jobs/job-scan.js'\nimport { generateManifest, writeManifest } from '../../server/scan/manifest.js'\nimport {\n buildManifest as buildServicesManifest,\n writeManifest as writeServicesManifest,\n} from '../../services/index.js'\n// G2 T2.2 — OpenAPI emit. Opt-in via `config.openapi`. Dual output:\n// 1. <distDir>/openapi.json (pre-Vite, dev surface + manifests sibling)\n// 2. dist/openapi.json (post-Vite, build artifact)\n// The dist emit awaits runAdapterBuild — if Vite fails, the second emit\n// never runs (EC-2 absorbed: no stale dist artifact).\nimport { emitOpenApi } from '../../vite-plugin/openapi-emit/emit.js'\nimport { loadRoutesForOpenApi } from '../../vite-plugin/openapi-emit/load-routes.js'\nimport { cleanOutDir } from '../cleanup/cleanup.js'\nimport { preflightNodeAndBindings } from '../preflight-node-version.js'\n\nimport { describeControllerArtifacts, emitControllerArtifacts } from './build/emit-controllers.js'\nimport { createBuildScanRoutes } from './build-scan-routes.js'\n\n// Adapters that do NOT support cron triggers natively. Build still\n// succeeds with crons declared, but emits a warning + skip note.\nconst CRON_NA_TARGETS = new Set<BuildTarget>(['bun', 'netlify', 'static'])\n\n// DERIVED, never restated. A hand-written list here went stale and told users\n// that three working targets were unsupported: it named node/vercel/cloudflare\n// while aws-lambda, deno-deploy and theo-cloud also translate crons. Deriving\n// from the two constants means adding a target cannot desynchronise the message.\nconst CRON_SUPPORTED_TARGETS = VALID_TARGETS.filter((t) => !CRON_NA_TARGETS.has(t))\n\nexport async function buildCommand(options?: { target?: string }): Promise<void> {\n const cwd = process.cwd()\n // Preflight (FIRST — BEFORE anything that touches native bindings).\n preflightNodeAndBindings(cwd)\n // Phase 1 (T1.2) — Load .env BEFORE config load.\n loadEnv({ cwd, mode: 'production' })\n\n const config = await loadConfig(cwd)\n // #95 — honor config.appDir so a custom frontend dir (e.g. apps/web) passes the structure gate.\n validateProjectStructure(cwd, config.appDir)\n\n // B-336 — EVERY refusal that is decidable from the target and the config alone runs BEFORE the\n // clean. `cleanOutDir` used to sit here, above even the check that the target EXISTS: measured on a\n // real project, `theokit build --target nao-existe` destroyed 302 files in `.theokit/client/assets`\n // and answered with a message about the typo. The comment above\n // `assertRateLimitEnforceable` already stated this intent in its own words — \"refused by name,\n // BEFORE the build writes anything\" — and the order defeated it.\n const target = (options?.target ?? 'node') as BuildTarget\n\n if (!VALID_TARGETS.includes(target)) {\n throw new Error(\n `Invalid build target \"${target}\". Available targets: ${VALID_TARGETS.join(', ')}`,\n )\n }\n\n const { resolveAdapter, streamingTargets } = await import('../../adapters/registry.js')\n const adapter = await resolveAdapter(target)\n const { assertRateLimitEnforceable, assertStreamingSupported } =\n await import('../../adapters/config-support.js')\n\n // #461 — a dropped `cors` degrades where someone can see it; a dropped RATE LIMIT looks exactly like\n // success until the abuse it was meant to stop. Refused by name, and now genuinely before anything is\n // written or destroyed.\n assertRateLimitEnforceable(config, adapter, target)\n assertStreamingSupported(config, adapter, target, await streamingTargets())\n\n // T2.2 — Clean .theokit/ at build start (Astro pattern). Skip .git*.\n const distDirAbs = resolve(cwd, config.distDir)\n await cleanOutDir({ dir: distDirAbs })\n\n // EC-201 — cross-reference note when config.adapters[] diverges from\n // the --target flag. --target is authoritative per ADR D2.\n const configAdapters = (config as { adapters?: readonly string[] }).adapters\n if (configAdapters && configAdapters.length > 0) {\n const otherAdapters = configAdapters.filter((a) => a !== target)\n if (otherAdapters.length > 0) {\n console.log(\n `\\n Note: theo.config.ts.adapters lists [${otherAdapters.join(', ')}]; ` +\n `this build translates for ${target} only. ` +\n `Run \\`theokit build --target=<adapter>\\` separately for each (cross-reference).`,\n )\n }\n }\n\n console.log(`\\n Building for ${target}...\\n`)\n\n // Manifests emit BEFORE adapter bundling (Vite). Why: manifests are\n // fast + deterministic + don't depend on Vite. If Vite fails (missing\n // dep, malformed entry), the user still gets manifests for diagnostics.\n const serverDir = resolve(cwd, config.serverDir)\n const distDir = distDirAbs\n // #95 follow-up — pass projectRoot (cwd) + config.agentsDir so agents scan honors a custom dir.\n const manifest = generateManifest(serverDir, cwd, config.agentsDir)\n writeManifest(manifest, distDir)\n\n const totalEndpoints =\n manifest.routes.length + manifest.actions.length + manifest.websockets.length\n console.log(\n ` ✓ Manifest: ${manifest.routes.length} routes, ${manifest.actions.length} actions, ${manifest.websockets.length} ws (${totalEndpoints} total)`,\n )\n\n // T1.1 — cron scan + manifest + per-target adapter translation\n await emitCronArtifacts({ cwd, serverDir, agentsDir: config.agentsDir, distDir, target })\n\n // T1.2 — job scan + manifest (no per-target translation needed)\n await emitJobArtifacts({ cwd, serverDir, distDir })\n\n // theokit#123 — compile `server/controllers/**` so `theokit start` can serve them.\n //\n // #122 made controllers first-class in dev, where Vite's swc transform compiles them on the fly.\n // Production has neither, so an uncompiled `.controller.ts` cannot load and its routes 404'd —\n // working in dev and failing in prod, which is the worst place for a gap to live.\n //\n // Deliberately NOT folded into `generateManifest` (ADR-5): the manifest is the deploy-adapter\n // contract, and a parallel route source in it would ripple through every adapter. This writes a\n // separate artifact only the Node start path reads. No controllers ⇒ no artifact at all.\n const controllerManifest = await emitControllerArtifacts({ serverDir, distDir })\n if (controllerManifest !== null) {\n console.log(` ${describeControllerArtifacts(controllerManifest)}`)\n }\n\n // Wave 2 (T1.2) — services manifest at <cwd>/.theokit/services.json. Always\n // emit (empty array when services: {} is empty) so adapters can rely on\n // the file existing. Topological order preserved by buildServicesManifest.\n //\n // Plan v1.2 T2.1 — when theo.config.ts declares `name`, emit services.json\n // v2 with that project identifier. Falling back to v1 (no project field)\n // keeps TheoCloud's deprecation warning path intact (services-bundle).\n const projectName = config.name\n const servicesManifest = buildServicesManifest(config.services, projectName)\n writeServicesManifest(cwd, servicesManifest)\n if (servicesManifest.services.length > 0) {\n const versionLabel = `v${String(servicesManifest.version)}`\n const projectLabel =\n servicesManifest.version === 2 ? ` project=\"${servicesManifest.project}\"` : ''\n console.log(\n ` ✓ Services manifest (${versionLabel}${projectLabel}): ${String(servicesManifest.services.length)} service(s) ` +\n `(${servicesManifest.services.map((s) => s.name).join(', ')})`,\n )\n } else if (servicesManifest.version === 1) {\n console.log(\n ' ⚠ services.json emitted as v1 (no `name` in theo.config.ts). ' +\n 'TheoCloud will accept this with a deprecation warning; sunset in theokit 0.6.0. ' +\n 'Run `theokit migrate services-json-v1-to-v2` to upgrade.',\n )\n }\n\n // G2 T2.2 — OpenAPI dev-surface emit (pre-Vite, sibling of manifests).\n // Opt-in: only when config.openapi is defined. Best-effort: a route load\n // failure produces a warning, not a build abort.\n if (config.openapi !== undefined) {\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const devResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distDir },\n })\n console.log(` ✓ OpenAPI: ${String(hydrated.length)} ops → ${devResult.path}`)\n }\n\n // Now run the adapter-specific bundling (Vite + adapter-specific work).\n await runAdapterBuild(target, config, cwd, adapter)\n\n // G2 T2.2 — OpenAPI build-artifact emit (post-Vite, EC-2 gated on success).\n // If runAdapterBuild threw, execution never reaches this point — no stale\n // dist/openapi.json is written.\n if (config.openapi !== undefined) {\n const distOut = resolve(cwd, 'dist')\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const distResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distOut },\n })\n console.log(` ✓ OpenAPI (dist): ${distResult.path}`)\n }\n\n // Derived, not asserted. This read `config.ssr` alone, so a target whose entry delegates the\n // document to a static host was announced as server-rendering — measured on `--target bun`, which\n // printed `(SSR)` and served an empty `<div id=\"root\">` (B-334).\n const ssrNote = config.ssr && targetRendersDocument(target) ? ' (SSR)' : ''\n console.log(`\\n ✓ Build complete → ${target}${ssrNote}\\n`)\n}\n\nasync function runAdapterBuild(\n target: BuildTarget,\n config: Awaited<ReturnType<typeof loadConfig>>,\n cwd: string,\n // Resolved by the caller, which needs it before `cleanOutDir` to run the refusals (B-336). Passing it\n // in rather than resolving again keeps one answer to \"which adapter is this build\".\n adapter: DeployAdapter,\n): Promise<void> {\n // T1.1 (architecture-cleanup) — CLI composes the Vite Plugin[] and INJECTS it into\n // the adapter via ctx.makeVitePlugins. This inverts the previous `adapters → vite-plugin`\n // edge — adapters no longer import from vite-plugin/ directly.\n //\n // theoPlugin AND `@vitejs/plugin-react` are dynamically imported so the deps are\n // materialized only when needed (adapter is `node`). This keeps the CLI's startup\n // path independent of optional build-time deps (so e.g. `theokit build --target=static`\n // does not need react installed). dep-cruiser's per-module rule allows `cli → vite-plugin`.\n //\n // 0.2.2 regression fix: switched sync `theoPlugin()` → `theoPluginAsync()` so the\n // returned Plugin[] includes the @theo/actions virtual module + typed-client +\n // services + @theokit/ui auto-chain. Without async, build-time Rollup couldn't\n // resolve `@theo/actions` even though dev-time Vite (which already used async)\n // could. See https://github.com/usetheo/theokit/commits — 0.2.2 changelog.\n const { theoPluginAsync } = await import('../../vite-plugin/index.js')\n const { default: react } = await import('@vitejs/plugin-react')\n const ctx: AdapterBuildContext = {\n // `react()` may return Plugin or Plugin[] depending on version; spread the\n // async chain so the contract returns a flat Plugin[] (AdapterBuildContext\n // type updated to `Plugin[] | Promise<Plugin[]>`).\n // #95 — inject the config dirs so the client build's router/entry + typed-client codegen honor\n // custom appDir/serverDir/agentsDir (e.g. \"apps/web\" / \"core\" / \"core/agents\").\n makeVitePlugins: async (opts) =>\n [\n react(),\n ...(await theoPluginAsync({\n ...opts,\n appDir: config.appDir,\n serverDir: config.serverDir,\n agentsDir: config.agentsDir,\n })),\n ].flat(),\n\n // #369 — the same inversion, for the same reason. A Worker has no filesystem, so the Cloudflare\n // entry bakes its routes at build time; importing the scanner from `adapters/` would add the\n // `adapters → server` edge that `adapters-may-only-depend-on-core-router-services` refuses. The\n // CLI already imports both sides, so it composes the scan and hands over the result.\n //\n // A module rather than a closure since B-312: the wrong argument it carried was unreachable from\n // any test while it lived in here, because reaching it meant running the whole build.\n scanRoutes: createBuildScanRoutes(cwd, config),\n }\n\n // T1.1 (architecture-medium-deferrals, ADR D1) — Adapter Registry replaces\n // the previous 9-case switch. New adapters add 1 line in `adapters/registry.ts`;\n // CLI is closed for modification (OCP).\n // #409 / #410 — a config key that validates and is then never read makes the\n // deployed app behave as if the operator had not written it, with nothing\n // anywhere saying so. Name it before the build output scrolls past.\n const { warnUnappliedConfig } = await import('../../adapters/config-support.js')\n\n // #461 / #321 / #322 — the rate-limit refusal moved to `buildCommand`, above `cleanOutDir`, because\n // this position made its own comment false: it claimed the combination was refused \"BEFORE the build\n // writes anything\" and it is reached a hundred lines after the output has been emptied (B-336).\n\n warnUnappliedConfig(config, adapter, target, (message) => {\n console.log(message)\n })\n\n await adapter.build(config, cwd, ctx)\n}\n\nasync function emitCronArtifacts(opts: {\n cwd: string\n serverDir: string\n agentsDir: string\n distDir: string\n target: BuildTarget\n}): Promise<void> {\n // Crons live in two conventional homes: `server/crons/` (a backend trigger) and\n // `agents/schedules/` (a scheduled agent run, kept in the agent domain). Both feed one manifest.\n const cronsDir = resolve(opts.serverDir, 'crons')\n const agentsSchedulesDir = resolve(opts.cwd, opts.agentsDir, 'schedules')\n\n const cronNodes = await scanCronDirs([cronsDir, agentsSchedulesDir])\n const manifestPath = resolve(opts.distDir, 'crons.json')\n writeCronManifest(manifestPath, cronNodes, opts.cwd)\n\n console.log(` ✓ Crons: ${cronNodes.length} declared`)\n\n if (cronNodes.length === 0) return\n\n // EC-201: target-specific translation. N/A targets emit a warning + skip.\n if (CRON_NA_TARGETS.has(opts.target)) {\n console.log(\n ` ⚠ Cron not supported by target \"${opts.target}\" — declared crons skipped. ` +\n `Supported targets: ${CRON_SUPPORTED_TARGETS.join(', ')}.`,\n )\n return\n }\n\n const manifestEntries = cronNodes.map((n) => ({\n name: n.name,\n filePath: relativize(n.filePath, opts.cwd),\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n\n try {\n switch (opts.target) {\n case 'vercel':\n translateCronToVercel(resolve(opts.cwd, 'vercel.json'), manifestEntries)\n console.log(` ✓ Cron → vercel.json crons[] (${cronNodes.length} entries)`)\n break\n case 'cloudflare':\n translateCronToCloudflare(resolve(opts.cwd, 'wrangler.toml'), manifestEntries)\n console.log(` ✓ Cron → wrangler.toml [triggers] (${cronNodes.length})`)\n break\n case 'aws-lambda':\n translateCronToAws(resolve(opts.cwd, 'serverless.yml'), manifestEntries)\n console.log(` ✓ Cron → serverless.yml functions (${cronNodes.length})`)\n break\n case 'deno-deploy':\n translateCronToDeno(resolve(opts.distDir, 'crons-entry.ts'), manifestEntries)\n console.log(` ✓ Cron → ${opts.distDir}/crons-entry.ts (Deno.cron)`)\n break\n case 'node':\n console.log(` ✓ Cron → in-process scheduler (theokit start)`)\n break\n }\n } catch (err) {\n if (err instanceof ExistingConfigUnparseableError) throw err\n throw err\n }\n}\n\nasync function emitJobArtifacts(opts: {\n cwd: string\n serverDir: string\n distDir: string\n}): Promise<void> {\n const jobsDir = resolve(opts.serverDir, 'jobs')\n\n const jobNodes = existsSync(jobsDir) ? await scanJobs(jobsDir) : []\n const manifestPath = resolve(opts.distDir, 'jobs.json')\n writeJobManifest(manifestPath, jobNodes, opts.cwd)\n console.log(` ✓ Jobs: ${jobNodes.length} declared`)\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time adapter translators: caller-controlled paths only.\n */\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronManifestEntry } from './cron-manifest.js'\n\n/**\n * Thrown when an existing platform-config file (vercel.json, wrangler.toml,\n * serverless.yml) cannot be parsed. Caller must fix the file before\n * re-running `theokit build`. We NEVER silently overwrite a user's config.\n */\nexport class ExistingConfigUnparseableError extends Error {\n readonly code = 'EXISTING_CONFIG_UNPARSEABLE'\n constructor(\n public readonly filePath: string,\n public readonly parseError: string,\n ) {\n super(\n `Existing config \"${filePath}\" could not be parsed: ${parseError}. ` +\n 'Fix or remove the file before re-running build — TheoKit never silently overwrites user configuration.',\n )\n this.name = 'ExistingConfigUnparseableError'\n }\n}\n\n// ──────────────────────────────────────────────────────────\n// Vercel — vercel.json crons[]\n// ──────────────────────────────────────────────────────────\n\ninterface VercelJson {\n crons?: { path: string; schedule: string }[]\n [key: string]: unknown\n}\n\n/**\n * Translate a TheoKit cron manifest into `vercel.json crons[]`.\n *\n * EC-105: existing fields (functions, headers, redirects, rewrites, env,\n * etc.) are preserved verbatim — ONLY the `crons[]` slice is replaced.\n */\nexport function translateCronToVercel(\n vercelJsonPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n let existing: VercelJson = {}\n if (existsSync(vercelJsonPath)) {\n const raw = readFileSync(vercelJsonPath, 'utf8')\n try {\n existing = JSON.parse(raw) as VercelJson\n } catch (err) {\n throw new ExistingConfigUnparseableError(\n vercelJsonPath,\n err instanceof Error ? err.message : String(err),\n )\n }\n }\n const merged: VercelJson = {\n ...existing,\n crons: crons.map((c) => ({\n path: `/api/__crons/${c.name}`,\n schedule: c.schedule,\n })),\n }\n writeAtomic(vercelJsonPath, JSON.stringify(merged, null, 2))\n}\n\n// ──────────────────────────────────────────────────────────\n// Cloudflare — wrangler.toml [triggers] crons\n// ──────────────────────────────────────────────────────────\n\n/**\n * Translate a TheoKit cron manifest into `wrangler.toml [triggers] crons`.\n *\n * EC-105: regex-based mutation that preserves comments + other sections\n * verbatim. Replaces only the `[triggers]` block (or appends if absent).\n */\nexport function translateCronToCloudflare(\n wranglerTomlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const schedules = crons.map((c) => `\"${c.schedule}\"`).join(', ')\n const triggersBlock = `[triggers]\\ncrons = [${schedules}]\\n`\n\n if (!existsSync(wranglerTomlPath)) {\n writeAtomic(wranglerTomlPath, triggersBlock)\n return\n }\n\n const existing = readFileSync(wranglerTomlPath, 'utf8')\n\n // Replace existing [triggers] section if present. Strategy: split into\n // line array, find the [triggers] header line, drop subsequent lines\n // until the next section header (line starting with `[`) or EOF.\n const lines = existing.split('\\n')\n const triggersIdx = lines.findIndex((l) => l.trim() === '[triggers]')\n\n let next: string\n if (triggersIdx !== -1) {\n let endIdx = lines.length\n for (let i = triggersIdx + 1; i < lines.length; i++) {\n if (lines[i].trim().startsWith('[')) {\n endIdx = i\n break\n }\n }\n const before = lines.slice(0, triggersIdx).join('\\n')\n const after = lines.slice(endIdx).join('\\n')\n next = `${before}\\n${triggersBlock.trimEnd()}\\n${after}`.replace(/\\n{3,}/g, '\\n\\n')\n } else {\n next = existing.endsWith('\\n')\n ? `${existing}\\n${triggersBlock}`\n : `${existing}\\n\\n${triggersBlock}`\n }\n writeAtomic(wranglerTomlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// AWS Lambda — serverless.yml functions.<fn>.events: schedule\n// ──────────────────────────────────────────────────────────\n\n/**\n * Convert TheoKit's 5-field UTC cron to AWS EventBridge's 6-field format.\n * EventBridge requires `?` in EITHER day-of-month OR day-of-week (not both `*`).\n *\n * Algorithm:\n * - If DOM is \"*\" and DOW is \"*\" → insert ? in DOW (default)\n * - If DOM is \"*\" and DOW is specific → insert ? in DOM\n * - If DOM is specific and DOW is \"*\" → insert ? in DOW\n * - Append \"*\" year field at end.\n */\nexport function convertToAwsCron(schedule: string): string {\n const parts = schedule.trim().split(/\\s+/)\n if (parts.length !== 5) {\n throw new Error(`Invalid 5-field schedule for AWS conversion: \"${schedule}\"`)\n }\n const [minute, hour, dom, month, dow] = parts\n let awsDom = dom\n let awsDow = dow\n if (dom === '*' && dow === '*') {\n awsDow = '?'\n } else if (dom === '*') {\n awsDom = '?'\n } else if (dow === '*') {\n awsDow = '?'\n }\n return `cron(${minute} ${hour} ${awsDom} ${month} ${awsDow} *)`\n}\n\n/**\n * Translate a TheoKit cron manifest into a `serverless.yml` functions\n * map with `events: - schedule: cron(...)` entries.\n *\n * EC-105: appends to `functions:` block, preserving all existing\n * functions/sections. Cron functions are named `cron_<name>` to avoid\n * collision with user-declared functions.\n */\nexport function translateCronToAws(\n serverlessYmlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const cronFunctionsYaml = crons\n .map(\n (c) => ` cron_${c.name}:\n handler: .theokit/server/crons/${c.name}.handler\n events:\n - schedule: ${convertToAwsCron(c.schedule)}`,\n )\n .join('\\n')\n\n const block = `\\nfunctions:\\n${cronFunctionsYaml}\\n`\n\n if (!existsSync(serverlessYmlPath)) {\n // Minimal serverless.yml scaffold\n writeAtomic(\n serverlessYmlPath,\n `service: theokit-app\\nprovider:\\n name: aws\\n runtime: nodejs22.x\\n${block}`,\n )\n return\n }\n\n const existing = readFileSync(serverlessYmlPath, 'utf8')\n\n // Look for an existing top-level `functions:` block; if present, append our\n // cron entries under it (don't replace user-declared functions).\n const functionsRe = /^functions:\\s*\\n/m\n let next: string\n if (functionsRe.test(existing)) {\n next = existing.replace(functionsRe, (match) => `${match}${cronFunctionsYaml}\\n`)\n } else {\n next = existing.endsWith('\\n') ? `${existing}${block}` : `${existing}\\n${block}`\n }\n writeAtomic(serverlessYmlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// Deno Deploy — Deno.cron registrations\n// ──────────────────────────────────────────────────────────\n\n/**\n * Emit a Deno entry file that registers each cron via `Deno.cron`.\n *\n * Unlike Vercel/CF/AWS, Deno.cron is an in-process runtime API — the\n * entry file is a managed artifact (overwritten each build), not a user\n * config (so EC-105 doesn't apply here).\n */\nexport function translateCronToDeno(entryPath: string, crons: readonly CronManifestEntry[]): void {\n const lines = crons.map(\n (c) =>\n `Deno.cron(\"${c.name}\", \"${c.schedule}\", async () => {\n const mod = await import(\"../${c.filePath}\");\n const def = mod.default;\n await def.handler({\n traceId: crypto.randomUUID().replace(/-/g, \"\"),\n scheduledAt: new Date(),\n signal: AbortSignal.timeout(60_000),\n });\n});`,\n )\n const content = `// AUTOGENERATED by TheoKit cron build — DO NOT EDIT.\n// Source: server/crons/*.ts → .theokit/crons.json → this file.\n${lines.join('\\n\\n')}\n`\n writeAtomic(entryPath, content)\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time atomic write: caller-controlled paths only. No HTTP input\n * reaches these fs calls.\n */\n// T5a.1b — Web Crypto migration. Build-time only; node:fs + node:path stay\n// because this is a manifest-write leaf (e.g. .theokit/jobs.json) and per\n// ADR-0028 the runtime-portable boundary is the request handler, not the\n// scanner. Only node:crypto is swapped out — Web Crypto's\n// getRandomValues works in every supported runtime.\nimport { mkdirSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\n/**\n * Write `content` to `path` atomically via the tmp + rename pattern.\n *\n * Two concurrent calls to `writeAtomic(path, ...)` are guaranteed to\n * leave `path` containing valid content from ONE of the calls (never\n * truncated, never interleaved). POSIX rename is atomic on the same\n * filesystem.\n *\n * EC-106 (jobs-crons-webhooks-cost-tracking-plan) — shared helper for\n * `.theokit/crons.json` and `.theokit/jobs.json` manifest writes so a\n * concurrent dev-server scan + build manifest emit never produces\n * partial JSON.\n *\n * @param path destination path\n * @param content bytes (UTF-8 string) to write\n */\nexport function writeAtomic(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n // Include a random suffix so two concurrent writes don't trample each\n // other's tmp file. Web Crypto getRandomValues is non-blocking +\n // collision-safe for the tiny entropy we need (8 hex chars = 32 bits).\n // Hex-encoded manually to avoid Buffer (runtime-agnostic per ADR-0028).\n const randBuf = new Uint8Array(4)\n globalThis.crypto.getRandomValues(randBuf)\n let suffix = ''\n for (const b of randBuf) suffix += b.toString(16).padStart(2, '0')\n const tmp = `${path}.tmp-${process.pid}-${suffix}`\n writeFileSync(tmp, content, 'utf8')\n renameSync(tmp, path)\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronNode } from './cron-scan.js'\n\nexport const CRON_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface CronManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: 'forbid' | 'allow'\n}\n\nexport interface CronManifest {\n readonly schemaVersion: typeof CRON_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly crons: readonly CronManifestEntry[]\n}\n\n/**\n * Build a `CronManifest` from scanned `CronNode[]`. Filepaths are kept\n * relative to the caller's project root for portability.\n */\nexport function buildCronManifest(nodes: readonly CronNode[], projectRoot?: string): CronManifest {\n const crons: CronManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n return {\n schemaVersion: CRON_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n crons,\n }\n}\n\n/**\n * Write the cron manifest to `path` atomically (EC-106).\n *\n * Accepts either a pre-built `CronManifest` OR an array of `CronNode[]`\n * (which gets converted via `buildCronManifest`). The atomic-write\n * helper guarantees `path` always contains valid JSON, even under\n * concurrent writes (e.g., dev-server rescan + build).\n */\nexport function writeCronManifest(\n path: string,\n input: readonly CronNode[] | CronManifest,\n projectRoot?: string,\n): void {\n const manifest: CronManifest = isManifest(input) ? input : buildCronManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is CronManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'crons' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only. No HTTP\n * input ever reaches these fs calls.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport { importUserModule } from '../../config/import-user-module.js'\nimport { compareByCodeUnit } from '../_internal/compare-by-code-unit.js'\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { CronConcurrencyPolicy, CronDefinition } from './cron-types.js'\n\n/**\n * One discovered cron from build-time scan. The handler is intentionally\n * NOT included — manifest is platform-neutral and consumed by adapters\n * that emit static config. Runtime dispatch loads the handler at fire time.\n */\nexport interface CronNode {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: CronConcurrencyPolicy\n}\n\nexport class DuplicateCronNameError extends Error {\n readonly code = 'DUPLICATE_CRON_NAME'\n constructor(\n public readonly cronName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate cron name \"${cronName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Cron names must be unique across server/crons/ and agents/schedules/.',\n )\n this.name = 'DuplicateCronNameError'\n }\n}\n\nconst CRON_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface CronModule {\n default?: unknown\n}\n\nfunction isCronDefinition(value: unknown): value is CronDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.schedule === 'string' &&\n typeof def.handler === 'function' &&\n (def.concurrency === 'forbid' || def.concurrency === 'allow')\n )\n}\n\n/**\n * Scan a directory for cron definition files and return the discovered\n * `CronNode[]` sorted by name. Throws `DuplicateCronNameError` on name\n * collision and `Error` on missing default export.\n *\n * Sequential by design — module imports are awaited one-by-one to keep\n * error messages anchored to the file that failed.\n */\nexport async function scanCrons(cronsDir: string): Promise<CronNode[]> {\n return scanCronDirs([cronsDir])\n}\n\n/**\n * Scan MULTIPLE cron directories and merge the results with a UNIFIED\n * duplicate-name guard across all of them. The framework discovers crons in\n * two conventional homes: `server/crons/` (a backend trigger) and\n * `agents/schedules/` (a scheduled agent run — kept in the agent domain). Both\n * feed the same manifest + deploy translation; a name may not collide across\n * the two dirs. Missing dirs are skipped (no error). Nodes are returned sorted\n * by name for a stable manifest.\n */\nexport async function scanCronDirs(dirs: readonly string[]): Promise<CronNode[]> {\n const filePaths: string[] = []\n for (const dir of dirs) {\n if (!existsSync(dir)) continue\n walkSourceFiles(dir, { extensions: CRON_EXTENSIONS }, (p) => {\n const base = basename(p)\n // Skip private helpers (`_helper.ts`) and OS junk (`.DS_Store`).\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n }\n\n const nodes: CronNode[] = []\n for (const filePath of filePaths) {\n let mod: CronModule\n try {\n mod = await importUserModule(filePath)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import cron file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isCronDefinition(exported)) {\n throw new Error(\n `Cron file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineCron(name, { schedule, handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n schedule: exported.schedule,\n concurrency: exported.concurrency,\n })\n }\n\n // Dup-name detection (unified across every scanned dir).\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateCronNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => compareByCodeUnit(a.name, b.name))\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { JobNode } from './job-scan.js'\n\nexport const JOB_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface JobManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport interface JobManifest {\n readonly schemaVersion: typeof JOB_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly jobs: readonly JobManifestEntry[]\n}\n\nexport function buildJobManifest(nodes: readonly JobNode[], projectRoot?: string): JobManifest {\n const jobs: JobManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n maxAttempts: n.maxAttempts,\n hasInputSchema: n.hasInputSchema,\n }))\n return {\n schemaVersion: JOB_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n jobs,\n }\n}\n\nexport function writeJobManifest(\n path: string,\n input: readonly JobNode[] | JobManifest,\n projectRoot?: string,\n): void {\n const manifest: JobManifest = isManifest(input) ? input : buildJobManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is JobManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'jobs' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport { importUserModule } from '../../config/import-user-module.js'\nimport { compareByCodeUnit } from '../_internal/compare-by-code-unit.js'\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { JobDefinition } from './job-types.js'\n\nexport interface JobNode {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport class DuplicateJobNameError extends Error {\n readonly code = 'DUPLICATE_JOB_NAME'\n constructor(\n public readonly jobName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate job name \"${jobName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Job names must be unique across server/jobs/.',\n )\n this.name = 'DuplicateJobNameError'\n }\n}\n\nconst JOB_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface JobModule {\n default?: unknown\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.handler === 'function' &&\n typeof def.maxAttempts === 'number' &&\n typeof def.hasInputSchema === 'boolean'\n )\n}\n\nexport async function scanJobs(jobsDir: string): Promise<JobNode[]> {\n if (!existsSync(jobsDir)) return []\n\n const filePaths: string[] = []\n walkSourceFiles(jobsDir, { extensions: JOB_EXTENSIONS }, (p) => {\n const base = basename(p)\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n\n const nodes: JobNode[] = []\n for (const filePath of filePaths) {\n let mod: JobModule\n try {\n mod = await importUserModule(filePath)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import job file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isJobDefinition(exported)) {\n throw new Error(\n `Job file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineJob(name, { handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n maxAttempts: exported.maxAttempts,\n hasInputSchema: exported.hasInputSchema,\n })\n }\n\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateJobNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => compareByCodeUnit(a.name, b.name))\n}\n","/**\n * State cleanup utilities (Phase 2 of\n *\n * - `cleanOutDir` — Astro pattern: empty a directory except a skip list,\n * used at `theokit build` start.\n * - `gcAgentRegistry` — Nuxt LRU pattern: delete oldest agent dirs when\n * count exceeds cap, used at `theokit dev` startup.\n *\n * EC-3 (MUST FIX, CRITICAL): cleanOutDir refuses to wipe anything outside\n * the current cwd. Prevents catastrophic `distDir: '/'` data loss.\n * EC-9 (SHOULD TEST): gcAgentRegistry handles dirs with mtime=0 (Docker overlay).\n * EC-11 (SHOULD TEST): cleanOutDir normalizes trailing-slash in skip basenames.\n * EC-12 (SHOULD TEST): cleanOutDir catches EROFS and continues.\n */\n\nimport { promises as fs } from 'node:fs'\nimport { basename, resolve as resolvePath, sep } from 'node:path'\n\nimport type {\n CleanOutDirOptions,\n CleanOutDirResult,\n GcAgentRegistryOptions,\n GcAgentRegistryResult,\n} from './cleanup-types.js'\n\nconst DEFAULT_SKIP = ['.git', '.gitkeep', '.gitignore']\n// DEFAULT_MAX_AGENTS removed in Phase 7 — gcAgentRegistry is a tombstone.\n\nfunction normalizeSkipName(name: string): string {\n // EC-11 — strip trailing slash + leading `./`\n return basename(name.replace(/\\/$/, ''))\n}\n\n/**\n * Empty a directory, preserving entries in the skip list.\n *\n * Throws if `opts.dir` is not inside `process.cwd()` (EC-3 path safety).\n * Returns `{deleted:0, kept:0}` when the directory does not exist.\n */\nexport async function cleanOutDir(opts: CleanOutDirOptions): Promise<CleanOutDirResult> {\n const resolvedDir = resolvePath(opts.dir)\n const resolvedCwd = resolvePath(process.cwd())\n\n // EC-3 — path safety guard. CRITICAL.\n if (resolvedDir === resolvedCwd) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be a child of cwd, not cwd itself`,\n )\n }\n if (!resolvedDir.startsWith(resolvedCwd + sep)) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be inside cwd (${resolvedCwd})`,\n )\n }\n\n const skip = new Set((opts.skip ?? DEFAULT_SKIP).map(normalizeSkipName))\n\n let entries: { name: string }[]\n try {\n entries = await fs.readdir(resolvedDir, { withFileTypes: true })\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return { deleted: 0, kept: 0 }\n throw err\n }\n\n let deleted = 0\n let kept = 0\n for (const entry of entries) {\n const name = entry.name\n if (skip.has(name)) {\n kept++\n continue\n }\n const fullPath = resolvePath(resolvedDir, name)\n try {\n await fs.rm(fullPath, { recursive: true, force: true, maxRetries: 3 })\n deleted++\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n deleted++ // already gone\n continue\n }\n // EC-12 — EROFS or other rm failure: warn + continue, don't crash.\n console.warn(\n `[theokit] cleanOutDir could not remove ${fullPath} (${code ?? 'unknown'}); skipping`,\n )\n kept++\n }\n }\n\n return { deleted, kept }\n}\n\n/**\n * Phase 7 — TOMBSTONE for backward-compat. The SDK v1.1.0's `Agent.registry`\n * handles GC natively; this function is a no-op + emits a deprecation warning\n * ONCE per process (EC-10).\n *\n * Will be deleted entirely in TheoKit 0.4.0. Marked deprecated via runtime\n * warning rather than `@deprecated` JSDoc tag to avoid the eslint\n * sonarjs/deprecation flagging our own internal symbols.\n */\nlet warnedOnce = false\nexport async function gcAgentRegistry(\n _opts: GcAgentRegistryOptions,\n): Promise<GcAgentRegistryResult> {\n if (!warnedOnce) {\n warnedOnce = true\n console.warn(\n '[theokit] gcAgentRegistry is deprecated; SDK Agent.registry handles GC natively (configure via theo.config.ts > agents.registry)',\n )\n }\n return Promise.resolve({ deleted: 0, kept: 0 })\n}\n\n/**\n * @internal — testing helper. Resets the module-scoped warnedOnce flag.\n */\nexport function __resetGcDeprecationWarnedForTests(): void {\n warnedOnce = false\n}\n","import { existsSync } from 'node:fs'\nimport { join, relative, resolve, sep } from 'node:path'\n\nimport type { AdapterBuildContext } from '../../adapters/types.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\nimport { scanServerRoutes } from '../../server/scan/scan.js'\nimport { scanWebSocketRoutes } from '../../server/scan/ws-scan.js'\n\n/**\n * What a scanned deploy target is handed instead of a filesystem.\n *\n * #369 — a Worker has no filesystem at request time, so the Cloudflare entry bakes its routes at\n * build time. Importing the scanner from `adapters/` would add the `adapters → server` edge that\n * `adapters-may-only-depend-on-core-router-services` refuses, so the CLI composes the scan and\n * hands over the result.\n *\n * ## Why this is a module rather than a closure inside `buildCommand`\n *\n * It was a closure, and the defect it carried was invisible to every test: `buildCommand` loads a\n * config, runs vite twice and writes a tree, so nothing could ask it one question about one call.\n * Extracted at B-312, whose whole content was a single argument being wrong.\n *\n * Paths are made relative to the project root here, where `projectRoot` is known: that string is\n * both the emitted import specifier and the key the executor looks a module up by, and the scanners\n * return absolute paths.\n */\nexport function createBuildScanRoutes(\n projectRoot: string,\n config: { agentsDir?: string },\n): NonNullable<AdapterBuildContext['scanRoutes']> {\n return (serverDir: string) => {\n const abs = resolve(projectRoot, serverDir)\n const toProjectRelative = (p: string): string => relative(projectRoot, p).split(sep).join('/')\n\n return {\n routes: scanServerRoutes(abs).map((route) => ({\n filePath: toProjectRelative(route.filePath),\n routePath: route.routePath,\n methods: route.methods ?? [],\n })),\n wsRoutes: scanWebSocketRoutes(abs).map((ws) =>\n toProjectRelative(typeof ws === 'string' ? ws : ws.filePath),\n ),\n // #367 — agents are a DIFFERENT scan served by a DIFFERENT function, which is why no adapter\n // had ever heard of them: the entries route `/api/` through `scanServerRoutes` +\n // `executeRoute` alone, so `/api/agents/<name>` matched nothing and 404'd on every target.\n // Scanned here, beside the routes, because the same inversion argument applies verbatim.\n //\n // B-312 — the root is the PROJECT ROOT, and was `dirname(abs)`. `config.agentsDir` is\n // documented and declared relative to the project root, while `dirname(serverDir)` is the\n // root only when `serverDir` is a direct child of it. The scaffold's own nested layout\n // (`serverDir: 'src/server'`, `agentsDir: 'src/server/agents'`) made the two disagree, and\n // `join()` produced `<root>/src/src/server/agents` — so `scanAgents` returned `[]` and every\n // `/api/agents/*` route 404'd on every scanned target. Measured on a live Cloudflare deploy,\n // 2026-09-26. Every other caller in the tree already passes the project root.\n agents: scanAgents(projectRoot, config.agentsDir).map((agent) => ({\n filePath: toProjectRelative(agent.filePath),\n agentPath: agent.agentPath,\n name: agent.name,\n })),\n // B-185 — the identity module, decided here for the same reason the agents are: this provider\n // is handed `serverDir`, and a Worker has no filesystem to look for it on. An app with no\n // `server/context.ts` yields `undefined`, and the generator then emits no import — importing\n // a file that is not there would fail the BUILD rather than one request.\n context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AQ,KAAK,KAAK,aAAa,GAAG,eAAe;AACvE,gBAAQ,IAAI,6CAAmC,UAAU,MAAM,WAAW;AAC1E;AAAA,MACF,KAAK;AACH,kCAA0BA,SAAQ,KAAK,KAAK,eAAe,GAAG,eAAe;AAC7E,gBAAQ,IAAI,kDAAwC,UAAU,MAAM,GAAG;AACvE;AAAA,MACF,KAAK;AACH,2BAAmBA,SAAQ,KAAK,KAAK,gBAAgB,GAAG,eAAe;AACvE,gBAAQ,IAAI,kDAAwC,UAAU,MAAM,GAAG;AACvE;AAAA,MACF,KAAK;AACH,4BAAoBA,SAAQ,KAAK,SAAS,gBAAgB,GAAG,eAAe;AAC5E,gBAAQ,IAAI,wBAAc,KAAK,OAAO,6BAA6B;AACnE;AAAA,MACF,KAAK;AACH,gBAAQ,IAAI,2DAAiD;AAC7D;AAAA,IACJ;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,eAAe,+BAAgC,OAAM;AACzD,UAAM;AAAA,EACR;AACF;AAEA,eAAe,iBAAiB,MAId;AAChB,QAAM,UAAUA,SAAQ,KAAK,WAAW,MAAM;AAE9C,QAAM,WAAWG,YAAW,OAAO,IAAI,MAAM,SAAS,OAAO,IAAI,CAAC;AAClE,QAAM,eAAeH,SAAQ,KAAK,SAAS,WAAW;AACtD,mBAAiB,cAAc,UAAU,KAAK,GAAG;AACjD,UAAQ,IAAI,kBAAa,SAAS,MAAM,WAAW;AACrD;AAEA,SAASE,YAAW,SAAiB,MAAsB;AACzD,MAAI,QAAQ,WAAW,IAAI,GAAG;AAC5B,UAAM,UAAU,QAAQ,MAAM,KAAK,MAAM;AACzC,WAAO,QAAQ,WAAW,GAAG,IAAI,QAAQ,MAAM,CAAC,IAAI;AAAA,EACtD;AACA,SAAO;AACT;","names":["existsSync","resolve","existsSync","existsSync","relativize","isManifest","existsSync","basename","existsSync","basename","basename","existsSync","sep","sep","existsSync","resolve","writeManifest","relativize","existsSync"]}