theokit 0.73.0 → 0.74.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) 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-QCDKQ6QD.js → actions-virtual-module-JV7URROJ.js} +5 -5
  4. package/dist/adapters/agent-mount.js +3 -3
  5. package/dist/adapters/security-headers.js +9 -4
  6. package/dist/adapters/security-headers.js.map +1 -1
  7. package/dist/{agent-OWJ5A7W5.js → agent-5J7CQAYR.js} +3 -3
  8. package/dist/{app-typed-client-ILLQYTXP.js → app-typed-client-EOA3A2AR.js} +5 -5
  9. package/dist/{app-typed-client-ILLQYTXP.js.map → app-typed-client-EOA3A2AR.js.map} +1 -1
  10. package/dist/{app-typed-client-2PTK2SJH.js → app-typed-client-XD4DZBV7.js} +6 -6
  11. package/dist/app-typed-client-XD4DZBV7.js.map +1 -0
  12. package/dist/{aws-lambda-OP2L5RKZ.js → aws-lambda-ZYSPTD3O.js} +61 -27
  13. package/dist/aws-lambda-ZYSPTD3O.js.map +1 -0
  14. package/dist/{build-CVP2XU5M.js → build-7YZSJGP2.js} +79 -72
  15. package/dist/build-7YZSJGP2.js.map +1 -0
  16. package/dist/{bun-CZXHPK2W.js → bun-I7YM3RDB.js} +81 -20
  17. package/dist/bun-I7YM3RDB.js.map +1 -0
  18. package/dist/{chunk-WBB3MEEN.js → chunk-2NG5T77O.js} +47 -12
  19. package/dist/{chunk-WBB3MEEN.js.map → chunk-2NG5T77O.js.map} +1 -1
  20. package/dist/{chunk-NO6HA4FG.js → chunk-4WP7A7RX.js} +41 -35
  21. package/dist/chunk-4WP7A7RX.js.map +1 -0
  22. package/dist/chunk-4X43VTST.js +31 -0
  23. package/dist/chunk-4X43VTST.js.map +1 -0
  24. package/dist/{chunk-FHQP23Z5.js → chunk-6R5F5YF2.js} +17 -14
  25. package/dist/chunk-6R5F5YF2.js.map +1 -0
  26. package/dist/chunk-72RSCKMW.js +53 -0
  27. package/dist/chunk-72RSCKMW.js.map +1 -0
  28. package/dist/{chunk-SEGD3JUC.js → chunk-EQJF2EH5.js} +8 -7
  29. package/dist/chunk-EQJF2EH5.js.map +1 -0
  30. package/dist/{chunk-6U67SO5U.js → chunk-HK57MPSZ.js} +2 -2
  31. package/dist/{chunk-R7G2B2WH.js → chunk-HKF6YNY4.js} +17 -14
  32. package/dist/{chunk-R7G2B2WH.js.map → chunk-HKF6YNY4.js.map} +1 -1
  33. package/dist/chunk-IJQQNHL7.js +34 -0
  34. package/dist/chunk-IJQQNHL7.js.map +1 -0
  35. package/dist/chunk-NPQ5A3RU.js +53 -0
  36. package/dist/chunk-NPQ5A3RU.js.map +1 -0
  37. package/dist/{chunk-D3M7LPHY.js → chunk-NQZIQJFH.js} +57 -17
  38. package/dist/{chunk-D3M7LPHY.js.map → chunk-NQZIQJFH.js.map} +1 -1
  39. package/dist/{chunk-M3DT6EMK.js → chunk-QAS5SKZP.js} +2 -2
  40. package/dist/{chunk-WRHT5NAJ.js → chunk-QX5Q3FBJ.js} +57 -17
  41. package/dist/chunk-QX5Q3FBJ.js.map +1 -0
  42. package/dist/{chunk-HDAILYVM.js → chunk-SG62LZOJ.js} +3 -3
  43. package/dist/{chunk-EDBQM6RB.js → chunk-SHIXTMQE.js} +47 -12
  44. package/dist/{chunk-EDBQM6RB.js.map → chunk-SHIXTMQE.js.map} +1 -1
  45. package/dist/{chunk-G7U7FQVC.js → chunk-UFBBFP75.js} +13 -3
  46. package/dist/chunk-UFBBFP75.js.map +1 -0
  47. package/dist/{chunk-4CIHLTSI.js → chunk-V7ISZGNS.js} +45 -39
  48. package/dist/chunk-V7ISZGNS.js.map +1 -0
  49. package/dist/{chunk-RCFD5W5V.js → chunk-WR5B2XNT.js} +6 -6
  50. package/dist/chunk-WR5B2XNT.js.map +1 -0
  51. package/dist/{chunk-R36YNWBU.js → chunk-XLFDYTWO.js} +2 -2
  52. package/dist/cli/index.js +8 -8
  53. package/dist/{cloudflare-2SVRRVV5.js → cloudflare-Q5SUXRXY.js} +184 -82
  54. package/dist/cloudflare-Q5SUXRXY.js.map +1 -0
  55. package/dist/{config-support-SB5NDQZB.js → config-support-MOZYHRWG.js} +13 -2
  56. package/dist/{config-support-SB5NDQZB.js.map → config-support-MOZYHRWG.js.map} +1 -1
  57. package/dist/{deno-deploy-OK4QFJIZ.js → deno-deploy-XW3Q6OMD.js} +109 -11
  58. package/dist/deno-deploy-XW3Q6OMD.js.map +1 -0
  59. package/dist/{dev-B2IZEVAD.js → dev-FZ4OTCPT.js} +7 -7
  60. package/dist/{dev-emit-7KZFUA7M.js → dev-emit-T3X6RR7M.js} +5 -5
  61. package/dist/{dev-emit-7KZFUA7M.js.map → dev-emit-T3X6RR7M.js.map} +1 -1
  62. package/dist/{dev-emit-JPJJFBXL.js → dev-emit-ZK5GCHXN.js} +6 -6
  63. package/dist/dev-emit-ZK5GCHXN.js.map +1 -0
  64. package/dist/index.js +5 -5
  65. package/dist/{internal-api-5Y3MLZH4.js → internal-api-GKPJYL3G.js} +5 -5
  66. package/dist/{internal-api-6XNLCNI5.js → internal-api-ZUBUYGCQ.js} +4 -4
  67. package/dist/{mcp-GJQIREYC.js → mcp-VUHRRX36.js} +3 -3
  68. package/dist/{netlify-IAC53FVZ.js → netlify-ALPCTQFO.js} +158 -48
  69. package/dist/netlify-ALPCTQFO.js.map +1 -0
  70. package/dist/{node-QUGTW6XV.js → node-4HQO6KKZ.js} +2 -2
  71. package/dist/{openapi-Q53YOBIU.js → openapi-C4UX2SFV.js} +5 -5
  72. package/dist/openapi-C4UX2SFV.js.map +1 -0
  73. package/dist/{preview-XBP622HM.js → preview-II33QNAC.js} +3 -3
  74. package/dist/registry-WVUO2WNR.js +34 -0
  75. package/dist/registry-WVUO2WNR.js.map +1 -0
  76. package/dist/{routes-FDF4SLOB.js → routes-3PTNISSO.js} +2 -2
  77. package/dist/server/index.js +2 -2
  78. package/dist/server/scan/index.d.ts +38 -2
  79. package/dist/server/scan/index.js +2 -2
  80. package/dist/{server-boundary-IFIYNGTA.js → server-boundary-QCJNECJP.js} +5 -5
  81. package/dist/{server-boundary-E5GFVPLB.js → server-boundary-RTRPHX5I.js} +4 -4
  82. package/dist/{start-JGNBTTG2.js → start-EREUCSN6.js} +6 -6
  83. package/dist/{static-NQPLPAB6.js → static-7LP7LPGN.js} +2 -2
  84. package/dist/theo-cloud-GIA67L4Q.js +40 -0
  85. package/dist/theo-cloud-GIA67L4Q.js.map +1 -0
  86. package/dist/{vercel-EHAOKPF7.js → vercel-VLR52RXT.js} +173 -73
  87. package/dist/vercel-VLR52RXT.js.map +1 -0
  88. package/dist/vite-plugin/index.d.ts +10 -1
  89. package/dist/vite-plugin/index.js +7 -5
  90. package/dist/{vite-plugin-54XIRMKT.js → vite-plugin-3LTZJTUM.js} +9 -7
  91. package/package.json +5 -5
  92. package/dist/app-typed-client-2PTK2SJH.js.map +0 -1
  93. package/dist/aws-lambda-OP2L5RKZ.js.map +0 -1
  94. package/dist/build-CVP2XU5M.js.map +0 -1
  95. package/dist/bun-CZXHPK2W.js.map +0 -1
  96. package/dist/chunk-4CIHLTSI.js.map +0 -1
  97. package/dist/chunk-FHQP23Z5.js.map +0 -1
  98. package/dist/chunk-G7U7FQVC.js.map +0 -1
  99. package/dist/chunk-NO6HA4FG.js.map +0 -1
  100. package/dist/chunk-RCFD5W5V.js.map +0 -1
  101. package/dist/chunk-SEGD3JUC.js.map +0 -1
  102. package/dist/chunk-WRHT5NAJ.js.map +0 -1
  103. package/dist/cloudflare-2SVRRVV5.js.map +0 -1
  104. package/dist/deno-deploy-OK4QFJIZ.js.map +0 -1
  105. package/dist/dev-emit-JPJJFBXL.js.map +0 -1
  106. package/dist/netlify-IAC53FVZ.js.map +0 -1
  107. package/dist/openapi-Q53YOBIU.js.map +0 -1
  108. package/dist/registry-L6JG75LY.js +0 -23
  109. package/dist/registry-L6JG75LY.js.map +0 -1
  110. package/dist/theo-cloud-HMFNZ3FS.js +0 -33
  111. package/dist/theo-cloud-HMFNZ3FS.js.map +0 -1
  112. package/dist/vercel-EHAOKPF7.js.map +0 -1
  113. /package/dist/{actions-virtual-module-OHENNMQG.js.map → actions-virtual-module-J2HYO7QZ.js.map} +0 -0
  114. /package/dist/{actions-virtual-module-QCDKQ6QD.js.map → actions-virtual-module-JV7URROJ.js.map} +0 -0
  115. /package/dist/{agent-OWJ5A7W5.js.map → agent-5J7CQAYR.js.map} +0 -0
  116. /package/dist/{chunk-6U67SO5U.js.map → chunk-HK57MPSZ.js.map} +0 -0
  117. /package/dist/{chunk-M3DT6EMK.js.map → chunk-QAS5SKZP.js.map} +0 -0
  118. /package/dist/{chunk-HDAILYVM.js.map → chunk-SG62LZOJ.js.map} +0 -0
  119. /package/dist/{chunk-R36YNWBU.js.map → chunk-XLFDYTWO.js.map} +0 -0
  120. /package/dist/{dev-B2IZEVAD.js.map → dev-FZ4OTCPT.js.map} +0 -0
  121. /package/dist/{internal-api-5Y3MLZH4.js.map → internal-api-GKPJYL3G.js.map} +0 -0
  122. /package/dist/{internal-api-6XNLCNI5.js.map → internal-api-ZUBUYGCQ.js.map} +0 -0
  123. /package/dist/{mcp-GJQIREYC.js.map → mcp-VUHRRX36.js.map} +0 -0
  124. /package/dist/{node-QUGTW6XV.js.map → node-4HQO6KKZ.js.map} +0 -0
  125. /package/dist/{preview-XBP622HM.js.map → preview-II33QNAC.js.map} +0 -0
  126. /package/dist/{routes-FDF4SLOB.js.map → routes-3PTNISSO.js.map} +0 -0
  127. /package/dist/{server-boundary-IFIYNGTA.js.map → server-boundary-QCJNECJP.js.map} +0 -0
  128. /package/dist/{server-boundary-E5GFVPLB.js.map → server-boundary-RTRPHX5I.js.map} +0 -0
  129. /package/dist/{start-JGNBTTG2.js.map → start-EREUCSN6.js.map} +0 -0
  130. /package/dist/{static-NQPLPAB6.js.map → static-7LP7LPGN.js.map} +0 -0
  131. /package/dist/{vite-plugin-54XIRMKT.js.map → vite-plugin-3LTZJTUM.js.map} +0 -0
package/README.md CHANGED
@@ -103,6 +103,8 @@ theokit mcp <agent> # serve an agent as an MCP server over stdi
103
103
  `theokit build --target <name>`: `node` (default), `theo-cloud`, `vercel`, `netlify`,
104
104
  `cloudflare`, `bun`, `deno-deploy`, `aws-lambda`, `static`.
105
105
 
106
+ Cloudflare Workers, step by step: [`docs/wiki/sops/cloudflare-deploy.md`](https://github.com/usetheokit/theokit/blob/main/docs/wiki/sops/cloudflare-deploy.md).
107
+
106
108
  ## Licence
107
109
 
108
110
  Apache-2.0 — see `LICENSE`.
@@ -1,5 +1,5 @@
1
1
  import "./chunk-D7STTNQN.js";
2
- import "./chunk-WBB3MEEN.js";
2
+ import "./chunk-2NG5T77O.js";
3
3
  import "./chunk-WSOAN4KN.js";
4
4
  import "./chunk-ENSFCKP6.js";
5
5
  import "./chunk-2Z7TANA4.js";
@@ -18,8 +18,8 @@ import "./chunk-SFGGRC35.js";
18
18
  import "./chunk-4ERYQBL6.js";
19
19
  import {
20
20
  scanServerActionsEnriched
21
- } from "./chunk-4CIHLTSI.js";
22
- import "./chunk-FHQP23Z5.js";
21
+ } from "./chunk-V7ISZGNS.js";
22
+ import "./chunk-6R5F5YF2.js";
23
23
  import "./chunk-DV34VG3N.js";
24
24
  import "./chunk-V6Y2SMRG.js";
25
25
  import "./chunk-ACKBVBUI.js";
@@ -234,4 +234,4 @@ export const actions = manifest
234
234
  export {
235
235
  actionsVirtualModule
236
236
  };
237
- //# sourceMappingURL=actions-virtual-module-OHENNMQG.js.map
237
+ //# sourceMappingURL=actions-virtual-module-J2HYO7QZ.js.map
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
- import "./chunk-EDBQM6RB.js";
3
+ import "./chunk-SHIXTMQE.js";
4
4
  import "./chunk-BINRCILF.js";
5
5
  import "./chunk-FNJVSFEC.js";
6
6
  import "./chunk-WSMLSIS5.js";
7
7
  import "./chunk-MX63AWEK.js";
8
8
  import "./chunk-C27VRUVN.js";
9
9
  import "./chunk-7UZZHCRN.js";
10
- import "./chunk-RCFD5W5V.js";
11
- import "./chunk-R7G2B2WH.js";
10
+ import "./chunk-WR5B2XNT.js";
11
+ import "./chunk-HKF6YNY4.js";
12
12
  import {
13
13
  scanServerActionsEnriched
14
- } from "./chunk-NO6HA4FG.js";
14
+ } from "./chunk-4WP7A7RX.js";
15
15
  import "./chunk-Z7CJHDLS.js";
16
16
  import "./chunk-U5PWXS3J.js";
17
17
  import "./chunk-D2R5SJEL.js";
@@ -218,4 +218,4 @@ export const actions = manifest
218
218
  export {
219
219
  actionsVirtualModule
220
220
  };
221
- //# sourceMappingURL=actions-virtual-module-QCDKQ6QD.js.map
221
+ //# sourceMappingURL=actions-virtual-module-JV7URROJ.js.map
@@ -3,10 +3,10 @@ import {
3
3
  createSubjectResolverFromFactory,
4
4
  matchAgentAuxRoute,
5
5
  serveMatchedAuxRoute
6
- } from "../chunk-6U67SO5U.js";
6
+ } from "../chunk-HK57MPSZ.js";
7
7
  import {
8
8
  mountAgent
9
- } from "../chunk-WBB3MEEN.js";
9
+ } from "../chunk-2NG5T77O.js";
10
10
  import "../chunk-SYIQV4UH.js";
11
11
  import "../chunk-P6OS7652.js";
12
12
  import "../chunk-IDWN2OSG.js";
@@ -16,7 +16,7 @@ import "../chunk-CHTAWXC2.js";
16
16
  import "../chunk-AVQU5CQF.js";
17
17
  import {
18
18
  scanAgents
19
- } from "../chunk-FHQP23Z5.js";
19
+ } from "../chunk-6R5F5YF2.js";
20
20
  import "../chunk-V6Y2SMRG.js";
21
21
  import "../chunk-ACKBVBUI.js";
22
22
  import "../chunk-IZ3TIL6K.js";
@@ -17,10 +17,15 @@ function renderSecurityHeadersConfigLiteral(headers) {
17
17
  return JSON.stringify(headers ?? {});
18
18
  }
19
19
  function withSecurityHeaders(response, headers) {
20
- for (const [key, value] of Object.entries(headers)) {
21
- if (!response.headers.has(key)) response.headers.set(key, value);
22
- }
23
- return response;
20
+ const missing = Object.entries(headers).filter(([key]) => !response.headers.has(key));
21
+ if (missing.length === 0) return response;
22
+ const next = new Headers(response.headers);
23
+ for (const [key, value] of missing) next.set(key, value);
24
+ return new Response(response.body, {
25
+ status: response.status,
26
+ statusText: response.statusText,
27
+ headers: next
28
+ });
24
29
  }
25
30
  function describeDeployedSecurityHeaders(limits) {
26
31
  const headers = buildSecurityHeaders(limits.securityHeaders ?? {}, { production: true });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/security-headers.ts"],"mappings":";;;;;;;;;AA2GO,SAAS,4BAA4B,QAAqD;AAC/F,SAAO;AAAA,IACL,mCAAmC,mCAAmC,MAAM,CAAC;AAAA,IAC7E;AAAA,EACF;AACF;AAEO,SAAS,mCACd,SACQ;AACR,SAAO,KAAK,UAAU,WAAW,CAAC,CAAC;AACrC;AAyBO,SAAS,oBAAoB,UAAoB,SAA2C;AACjG,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,GAAG;AAClD,QAAI,CAAC,SAAS,QAAQ,IAAI,GAAG,EAAG,UAAS,QAAQ,IAAI,KAAK,KAAK;AAAA,EACjE;AACA,SAAO;AACT;AAkDO,SAAS,gCAAgC,QAA8C;AAC5F,QAAM,UAAU,qBAAqB,OAAO,mBAAmB,CAAC,GAAG,EAAE,YAAY,KAAK,CAAC;AACvF,QAAM,QAAQ,OAAO,KAAK,OAAO;AACjC,MAAI,MAAM,WAAW,GAAG;AACtB,WAAO,SAAS,OAAO,MAAM;AAAA,EAC/B;AAEA,QAAM,QAAQ;AAAA,IACZ,iDAA4C,OAAO,MAAM,eAAe,MAAM,KAAK,IAAI,CAAC;AAAA,EAC1F;AACA,QAAM,WAAW,MAAM,KAAK,CAAC,SAAS,KAAK,WAAW,yBAAyB,CAAC;AAChF,MAAI,YAAY,CAAC,OAAO,YAAY;AAClC,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA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AAM,KAAK,IAAI,CAAC;AAAA,EAC1F;AACA,QAAM,WAAW,MAAM,KAAK,CAAC,SAAS,KAAK,WAAW,yBAAyB,CAAC;AAChF,MAAI,YAAY,CAAC,OAAO,YAAY;AAClC,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,OAAO,oBAAoB,uBAAuB;AACpD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,OAAO,oBAAoB,sBAAsB;AACnD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
@@ -3,13 +3,13 @@ import "tsx/esm";
3
3
  import {
4
4
  agentCommand,
5
5
  createAgentSsrLoader
6
- } from "./chunk-HDAILYVM.js";
6
+ } from "./chunk-SG62LZOJ.js";
7
7
  import "./chunk-BINRCILF.js";
8
- import "./chunk-R7G2B2WH.js";
8
+ import "./chunk-HKF6YNY4.js";
9
9
  import "./chunk-Z7CJHDLS.js";
10
10
  import "./chunk-3QPVEJ7D.js";
11
11
  export {
12
12
  agentCommand,
13
13
  createAgentSsrLoader
14
14
  };
15
- //# sourceMappingURL=agent-OWJ5A7W5.js.map
15
+ //# sourceMappingURL=agent-5J7CQAYR.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  scanControllerModules
3
3
  } from "./chunk-D7STTNQN.js";
4
- import "./chunk-WBB3MEEN.js";
4
+ import "./chunk-2NG5T77O.js";
5
5
  import "./chunk-WSOAN4KN.js";
6
6
  import "./chunk-ENSFCKP6.js";
7
7
  import "./chunk-2Z7TANA4.js";
@@ -20,8 +20,8 @@ import "./chunk-SFGGRC35.js";
20
20
  import "./chunk-4ERYQBL6.js";
21
21
  import {
22
22
  generateManifest
23
- } from "./chunk-4CIHLTSI.js";
24
- import "./chunk-FHQP23Z5.js";
23
+ } from "./chunk-V7ISZGNS.js";
24
+ import "./chunk-6R5F5YF2.js";
25
25
  import {
26
26
  HTTP_METHODS
27
27
  } from "./chunk-DV34VG3N.js";
@@ -339,7 +339,7 @@ async function emitClientDts(opts) {
339
339
  path: stubPath
340
340
  };
341
341
  }
342
- const manifest = generateManifest(opts.serverDir);
342
+ const manifest = generateManifest(opts.serverDir, opts.cwd, opts.agentsDir);
343
343
  if (opts.extraRoutes?.length) {
344
344
  manifest.routes.push(...opts.extraRoutes);
345
345
  }
@@ -427,4 +427,4 @@ export {
427
427
  generateClientDts,
428
428
  shouldReemitForFile
429
429
  };
430
- //# sourceMappingURL=app-typed-client-ILLQYTXP.js.map
430
+ //# sourceMappingURL=app-typed-client-EOA3A2AR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vite-plugin/app-typed-client.ts","../src/vite-plugin/controller-client-emit.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAS,WAAW,cAAc,YAAY,eAAe,kBAAkB;AAC/E,SAAS,SAAS,YAAY,OAAO,UAAU,eAAe;;;ACP9D,SAAS,uBAAuB,8BAA8B;AAmD9D,SAAS,eACP,QACA,eACoB;AACpB,MAAI,WAAW,UAAa,WAAW,KAAM,QAAO;AACpD,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,aAAa,GAAG;AAGzD,QAAI,UAAU,OAAQ,QAAO;AAAA,EAC/B;AACA,SAAO;AACT;AAOA,eAAsB,2BAA2B,MAGd;AACjC,QAAM,SAAS,KAAK,cAAc;AAClC,QAAM,UAAU,MAAM,sBAAsB,KAAK,gBAAgB,MAAM;AACvE,QAAM,MAA6B,CAAC;AACpC,aAAW,EAAE,UAAU,KAAK,QAAQ,KAAK,SAAS;AAChD,UAAM,YAAa,IAAyB;AAC5C,eAAW,QAAQ,uBAAuB,GAAG,GAAG;AAC9C,YAAM,mBAAmB,eAAe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IACF;AAAA,IACA,gBAAgB,QAAQ;AACtB,mBAAa;AACb,YAAM,aAAa,MAAM,KAAK,KAAK,UAAU,QAAQ,OAAO,GAAG,GAAG,QAAQ;AAC1E,YAAM,kBAAkB,MAAM,KAAK,KAAK,UAAU,QAAQ,OAAO,GAAG,GAAG,aAAa;AACpF,YAAM,SAAS,CAAC,SAAuB;AACrC,YAAI,oBAAoB,MAAM,YAAY,eAAe,EAAG,cAAa;AAAA,MAC3E;AACA,aAAO,QAAQ,GAAG,OAAO,MAAM;AAC/B,aAAO,QAAQ,GAAG,UAAU,MAAM;AAClC,aAAO,QAAQ,GAAG,UAAU,MAAM;AAAA,IACpC;AAAA,IACA,UAAU,IAAI;AACZ,UAAI,OAAO,sBAAuB,QAAO;AACzC,aAAO;AAAA,IACT;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,wBAAwB;AACjC,eAAO;AAAA,UACL;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF,EAAE,KAAK,IAAI;AAAA,MACb;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
- import "./chunk-EDBQM6RB.js";
3
+ import "./chunk-SHIXTMQE.js";
4
4
  import "./chunk-BINRCILF.js";
5
5
  import {
6
6
  scanControllerModules
@@ -11,11 +11,11 @@ import "./chunk-C27VRUVN.js";
11
11
  import "./chunk-7UZZHCRN.js";
12
12
  import {
13
13
  generateManifest
14
- } from "./chunk-RCFD5W5V.js";
15
- import "./chunk-R7G2B2WH.js";
14
+ } from "./chunk-WR5B2XNT.js";
15
+ import "./chunk-HKF6YNY4.js";
16
16
  import {
17
17
  HTTP_METHODS
18
- } from "./chunk-NO6HA4FG.js";
18
+ } from "./chunk-4WP7A7RX.js";
19
19
  import "./chunk-Z7CJHDLS.js";
20
20
  import "./chunk-U5PWXS3J.js";
21
21
  import "./chunk-D2R5SJEL.js";
@@ -323,7 +323,7 @@ async function emitClientDts(opts) {
323
323
  path: stubPath
324
324
  };
325
325
  }
326
- const manifest = generateManifest(opts.serverDir);
326
+ const manifest = generateManifest(opts.serverDir, opts.cwd, opts.agentsDir);
327
327
  if (opts.extraRoutes?.length) {
328
328
  manifest.routes.push(...opts.extraRoutes);
329
329
  }
@@ -411,4 +411,4 @@ export {
411
411
  generateClientDts,
412
412
  shouldReemitForFile
413
413
  };
414
- //# sourceMappingURL=app-typed-client-2PTK2SJH.js.map
414
+ //# sourceMappingURL=app-typed-client-XD4DZBV7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vite-plugin/app-typed-client.ts","../src/vite-plugin/controller-client-emit.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Codegen-time fs ops: all paths derive from `opts.serverDir` / `opts.distDir`\n * (vite plugin opts — trusted, set by the framework's CLI). The plugin only\n * runs at dev/build time, never serves user HTTP input. No path traversal\n * surface here.\n */\n/**\n * Phase 2 + Phase 4 of G1 (g1-client-codegen-plan.md):\n *\n * 1. `generateClientDts(manifest, dtsOutPath)` — pure function emitting the\n * `.theokit/client.d.ts` shape (declared module `@theo/client`).\n * 2. `appTypedClientPlugin(opts)` — Vite plugin wrapper that calls (1),\n * writes the file atomically, and rewrites on route file changes.\n *\n * Implementation notes:\n * - Pure (1) is unit-testable without Vite or a filesystem (see G1-P2 tests).\n * - EC-2: segments are kept literal; anything not a valid identifier is a bracket key (#470).\n * - EC-3: collision between HTTP method name and sub-segment name → method\n * wins; a sub-segment gets a `_` suffix + a warning comment.\n * - EC-6: the write is `writeFileSync(tmp) + renameSync(tmp, final)` (POSIX atomic).\n * - EC-8: imports normalize `\\\\` → `/`.\n */\n\nimport { mkdirSync, readFileSync, renameSync, writeFileSync, existsSync } from 'node:fs'\nimport { dirname, isAbsolute, posix, relative, resolve } from 'node:path'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\nimport { HTTP_METHODS, type HttpMethod } from '../core/contracts/http-methods.js'\nimport { generateManifest, type ManifestRoute, type TheoManifest } from '../server/internal-api.js'\n\nimport { collectControllerRouteData, type ControllerRouteData } from './controller-client-emit.js'\n\nconst FILE_HEADER = `// AUTO-GENERATED by theokit — do not edit.\n// Source: theokit/packages/theo/src/vite-plugin/app-typed-client.ts (G1 plan).\n// To refresh: \\`pnpm dev\\` or \\`pnpm build\\` regenerates this file on every route change.\n\n/* eslint-disable */\n`\n\ninterface ControllerLeaf {\n /**\n * Where the controller class lives, named inline like the route exports beside it (#469). The\n * alias form it replaced is fragile in a way that is hard to characterise: measured, the same\n * aliased class resolved correctly in one `declare module` block and to `any` in another, with\n * nothing in the file to say which. Inline resolves relative to the file and always survived, so\n * no aliased relative import is left in the generated output at all.\n */\n classSource: { importPath: string; className: string }\n /** Controller method name backing the route (`findById`). */\n methodName: string\n /**\n * theokit#124 — module specifier + exported name of the `@Body` schema, when it has one, so the\n * emitted signature can say `z.infer<typeof import('...').zCreate>` instead of `unknown`.\n */\n bodySchema?: { importPath: string; exportName: string }\n /** theokit#124 — same for `@Query`. */\n querySchema?: { importPath: string; exportName: string }\n}\n\ninterface TreeNode {\n /** sub-namespaces — keyed by segment name (already normalized). */\n children: Map<string, TreeNode>\n /**\n * File-based routes: HTTP method → where the route export lives, so the signature can name it\n * INLINE as `typeof import('...').GET`.\n *\n * It used to hold an import alias, declared once at the top of the `declare module` block. That\n * alias silently resolves to `any` when fed to an external package's conditional type — measured\n * in #469, with no error at all, so every call through the generated client returned `any` while\n * the app compiled. The controller path beside this one already emits schemas inline for the same\n * reason; this brings routes onto the shape that works.\n */\n methods: Map<HttpMethod, { importPath: string; exportName: HttpMethod }>\n /** Decorator controllers: HTTP method → class alias + method (`Awaited<ReturnType<...>>`). */\n controllerMethods: Map<HttpMethod, ControllerLeaf>\n /** Whether any descendant declares dynamic params (for params type construction). */\n paramNamesAccumulated: string[]\n}\n\nfunction makeNode(): TreeNode {\n return {\n children: new Map(),\n methods: new Map(),\n controllerMethods: new Map(),\n paramNamesAccumulated: [],\n }\n}\n\n/**\n * Normalize a path segment to a valid TS identifier when possible.\n * EC-2: the segment is kept literal; pure dynamic (`:name`) → identifier `name`;\n * starts with digit or unsafe char → emit as bracket-access key.\n */\nfunction normalizeSegment(raw: string): { identifier: string; bracket: boolean } {\n // Dynamic segment: leading `:` (e.g. `:id` or `:...slug`).\n let s = raw\n if (s.startsWith(':...')) s = s.slice(4)\n else if (s.startsWith(':')) s = s.slice(1)\n\n // The segment is kept LITERAL (#470). It used to be camelCased — `agents-config` became\n // `agentsConfig` — while the runtime Proxy builds the URL from the key it was handed and knows\n // nothing of the transformation. So the type offered `client.agentsConfig.get()`, the request\n // went to `/api/agentsConfig`, and the route served at `/api/agents-config` answered 404. The\n // call compiled; the failure arrived at runtime.\n //\n // Translating back in the Proxy would have kept the prettier key, at the cost of a second source\n // of truth for every segment name. A generated client is worth more as a faithful mirror of the\n // URLs: bracket access for a hyphenated segment is the honest cost, and the machinery for it was\n // already here for segments that cannot be identifiers at all (`2fa`).\n if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(s)) {\n return { identifier: s, bracket: false }\n }\n return { identifier: s, bracket: true }\n}\n\nfunction importPathFor(dtsOutPath: string, routeFileAbs: string): string {\n let rel = relative(dirname(dtsOutPath), routeFileAbs)\n // EC-8: normalize Windows path separators.\n rel = rel.replace(/\\\\/g, '/')\n // Strip extension (`.ts` / `.tsx`); TS module resolution likes extensionless.\n rel = rel.replace(/\\.[jt]sx?$/, '')\n if (!rel.startsWith('.') && !rel.startsWith('/')) {\n rel = './' + rel\n }\n return rel\n}\n\n/**\n * Convert a route path (e.g. `/api/users/:id/posts`) into the tree segments\n * we want under the `client` root. Strips the `/api/` prefix and splits.\n */\nfunction routePathSegments(routePath: string): string[] {\n let p = routePath\n if (p.startsWith('/api/')) p = p.slice(5)\n else if (p.startsWith('/api')) p = p.slice(4)\n if (p.startsWith('/')) p = p.slice(1)\n if (p === '') return []\n return p.split('/').filter(Boolean)\n}\n\nfunction paramNamesFromRoute(routePath: string): string[] {\n const out: string[] = []\n const re = /:(?:\\.\\.\\.)?([^/]+)/g\n let m: RegExpExecArray | null\n while ((m = re.exec(routePath)) !== null) {\n out.push(m[1])\n }\n return out\n}\n\ninterface BuildContext {\n root: TreeNode\n /** Lines emitted at the top of the declared module (one per route file). */\n /** Diagnostic warnings rendered as block comments inside the declared module. */\n warnings: string[]\n dtsOutPath: string\n serverDir: string\n}\n\nfunction buildOneRoute(route: ManifestRoute, ctx: BuildContext): void {\n if (!route.methods || route.methods.length === 0) return\n // Resolve absolute path for the route file (manifest stores it relative to serverDir).\n const absRouteFile = isAbsolute(route.filePath)\n ? route.filePath\n : resolve(ctx.serverDir, route.filePath)\n const importPath = importPathFor(ctx.dtsOutPath, absRouteFile)\n const aliases = route.methods\n .filter((m): m is HttpMethod => (HTTP_METHODS as readonly string[]).includes(m))\n .map((method) => ({ method }))\n if (aliases.length === 0) return\n // No import line: the method signatures name the export inline (see `TreeNode.methods`).\n\n // Walk segments + register methods at the leaf node.\n const segments = routePathSegments(route.routePath)\n let node = ctx.root\n for (const seg of segments) {\n const norm = normalizeSegment(seg)\n let child = node.children.get(norm.identifier)\n if (child === undefined) {\n child = makeNode()\n node.children.set(norm.identifier, child)\n }\n node = child\n }\n // Accumulated param names for typed params (e.g. `{ id: string }`).\n node.paramNamesAccumulated = paramNamesFromRoute(route.routePath)\n\n // Register each HTTP method (collision detection runs in a post-pass).\n for (const { method } of aliases) {\n if (node.methods.has(method)) {\n ctx.warnings.push(\n `// WARNING: duplicate ${method} export at /${segments.join('/')} (route file declared twice). Keeping last definition.`,\n )\n }\n node.methods.set(method, { importPath, exportName: method })\n }\n}\n\n/**\n * #122 (T2.1) — register one decorator-controller route into the tree. The class\n * import alias is shared across the class's methods (resolved by the caller). A\n * file-based route at the same node+verb WINS (file routes are the default); the\n * controller entry is skipped with a warning to keep the emitted `.d.ts` valid.\n */\nfunction buildOneController(\n cr: ControllerRouteData,\n classSource: { importPath: string; className: string },\n ctx: BuildContext,\n): void {\n const verb = cr.verb.toUpperCase()\n if (!(HTTP_METHODS as readonly string[]).includes(verb)) return\n const method = verb as HttpMethod\n\n const segments = routePathSegments(cr.fullPath)\n let node = ctx.root\n for (const seg of segments) {\n const norm = normalizeSegment(seg)\n let child = node.children.get(norm.identifier)\n if (child === undefined) {\n child = makeNode()\n node.children.set(norm.identifier, child)\n }\n node = child\n }\n node.paramNamesAccumulated = paramNamesFromRoute(cr.fullPath)\n\n if (node.methods.has(method)) {\n ctx.warnings.push(\n `WARNING (#122): controller ${cr.className}.${cr.methodName} (${method} /${segments.join('/')}) collides with a file-based route at the same path; file route wins.`,\n )\n return\n }\n if (cr.schemaNotExported === true) {\n // theokit#124 — a note, not a warning: the author did nothing wrong, and the emitted file is\n // valid. It exists so a reader who sees one typed method beside an untyped one knows the reason\n // is reachability, and knows the one-word fix.\n const note = `NOTE (#124): ${cr.className}.${cr.methodName} validates with a schema that is not exported, so its request type falls back to \\`unknown\\`. To get the type, export the schema (\\`export const zX = z.object({...})\\`).`\n if (!ctx.warnings.includes(note)) ctx.warnings.push(note)\n }\n node.controllerMethods.set(method, {\n classSource,\n methodName: cr.methodName,\n // theokit#124 — an EXPORTED schema is referenceable from the emitted `.d.ts`; an inline one is\n // not, and falls through to the documented `unknown`.\n ...(cr.bodySchemaExport !== undefined\n ? {\n bodySchema: {\n importPath: importPathFor(ctx.dtsOutPath, cr.filePath),\n exportName: cr.bodySchemaExport,\n },\n }\n : {}),\n ...(cr.querySchemaExport !== undefined\n ? {\n querySchema: {\n importPath: importPathFor(ctx.dtsOutPath, cr.filePath),\n exportName: cr.querySchemaExport,\n },\n }\n : {}),\n })\n}\n\n/**\n * EC-3: walk the tree post-build and resolve any node where a method's\n * lowercase name clashes with a child segment. HTTP method wins (more common);\n * the offending child gets a `_` suffix + a warning entry.\n */\nfunction resolveCollisions(node: TreeNode, pathPrefix: string, warnings: string[]): void {\n const methodLowerNames = new Set<string>()\n for (const method of node.methods.keys()) {\n methodLowerNames.add(method.toLowerCase())\n }\n for (const method of node.controllerMethods.keys()) {\n methodLowerNames.add(method.toLowerCase())\n }\n const renames: { from: string; to: string }[] = []\n for (const childName of node.children.keys()) {\n if (methodLowerNames.has(childName)) {\n renames.push({ from: childName, to: `${childName}_` })\n }\n }\n for (const { from, to } of renames) {\n const old = node.children.get(from)\n if (old !== undefined) {\n node.children.delete(from)\n node.children.set(to, old)\n warnings.push(\n `WARNING (EC-3): path collision — method '${from}' clashed with sub-namespace at ${pathPrefix}/${from}; sub-namespace renamed to '${to}'.`,\n )\n }\n }\n // Recurse into all children (including the renamed ones).\n for (const [name, child] of node.children) {\n resolveCollisions(child, `${pathPrefix}/${name}`, warnings)\n }\n}\n\nfunction renderTreeNode(node: TreeNode, indent: string, _isRoot: boolean): string {\n // _isRoot is reserved for callers; current rendering is uniform across roots\n // and children (both open with `{`). Kept in the signature for future overrides.\n const lines: string[] = ['{']\n // Methods first\n for (const [method, source] of node.methods) {\n const lower = method.toLowerCase()\n // Routes with path params (`:id`, `:name`) emit a `{ params: {...} }` object\n // intersected with TheoFetchOptions. Without the outer `{...}` wrap the\n // generated signature `(opts: params: {...} & ...)` is invalid TS syntax\n // (parser reads `params:` as a parameter label, then `{...}` as type — invalid).\n const paramsList = node.paramNamesAccumulated.map((p) => `${p}: string`).join('; ')\n const paramsField =\n node.paramNamesAccumulated.length > 0 ? `{ params: { ${paramsList} } } & ` : ''\n const optionalMark = node.paramNamesAccumulated.length === 0 ? '?' : ''\n // Inline, not an alias declared at the top of the block: an aliased relative `import type`\n // inside `declare module` collapses to `any` once an external package's conditional type is\n // applied to it, with no error (#469).\n const routeType = `typeof import('${source.importPath}').${source.exportName}`\n lines.push(\n `${indent} ${lower}: (opts${optionalMark}: ${paramsField}import('theokit/client').TheoFetchOptions<${routeType}>) => Promise<import('theokit/client').InferResponse<${routeType}>>`,\n )\n }\n // #122 (T2.1) — decorator-controller methods. Response inferred via\n // `Awaited<ReturnType<...>>`; params typed from the route pattern.\n //\n // theokit#124 — the request side too, when the `@Body`/`@Query` schema is EXPORTED. The ADR-2\n // checkpoint was right that the type cannot come from the class (parameter decorators erase to\n // runtime metadata, so `Parameters<...>[N]` is positional-only), and right that the runtime schema\n // carries no source identifier. What it missed is that the codegen LOADS the module, so the schema\n // object can be matched back to an export by reference identity — see `exportedNameOf`. An inline\n // schema has no name to reference and keeps the documented `unknown`.\n for (const [method, leaf] of node.controllerMethods) {\n const lower = method.toLowerCase()\n const paramsList = node.paramNamesAccumulated.map((p) => `${p}: string`).join('; ')\n const paramsField =\n node.paramNamesAccumulated.length > 0 ? `{ params: { ${paramsList} } } & ` : ''\n const optionalMark = node.paramNamesAccumulated.length === 0 ? '?' : ''\n const bodyType =\n leaf.bodySchema === undefined\n ? 'body?: unknown'\n : `body: import('zod').infer<typeof import('${leaf.bodySchema.importPath}').${leaf.bodySchema.exportName}>`\n const queryType =\n leaf.querySchema === undefined\n ? 'query?: Record<string, string>'\n : `query: import('zod').infer<typeof import('${leaf.querySchema.importPath}').${leaf.querySchema.exportName}>`\n lines.push(\n `${indent} ${lower}: (opts${optionalMark}: ${paramsField}{ ${bodyType}; ${queryType} }) => Promise<Awaited<ReturnType<InstanceType<typeof import('${leaf.classSource.importPath}').${leaf.classSource.className}>['${leaf.methodName}']>>>`,\n )\n }\n // Children\n for (const [name, child] of node.children) {\n // Backslash first, then the quote: escaping the quote while leaving the escape character\n // untouched means `back\\` emits as `'back\\'`, whose trailing backslash escapes the closing\n // quote and swallows the rest of the line. A backslash is a legal POSIX filename character, so\n // it reaches here from `server/routes/`.\n const propKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n ? name\n : `'${name.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n lines.push(`${indent} ${propKey}: ${renderTreeNode(child, indent + ' ', false)}`)\n }\n lines.push(`${indent}}`)\n return lines.join('\\n')\n}\n\ninterface GenerateClientDtsOptions {\n manifest: TheoManifest\n /** Absolute path to the .d.ts that will be emitted. Used to compute import paths. */\n dtsOutPath: string\n /** Absolute serverDir; manifest's filePath entries are relative to this. */\n serverDir: string\n /**\n * #122 (T2.1) — decorator-controller routes (from `collectControllerRouteData`),\n * merged into the same `client.<ns>.<method>()` tree as file routes. Absent/empty\n * → zero controller output (ADR-5 routes-only byte-identity).\n */\n controllerRoutes?: ControllerRouteData[]\n}\n\nexport function generateClientDts({\n manifest,\n dtsOutPath,\n serverDir,\n controllerRoutes,\n}: GenerateClientDtsOptions): string {\n const ctx: BuildContext = {\n root: makeNode(),\n warnings: [],\n dtsOutPath,\n serverDir,\n }\n for (const route of manifest.routes) {\n buildOneRoute(route, ctx)\n }\n // #122 (T2.1) — merge decorator controllers into the same tree. One import\n // alias per class (shared across its methods), keyed by source file.\n if (controllerRoutes?.length) {\n for (const cr of controllerRoutes) {\n buildOneController(\n cr,\n { importPath: importPathFor(dtsOutPath, cr.filePath), className: cr.className },\n ctx,\n )\n }\n }\n // EC-3: resolve collisions in a post-build pass (collisions materialize\n // when two routes are both processed, not during a single route's build).\n resolveCollisions(ctx.root, '', ctx.warnings)\n\n // No import block at all since #469: every type is named inline as `typeof import('...')`, which\n // is the only form measured to survive inside `declare module`. Nothing pushes here any more, so\n // the seam is gone rather than left empty — an empty seam invites the next author to use it.\n const importsBlock = '\\n'\n const warningsBlock =\n ctx.warnings.length > 0 ? ' // ' + ctx.warnings.join('\\n // ') + '\\n\\n' : ''\n\n // Empty manifest (no routes with methods) → emit a stub interface so consumers\n // still get `client.X` autocomplete-friendly errors instead of \"Module not found\".\n const treeBody =\n ctx.root.children.size === 0 &&\n ctx.root.methods.size === 0 &&\n ctx.root.controllerMethods.size === 0\n ? '{\\n // No routes detected — add `server/routes/*.ts` to populate this client.\\n }'\n : renderTreeNode(ctx.root, ' ', /* isRoot */ true)\n\n return `${FILE_HEADER}\ndeclare module '@theo/client' {\n${importsBlock}${warningsBlock} export interface AppClient ${treeBody}\n export const client: AppClient\n}\n`\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Phase 4 — Vite plugin\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface AppTypedClientPluginOptions {\n /** Project root (cwd). */\n cwd: string\n /** Absolute path to the user's `server/` dir. */\n serverDir: string\n /** Absolute path to the `.theokit/` output dir (where `client.d.ts` lands). */\n distDir: string\n /**\n * Additional routes to merge into the typed client alongside file-system routes.\n * Each entry follows ManifestRoute shape (filePath, routePath, methods, paramNames).\n *\n * Used by `@theokit/http` `httpDecoratorsPlugin` to inject\n * decorator-defined routes — zero coupling between theokit core and the\n * decorator package (the walk happens in http-decorators; only data arrives here).\n */\n extraRoutes?: ManifestRoute[]\n /**\n * The agents dir NAME, relative to `cwd` (config `agentsDir`).\n *\n * B-313 — `cwd` was already here and the `generateManifest` call below passed neither, so the manifest\n * guessed the root as the server dir's parent and the agents dir as `'agents'`. Optional and\n * undefaulted, so \"the project configured nothing\" passes through as itself.\n */\n agentsDir?: string\n}\n\nconst VIRTUAL_APP_CLIENT_ID = '@theo/client'\nconst RESOLVED_APP_CLIENT_ID = '\\0@theo/client'\n\n/**\n * Should a watcher file event under `routes/` or `controllers/` trigger a client\n * re-emit? Ignores the `.__decorated__.mjs` temp files that `loadControllerWithSwc`\n * writes+unlinks during controller codegen — reacting to them would create a\n * perpetual emit→temp-write→watcher→emit loop (#122 T2.1).\n */\nexport function shouldReemitForFile(\n file: string,\n routesGlob: string,\n controllersGlob: string,\n): boolean {\n const normalized = file.replace(/\\\\/g, '/')\n if (normalized.includes('.__decorated__.')) return false\n return normalized.startsWith(routesGlob) || normalized.startsWith(controllersGlob)\n}\n\n/** Atomic write via tmp + rename (EC-6). Skips when content is unchanged. */\nfunction writeFileIfChanged(filePath: string, content: string): { changed: boolean } {\n if (existsSync(filePath)) {\n try {\n const current = readFileSync(filePath, 'utf-8')\n if (current === content) return { changed: false }\n } catch {\n // fall through to write\n }\n }\n mkdirSync(dirname(filePath), { recursive: true })\n const tmp = `${filePath}.${process.pid}.tmp`\n writeFileSync(tmp, content)\n renameSync(tmp, filePath)\n return { changed: true }\n}\n\nasync function emitClientDts(\n opts: AppTypedClientPluginOptions,\n): Promise<{ changed: boolean; path: string }> {\n if (!existsSync(opts.serverDir)) {\n // No server dir — emit empty stub to avoid \"module not found\".\n const stubPath = posix.join(opts.distDir.replace(/\\\\/g, '/'), 'client.d.ts')\n return {\n changed: writeFileIfChanged(\n stubPath,\n generateClientDts({\n manifest: {\n version: 1,\n generatedAt: new Date().toISOString(),\n routes: [],\n actions: [],\n websockets: [],\n },\n dtsOutPath: stubPath,\n serverDir: opts.serverDir,\n }),\n ).changed,\n path: stubPath,\n }\n }\n const manifest = generateManifest(opts.serverDir, opts.cwd, opts.agentsDir)\n\n // Decorator-client-bridge: merge extra routes (from @theokit/http\n // or any other source) into the manifest so generateClientDts() produces a\n // SINGLE typed client covering both file-system routes AND injected routes.\n if (opts.extraRoutes?.length) {\n manifest.routes.push(...opts.extraRoutes)\n }\n\n // #122 (T2.1) — merge decorator controllers under `<serverDir>/controllers/`\n // into the same typed client. Zero output when the dir is absent/empty (ADR-5).\n const controllersDir = resolve(opts.serverDir, 'controllers')\n const controllerRoutes = existsSync(controllersDir)\n ? await collectControllerRouteData({ controllersDir })\n : []\n\n const dtsOutPath = posix.join(opts.distDir.replace(/\\\\/g, '/'), 'client.d.ts')\n const content = generateClientDts({\n manifest,\n dtsOutPath,\n serverDir: opts.serverDir,\n controllerRoutes,\n })\n const { changed } = writeFileIfChanged(dtsOutPath, content)\n return { changed, path: dtsOutPath }\n}\n\nexport function appTypedClientPlugin(opts: AppTypedClientPluginOptions): Plugin {\n let debounceTimer: NodeJS.Timeout | undefined\n let viteServer: ViteDevServer | undefined\n\n function scheduleEmit(): void {\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n void (async () => {\n try {\n await emitClientDts(opts)\n // Invalidate the virtual module so re-imports pick up potential new shape.\n if (viteServer) {\n const mod = viteServer.moduleGraph.getModuleById(RESOLVED_APP_CLIENT_ID)\n if (mod) viteServer.moduleGraph.invalidateModule(mod)\n }\n } catch (err) {\n // Surface but don't crash dev server.\n console.error('[theokit:app-typed-client] codegen error:', err)\n }\n })()\n }, 100)\n }\n\n return {\n name: 'theokit:app-typed-client',\n enforce: 'post',\n async configResolved() {\n try {\n await emitClientDts(opts)\n } catch (err) {\n console.error('[theokit:app-typed-client] initial codegen error:', err)\n }\n },\n async buildEnd() {\n try {\n await emitClientDts(opts)\n } catch (err) {\n console.error('[theokit:app-typed-client] buildEnd codegen error:', err)\n }\n },\n configureServer(server) {\n viteServer = server\n const routesGlob = posix.join(opts.serverDir.replace(/\\\\/g, '/'), 'routes')\n const controllersGlob = posix.join(opts.serverDir.replace(/\\\\/g, '/'), 'controllers')\n const onFile = (file: string): void => {\n if (shouldReemitForFile(file, routesGlob, controllersGlob)) scheduleEmit()\n }\n server.watcher.on('add', onFile)\n server.watcher.on('change', onFile)\n server.watcher.on('unlink', onFile)\n },\n resolveId(id) {\n if (id === VIRTUAL_APP_CLIENT_ID) return RESOLVED_APP_CLIENT_ID\n return null\n },\n load(id) {\n if (id === RESOLVED_APP_CLIENT_ID) {\n return [\n `import { createAppClient } from 'theokit/client'`,\n `export const client = createAppClient()`,\n `export default client`,\n ``,\n ].join('\\n')\n }\n return null\n },\n }\n}\n\nexport { VIRTUAL_APP_CLIENT_ID, RESOLVED_APP_CLIENT_ID, emitClientDts }\n","/**\n * #122 (T2.1) — typed-client codegen for decorator controllers.\n *\n * Collects the routing metadata of every `@Controller` under `controllersDir`\n * so the app-typed-client codegen can emit `client.<ns>.<method>()` entries.\n * Codegen loads controllers via `loadControllerWithSwc` (swc-compile + import,\n * no Vite dev server needed) — distinct from the dev SERVING path, which loads\n * through Vite's `ssrLoadModule`.\n *\n * ADR-2 checkpoint (LOCKED — see the plan's Unresolved Questions): only the\n * RESPONSE type is inferred, via `Awaited<ReturnType<InstanceType<typeof C>['m']>>`.\n * Request `@Body` types are NOT inferred from the class — parameter decorators are\n * erased runtime metadata, invisible to the type system, so `Parameters<...>[N]` is\n * positional-only and cannot tell body from param from query. Body falls back to\n * `unknown` (runtime `@Body` Zod validation from Phase 1 still applies). Full body\n * inference is tracked in the follow-up issue.\n */\nimport { loadControllerWithSwc, walkControllerMetadata } from '@theokit/http'\n\nimport {\n scanControllerModules,\n type ControllerModuleLoader,\n} from '../server/http/controller-dispatch.js'\n\n/** One controller route, flattened for the client codegen. */\nexport interface ControllerRouteData {\n /** Absolute path to the `*.controller.ts` source (for the `import type` line). */\n filePath: string\n /** The exported class name (e.g. `TasksController`). */\n className: string\n /** Full route path, e.g. `/api/v2/tasks/:id`. */\n fullPath: string\n /** HTTP verb (`GET`, `POST`, …). */\n verb: string\n /** The controller method name backing this route (e.g. `findById`). */\n methodName: string\n /**\n * theokit#124 — the EXPORTED name of the `@Body(schema)` Zod schema, when it has one.\n *\n * Absent when the schema is declared inline or otherwise not exported: there is then no\n * identifier the emitted `.d.ts` could reference, and the body stays `unknown`.\n */\n bodySchemaExport?: string\n /** theokit#124 — same for `@Query(schema)`. */\n querySchemaExport?: string\n /**\n * theokit#124 — a `@Body`/`@Query` schema EXISTS on this route but is not exported, so no name\n * could be referenced and the type degraded to `unknown`.\n *\n * Distinct from \"there is no schema at all\": that route was never going to be typed and needs no\n * explanation, while this one looks arbitrarily untyped next to a typed neighbour. The codegen\n * turns this into a note in the emitted file so the difference is legible.\n */\n schemaNotExported?: boolean\n}\n\n/**\n * Recover the EXPORTED name of a runtime schema object — theokit#124.\n *\n * `WalkResult.bodySchema` is a `z.ZodType` instance with no source identifier, which is why #122's\n * ADR-2 checkpoint concluded the request type was unrecoverable. It is recoverable, just not from\n * the metadata: the codegen already imports the module, so this object IS the one the module\n * exported, and reference identity gives back its name. No parsing, no heuristics — either some\n * export is the same object or none is.\n *\n * Returns `undefined` for an inline schema, which is a real limit rather than a bug: an unexported\n * value has no name a `.d.ts` can import.\n */\nfunction exportedNameOf(\n schema: unknown,\n moduleExports: Readonly<Record<string, unknown>>,\n): string | undefined {\n if (schema === undefined || schema === null) return undefined\n for (const [name, value] of Object.entries(moduleExports)) {\n // Reference identity, never structural comparison: two distinct schemas can be deeply equal,\n // and emitting the wrong name would type the client against the wrong contract silently.\n if (value === schema) return name\n }\n return undefined\n}\n\n/**\n * Scan `controllersDir` and flatten every controller's routes into\n * {@link ControllerRouteData}. Returns `[]` when the directory has no controllers\n * (so the codegen contributes zero bytes — ADR-5 routes-only byte-identity).\n */\nexport async function collectControllerRouteData(opts: {\n controllersDir: string\n loadModule?: ControllerModuleLoader\n}): Promise<ControllerRouteData[]> {\n const loader = opts.loadModule ?? loadControllerWithSwc\n const modules = await scanControllerModules(opts.controllersDir, loader)\n const out: ControllerRouteData[] = []\n for (const { filePath, cls, exports } of modules) {\n const className = (cls as { name: string }).name\n for (const walk of walkControllerMetadata(cls)) {\n const bodySchemaExport = exportedNameOf(walk.bodySchema, exports)\n // `walk.querySchema` is DECLARED on `WalkResult` and never populated — `walkControllerMetadata`\n // resolves a body schema and has no query counterpart, so the field always reads `undefined`\n // (grep: the only occurrence in `@theokit/http` is its own declaration). Reading the entry\n // directly is therefore not a shortcut around an API; it is the only place the schema exists.\n //\n // Deliberately NOT fixed by populating `querySchema` here: that field feeds runtime validation\n // for `@Body`, so filling the query one would start VALIDATING query strings that are not\n // validated today. This issue is about editor types; silently turning on runtime rejection\n // under it would be a behaviour change nobody asked for. Filed separately.\n const queryEntry = walk.paramEntries.find(\n (e) => e.source === 'query' && e.schema !== undefined,\n )\n const querySchemaExport = exportedNameOf(queryEntry?.schema, exports)\n out.push({\n filePath,\n className,\n fullPath: walk.fullPath,\n verb: walk.verb,\n methodName: String(walk.propertyKey),\n ...(bodySchemaExport !== undefined ? { bodySchemaExport } : {}),\n ...(querySchemaExport !== undefined ? { querySchemaExport } : {}),\n ...((walk.bodySchema !== undefined && bodySchemaExport === undefined) ||\n (queryEntry?.schema !== undefined && querySchemaExport === undefined)\n ? { schemaNotExported: true }\n : {}),\n })\n }\n }\n return out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F;AACF;","names":[]}
@@ -1,23 +1,28 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
+ import {
4
+ bundleDeployedFunction
5
+ } from "./chunk-NPQ5A3RU.js";
6
+ import {
7
+ renderBakedRoutes,
8
+ routeRuntimeLines
9
+ } from "./chunk-72RSCKMW.js";
3
10
  import {
4
11
  deployedEntryPreamble
5
- } from "./chunk-R36YNWBU.js";
12
+ } from "./chunk-XLFDYTWO.js";
6
13
  import {
7
14
  JSON_NOT_FOUND_RESPONSE,
8
- agentsDirLiteral,
9
15
  deployedAgentsFragment,
10
16
  deployedRateLimitFragment,
11
17
  deployedRuntimeConfigFragment,
12
18
  deployedTraceFragment,
13
19
  describeDeployedSecurityHeaders,
14
20
  rateLimitCheckFragment,
15
- scannedFromLoaderCache,
16
21
  serverDirLiteral
17
- } from "./chunk-SEGD3JUC.js";
22
+ } from "./chunk-EQJF2EH5.js";
18
23
  import {
19
24
  nodeAdapter
20
- } from "./chunk-G7U7FQVC.js";
25
+ } from "./chunk-UFBBFP75.js";
21
26
  import "./chunk-WSMLSIS5.js";
22
27
  import {
23
28
  assertServicesUnsupported,
@@ -25,7 +30,7 @@ import {
25
30
  } from "./chunk-ZNZISJDZ.js";
26
31
 
27
32
  // src/adapters/aws-lambda.ts
28
- import { mkdirSync, writeFileSync } from "fs";
33
+ import { mkdirSync } from "fs";
29
34
  import { resolve } from "path";
30
35
  var BINARY_CONTENT_TYPES = [
31
36
  "application/octet-stream",
@@ -110,7 +115,7 @@ function awsLambdaHandlerFragment(runtimeSpread, agentsBranch, agentsHostBypass,
110
115
  `// routeRequest, so the security baseline is applied at ONE place and the`,
111
116
  `// v2 result object is built from headers that already carry it.`,
112
117
  ...rateLimit === void 0 ? [] : [
113
- `import { createRateLimiterWeb } from 'theokit/server'`,
118
+ `import { createRateLimiterWeb } from 'theokit/server/rate-limit'`,
114
119
  `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,
115
120
  ``
116
121
  ],
@@ -158,8 +163,6 @@ function awsLambdaHandlerFragment(runtimeSpread, agentsBranch, agentsHostBypass,
158
163
  ` )`,
159
164
  ` }`,
160
165
  ``,
161
- ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,
162
- ` if (!loaderCache) loaderCache = createProductionLoader()`,
163
166
  ``,
164
167
  // B-235 — hoisted above the agents branch, which names `request` like every other host's.
165
168
  // It was declared below `matchRoute`, and an agent path never reaches a route match. Building
@@ -170,35 +173,45 @@ function awsLambdaHandlerFragment(runtimeSpread, agentsBranch, agentsHostBypass,
170
173
  ``,
171
174
  ...agentsBranch,
172
175
  ``,
173
- ` const match = matchRoute(path, routesCache)`,
176
+ ` const match = matchRoute(path, routes)`,
174
177
  ` if (!match) return ${JSON_NOT_FOUND_RESPONSE}`,
175
178
  ``,
176
179
  ` const { req, res, toResponse } = createWebShim(request)`,
177
180
  ...deployedTraceFragment("request", " "),
178
181
  ` const method = request.method.toUpperCase()`,
179
- ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,
182
+ ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,
180
183
  `}`
181
184
  ];
182
185
  }
183
186
  function renderAwsLambdaEntry(opts = {}) {
184
187
  const runtimeConfig = deployedRuntimeConfigFragment(opts);
185
- const agentsFragment = deployedAgentsFragment(scannedFromLoaderCache(agentsDirLiteral(opts)), {
186
- pathname: "path",
187
- notFound: JSON_NOT_FOUND_RESPONSE
188
- });
188
+ const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(
189
+ opts.routes ?? []
190
+ );
191
+ const agentsFragment = deployedAgentsFragment(
192
+ { kind: "baked", agents: opts.agents ?? [], contextModule: opts.contextModule },
193
+ {
194
+ pathname: "path",
195
+ // This entry has no `url` object: `eventV2ToRequest` builds a STRING, in another function.
196
+ // `request` is what routeRequest holds, and it carries the same absolute URL that string was.
197
+ baseUrl: "new URL(request.url).origin",
198
+ notFound: JSON_NOT_FOUND_RESPONSE
199
+ }
200
+ );
189
201
  return [
190
202
  `// Generated by Theo \u2014 AWS Lambda Adapter`,
191
203
  `// Use with API Gateway HTTP API v2 (default).`,
192
204
  ``,
193
205
  `import { resolve } from 'node:path'`,
194
- `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,
206
+ `import { matchRoute, compilePattern } from 'theokit/server/scan'
207
+ import { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'`,
208
+ ...routeImports,
195
209
  `import { createWebShim } from 'theokit/adapters/web-shim'`,
196
210
  `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,
197
211
  ``,
198
212
  `const cwd = process.cwd()`,
199
213
  `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,
200
- `let routesCache = null`,
201
- `let loaderCache = null`,
214
+ ...routeRuntimeLines(routeModuleEntries, routeTableEntries, TARGET),
202
215
  ``,
203
216
  `// #410 \u2014 the security baseline \`theokit start\` puts on every response,`,
204
217
  `// carried here as a literal because the deployed function has no`,
@@ -236,20 +249,32 @@ function renderAwsLambdaEntry(opts = {}) {
236
249
  )
237
250
  ].join("\n");
238
251
  }
252
+ function resolveAwsLambdaDeps(deps) {
253
+ return {
254
+ runNodeBuild: deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter),
255
+ bundleFunction: deps.bundleFunction ?? bundleDeployedFunction,
256
+ ensureDir: deps.ensureDir ?? ((path) => mkdirSync(path, { recursive: true }))
257
+ };
258
+ }
239
259
  async function buildAwsLambda(config, cwd, deps = {}, ctx) {
260
+ const { runNodeBuild, bundleFunction, ensureDir } = resolveAwsLambdaDeps(deps);
240
261
  assertServicesUnsupported("aws-lambda", readManifest(cwd));
241
262
  if (config.ssrStreaming) {
242
- throw new Error(
243
- "[adapter-aws-lambda] ssrStreaming is on, but the aws-lambda target does not stream responses: the Lambda v2 result object carries the body as a string, so nothing can leave the function before the run ends. Response streaming would need awslambda.streamifyResponse plus a Function URL in RESPONSE_STREAM invoke mode, which this adapter does not emit. Build a streaming target instead (cloudflare, vercel, netlify, bun, deno-deploy, node), or set ssrStreaming: false in theo.config.ts."
244
- );
263
+ const { assertStreamingSupported } = await import("./config-support-MOZYHRWG.js");
264
+ assertStreamingSupported(config, awsLambdaAdapter, "aws-lambda");
245
265
  }
246
- const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter);
247
266
  await runNodeBuild(config, cwd, ctx);
248
267
  const outputDir = resolve(cwd, ".theokit/aws");
249
- const ensureDir = deps.ensureDir ?? ((p) => mkdirSync(p, { recursive: true }));
250
268
  ensureDir(outputDir);
269
+ const scanned = ctx?.scanRoutes?.(config.serverDir);
251
270
  const entry = renderAwsLambdaEntry({
271
+ routes: scanned?.routes,
272
+ agents: scanned?.agents,
273
+ contextModule: scanned?.contextModule,
252
274
  securityHeaders: config.security?.headers,
275
+ // B-315 — the same shape as the B-235 note below, one option over: this build never passed
276
+ // `serverDir`, so a project declaring `src/server` got an entry resolving `server`.
277
+ serverDir: config.serverDir,
253
278
  // B-235 — pillar (a): the option existed and no build passed it, so a project with a
254
279
  // configured agents directory got the default `agents` on this target. Same defect
255
280
  // B-185 fixed for bun and deno, one target over.
@@ -260,10 +285,13 @@ async function buildAwsLambda(config, cwd, deps = {}, ctx) {
260
285
  // #425 — a selector, not a transformer, so it rides as a literal like the values above.
261
286
  serialization: config.serialization
262
287
  });
263
- const write = deps.writeEntry ?? ((p, c) => {
264
- writeFileSync(p, c);
288
+ await bundleFunction({
289
+ projectRoot: cwd,
290
+ entrySource: entry,
291
+ stagePath: ".theokit/aws/handler.entry.mjs",
292
+ outDir: outputDir,
293
+ entryFileName: "handler.mjs"
265
294
  });
266
- write(resolve(outputDir, "handler.mjs"), entry);
267
295
  console.log("\n \u2713 AWS Lambda output \u2192 .theokit/aws/handler.mjs");
268
296
  console.log(
269
297
  `${describeDeployedSecurityHeaders({
@@ -276,9 +304,15 @@ async function buildAwsLambda(config, cwd, deps = {}, ctx) {
276
304
  );
277
305
  }
278
306
  var awsLambdaAdapter = {
307
+ // B-342 / B-344 — measured by INVOKING the handler from a directory with no `node_modules`:
308
+ // `ERR_MODULE_NOT_FOUND: Cannot find package 'theokit'` as source, then 404 once bundled but
309
+ // still scanning, then 200 with routes and agents baked.
310
+ readsSourceAtRunTime: false,
311
+ specifiersResolvedBy: "this-adapter",
279
312
  name: TARGET,
280
313
  // #382 — delisted for streaming, deliberately. See DeployAdapter.
281
314
  streamsResponses: false,
315
+ streamingUnsupportedDetail: "The Lambda v2 result object carries the body as a string, so nothing can leave the function before the run ends. Response streaming would need awslambda.streamifyResponse plus a Function URL in RESPONSE_STREAM invoke mode, which this adapter does not emit.",
282
316
  // #409 / #410 — the generated entry calls `executeRoute` with routes, loader
283
317
  // and serverDir only. CSRF, route policy, file middleware and Zod validation
284
318
  // still run because they live inside `executeRoute`; none of the remaining
@@ -302,4 +336,4 @@ export {
302
336
  renderAwsLambdaEntry,
303
337
  responseToLambdaResultV2
304
338
  };
305
- //# sourceMappingURL=aws-lambda-OP2L5RKZ.js.map
339
+ //# sourceMappingURL=aws-lambda-ZYSPTD3O.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/aws-lambda.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * AWS Lambda adapter. Writes to `cwd/.theokit/lambda/`. Build-time tool.\n */\nimport { mkdirSync } 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;A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