theokit 0.43.6 → 0.43.12

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 (244) hide show
  1. package/LICENSE +201 -0
  2. package/dist/{actions-virtual-module-N7GKUS3D.js → actions-virtual-module-HG66SZ7T.js} +8 -8
  3. package/dist/actions-virtual-module-HG66SZ7T.js.map +1 -0
  4. package/dist/{actions-virtual-module-LD3YKWIX.js → actions-virtual-module-RSFRPJQZ.js} +7 -7
  5. package/dist/actions-virtual-module-RSFRPJQZ.js.map +1 -0
  6. package/dist/{add-W6FNTAFS.js → add-3VLFUPF4.js} +1 -1
  7. package/dist/add-3VLFUPF4.js.map +1 -0
  8. package/dist/{agent-U35G3WNE.js → agent-OXRRKB55.js} +5 -5
  9. package/dist/{agents-typed-client-NJ73Z6XY.js → agents-typed-client-X56CQ6FX.js} +1 -1
  10. package/dist/agents-typed-client-X56CQ6FX.js.map +1 -0
  11. package/dist/{agents-typed-client-CHMVW7MK.js → agents-typed-client-ZP7BKJB3.js} +1 -1
  12. package/dist/agents-typed-client-ZP7BKJB3.js.map +1 -0
  13. package/dist/{app-typed-client-6YZRDAPY.js → app-typed-client-GDF2OMJ2.js} +8 -8
  14. package/dist/app-typed-client-GDF2OMJ2.js.map +1 -0
  15. package/dist/{app-typed-client-V77SVU2O.js → app-typed-client-USLAMN7X.js} +7 -7
  16. package/dist/app-typed-client-USLAMN7X.js.map +1 -0
  17. package/dist/{aws-lambda-7GSCNLPY.js → aws-lambda-473QCOL6.js} +3 -3
  18. package/dist/{body-parser-web-MUWBKZ3F.js → body-parser-web-NNEJGX6Y.js} +1 -1
  19. package/dist/body-parser-web-NNEJGX6Y.js.map +1 -0
  20. package/dist/{body-parser-web-FV5HWCY3.js → body-parser-web-TIOTXPDW.js} +1 -1
  21. package/dist/body-parser-web-TIOTXPDW.js.map +1 -0
  22. package/dist/broadcast-LUMOJIJT.js +0 -0
  23. package/dist/{build-BYLQZJT2.js → build-MQHIJROR.js} +11 -11
  24. package/dist/{build-BYLQZJT2.js.map → build-MQHIJROR.js.map} +1 -1
  25. package/dist/{build-request-body-preview-EOP2Y4F3.js → build-request-body-preview-FVBQ7LCE.js} +1 -1
  26. package/dist/build-request-body-preview-FVBQ7LCE.js.map +1 -0
  27. package/dist/{build-request-body-preview-QMWD2IXK.js → build-request-body-preview-XPZ2GYMG.js} +1 -1
  28. package/dist/build-request-body-preview-XPZ2GYMG.js.map +1 -0
  29. package/dist/{bun-KP2KES6S.js → bun-OQUCL3XW.js} +3 -3
  30. package/dist/{check-PD2FTKMM.js → check-45NKUVSQ.js} +1 -1
  31. package/dist/check-45NKUVSQ.js.map +1 -0
  32. package/dist/{chunk-FRUEDJFX.js → chunk-226KMIGZ.js} +3 -3
  33. package/dist/{chunk-FRUEDJFX.js.map → chunk-226KMIGZ.js.map} +1 -1
  34. package/dist/{chunk-U3NTEK46.js → chunk-26ECIX74.js} +2 -2
  35. package/dist/chunk-2CVV6CNN.js +0 -0
  36. package/dist/{chunk-FEDSPOY6.js → chunk-2WH6SD3C.js} +6 -6
  37. package/dist/chunk-2WH6SD3C.js.map +1 -0
  38. package/dist/{chunk-JAIKGP3Q.js → chunk-47VNWTL4.js} +1 -1
  39. package/dist/chunk-47VNWTL4.js.map +1 -0
  40. package/dist/{chunk-D7ZH7DTG.js → chunk-4B2ZMX45.js} +1 -1
  41. package/dist/chunk-4B2ZMX45.js.map +1 -0
  42. package/dist/{chunk-IHJZPQEF.js → chunk-4HAU7AJM.js} +3 -3
  43. package/dist/chunk-4HAU7AJM.js.map +1 -0
  44. package/dist/{chunk-IPC5UREF.js → chunk-575PAX5L.js} +17 -17
  45. package/dist/chunk-575PAX5L.js.map +1 -0
  46. package/dist/chunk-5ODOE6EF.js +0 -0
  47. package/dist/{chunk-X2VVCJ4V.js → chunk-65EFIUDD.js} +1 -1
  48. package/dist/chunk-65EFIUDD.js.map +1 -0
  49. package/dist/{chunk-GY5Q27BJ.js → chunk-6FK7FKY6.js} +1 -1
  50. package/dist/{chunk-GY5Q27BJ.js.map → chunk-6FK7FKY6.js.map} +1 -1
  51. package/dist/{chunk-GSO77FSM.js → chunk-6OXCZMW3.js} +45 -47
  52. package/dist/chunk-6OXCZMW3.js.map +1 -0
  53. package/dist/{chunk-P37RZRFV.js → chunk-A7JBF5FO.js} +1 -1
  54. package/dist/chunk-A7JBF5FO.js.map +1 -0
  55. package/dist/{chunk-AFVTEAES.js → chunk-CJNMJUHE.js} +2 -2
  56. package/dist/{chunk-AXVFVMLM.js → chunk-DJFMAWH5.js} +8 -4
  57. package/dist/chunk-DJFMAWH5.js.map +1 -0
  58. package/dist/{chunk-2ZX4J4SX.js → chunk-DQVBL2G4.js} +58 -56
  59. package/dist/chunk-DQVBL2G4.js.map +1 -0
  60. package/dist/{chunk-GW5H4KB4.js → chunk-FX72VHAE.js} +3 -3
  61. package/dist/chunk-GDN3PXFH.js +0 -0
  62. package/dist/chunk-GEQJAFSV.js +0 -0
  63. package/dist/{chunk-5AVPWHUE.js → chunk-HGUZWG2C.js} +7 -4
  64. package/dist/chunk-HGUZWG2C.js.map +1 -0
  65. package/dist/chunk-HGZL5EOI.js +0 -0
  66. package/dist/chunk-HNBWZKIQ.js +0 -0
  67. package/dist/{chunk-UNLG36Z5.js → chunk-IE6C4KZX.js} +10 -5
  68. package/dist/chunk-IE6C4KZX.js.map +1 -0
  69. package/dist/chunk-IEES3CHD.js +0 -0
  70. package/dist/{chunk-QWBXUZAX.js → chunk-JIL74SFK.js} +4 -4
  71. package/dist/chunk-JIL74SFK.js.map +1 -0
  72. package/dist/{chunk-KI7OWQUX.js → chunk-L2S2R3TI.js} +63 -20
  73. package/dist/chunk-L2S2R3TI.js.map +1 -0
  74. package/dist/{chunk-L4GCEMNW.js → chunk-LNVMHQ2Z.js} +2 -2
  75. package/dist/{chunk-SPJNVWOK.js → chunk-N2D5AVRR.js} +2 -3
  76. package/dist/chunk-N2D5AVRR.js.map +1 -0
  77. package/dist/{chunk-UO7WS32S.js → chunk-OI6DK6ZJ.js} +3 -3
  78. package/dist/chunk-OI6DK6ZJ.js.map +1 -0
  79. package/dist/{chunk-RMU7EBRO.js → chunk-OP7QCTR5.js} +2 -2
  80. package/dist/{chunk-RMU7EBRO.js.map → chunk-OP7QCTR5.js.map} +1 -1
  81. package/dist/{chunk-GUUWDMR2.js → chunk-OVHW23YC.js} +2 -2
  82. package/dist/{chunk-NQRNDPZJ.js → chunk-OXCALO3W.js} +3 -3
  83. package/dist/{chunk-45C3WUQ7.js → chunk-QPVXGC7O.js} +1 -1
  84. package/dist/chunk-QPVXGC7O.js.map +1 -0
  85. package/dist/{chunk-FOZIR3TG.js → chunk-SMP2T335.js} +2 -2
  86. package/dist/{chunk-M6NMS5LR.js → chunk-TDNNBLGW.js} +1 -1
  87. package/dist/chunk-TDNNBLGW.js.map +1 -0
  88. package/dist/{chunk-WFNLNIJX.js → chunk-VPISAMXU.js} +2 -2
  89. package/dist/{chunk-5PU65T5W.js → chunk-XZ6B2Y2R.js} +1 -1
  90. package/dist/chunk-XZ6B2Y2R.js.map +1 -0
  91. package/dist/cli/index.js +15 -15
  92. package/dist/client/index.d.ts +1 -1
  93. package/dist/client/index.js +20 -25
  94. package/dist/client/index.js.map +1 -1
  95. package/dist/{cloudflare-C6E5SPAE.js → cloudflare-4YT5CK3P.js} +3 -3
  96. package/dist/configure-agent-registry-ZOBVU3MV.js +0 -0
  97. package/dist/{controller-swc-transform-URELVCBM.js → controller-swc-transform-JJRMTSDY.js} +1 -1
  98. package/dist/controller-swc-transform-JJRMTSDY.js.map +1 -0
  99. package/dist/{controller-swc-transform-XV3ETSE3.js → controller-swc-transform-LUJ4VAZJ.js} +1 -1
  100. package/dist/controller-swc-transform-LUJ4VAZJ.js.map +1 -0
  101. package/dist/{db-3UNAMSFK.js → db-IVVCQE5Z.js} +1 -2
  102. package/dist/db-IVVCQE5Z.js.map +1 -0
  103. package/dist/{deno-deploy-RFZN56X4.js → deno-deploy-YYN6BNLF.js} +3 -3
  104. package/dist/{dev-PS2NGT6I.js → dev-WQ4LWCAW.js} +13 -13
  105. package/dist/{dev-emit-2DL3MCLM.js → dev-emit-HLGJK3PP.js} +3 -3
  106. package/dist/dev-emit-HLGJK3PP.js.map +1 -0
  107. package/dist/{dev-emit-XVTJXZGA.js → dev-emit-J7V6GWSK.js} +6 -6
  108. package/dist/devtools/entry.js +43 -15
  109. package/dist/devtools/entry.js.map +1 -1
  110. package/dist/{dispatcher-63LBXYLE.js → dispatcher-DLKIXYNO.js} +2 -2
  111. package/dist/{dispatcher-EJHL6JMJ.js → dispatcher-KMZBGMM5.js} +1 -1
  112. package/dist/dispatcher-KMZBGMM5.js.map +1 -0
  113. package/dist/docker-LZZB4D5E.js +0 -0
  114. package/dist/{generate-5X4LG77M.js → generate-GXWPUVS7.js} +4 -5
  115. package/dist/generate-GXWPUVS7.js.map +1 -0
  116. package/dist/index.js +9 -9
  117. package/dist/{info-2OOXFTJX.js → info-75U6GCMD.js} +4 -4
  118. package/dist/info-75U6GCMD.js.map +1 -0
  119. package/dist/{internal-api-LFW7R65K.js → internal-api-DV3H5NNV.js} +7 -9
  120. package/dist/{internal-api-FBFV265J.js → internal-api-JFORKYLR.js} +8 -10
  121. package/dist/{load-config-3EAQTXPH.js → load-config-XP7NSSA7.js} +4 -4
  122. package/dist/{mcp-ML4QK5ON.js → mcp-FF3NTCHB.js} +6 -6
  123. package/dist/mcp-FF3NTCHB.js.map +1 -0
  124. package/dist/{netlify-PMLHVPN4.js → netlify-2WZUQYI3.js} +3 -3
  125. package/dist/node-CMAYKDCM.js +10 -0
  126. package/dist/{openapi-2HVGJMSN.js → openapi-ZPXYRAM2.js} +9 -9
  127. package/dist/openapi-ZPXYRAM2.js.map +1 -0
  128. package/dist/registry-72YH7ZJM.js +23 -0
  129. package/dist/registry-72YH7ZJM.js.map +1 -0
  130. package/dist/{router-TLEAOFID.js → router-6MAACS25.js} +1 -2
  131. package/dist/router-6MAACS25.js.map +1 -0
  132. package/dist/{routes-XNS3UM3B.js → routes-ZVDKABXZ.js} +6 -6
  133. package/dist/scan-7MJC6PYU.js +0 -0
  134. package/dist/schema-FBOTN46F.js +22 -0
  135. package/dist/server/agent/index.js +1 -1
  136. package/dist/server/cost/index.js +1 -1
  137. package/dist/server/cron/index.js +2 -2
  138. package/dist/server/http/index.js +3 -3
  139. package/dist/server/index.js +11 -11
  140. package/dist/server/jobs/index.js +3 -3
  141. package/dist/server/observability/index.d.ts +1 -38
  142. package/dist/server/observability/index.js +2 -2
  143. package/dist/server/scan/index.js +2 -2
  144. package/dist/server-error-to-envelope-UUXDSLAZ.js +0 -0
  145. package/dist/{server-routes-hmr-VZXOP5YT.js → server-routes-hmr-4W5L2MKN.js} +1 -1
  146. package/dist/server-routes-hmr-4W5L2MKN.js.map +1 -0
  147. package/dist/{server-routes-hmr-PBHSKCQJ.js → server-routes-hmr-RI7SYNT2.js} +1 -1
  148. package/dist/server-routes-hmr-RI7SYNT2.js.map +1 -0
  149. package/dist/{services-json-Y3XODNB5.js → services-json-7ZXJ4CIS.js} +1 -1
  150. package/dist/services-json-7ZXJ4CIS.js.map +1 -0
  151. package/dist/{services-typed-client-IETY2SAK.js → services-typed-client-AU6DKXAO.js} +2 -2
  152. package/dist/services-typed-client-AU6DKXAO.js.map +1 -0
  153. package/dist/{services-typed-client-32KMTTXR.js → services-typed-client-EO4RFNTZ.js} +2 -2
  154. package/dist/services-typed-client-EO4RFNTZ.js.map +1 -0
  155. package/dist/{start-YLR2SFHU.js → start-2U3FUCJX.js} +12 -12
  156. package/dist/start-2U3FUCJX.js.map +1 -0
  157. package/dist/{static-MB2CD5Y3.js → static-25H5K42R.js} +3 -3
  158. package/dist/{static-MB2CD5Y3.js.map → static-25H5K42R.js.map} +1 -1
  159. package/dist/storage-manager-ZSQFLEYT.js +0 -0
  160. package/dist/{theo-cloud-DQRP6S6M.js → theo-cloud-JL2KXHIS.js} +2 -2
  161. package/dist/{upgrade-readiness-ACGW44JC.js → upgrade-readiness-77P6VNB4.js} +1 -1
  162. package/dist/upgrade-readiness-77P6VNB4.js.map +1 -0
  163. package/dist/{vercel-J6G7ZHYQ.js → vercel-FP3C6LN6.js} +3 -3
  164. package/dist/vite-plugin/index.js +9 -9
  165. package/dist/{vite-plugin-6VVU6PPC.js → vite-plugin-D2NTPZNC.js} +13 -13
  166. package/package.json +10 -13
  167. package/dist/actions-virtual-module-LD3YKWIX.js.map +0 -1
  168. package/dist/actions-virtual-module-N7GKUS3D.js.map +0 -1
  169. package/dist/add-W6FNTAFS.js.map +0 -1
  170. package/dist/agents-typed-client-CHMVW7MK.js.map +0 -1
  171. package/dist/agents-typed-client-NJ73Z6XY.js.map +0 -1
  172. package/dist/app-typed-client-6YZRDAPY.js.map +0 -1
  173. package/dist/app-typed-client-V77SVU2O.js.map +0 -1
  174. package/dist/body-parser-web-FV5HWCY3.js.map +0 -1
  175. package/dist/body-parser-web-MUWBKZ3F.js.map +0 -1
  176. package/dist/build-request-body-preview-EOP2Y4F3.js.map +0 -1
  177. package/dist/build-request-body-preview-QMWD2IXK.js.map +0 -1
  178. package/dist/check-PD2FTKMM.js.map +0 -1
  179. package/dist/chunk-2ZX4J4SX.js.map +0 -1
  180. package/dist/chunk-45C3WUQ7.js.map +0 -1
  181. package/dist/chunk-5AVPWHUE.js.map +0 -1
  182. package/dist/chunk-5PU65T5W.js.map +0 -1
  183. package/dist/chunk-AXVFVMLM.js.map +0 -1
  184. package/dist/chunk-D7ZH7DTG.js.map +0 -1
  185. package/dist/chunk-FEDSPOY6.js.map +0 -1
  186. package/dist/chunk-GSO77FSM.js.map +0 -1
  187. package/dist/chunk-IHJZPQEF.js.map +0 -1
  188. package/dist/chunk-IPC5UREF.js.map +0 -1
  189. package/dist/chunk-JAIKGP3Q.js.map +0 -1
  190. package/dist/chunk-KI7OWQUX.js.map +0 -1
  191. package/dist/chunk-M6NMS5LR.js.map +0 -1
  192. package/dist/chunk-P37RZRFV.js.map +0 -1
  193. package/dist/chunk-QWBXUZAX.js.map +0 -1
  194. package/dist/chunk-SPJNVWOK.js.map +0 -1
  195. package/dist/chunk-UNLG36Z5.js.map +0 -1
  196. package/dist/chunk-UO7WS32S.js.map +0 -1
  197. package/dist/chunk-X2VVCJ4V.js.map +0 -1
  198. package/dist/controller-swc-transform-URELVCBM.js.map +0 -1
  199. package/dist/controller-swc-transform-XV3ETSE3.js.map +0 -1
  200. package/dist/db-3UNAMSFK.js.map +0 -1
  201. package/dist/dev-emit-2DL3MCLM.js.map +0 -1
  202. package/dist/dispatcher-EJHL6JMJ.js.map +0 -1
  203. package/dist/generate-5X4LG77M.js.map +0 -1
  204. package/dist/info-2OOXFTJX.js.map +0 -1
  205. package/dist/mcp-ML4QK5ON.js.map +0 -1
  206. package/dist/node-BPJ3Z4DT.js +0 -10
  207. package/dist/openapi-2HVGJMSN.js.map +0 -1
  208. package/dist/registry-FKPH7XEL.js +0 -24
  209. package/dist/registry-FKPH7XEL.js.map +0 -1
  210. package/dist/router-TLEAOFID.js.map +0 -1
  211. package/dist/schema-LYOLNHZ7.js +0 -30
  212. package/dist/server-routes-hmr-PBHSKCQJ.js.map +0 -1
  213. package/dist/server-routes-hmr-VZXOP5YT.js.map +0 -1
  214. package/dist/services-json-Y3XODNB5.js.map +0 -1
  215. package/dist/services-typed-client-32KMTTXR.js.map +0 -1
  216. package/dist/services-typed-client-IETY2SAK.js.map +0 -1
  217. package/dist/start-YLR2SFHU.js.map +0 -1
  218. package/dist/upgrade-readiness-ACGW44JC.js.map +0 -1
  219. /package/dist/{agent-U35G3WNE.js.map → agent-OXRRKB55.js.map} +0 -0
  220. /package/dist/{aws-lambda-7GSCNLPY.js.map → aws-lambda-473QCOL6.js.map} +0 -0
  221. /package/dist/{bun-KP2KES6S.js.map → bun-OQUCL3XW.js.map} +0 -0
  222. /package/dist/{chunk-U3NTEK46.js.map → chunk-26ECIX74.js.map} +0 -0
  223. /package/dist/{chunk-AFVTEAES.js.map → chunk-CJNMJUHE.js.map} +0 -0
  224. /package/dist/{chunk-GW5H4KB4.js.map → chunk-FX72VHAE.js.map} +0 -0
  225. /package/dist/{chunk-L4GCEMNW.js.map → chunk-LNVMHQ2Z.js.map} +0 -0
  226. /package/dist/{chunk-GUUWDMR2.js.map → chunk-OVHW23YC.js.map} +0 -0
  227. /package/dist/{chunk-NQRNDPZJ.js.map → chunk-OXCALO3W.js.map} +0 -0
  228. /package/dist/{chunk-FOZIR3TG.js.map → chunk-SMP2T335.js.map} +0 -0
  229. /package/dist/{chunk-WFNLNIJX.js.map → chunk-VPISAMXU.js.map} +0 -0
  230. /package/dist/{cloudflare-C6E5SPAE.js.map → cloudflare-4YT5CK3P.js.map} +0 -0
  231. /package/dist/{deno-deploy-RFZN56X4.js.map → deno-deploy-YYN6BNLF.js.map} +0 -0
  232. /package/dist/{dev-PS2NGT6I.js.map → dev-WQ4LWCAW.js.map} +0 -0
  233. /package/dist/{dev-emit-XVTJXZGA.js.map → dev-emit-J7V6GWSK.js.map} +0 -0
  234. /package/dist/{dispatcher-63LBXYLE.js.map → dispatcher-DLKIXYNO.js.map} +0 -0
  235. /package/dist/{internal-api-FBFV265J.js.map → internal-api-DV3H5NNV.js.map} +0 -0
  236. /package/dist/{internal-api-LFW7R65K.js.map → internal-api-JFORKYLR.js.map} +0 -0
  237. /package/dist/{load-config-3EAQTXPH.js.map → load-config-XP7NSSA7.js.map} +0 -0
  238. /package/dist/{netlify-PMLHVPN4.js.map → netlify-2WZUQYI3.js.map} +0 -0
  239. /package/dist/{node-BPJ3Z4DT.js.map → node-CMAYKDCM.js.map} +0 -0
  240. /package/dist/{routes-XNS3UM3B.js.map → routes-ZVDKABXZ.js.map} +0 -0
  241. /package/dist/{schema-LYOLNHZ7.js.map → schema-FBOTN46F.js.map} +0 -0
  242. /package/dist/{theo-cloud-DQRP6S6M.js.map → theo-cloud-JL2KXHIS.js.map} +0 -0
  243. /package/dist/{vercel-J6G7ZHYQ.js.map → vercel-FP3C6LN6.js.map} +0 -0
  244. /package/dist/{vite-plugin-6VVU6PPC.js.map → vite-plugin-D2NTPZNC.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/transformer.ts","../src/server/agent/agent-card-handler.ts","../src/server/agent/approve-agent.ts","../src/server/agent/list-approvals-handler.ts","../src/server/agent/handle-agent-run-reconnect.ts","../src/server/agent/thread-dispatcher.ts","../src/server/agent/thread-run-registry.ts","../src/server/agent/handle-thread-routes.ts","../src/server/agent/serve-aux-routes.ts","../src/server/http/node-web-adapter.ts"],"sourcesContent":["import superjson from 'superjson'\n\n/**\n * T5.2 — pluggable response/request transformer.\n *\n * `superjson` is the default, preserving Date/Map/Set/BigInt/etc.\n * `json` is the lightweight option (plain JSON.stringify/parse).\n * Users can supply a custom object implementing this contract.\n */\nexport interface TheoTransformer {\n name: string\n serialize: (value: unknown) => string\n deserialize: (raw: string) => unknown\n}\n\nexport const superjsonTransformer: TheoTransformer = {\n name: 'superjson',\n serialize: (v) => JSON.stringify(superjson.serialize(v)),\n deserialize: (raw) => {\n const parsed = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(parsed)\n },\n}\n\nexport const jsonTransformer: TheoTransformer = {\n name: 'json',\n serialize: (v) => JSON.stringify(v),\n deserialize: (raw) => JSON.parse(raw) as unknown,\n}\n\nconst BUILT_INS: Record<string, TheoTransformer> = {\n superjson: superjsonTransformer,\n json: jsonTransformer,\n}\n\nexport function resolveTransformer(\n selector: 'json' | 'superjson' | TheoTransformer,\n): TheoTransformer {\n if (typeof selector === 'string') {\n // selector is 'json' | 'superjson' literal — both keys exist in\n // BUILT_INS by construction. Type system guarantees a hit; we keep\n // a defensive fallback that the compiler cannot see is unreachable\n // at runtime, just in case someone adds a new literal to the union\n // but forgets to register the built-in.\n const built = BUILT_INS[selector]\n // Defensive: the public union ensures `built` is defined, but if a\n // future contributor extends the union without registering the impl,\n // the cast keeps the failure mode loud.\n if ((built as TheoTransformer | undefined) === undefined) {\n throw new Error(\n `Unknown transformer \"${selector}\". Built-in options: ${Object.keys(BUILT_INS).join(', ')}.`,\n )\n }\n return built\n }\n if (\n typeof selector !== 'object' ||\n typeof selector.serialize !== 'function' ||\n typeof selector.deserialize !== 'function'\n ) {\n throw new Error(\n `Custom transformer must have serialize and deserialize functions. Got: ${JSON.stringify(selector)}`,\n )\n }\n return selector\n}\n","/**\n * M15 (theokit-ai-first) — serve the A2A agent card at `/.well-known/<name>/agent-card.json`.\n *\n * `buildAgentCard` (@theokit/agents) is the pure generator; this handler compiles a loaded agent\n * module to its tools + streaming capability, builds the card, and returns it as a Web-Standard\n * JSON `Response` (G8). The dev middleware + prod handler branch to this before the agent POST route.\n */\nimport {\n type AgentManifestEntry,\n buildAgentCard,\n compileAgentModule,\n} from '@theokit/agents'\n\nconst WELL_KNOWN = /^\\/\\.well-known\\/([^/]+)\\/agent-card\\.json$/\n\n/** Return the agent name when `urlPath` is a well-known card path, else `null`. */\nexport function isAgentCardPath(urlPath: string): string | null {\n const match = WELL_KNOWN.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Build a minimal manifest entry (the subset `buildAgentCard` reads) from a compiled agent. */\nfunction toManifestEntry(name: string, route: string, mod: unknown): AgentManifestEntry {\n const compiled = compileAgentModule(mod, `agent card for \"${name}\"`)\n return {\n name,\n route,\n stream: compiled.stream,\n mainLoop: { method: '', strategy: '' },\n guards: [],\n interceptors: [],\n tools: compiled.tools.map((t) => ({\n name: t.name,\n description: t.description,\n approval: false,\n trace: false,\n audit: false,\n })),\n subAgents: [],\n }\n}\n\n/**\n * Serve the A2A card for a loaded agent module. Returns 200 with the card JSON, or 500 with an\n * error body if the module is not a valid agent (fail-clear, not a silent empty card).\n */\nexport function handleAgentCard(mod: unknown, name: string, route: string, baseUrl: string): Response {\n try {\n const card = buildAgentCard(toManifestEntry(name, route, mod), { baseUrl })\n return new Response(JSON.stringify(card), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n } catch (err) {\n return new Response(\n JSON.stringify({ error: { code: 'AGENT_CARD_FAILED', message: err instanceof Error ? err.message : 'card build failed' } }),\n { status: 500, headers: { 'content-type': 'application/json; charset=utf-8' } },\n )\n }\n}\n","/**\n * M4 (theokit-ai-first) — the HITL approve endpoint: `POST /api/agents/<name>/approve/<approvalId>`.\n *\n * The counterpart to `mountAgent`'s HITL pause. While a gated tool holds the SDK run paused (the\n * awaited `pre_tool_call` hook), the client POSTs here with `{ approved }`; this resolves the\n * pending approval in the shared registry, which un-pauses the run (allow) or vetoes the tool (deny).\n *\n * Web-Standard `Request` → `Response`, one wiring point shared by dev (vite middleware) and prod\n * (built server) so the two never drift (EC-4 parity with `mountAgent`). The registry is INJECTED —\n * dev/prod pass the process singleton (`getApprovalRegistry`), tests pass a fresh instance.\n */\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport type { ApprovalDecision, ApprovalRegistry } from './approval-registry.js'\n\n/** The path segment separating the agent name from the approval id. */\nconst APPROVE_SEGMENT = '/approve/'\n\n/**\n * Extract the `<approvalId>` from a `/api/agents/<name>/approve/<approvalId>` path.\n * Returns `null` when the path has no `/approve/` segment or an empty / nested id.\n */\nexport function parseApprovalId(urlPath: string): string | null {\n const at = urlPath.indexOf(APPROVE_SEGMENT)\n if (at === -1) return null\n const id = urlPath.slice(at + APPROVE_SEGMENT.length)\n return id.length > 0 && !id.includes('/') ? id : null\n}\n\n/** True when `urlPath` targets a HITL approve endpoint (used by dev/prod routing to branch early). */\nexport function isApprovalPath(urlPath: string): boolean {\n return urlPath.includes(APPROVE_SEGMENT)\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * M20 — cap on the serialized custom payload (16 KiB). A payload is a small structured note\n * (edited args, a reviewer comment), not a data channel — an oversized one is rejected fail-fast\n * rather than silently truncated (Rule 8).\n */\nconst MAX_PAYLOAD_BYTES = 16 * 1024\n\n/**\n * Extract an {@link ApprovalDecision} from an untrusted body; `null` when the shape is wrong.\n *\n * M20 — accepts an optional `reason` (string) and `payload` (object, capped at\n * {@link MAX_PAYLOAD_BYTES}). Backward-compatible: `{ approved }` and `{ approved, reason }` parse\n * unchanged. A non-object or oversized `payload` is rejected (returns `null` → the route 400s).\n *\n * @public\n */\nexport function parseApprovalBody(body: unknown): ApprovalDecision | null {\n if (typeof body !== 'object' || body === null) return null\n const b = body as Record<string, unknown>\n if (typeof b.approved !== 'boolean') return null\n const decision: ApprovalDecision = { approved: b.approved }\n if (b.reason !== undefined) {\n if (typeof b.reason !== 'string') return null\n decision.reason = b.reason\n }\n if (b.payload !== undefined) {\n if (typeof b.payload !== 'object' || b.payload === null || Array.isArray(b.payload)) return null\n if (JSON.stringify(b.payload).length > MAX_PAYLOAD_BYTES) return null\n decision.payload = b.payload\n }\n return decision\n}\n\n/**\n * Resolve a pending HITL approval. CSRF-guarded like `mountAgent` (the custom `X-Theo-Action`\n * header + Origin match) — a cross-origin POST must not approve a paused tool. Returns:\n * 403 CSRF_FAILED — strict CSRF check failed\n * 400 BAD_REQUEST — no `/approve/<id>` in the path, or body lacks a boolean `approved`\n * 404 NOT_PENDING — the id is unknown or already settled (idempotent double-submit)\n * 200 { resolved:true } — the approval was settled by this call\n */\nexport async function handleAgentApproval(\n request: Request,\n urlPath: string,\n registry: ApprovalRegistry,\n csrfMode: CsrfMode = 'strict',\n): Promise<Response> {\n if (csrfMode !== 'off') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid && csrfMode === 'strict') {\n return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n }\n\n const approvalId = parseApprovalId(urlPath)\n if (approvalId === null) {\n return jsonError(400, 'BAD_REQUEST', 'Approval path must be /api/agents/<name>/approve/<id>.')\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → handled below as a 400 */\n }\n const parsed = parseApprovalBody(body)\n if (parsed === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request body must contain a boolean `approved`.')\n }\n\n const resolved = registry.resolve(approvalId, parsed)\n if (!resolved) {\n return jsonError(404, 'NOT_PENDING', `No pending approval for id '${approvalId}'.`)\n }\n return new Response(JSON.stringify({ resolved: true }), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n })\n}\n","/**\n * M14 (theokit-ai-first) — GET /api/agents/<name>/approvals: list pending HITL approvals.\n *\n * Serves `ApprovalRegistry.list()` as JSON. Single-process contract (ADR 0038) — the list is\n * process-wide; the `<name>` segment is accepted for a future per-agent/durable store but the\n * in-process registry lists all pending approvals. Web Standards Response (G8).\n */\nimport type { ApprovalRegistry } from './approval-registry.js'\n\nconst LIST_PATH = /^\\/api\\/agents\\/([^/]+)\\/approvals$/\n\n/** Return the agent name when `urlPath` is the approvals-listing path, else `null`. */\nexport function isListApprovalsPath(urlPath: string): string | null {\n const match = LIST_PATH.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Serve the currently-pending approvals as `{ approvals: [...] }` JSON. */\nexport function handleListApprovals(registry: ApprovalRegistry): Response {\n return new Response(JSON.stringify({ approvals: registry.list() }), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n","import {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport type { RunEventCache } from './run-event-cache.js'\n\n/**\n * M37 (ADR-0046 D5) — the reconnect / observe endpoint handler for\n * `GET /api/agents/<name>/runs/<runId>/stream`.\n *\n * Replays the frames the client missed (`seq > Last-Event-ID`, SSE-native), then\n * — if the run is still live — follows the live tail; a SECOND client can\n * observe a run a first started. Run already ended ⇒ replay + `[DONE]`. Unknown\n * `runId` ⇒ 404. The request `AbortSignal` unsubscribes on disconnect.\n */\n\nconst RUN_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/runs\\/([^/]+)\\/stream$/\n\n/**\n * Match `GET /api/agents/<name>/runs/<runId>/stream`; returns the decoded\n * `{ name, runId }` or `null` to fall through (mirrors `isMcpPath` etc.).\n */\nexport function isAgentRunStreamPath(urlPath: string): { name: string; runId: string } | null {\n const m = RUN_STREAM_PATH.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), runId: decodeURIComponent(m[2]) } : null\n}\n\n/** Parse `Last-Event-ID` (a frame `seq`) to a number; absent/invalid ⇒ -1 (replay from the start). */\nfunction parseLastEventId(raw: string | null): number {\n if (raw === null) return -1\n const n = Number.parseInt(raw, 10)\n return Number.isInteger(n) && n >= 0 ? n : -1\n}\n\nexport function handleAgentRunReconnect(\n runId: string,\n request: Request,\n cache: RunEventCache,\n): Response {\n // Unknown run ⇒ 404 (a run never started here, or already evicted).\n if (!cache.has(runId)) {\n return new Response(\n JSON.stringify({ error: { code: 'RUN_NOT_FOUND', message: `Unknown run '${runId}'.` } }),\n {\n status: 404,\n headers: { 'content-type': 'application/json' },\n },\n )\n }\n\n const afterSeq = parseLastEventId(request.headers.get('last-event-id'))\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const safeEnqueue = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* controller already closed by an abort race — ignore */\n }\n }\n const close = (): void => {\n if (closed) return\n safeEnqueue(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n\n // Atomic: snapshot replay frames AND subscribe to the live tail in one tick.\n const res = cache.attach(\n runId,\n afterSeq,\n (frame) => {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n // Evicted between has() and attach() (rare TOCTOU) ⇒ just end the stream.\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n }\n if (res.ended) {\n close()\n return\n }\n // Client disconnects ⇒ detach the live listener + close.\n request.signal.addEventListener('abort', () => {\n res.unsubscribe()\n close()\n })\n },\n })\n\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS, [RUN_ID_HEADER]: runId } })\n}\n","/**\n * M39 (ADR-0048) — the thread follow-up dispatcher.\n *\n * Drives a run over the M37 durable cache HEADLESS — it iterates the SDK chunk\n * generator and `cache.append`s directly, NOT via a `Response` `ReadableStream`\n * (whose backpressure would stall a run with no HTTP reader). Subscribers read\n * from the cache via the thread / reconnect stream.\n *\n * - Post to an IDLE thread ⇒ start a run + pump.\n * - Post to an ACTIVE thread ⇒ FIFO-queue the follow-up.\n * - On terminal ⇒ `registry.endRun` hands back the next queued follow-up, which\n * is dispatched as a continuation on the SAME sessionId (⇒ the SDK continues\n * the conversation via its `ConversationStorageAdapter`).\n *\n * This adds NO agent loop — it reuses the SDK run (`startRun`) + the M37 cache.\n * Single-process (ADR-0048 D2).\n */\n\nimport type { UIMessageChunk } from 'ai'\n\nimport { type RunEventCache, mintRunId } from './run-event-cache.js'\nimport type { ThreadRunRegistry } from './thread-run-registry.js'\n\nexport interface ThreadDispatchDeps {\n readonly registry: ThreadRunRegistry\n readonly cache: RunEventCache\n /** Start a run for a follow-up on `sessionId`; returns the SDK chunk stream. */\n readonly startRun: (sessionId: string, message: string) => AsyncIterable<UIMessageChunk>\n}\n\n/** Result of posting a follow-up: the started `runId` (idle thread) or `queued` (active thread). */\nexport type PostFollowUpResult = { runId: string } | { queued: true }\n\n/**\n * Post a follow-up on a thread. IDLE ⇒ start a run (returns its `runId`); ACTIVE\n * ⇒ FIFO-queue it (returns `{ queued: true }`) — dispatched when the active run ends.\n */\nexport function postThreadFollowUp(\n deps: ThreadDispatchDeps,\n sessionId: string,\n message: string,\n): PostFollowUpResult {\n if (deps.registry.getActive(sessionId) !== null) {\n deps.registry.queue(sessionId, { message })\n return { queued: true }\n }\n return { runId: startAndPump(deps, sessionId, message) }\n}\n\n/** Mint a runId, mark the thread active, and pump the run into the cache headless. */\nfunction startAndPump(deps: ThreadDispatchDeps, sessionId: string, message: string): string {\n const runId = mintRunId()\n // Register the run in the cache SYNCHRONOUSLY (before the async pump appends its\n // first frame) so a subscriber resolving the active runId can attach immediately.\n deps.cache.begin(runId)\n deps.registry.startRun(sessionId, runId)\n pumpIntoCache(deps, sessionId, runId, deps.startRun(sessionId, message))\n return runId\n}\n\n/**\n * Drive `chunks` into the cache under `runId`, then end the run and dispatch the\n * next queued follow-up (if any) as a continuation. Fire-and-forget — the caller\n * does not await the run; subscribers observe it via the cache.\n */\nfunction pumpIntoCache(\n deps: ThreadDispatchDeps,\n sessionId: string,\n runId: string,\n chunks: AsyncIterable<UIMessageChunk>,\n): void {\n void (async () => {\n try {\n for await (const chunk of chunks) {\n deps.cache.append(runId, JSON.stringify(chunk))\n }\n } catch {\n // The SDK translator owns error semantics (surfaces failures as chunks);\n // the transport guarantees only a terminated, cache-ended run.\n } finally {\n deps.cache.end(runId)\n const next = deps.registry.endRun(sessionId, runId)\n if (next !== undefined) startAndPump(deps, sessionId, next.message)\n }\n })()\n}\n","/**\n * M39 (ADR-0048) — the in-process thread→run registry.\n *\n * A thread is the existing `sessionId` (the SDK conversation key). This registry\n * tracks, per thread, the single ACTIVE run, a FIFO queue of follow-ups to\n * dispatch as continuations, and one-shot \"next run\" waiters (so a client can\n * subscribe to a thread before posting a message and attach when the run starts).\n *\n * Pure state only — it never starts a run or touches the transport. The route\n * layer owns dispatch: on `endRun` it receives the next queued follow-up (if any)\n * and starts the continuation over the M37 durable transport.\n *\n * Single-process contract (ADR-0048 D2): a multi-instance deploy needs a shared\n * registry + leasing — that is infra (TheoCloud), explicitly out of M39. The\n * interface is injectable so a durable impl slots in later without touching the\n * routes. We do NOT build a distributed store now (YAGNI).\n */\n\n/** A follow-up message queued on an active thread, dispatched as a continuation. */\nexport interface FollowUp {\n readonly message: string\n}\n\nexport interface ThreadRunRegistry {\n /** The active runId for a thread, or `null` when the thread is idle. */\n getActive(sessionId: string): string | null\n /** Mark a run started for a thread (sets it active; fires + clears one-shot waiters). */\n startRun(sessionId: string, runId: string): void\n /**\n * Mark `runId` ended for a thread. A no-op unless `runId` is the current active\n * run (a stale terminal never clears a newer run). Clears the active run and\n * returns the next FIFO follow-up to dispatch as a continuation, or `undefined`.\n */\n endRun(sessionId: string, runId: string): FollowUp | undefined\n /** FIFO-enqueue a follow-up on a thread (dispatched when the active run ends). */\n queue(sessionId: string, followUp: FollowUp): void\n /**\n * Register a ONE-SHOT waiter fired with the runId of the NEXT run started on\n * this thread. Returns an unsubscribe fn. Used by subscribe-by-thread on an\n * idle thread (attach when the next run starts).\n */\n onNextRun(sessionId: string, cb: (runId: string) => void): () => void\n}\n\ninterface ThreadState {\n activeRunId: string | null\n readonly queue: FollowUp[]\n readonly waiters: Set<(runId: string) => void>\n}\n\nexport function createInProcessThreadRunRegistry(): ThreadRunRegistry {\n const threads = new Map<string, ThreadState>()\n const ensure = (sessionId: string): ThreadState => {\n let s = threads.get(sessionId)\n if (s === undefined) {\n s = { activeRunId: null, queue: [], waiters: new Set() }\n threads.set(sessionId, s)\n }\n return s\n }\n\n return {\n getActive(sessionId) {\n return threads.get(sessionId)?.activeRunId ?? null\n },\n startRun(sessionId, runId) {\n const s = ensure(sessionId)\n s.activeRunId = runId\n // Fire one-shot waiters, then clear them (single-threaded → no re-entrancy race).\n const waiters = [...s.waiters]\n s.waiters.clear()\n for (const cb of waiters) cb(runId)\n },\n endRun(sessionId, runId) {\n const s = threads.get(sessionId)\n if (s?.activeRunId !== runId) return undefined\n s.activeRunId = null\n return s.queue.shift()\n },\n queue(sessionId, followUp) {\n ensure(sessionId).queue.push(followUp)\n },\n onNextRun(sessionId, cb) {\n const s = ensure(sessionId)\n s.waiters.add(cb)\n return () => {\n s.waiters.delete(cb)\n }\n },\n }\n}\n\nlet serverRegistry: ThreadRunRegistry | undefined\n\n/** Process-wide singleton (mirrors `getRunEventCache` / `getApprovalRegistry`). */\nexport function getThreadRunRegistry(): ThreadRunRegistry {\n serverRegistry ??= createInProcessThreadRunRegistry()\n return serverRegistry\n}\n","/**\n * M39 (ADR-0048) — the thread signal routes over the M37 durable transport:\n *\n * - `POST /api/agents/<name>/threads/<sessionId>/message` — a follow-up. ACTIVE\n * run ⇒ FIFO-queue (dispatched as a continuation when it ends); IDLE ⇒ start a\n * run. Returns `202` (the run streams headless into the cache; observe it via\n * the thread stream). Spends LLM tokens ⇒ CSRF-gated (parity with mount-agent).\n * - `GET /api/agents/<name>/threads/<sessionId>/stream` — subscribe. ACTIVE ⇒\n * attach to the durable stream (reuse the M37 reconnect handler); IDLE ⇒ wait\n * (bounded) for the next run on the thread, then attach (subscribe-then-post).\n *\n * These DRIVE the SDK run (via `makeThreadStartRun`) + the M37 cache — no new loop.\n */\n\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { makeThreadStartRun } from './build-agent-streamer.js'\nimport {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport { handleAgentRunReconnect } from './handle-agent-run-reconnect.js'\nimport { parseAgentRequestBody } from './mount-agent.js'\nimport { getRunEventCache, type RunEventCache } from './run-event-cache.js'\nimport { postThreadFollowUp } from './thread-dispatcher.js'\nimport { getThreadRunRegistry, type ThreadRunRegistry } from './thread-run-registry.js'\n\nconst THREAD_MESSAGE_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/message$/\nconst THREAD_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/stream$/\n\n/** How long a subscribe-to-idle-thread waits for the next run before closing. */\nconst DEFAULT_IDLE_WAIT_MS = 30_000\n\nfunction matchThread(re: RegExp, urlPath: string): { name: string; sessionId: string } | null {\n const m = re.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), sessionId: decodeURIComponent(m[2]) } : null\n}\n\nexport const isThreadMessagePath = (urlPath: string) => matchThread(THREAD_MESSAGE_PATH, urlPath)\nexport const isThreadStreamPath = (urlPath: string) => matchThread(THREAD_STREAM_PATH, urlPath)\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Inputs for {@link handleThreadMessage} (bundled to stay within the arity budget). */\nexport interface ThreadMessageArgs {\n readonly mod: unknown\n readonly apiKey: string\n readonly sessionId: string\n readonly request: Request\n readonly source: string\n readonly csrfMode?: CsrfMode\n}\n\n/** POST a follow-up on a thread. Returns `202` with `{ runId }` (started) or `{ queued: true }`. */\nexport async function handleThreadMessage(args: ThreadMessageArgs): Promise<Response> {\n const { mod, apiKey, sessionId, request, source, csrfMode = 'strict' } = args\n // A follow-up drives the agent (spends LLM tokens) — reject a cross-origin POST.\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → 400 below */\n }\n const input = parseAgentRequestBody(body)\n if (input === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request must contain a non-empty message.')\n }\n const result = postThreadFollowUp(\n {\n registry: getThreadRunRegistry(),\n cache: getRunEventCache(),\n startRun: makeThreadStartRun(mod, apiKey, source),\n },\n sessionId,\n input.message,\n )\n const headers: Record<string, string> = { 'content-type': 'application/json; charset=utf-8' }\n if ('runId' in result) headers[RUN_ID_HEADER] = result.runId\n return new Response(JSON.stringify(result), { status: 202, headers })\n}\n\n/** GET the thread's durable stream. Active ⇒ attach now; idle ⇒ wait (bounded) for the next run. */\nexport function handleThreadStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry = getThreadRunRegistry(),\n cache: RunEventCache = getRunEventCache(),\n idleWaitMs = DEFAULT_IDLE_WAIT_MS,\n): Response {\n const active = registry.getActive(sessionId)\n if (active !== null && cache.has(active)) {\n // Reuse the M37 reconnect handler — replay + live tail on the active run.\n return handleAgentRunReconnect(active, request, cache)\n }\n return waitThenAttachStream(sessionId, request, registry, cache, idleWaitMs)\n}\n\n/** Subscribe to an idle thread: wait (bounded) for the NEXT run to start, then attach + tail. */\nfunction waitThenAttachStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry,\n cache: RunEventCache,\n idleWaitMs: number,\n): Response {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const send = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* closed by an abort race */\n }\n }\n let detachAttach: (() => void) | undefined\n const close = (): void => {\n if (closed) return\n send(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n const offNext = registry.onNextRun(sessionId, (runId) => {\n const res = cache.attach(\n runId,\n -1,\n (frame) => {\n send(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) send(formatSseFrame(frame.seq, frame.data))\n if (res.ended) {\n close()\n return\n }\n detachAttach = res.unsubscribe\n })\n // HIGH-1 — the waiter teardown MUST run on BOTH the idle-wait timeout AND the\n // client abort, else the (one-shot) `onNextRun` waiter leaks in the registry\n // when a timed-out subscriber's session never receives another run.\n const teardownWaiter = (): void => {\n offNext()\n detachAttach?.()\n }\n const timer = setTimeout(() => {\n teardownWaiter()\n close()\n }, idleWaitMs)\n timer.unref()\n request.signal.addEventListener('abort', () => {\n teardownWaiter()\n clearTimeout(timer)\n close()\n })\n },\n })\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS } })\n}\n","/**\n * M15/M16 follow-up — shared dispatcher for the agent AUXILIARY routes that BOTH dev (vite\n * middleware) and prod (`theokit start` handler) must serve identically. Before this, these routes\n * were wired only into the dev middleware, so a built/deployed app served none of them (agent cards,\n * MCP, pending-approvals listing all 404'd in production).\n *\n * Single source of truth (DRY): one Web-Request→Response dispatcher, two callers. It handles the\n * routes that derive purely from the agent module + shared registry:\n * - **M15** `GET /.well-known/<name>/agent-card.json` → {@link handleAgentCard}\n * - **M14** `GET /api/agents/<name>/approvals` → {@link handleListApprovals}\n * - **M16** `POST /api/agents/<name>/mcp` → {@link handleMcpJsonRpc}\n *\n * Channels (M27) are NOT here: a channel webhook needs app-supplied `validators` + `onMessage`, so\n * the app wires `handleChannelWebhook` in its own route (it cannot be auto-derived from the module).\n * The HITL approve route stays in each caller (it carries caller-specific rate-limiting/CSRF plumbing).\n */\nimport type { AgentNode } from '../scan/agent-scan.js'\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { isAgentCardPath, handleAgentCard } from './agent-card-handler.js'\nimport { getApprovalRegistry } from './approval-registry.js'\nimport { handleAgentRunReconnect, isAgentRunStreamPath } from './handle-agent-run-reconnect.js'\nimport {\n handleThreadMessage,\n handleThreadStream,\n isThreadMessagePath,\n isThreadStreamPath,\n} from './handle-thread-routes.js'\nimport { isListApprovalsPath, handleListApprovals } from './list-approvals-handler.js'\nimport { extractAppResources } from './mcp-app-resources.js'\nimport { isMcpPath, handleMcpJsonRpc } from './mcp-handler.js'\nimport { getRunEventCache } from './run-event-cache.js'\n\n/** JSON error envelope (mirrors mount-agent.ts:37 — the parity source for the MCP CSRF gate). */\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Dependencies the aux dispatcher needs from its caller (dev or prod). */\nexport interface AuxRouteDeps {\n /** Discovered agents (from `scanAgents`). */\n agents: readonly AgentNode[]\n /** Load an agent module from its file path (dev: vite loader; prod: dynamic import). */\n loadModule: (filePath: string) => Promise<unknown>\n /** Absolute base URL (`http(s)://host`) for the agent-card endpoint URLs. */\n baseUrl: string\n /**\n * M34 (#97) — CSRF enforcement mode for the MCP route. `POST /api/agents/<name>/mcp` drives the\n * agent (spends LLM tokens), so a cross-origin POST MUST be rejected in `'strict'` — parity with\n * the agent-run route (`mount-agent.ts:83-91`). Defaults to `'strict'` (safe-by-default); a caller\n * that already gated upstream may pass `'off'`.\n */\n csrfMode?: CsrfMode\n /**\n * M39 — lazily resolve the provider apiKey. Required only for the thread\n * follow-up route (which drives the agent); resolved on demand so non-agent\n * aux routes (card, approvals, stream) never need a provider key.\n */\n resolveApiKey?: () => string\n}\n\n/**\n * Serve an agent auxiliary route. Returns a `Response` when `urlPath` matches an aux route (card /\n * list-approvals / mcp) and the method + agent resolve; returns `null` to fall through (not an aux\n * route, wrong method, or unknown agent — the caller then owns the 404/next).\n */\nexport async function serveAgentAuxRoute(\n request: Request,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n const method = request.method.toUpperCase()\n\n // M15 — A2A agent card at `/.well-known/<name>/agent-card.json` (GET).\n const cardName = isAgentCardPath(urlPath)\n if (cardName !== null) {\n if (method !== 'GET') return null\n const agent = deps.agents.find((a) => a.name === cardName)\n if (!agent) return null\n const mod = await deps.loadModule(agent.filePath)\n return handleAgentCard(mod, agent.name, agent.agentPath, deps.baseUrl)\n }\n\n // M14 — GET /api/agents/<name>/approvals (pending HITL approvals).\n if (isListApprovalsPath(urlPath)) {\n if (method !== 'GET') return null\n return handleListApprovals(getApprovalRegistry())\n }\n\n // M37 — GET /api/agents/<name>/runs/<runId>/stream (durable reconnect / observe).\n // INTENTIONALLY open (no CSRF, no auth gate): a GET is not CSRF-vulnerable, the\n // run-start POST is already gated, and the `runId` is a 122-bit UUID (unguessable).\n // Observe-by-runId is a FEATURE (ADR-0046 D5) — a second client resumes a run a\n // first started. Do NOT add a custom-header CSRF check here: browsers send NO\n // custom headers with `EventSource`, so it would break native SSE reconnect.\n const runStream = isAgentRunStreamPath(urlPath)\n if (runStream !== null) {\n if (method !== 'GET') return null\n if (!deps.agents.some((a) => a.name === runStream.name)) return null\n return handleAgentRunReconnect(runStream.runId, request, getRunEventCache())\n }\n\n // M39 — thread signal routes (follow-up message + subscribe-by-thread). Extracted\n // to keep this dispatcher within the cognitive-complexity budget (G6).\n const threadResponse = await serveThreadRoute(request, method, urlPath, deps)\n if (threadResponse !== null) return threadResponse\n\n // M16 — POST /api/agents/<name>/mcp (JSON-RPC MCP server). Extracted to keep this dispatcher\n // within the cognitive-complexity budget (G6).\n const mcpName = isMcpPath(urlPath)\n if (mcpName !== null) {\n return serveMcpRoute(request, method, mcpName, deps)\n }\n\n return null\n}\n\n/**\n * M39 — serve the thread routes:\n * - `POST .../threads/<sessionId>/message` (follow-up) — loads the module, drives\n * the run headless via the thread dispatcher. Needs `resolveApiKey` (drives the\n * agent) → 501 when absent (rather than a silent 404).\n * - `GET .../threads/<sessionId>/stream` (subscribe) — attach to the active/next\n * run's durable stream. INTENTIONALLY open (GET, no custom headers — like the\n * M37 reconnect route).\n *\n * SECURITY (thread stream): unlike the M37 reconnect route — keyed on an\n * `mintRunId()` UUID (122-bit unguessable) — the thread stream is keyed on the\n * caller-supplied `sessionId`. The open GET is safe ONLY if the `sessionId` is\n * unguessable (e.g. a client-minted UUID). An app that uses a PREDICTABLE\n * sessionId (user id, email, sequential id) MUST add its own auth gate before\n * this endpoint, or any party who can guess the sessionId can read the thread's\n * live conversation stream. Documented in `docs/architecture/multi-surface-architecture.md`.\n *\n * Returns `null` to fall through (not a thread route, wrong method, unknown agent).\n */\nasync function serveThreadRoute(\n request: Request,\n method: string,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n const stream = isThreadStreamPath(urlPath)\n if (stream !== null) {\n if (method !== 'GET') return null\n if (!deps.agents.some((a) => a.name === stream.name)) return null\n return handleThreadStream(stream.sessionId, request)\n }\n\n const msg = isThreadMessagePath(urlPath)\n if (msg !== null) {\n if (method !== 'POST') return null\n const agent = deps.agents.find((a) => a.name === msg.name)\n if (!agent) return null\n if (deps.resolveApiKey === undefined) {\n // MEDIUM-1 — the path matched but the caller wired no provider-key resolver.\n // Fail loudly (501) instead of a silent 404 that reads as \"route not found\".\n return jsonError(\n 501,\n 'NOT_CONFIGURED',\n 'Thread follow-up requires a provider API key (resolveApiKey was not provided to serveAgentAuxRoute).',\n )\n }\n const mod = await deps.loadModule(agent.filePath)\n return handleThreadMessage({\n mod,\n apiKey: deps.resolveApiKey(),\n sessionId: msg.sessionId,\n request,\n source: `agent \"${msg.name}\"`,\n csrfMode: deps.csrfMode ?? 'strict',\n })\n }\n return null\n}\n\n/**\n * Serve the MCP route with the M34 gates: default-DENY opt-in → CSRF → dispatch. Returns `null` to\n * fall through (wrong method / unknown or non-opted-in agent), a 403 on CSRF failure, else the\n * JSON-RPC response.\n */\nasync function serveMcpRoute(\n request: Request,\n method: string,\n mcpName: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n if (method !== 'POST') return null\n const agent = deps.agents.find((a) => a.name === mcpName)\n if (!agent) return null\n\n const mod = await deps.loadModule(agent.filePath)\n\n // M34 — DEFAULT-DENY: an agent is NOT exposed on MCP unless it explicitly opts in with a named\n // `export const mcp = true` (blueprint D5 — default-EXPOSE is the footgun magnified by the\n // multi-surface thesis). Absent the opt-in, fall through to 404 (the agent is web-only). This is a\n // breaking change from the M16 auto-mount (documented in the CHANGELOG § Security).\n if (!isMcpExposed(mod)) return null\n\n // M34 (#97) — enforce CSRF BEFORE any work. The MCP route drives the agent (real LLM tokens), so a\n // cross-origin POST must be rejected — parity with the agent-run route (`mount-agent.ts:83-91`).\n const csrfMode = deps.csrfMode ?? 'strict'\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* malformed/empty JSON → handleMcpJsonRpc returns a -32600 envelope */\n }\n // M30 — pass the agent's declared `ui://` App resources (named `appResources` export) so the MCP\n // server advertises + serves them via resources/list + resources/read.\n return handleMcpJsonRpc(mod, agent.name, body, extractAppResources(mod))\n}\n\n/**\n * M34 — DEFAULT-DENY opt-in check: is this agent module exposed on the MCP surface? An agent opts in\n * with a named `export const mcp = true` (mirroring the `appResources` named-export convention).\n * Anything else (absent / falsy) → NOT exposed. Read at the emit layer (blueprint D5).\n */\nfunction isMcpExposed(mod: unknown): boolean {\n return (mod as { mcp?: unknown } | null | undefined)?.mcp === true\n}\n","/**\n * T5a.2 Phase G slice 5/N — Node adapter shim for the Web request handler.\n *\n * Bridges Node's `IncomingMessage` + `ServerResponse` shape to the\n * Web-Standards `executeWebRequest` (Phase A → G slices 1-4). Per\n * ADR-0028 R3a, the Node adapter is the ONLY place IncomingMessage ↔\n * Request conversion happens — every other layer of `server/` flows\n * through Web `Request`/`Response`.\n *\n * **Two conversions:**\n *\n * 1. `incomingMessageToWebRequest(req)` — Node → Web. Reads\n * `req.method`, `req.url`, `req.headers`, and (for POST/PUT/etc.)\n * drains the Node Readable body into a Web `ReadableStream`. The\n * request URL is resolved to absolute form using `req.headers.host`\n * (Web Request guarantees absolute URL).\n *\n * 2. `writeWebResponseToServerResponse(response, res)` — Web → Node.\n * Sets status code + status text, copies headers (including all\n * `Set-Cookie` values via `getSetCookie()`), then drains the Web\n * `ReadableStream` body into the Node ServerResponse.\n *\n * Plus the convenience composer `executeWebRequestFromNode(req, res,\n * routeModule, opts?)` that wires both ends — exactly what api-middleware\n * (and the prod CLI start path) need to migrate from the legacy\n * `executeRoute` to `executeWebRequest` without touching call sites.\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase G slice 5/N (closes the executor bridge surface).\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { executeWebRequest, type ExecuteWebRequestOptions } from '../web-handler.js'\n\nimport { incomingMessageToWebRequest } from './node-request.js'\n\n// The primitive `IncomingMessage` → Web `Request` converters live in\n// `node-request.js` (dependency-free, shared with the executor). Re-exported\n// here so existing importers of the adapter keep resolving them.\nexport { incomingMessageToWebRequest, incomingMessageToHandlerRequest } from './node-request.js'\n\n/**\n * Write a Web `Response` into a Node `ServerResponse`. Mirrors the Node\n * `res.writeHead` + `res.end` pattern.\n *\n * Set-Cookie is the only multi-value header the Web spec exposes via\n * `getSetCookie()`. We append each entry individually so Node emits\n * separate `Set-Cookie:` lines per the HTTP spec.\n *\n * If the Response body is a `ReadableStream`, it's piped chunk-by-chunk\n * to `res`. Empty body (null) → just close.\n */\nexport async function writeWebResponseToServerResponse(\n response: Response,\n res: ServerResponse,\n): Promise<void> {\n // Status + headers FIRST (writeHead locks them).\n // EC-3: Set-Cookie needs special handling (writeHead's plain object\n // shape conflicts with multi-value headers; we set them via setHeader\n // BEFORE writeHead so the array form is preserved).\n const setCookies = response.headers.getSetCookie()\n if (setCookies.length > 0) {\n res.setHeader('Set-Cookie', setCookies)\n }\n const otherHeaders: Record<string, string> = {}\n for (const [key, value] of response.headers.entries()) {\n if (key.toLowerCase() === 'set-cookie') continue\n otherHeaders[key] = value\n }\n res.writeHead(response.status, response.statusText, otherHeaders)\n\n // Body — drain ReadableStream OR just end() for null body.\n if (response.body === null) {\n res.end()\n return\n }\n const reader = response.body.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n // Node's res.write accepts Uint8Array natively (no conversion needed).\n res.write(value)\n }\n res.end()\n } finally {\n reader.releaseLock()\n }\n}\n\n/**\n * Convenience composer — full request lifecycle Node → Web → Node.\n *\n * Use case: existing api-middleware (and the prod CLI start path)\n * receive Node `(req, res)` from `http.createServer`. To migrate to the\n * Web-Standards executor without rewriting every call site, wrap with\n * this composer:\n *\n * import * as users from './app/users/route.js'\n * await executeWebRequestFromNode(req, res, users, { csrfMode: 'strict' })\n *\n * The Web request is built, dispatched through executeWebRequest, and\n * the Response is drained back into `res`. Caller does NOT need to call\n * `res.end()` afterwards — this composer handles it.\n */\nexport async function executeWebRequestFromNode(\n req: IncomingMessage,\n res: ServerResponse,\n routeModule: Parameters<typeof executeWebRequest>[1],\n opts?: ExecuteWebRequestOptions,\n): Promise<void> {\n const webRequest = incomingMessageToWebRequest(req)\n const webResponse = await executeWebRequest(webRequest, routeModule, opts)\n await write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C,aAAW,CAAC,KAAK,KAAK,KAAK,SAAS,QAAQ,QAAQ,GAAG;AACrD,QAAI,IAAI,YAAY,MAAM,aAAc;AACxC,iBAAa,GAAG,IAAI;AAAA,EACtB;AACA,MAAI,UAAU,SAAS,QAAQ,SAAS,YAAY,YAAY;AAGhE,MAAI,SAAS,SAAS,MAAM;AAC1B,QAAI,IAAI;AACR;AAAA,EACF;AACA,QAAM,SAAS,SAAS,KAAK,UAAU;AACvC,MAAI;AACF,eAAS;AACP,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAC1C,UAAI,KAAM;AAEV,UAAI,MAAM,KAAK;AAAA,IACjB;AACA,QAAI,IAAI;AAAA,EACV,UAAE;AACA,WAAO,YAAY;AAAA,EACrB;AACF;","names":["jsonError","jsonError"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/_internal/scan-walker.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: walks directories derived from cwd.\n * No HTTP input ever reaches these fs calls.\n */\nimport { readdirSync } from 'node:fs'\nimport { extname, join, resolve } from 'node:path'\n\n/**\n * Options for walkSourceFiles.\n *\n * Sequential by design — callers (route precedence) depend on insertion\n * order (EC-19 documented decision). Async-callback support is implicit\n * via JavaScript's serial await loop.\n *\n * Tested on macOS + Linux. Windows long-path support not validated (EC-20).\n */\nexport interface WalkOptions {\n /** File extensions to include (e.g., new Set(['.ts', '.tsx'])). */\n extensions: ReadonlySet<string>\n /** Skip directories whose name starts with any of these (default: ['_', '.']). */\n skipPrefixes?: readonly string[]\n}\n\n/**\n * Recursively walk `root`, invoking `onFile(absPath)` for every file matching\n * `opts.extensions`. Directories whose name starts with any `skipPrefixes`\n * char are skipped (defaults to `_` and `.`).\n *\n * Replaces 3 near-identical recursive walkers in scan.ts, action-scan.ts,\n * ws-scan.ts (PV-3 — DRY consolidation). Resolves T3.1 of\n * architecture-review-remediation-plan.\n *\n * Symlink loops are NOT tracked — callers must avoid them or pre-resolve\n * via `fs.realpath`. EC-11 documented but not implemented (rare in dev).\n */\nexport function walkSourceFiles(\n root: string,\n opts: WalkOptions,\n onFile: (absPath: string) => void,\n): void {\n const skipPrefixes = opts.skipPrefixes ?? ['_', '.']\n const visit = (dir: string): void => {\n let entries\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n // Silently skip unreadable directories — caller controls discoverability\n return\n }\n for (const entry of entries) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory() && !skipPrefixes.some((p) => entry.name.startsWith(p))) {\n visit(fullPath)\n } else if (entry.isFile() && opts.extensions.has(extname(entry.name))) {\n onFile(resolve(fullPath))\n }\n }\n }\n visit(root)\n}\n"],"mappings":";AAIA,SAAS,mBAAmB;AAC5B,SAAS,SAAS,MAAM,eAAe;AA8BhC,SAAS,gBACd,MACA,MACA,QACM;AACN,QAAM,eAAe,KAAK,gBAAgB,CAAC,KAAK,GAAG;AACnD,QAAM,QAAQ,CAAC,QAAsB;AACnC,QAAI;AACJ,QAAI;AACF,gBAAU,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC;AAAA,IACpD,QAAQ;AAEN;AAAA,IACF;AACA,eAAW,SAAS,SAAS;AAC3B,YAAM,WAAW,KAAK,KAAK,MAAM,IAAI;AACrC,UAAI,MAAM,YAAY,KAAK,CAAC,aAAa,KAAK,CAAC,MAAM,MAAM,KAAK,WAAW,CAAC,CAAC,GAAG;AAC9E,cAAM,QAAQ;AAAA,MAChB,WAAW,MAAM,OAAO,KAAK,KAAK,WAAW,IAAI,QAAQ,MAAM,IAAI,CAAC,GAAG;AACrE,eAAO,QAAQ,QAAQ,CAAC;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACA,QAAM,IAAI;AACZ;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/vite-plugin/controller-swc-transform.ts"],"sourcesContent":["import { resolve } from 'node:path'\n\nimport { transformControllerSource, type SwcCore } from '@theokit/http'\nimport type { Plugin } from 'vite'\n\n/** Vite normalizes module ids to POSIX `/` on every OS; normalize the prefix to match. */\nfunction toPosix(p: string): string {\n return p.replace(/\\\\/g, '/')\n}\n\n/**\n * Vite plugin that compiles `<serverDir>/controllers/**` through @theokit/http's\n * swc transform so parameter decorators (`@Body`, `@Param`, `@Query`) emit the\n * `design:paramtypes` metadata esbuild silently drops. Without it, controller\n * dispatch (Task 1.2) cannot validate `@Body` or bind `@Param`.\n *\n * Scope discipline (ADR-4): the transform is a strict no-op for every file\n * outside `controllers/`, so file-based `route()` compilation is byte-for-byte\n * unchanged. `enforce: 'pre'` runs it before esbuild would mangle the decorators.\n *\n * The swc-loader is REUSED, never reimplemented (ADR-1 / Rule 9 / G12): the swc\n * option block lives once in `@theokit/http`.\n */\nexport interface ControllerSwcTransformOptions {\n /** Absolute backend root (config `serverDir`). Only `controllers/` under it is transformed. */\n serverDir: string\n /**\n * Injectable `@swc/core` loader — test seam only. Defaults to the loader\n * inside `transformControllerSource`, which resolves + caches @swc/core.\n */\n loadSwcCore?: () => Promise<SwcCore | null>\n}\n\nexport function controllerSwcTransformPlugin(options: ControllerSwcTransformOptions): Plugin {\n // Trailing `/` so `server/controllers-ui/` cannot false-match `server/controllers`.\n // POSIX-normalized so the prefix compares against Vite's `/`-separated ids on Windows too.\n const controllersDir = toPosix(resolve(options.serverDir, 'controllers')) + '/'\n\n return {\n name: 'theo:controller-swc-transform',\n enforce: 'pre',\n async transform(code: string, id: string) {\n // Strip Vite's query suffix (`?t=...`, `?worker`, etc.) + normalize separators.\n const cleanId = toPosix(id.split('?')[0])\n if (!cleanId.startsWith(controllersDir) || !cleanId.endsWith('.ts')) {\n return null\n }\n const transformed = await transformControllerSource(code, cleanId, options.loadSwcCore)\n return { code: transformed, map: null }\n },\n }\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AAExB,SAAS,iCAA+C;AAIxD,SAAS,QAAQ,GAAmB;AAClC,SAAO,EAAE,QAAQ,OAAO,GAAG;AAC7B;AAyBO,SAAS,6BAA6B,SAAgD;AAG3F,QAAM,iBAAiB,QAAQ,QAAQ,QAAQ,WAAW,aAAa,CAAC,IAAI;AAE5E,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MAAM,UAAU,MAAc,IAAY;AAExC,YAAM,UAAU,QAAQ,GAAG,MAAM,GAAG,EAAE,CAAC,CAAC;AACxC,UAAI,CAAC,QAAQ,WAAW,cAAc,KAAK,CAAC,QAAQ,SAAS,KAAK,GAAG;AACnE,eAAO;AAAA,MACT;AACA,YAAM,cAAc,MAAM,0BAA0B,MAAM,SAAS,QAAQ,WAAW;AACtF,aAAO,EAAE,MAAM,aAAa,KAAK,KAAK;AAAA,IACxC;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/vite-plugin/controller-swc-transform.ts"],"sourcesContent":["import { resolve } from 'node:path'\n\nimport { transformControllerSource, type SwcCore } from '@theokit/http'\nimport type { Plugin } from 'vite'\n\n/** Vite normalizes module ids to POSIX `/` on every OS; normalize the prefix to match. */\nfunction toPosix(p: string): string {\n return p.replace(/\\\\/g, '/')\n}\n\n/**\n * Vite plugin that compiles `<serverDir>/controllers/**` through @theokit/http's\n * swc transform so parameter decorators (`@Body`, `@Param`, `@Query`) emit the\n * `design:paramtypes` metadata esbuild silently drops. Without it, controller\n * dispatch (Task 1.2) cannot validate `@Body` or bind `@Param`.\n *\n * Scope discipline (ADR-4): the transform is a strict no-op for every file\n * outside `controllers/`, so file-based `route()` compilation is byte-for-byte\n * unchanged. `enforce: 'pre'` runs it before esbuild would mangle the decorators.\n *\n * The swc-loader is REUSED, never reimplemented (ADR-1 / Rule 9 / G12): the swc\n * option block lives once in `@theokit/http`.\n */\nexport interface ControllerSwcTransformOptions {\n /** Absolute backend root (config `serverDir`). Only `controllers/` under it is transformed. */\n serverDir: string\n /**\n * Injectable `@swc/core` loader — test seam only. Defaults to the loader\n * inside `transformControllerSource`, which resolves + caches @swc/core.\n */\n loadSwcCore?: () => Promise<SwcCore | null>\n}\n\nexport function controllerSwcTransformPlugin(options: ControllerSwcTransformOptions): Plugin {\n // Trailing `/` so `server/controllers-ui/` cannot false-match `server/controllers`.\n // POSIX-normalized so the prefix compares against Vite's `/`-separated ids on Windows too.\n const controllersDir = toPosix(resolve(options.serverDir, 'controllers')) + '/'\n\n return {\n name: 'theo:controller-swc-transform',\n enforce: 'pre',\n async transform(code: string, id: string) {\n // Strip Vite's query suffix (`?t=...`, `?worker`, etc.) + normalize separators.\n const cleanId = toPosix(id.split('?')[0])\n if (!cleanId.startsWith(controllersDir) || !cleanId.endsWith('.ts')) {\n return null\n }\n const transformed = await transformControllerSource(code, cleanId, options.loadSwcCore)\n return { code: transformed, map: null }\n },\n }\n}\n"],"mappings":";;;;AAAA,SAAS,eAAe;AAExB,SAAS,iCAA+C;AAIxD,SAAS,QAAQ,GAAmB;AAClC,SAAO,EAAE,QAAQ,OAAO,GAAG;AAC7B;AAyBO,SAAS,6BAA6B,SAAgD;AAG3F,QAAM,iBAAiB,QAAQ,QAAQ,QAAQ,WAAW,aAAa,CAAC,IAAI;AAE5E,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MAAM,UAAU,MAAc,IAAY;AAExC,YAAM,UAAU,QAAQ,GAAG,MAAM,GAAG,EAAE,CAAC,CAAC;AACxC,UAAI,CAAC,QAAQ,WAAW,cAAc,KAAK,CAAC,QAAQ,SAAS,KAAK,GAAG;AACnE,eAAO;AAAA,MACT;AACA,YAAM,cAAc,MAAM,0BAA0B,MAAM,SAAS,QAAQ,WAAW;AACtF,aAAO,EAAE,MAAM,aAAa,KAAK,KAAK;AAAA,IACxC;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/db.ts"],"sourcesContent":["import { execSync } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nexport type DbAction = 'migrate' | 'generate' | 'seed'\n\nconst VALID_ACTIONS = new Set<DbAction>(['migrate', 'generate', 'seed'])\n\nexport interface DbCommandResult {\n status: 'success' | 'error' | 'invalid_action'\n message: string\n action?: DbAction\n}\n\nfunction assertFileExists(cwd: string, relPath: string, hint: string): void {\n if (!existsSync(resolve(cwd, relPath))) {\n throw new Error(`${relPath} not found. ${hint}`)\n }\n}\n\nfunction assertBinExists(cwd: string, bin: string): void {\n const binPath = resolve(cwd, 'node_modules', '.bin', bin)\n if (!existsSync(binPath)) {\n throw new Error(`${bin} not found. Run: npm install -D ${bin}`)\n }\n}\n\nexport function dbCommand(action: string, cwd: string): DbCommandResult {\n if (!VALID_ACTIONS.has(action as DbAction)) {\n return {\n status: 'invalid_action',\n message: `Unknown db action \"${action}\". Available: ${[...VALID_ACTIONS].join(', ')}`,\n }\n }\n\n const dbAction = action as DbAction\n\n try {\n switch (dbAction) {\n case 'migrate': {\n assertFileExists(cwd, 'drizzle.config.ts', 'Create a drizzle.config.ts for your project.')\n assertBinExists(cwd, 'drizzle-kit')\n console.log('\\n ▸ Running drizzle-kit push...\\n')\n execSync('npx drizzle-kit push', { cwd, stdio: 'inherit' })\n return { status: 'success', message: 'Database migrated successfully', action: dbAction }\n }\n case 'generate': {\n assertFileExists(cwd, 'drizzle.config.ts', 'Create a drizzle.config.ts for your project.')\n assertBinExists(cwd, 'drizzle-kit')\n console.log('\\n ▸ Running drizzle-kit generate...\\n')\n execSync('npx drizzle-kit generate', { cwd, stdio: 'inherit' })\n return {\n status: 'success',\n message: 'Migration files generated in drizzle/',\n action: dbAction,\n }\n }\n case 'seed': {\n assertFileExists(cwd, 'server/db/seed.ts', 'Create server/db/seed.ts with your seed data.')\n console.log('\\n ▸ Running seed...\\n')\n execSync('npx tsx server/db/seed.ts', { cwd, stdio: 'inherit' })\n return { status: 'success', message: 'Database seeded successfully', action: dbAction }\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { status: 'error', message: msg, action: dbAction }\n }\n}\n\nexport function dbCommandCli(action: string): void {\n const result = dbCommand(action, process.cwd())\n if (result.status === 'success') {\n console.log(`\\n ✓ ${result.message}\\n`)\n } else {\n console.error(`\\n ✗ ${result.message}\\n`)\n process.exit(1)\n }\n}\n"],"mappings":";;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AAIxB,IAAM,gBAAgB,oBAAI,IAAc,CAAC,WAAW,YAAY,MAAM,CAAC;AAQvE,SAAS,iBAAiB,KAAa,SAAiB,MAAoB;AAC1E,MAAI,CAAC,WAAW,QAAQ,KAAK,OAAO,CAAC,GAAG;AACtC,UAAM,IAAI,MAAM,GAAG,OAAO,eAAe,IAAI,EAAE;AAAA,EACjD;AACF;AAEA,SAAS,gBAAgB,KAAa,KAAmB;AACvD,QAAM,UAAU,QAAQ,KAAK,gBAAgB,QAAQ,GAAG;AACxD,MAAI,CAAC,WAAW,OAAO,GAAG;AACxB,UAAM,IAAI,MAAM,GAAG,GAAG,mCAAmC,GAAG,EAAE;AAAA,EAChE;AACF;AAEO,SAAS,UAAU,QAAgB,KAA8B;AACtE,MAAI,CAAC,cAAc,IAAI,MAAkB,GAAG;AAC1C,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SAAS,sBAAsB,MAAM,iBAAiB,CAAC,GAAG,aAAa,EAAE,KAAK,IAAI,CAAC;AAAA,IACrF;AAAA,EACF;AAEA,QAAM,WAAW;AAEjB,MAAI;AACF,YAAQ,UAAU;AAAA,MAChB,KAAK,WAAW;AACd,yBAAiB,KAAK,qBAAqB,8CAA8C;AACzF,wBAAgB,KAAK,aAAa;AAClC,gBAAQ,IAAI,0CAAqC;AACjD,iBAAS,wBAAwB,EAAE,KAAK,OAAO,UAAU,CAAC;AAC1D,eAAO,EAAE,QAAQ,WAAW,SAAS,kCAAkC,QAAQ,SAAS;AAAA,MAC1F;AAAA,MACA,KAAK,YAAY;AACf,yBAAiB,KAAK,qBAAqB,8CAA8C;AACzF,wBAAgB,KAAK,aAAa;AAClC,gBAAQ,IAAI,8CAAyC;AACrD,iBAAS,4BAA4B,EAAE,KAAK,OAAO,UAAU,CAAC;AAC9D,eAAO;AAAA,UACL,QAAQ;AAAA,UACR,SAAS;AAAA,UACT,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,MACA,KAAK,QAAQ;AACX,yBAAiB,KAAK,qBAAqB,+CAA+C;AAC1F,gBAAQ,IAAI,8BAAyB;AACrC,iBAAS,6BAA6B,EAAE,KAAK,OAAO,UAAU,CAAC;AAC/D,eAAO,EAAE,QAAQ,WAAW,SAAS,gCAAgC,QAAQ,SAAS;AAAA,MACxF;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,WAAO,EAAE,QAAQ,SAAS,SAAS,KAAK,QAAQ,SAAS;AAAA,EAC3D;AACF;AAEO,SAAS,aAAa,QAAsB;AACjD,QAAM,SAAS,UAAU,QAAQ,QAAQ,IAAI,CAAC;AAC9C,MAAI,OAAO,WAAW,WAAW;AAC/B,YAAQ,IAAI;AAAA,WAAS,OAAO,OAAO;AAAA,CAAI;AAAA,EACzC,OAAO;AACL,YAAQ,MAAM;AAAA,WAAS,OAAO,OAAO;AAAA,CAAI;AACzC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/vite-plugin/openapi-emit/emit.ts","../src/vite-plugin/openapi-emit/zod-to-openapi.ts","../src/vite-plugin/openapi-emit/load-routes.ts","../src/vite-plugin/openapi-emit/dev-emit.ts"],"sourcesContent":["/**\n * In-house `emitOpenApi()` orchestrator (build-time only).\n *\n * Pure transformation: takes a route manifest (already hydrated with Zod\n * schemas extracted from `defineRoute()` config) + the openapi config\n * block, builds an OpenAPI 3.x document, writes `<outDir>/openapi.json`,\n * returns the document for downstream callers (CLI logs, tests).\n *\n * Per G2 plan v1.1 T2.1. Modelled on trpc-openapi's\n * `generateOpenApiDocument` + encore's `Generator.Generate()`.\n *\n * NEVER ship to runtime — devDep-shaped artifact.\n *\n * Path templating: TheoKit's `:param` syntax is converted to OpenAPI's\n * `{param}` per the spec. Env-var override: `THEOKIT_OPENAPI_SERVER_URL`\n * overrides `servers[0].url` without rebuilding the config.\n */\n/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time emit. outDir is a config-controlled relative path. The\n * caller already refused absolute paths via theoConfigSchema.distDir\n * pattern; the openapi.outDir field follows the same convention.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport type { z } from 'zod'\n\nimport { zodToOpenApiSchema, type ConvertCtx, type OpenApiSchema } from './zod-to-openapi.js'\n\nexport interface OpenApiManifestRoute {\n /** TheoKit-style path with `:param` placeholders (`/users/:id`). */\n routePath: string\n /** Uppercase HTTP methods the route exports (`['GET','POST']`). */\n methods: string[]\n /** Optional `defineRoute({body})` schema. */\n body?: z.ZodType\n /** Optional `defineRoute({query})` schema. */\n query?: z.ZodType\n /** Optional `defineRoute({params})` schema. */\n params?: z.ZodType\n /** Optional `defineRoute({response})` schema. */\n response?: z.ZodType\n}\n\nexport interface OpenApiEmitConfig {\n servers: { url: string; description?: string }[]\n specVersion: '3.1.0' | '3.0.3'\n title: string\n version: string\n outDir: string\n}\n\nexport interface OpenApiOperation {\n operationId?: string\n parameters?: OpenApiParameter[]\n requestBody?: {\n required?: boolean\n content: Record<string, { schema: OpenApiSchema }>\n }\n responses: Record<\n string,\n { description: string; content?: Record<string, { schema: OpenApiSchema }> }\n >\n}\n\nexport interface OpenApiParameter {\n name: string\n in: 'path' | 'query' | 'header' | 'cookie'\n required: boolean\n schema: OpenApiSchema\n description?: string\n}\n\nexport type OpenApiPathItem = Partial<\n Record<'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options', OpenApiOperation>\n>\n\nexport interface OpenApiDocument {\n openapi: '3.1.0' | '3.0.3'\n info: { title: string; version: string }\n servers: { url: string; description?: string }[]\n paths: Record<string, OpenApiPathItem>\n components?: { schemas?: Record<string, OpenApiSchema> }\n}\n\nexport interface EmitOpenApiInput {\n manifest: OpenApiManifestRoute[]\n config: OpenApiEmitConfig\n}\n\nexport interface EmitOpenApiResult {\n document: OpenApiDocument\n path: string\n}\n\nconst METHOD_TO_KEY: Record<string, keyof OpenApiPathItem> = {\n GET: 'get',\n POST: 'post',\n PUT: 'put',\n PATCH: 'patch',\n DELETE: 'delete',\n HEAD: 'head',\n OPTIONS: 'options',\n}\n\n/** Convert `/users/:id/posts/:postId?` → `/users/{id}/posts/{postId}`. */\nexport function templatePath(routePath: string): string {\n // Bounded quantifier (\\w{0,64}) is OSS-safe — TheoKit route param names\n // never exceed 64 chars in practice; cap prevents super-linear backtracking.\n return routePath.replace(/:([A-Za-z_]\\w{0,64})\\??/g, '{$1}')\n}\n\nfunction buildParameters(\n paramsSchema: z.ZodType | undefined,\n querySchema: z.ZodType | undefined,\n ctx: ConvertCtx,\n): OpenApiParameter[] {\n const out: OpenApiParameter[] = []\n if (paramsSchema !== undefined) {\n appendObjectAsParameters(paramsSchema, 'path', out, ctx)\n }\n if (querySchema !== undefined) {\n appendObjectAsParameters(querySchema, 'query', out, ctx)\n }\n return out\n}\n\nfunction appendObjectAsParameters(\n schema: z.ZodType,\n location: 'path' | 'query',\n out: OpenApiParameter[],\n ctx: ConvertCtx,\n): void {\n // We expect an object schema; if it's not, skip silently (caller already\n // validated upstream when scanning defineRoute()).\n const shape = (schema as unknown as { shape?: Record<string, z.ZodType> }).shape\n if (shape === undefined) return\n for (const [name, child] of Object.entries(shape)) {\n // A field is optional iff the schema accepts `undefined` (covers\n // `.optional()` + `.default()`). Runtime check via safeParse — robust\n // across zod versions, unlike reading the changed `_def.typeName` internal\n // (zod 3) / `def.type` (zod 4).\n const optional = child.safeParse(undefined).success\n out.push({\n name,\n in: location,\n required: location === 'path' ? true : !optional,\n schema: zodToOpenApiSchema(child, { ctx }),\n })\n }\n}\n\nfunction buildOperation(\n route: OpenApiManifestRoute,\n ctx: ConvertCtx,\n method: string,\n): OpenApiOperation {\n // Bounded sanitizer: two single-pass replacements (no nested quantifiers).\n const sanitized = route.routePath.replace(/[/:\\-{}]/g, '_').replace(/_+/g, '_')\n const operationId = `${method.toLowerCase()}_${sanitized.replace(/^_|_$/g, '')}`\n const op: OpenApiOperation = {\n operationId,\n responses: {\n '200': { description: 'OK' },\n },\n }\n\n const parameters = buildParameters(route.params, route.query, ctx)\n if (parameters.length > 0) op.parameters = parameters\n\n // Body only meaningful for write methods; we still attach if defined so\n // the document is honest about the contract.\n if (route.body !== undefined) {\n op.requestBody = {\n required: true,\n content: {\n 'application/json': { schema: zodToOpenApiSchema(route.body, { ctx }) },\n },\n }\n }\n\n if (route.response !== undefined) {\n op.responses['200'] = {\n description: 'OK',\n content: {\n 'application/json': { schema: zodToOpenApiSchema(route.response, { ctx }) },\n },\n }\n }\n\n return op\n}\n\nexport function emitOpenApi(input: EmitOpenApiInput): EmitOpenApiResult {\n const { manifest, config } = input\n\n const ctx: ConvertCtx = { seen: new Map(), components: {} }\n\n const paths: Record<string, OpenApiPathItem> = {}\n for (const route of manifest) {\n const templatedPath = templatePath(route.routePath)\n const item: OpenApiPathItem = paths[templatedPath] ?? {}\n for (const method of route.methods) {\n // Defensive: manifest emitter normalizes to uppercase, but if a\n // future scanner produces a non-HTTP verb the key lookup yields\n // undefined and we skip silently. TS narrows the indexed type to\n // keyof OpenApiPathItem; the runtime undefined check is honest.\n const key = METHOD_TO_KEY[method.toUpperCase()] as keyof OpenApiPathItem | undefined\n if (key === undefined) continue\n item[key] = buildOperation(route, ctx, method)\n }\n paths[templatedPath] = item\n }\n\n const servers = applyServerOverride(config.servers)\n\n const document: OpenApiDocument = {\n openapi: config.specVersion,\n info: { title: config.title, version: config.version },\n servers,\n paths,\n }\n\n if (Object.keys(ctx.components).length > 0) {\n document.components = { schemas: ctx.components }\n }\n\n mkdirSync(config.outDir, { recursive: true })\n const outPath = join(config.outDir, 'openapi.json')\n writeFileSync(outPath, `${JSON.stringify(document, null, 2)}\\n`, 'utf8')\n\n return { document, path: outPath }\n}\n\nfunction applyServerOverride(\n servers: { url: string; description?: string }[],\n): { url: string; description?: string }[] {\n const override = process.env.THEOKIT_OPENAPI_SERVER_URL\n if (override === undefined || override === '') return servers\n if (servers.length === 0) return [{ url: override }]\n const [first, ...rest] = servers\n return [\n {\n url: override,\n ...(first.description !== undefined ? { description: first.description } : {}),\n },\n ...rest,\n ]\n}\n","/**\n * Zod → OpenAPI 3.0 Schema converter (build-time only).\n *\n * Uses Zod v4's native `z.toJSONSchema()` and post-processes\n * the JSON Schema output into OpenAPI 3.0 format:\n * - Removes `$schema` (invalid in OpenAPI 3.0)\n * - Converts `type: [\"string\", \"null\"]` → `{ type: \"string\", nullable: true }`\n * - Recursively normalizes nested schemas\n *\n * NEVER ship to runtime — devDep-shaped artifact.\n */\nimport { z } from 'zod'\n\nexport interface OpenApiSchema {\n type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null'\n format?: string\n items?: OpenApiSchema\n properties?: Record<string, OpenApiSchema>\n required?: string[]\n additionalProperties?: boolean | OpenApiSchema\n oneOf?: OpenApiSchema[]\n anyOf?: OpenApiSchema[]\n allOf?: OpenApiSchema[]\n discriminator?: { propertyName: string; mapping?: Record<string, string> }\n enum?: unknown[]\n nullable?: boolean\n description?: string\n default?: unknown\n $ref?: string\n}\n\nexport interface ConvertCtx {\n seen: Map<z.ZodType, string>\n components: Record<string, OpenApiSchema>\n}\n\nexport interface ConvertOptions {\n ctx?: ConvertCtx\n name?: string\n}\n\nexport class ZodToOpenApiError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ZodToOpenApiError'\n }\n}\n\nexport function zodToOpenApiSchema(schema: z.ZodType, options: ConvertOptions = {}): OpenApiSchema {\n const ctx: ConvertCtx = options.ctx ?? { seen: new Map(), components: {} }\n\n const name = options.name\n if (name !== undefined) {\n if (Object.prototype.hasOwnProperty.call(ctx.components, name)) {\n return { $ref: `#/components/schemas/${name}` }\n }\n ctx.seen.set(schema, name)\n ctx.components[name] = {}\n const body = convertSchema(schema, ctx)\n ctx.components[name] = body\n return { $ref: `#/components/schemas/${name}` }\n }\n\n return convertSchema(schema, ctx)\n}\n\ninterface ZodInternalDef {\n type?: string\n discriminator?: string\n in?: z.ZodType\n}\n\n/** Read zod v4's internal schema def (the `.def` getter) without a hard `any`. */\nfunction zodDef(schema: z.ZodType): ZodInternalDef | undefined {\n return (schema as unknown as { def?: ZodInternalDef }).def\n}\n\nfunction convertSchema(schema: z.ZodType, ctx: ConvertCtx): OpenApiSchema {\n const existing = ctx.seen.get(schema)\n if (existing !== undefined) {\n return { $ref: `#/components/schemas/${existing}` }\n }\n\n const def = zodDef(schema)\n // Fail loud on schema kinds that have no OpenAPI representation (rather than\n // swallowing the zod throw into `{}`). z.function() is the canonical case.\n if (def?.type === 'function') {\n throw new ZodToOpenApiError(\n 'z.function() cannot be represented in an OpenAPI schema (functions are not serializable).',\n )\n }\n\n // A transform / pipe (`z.string().transform(...)`) has no JSON-Schema of its\n // own — zod throws. The wire shape is the INPUT (transforms run post-parse),\n // so emit the input schema. This avoids the global `io: 'input'` mode, which\n // would also flip object `additionalProperties` semantics.\n if (def?.type === 'pipe' && def.in !== undefined) {\n return convertSchema(def.in, ctx)\n }\n\n try {\n const jsonSchema = z.toJSONSchema(schema) as Record<string, unknown>\n const out = toOpenApi3(jsonSchema)\n // zod v4 emits a discriminated union as `oneOf` but drops the discriminator\n // key; re-attach it from the zod def so OpenAPI consumers can branch.\n if (def?.type === 'union' && def.discriminator !== undefined && out.oneOf !== undefined) {\n out.discriminator = { propertyName: def.discriminator }\n }\n return out\n } catch (err) {\n if (err instanceof ZodToOpenApiError) throw err\n return {}\n }\n}\n\n/** JS safe-integer bounds zod v4 attaches to `.int()` — noise for OpenAPI, stripped. */\nconst SAFE_INT_MIN = Number.MIN_SAFE_INTEGER\nconst SAFE_INT_MAX = Number.MAX_SAFE_INTEGER\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\n/** Drop zod-v4 noise keys: redundant `pattern` when `format` is set; JS safe-integer sentinel bounds. */\nfunction isNoiseKey(key: string, value: unknown, isInteger: boolean, hasFormat: boolean): boolean {\n if (key === 'pattern' && hasFormat) return true\n if (isInteger && key === 'minimum' && value === SAFE_INT_MIN) return true\n if (isInteger && key === 'maximum' && value === SAFE_INT_MAX) return true\n return false\n}\n\n/** Recursively normalize one JSON-Schema value (properties/items/*Of/additionalProperties). */\nfunction normalizeValue(key: string, value: unknown): unknown {\n if (key === 'properties' && isRecord(value)) {\n const props: Record<string, unknown> = {}\n for (const [pk, pv] of Object.entries(value)) props[pk] = isRecord(pv) ? toOpenApi3(pv) : pv\n return props\n }\n if (key === 'items' && isRecord(value)) return toOpenApi3(value)\n if ((key === 'anyOf' || key === 'oneOf' || key === 'allOf') && Array.isArray(value)) {\n const arr: unknown[] = value\n return arr.map((v) => (isRecord(v) ? toOpenApi3(v) : v))\n }\n if (key === 'additionalProperties' && isRecord(value)) return toOpenApi3(value)\n return value\n}\n\n/** Convert zod v4's `anyOf` (used for `.nullable()` + `z.union()`) to OpenAPI 3.0 shape. */\nfunction convertAnyOf(branches: unknown[], rest: Record<string, unknown>): OpenApiSchema {\n const records = branches.filter(isRecord)\n const hasNull = records.some((b) => b.type === 'null')\n const nonNull = records.filter((b) => b.type !== 'null')\n if (hasNull && nonNull.length === 1) {\n return { ...toOpenApi3(nonNull[0]), nullable: true }\n }\n const result: OpenApiSchema = { oneOf: nonNull.map((b) => toOpenApi3(b)) }\n if (hasNull) result.nullable = true\n for (const [k, v] of Object.entries(rest))\n if (k !== 'anyOf') (result as Record<string, unknown>)[k] = v\n return result\n}\n\n/**\n * Post-process JSON Schema (draft-2020-12) → OpenAPI 3.0:\n * - strip `$schema`/`$defs`\n * - `.nullable()`/union `anyOf` → `nullable: true` / `oneOf`\n * - `type: [\"string\",\"null\"]` → `{ type: \"string\", nullable: true }`\n * - drop zod-v4 noise (redundant pattern, safe-integer bounds)\n * - recurse into nested schemas\n */\nfunction toOpenApi3(js: Record<string, unknown>): OpenApiSchema {\n const { $schema: _, $defs: _defs, ...rest } = js\n if (Array.isArray(rest.anyOf)) return convertAnyOf(rest.anyOf, rest)\n\n const isInteger = rest.type === 'integer'\n const hasFormat = typeof rest.format === 'string'\n const out: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(rest)) {\n if (isNoiseKey(key, value, isInteger, hasFormat)) continue\n // `const` is JSON-Schema / OpenAPI-3.1 only; `enum: [x]` is the 3.0-and-3.1\n // compatible spelling. zod v4 emits `const` for literals (discriminator tags).\n if (key === 'const') {\n out.enum = [value]\n continue\n }\n if (key === 'type' && Array.isArray(value)) {\n const types = value.filter((t): t is string => typeof t === 'string')\n const nonNull = types.filter((t) => t !== 'null')\n out.type = nonNull.length === 1 ? nonNull[0] : nonNull\n if (types.includes('null')) out.nullable = true\n } else {\n out[key] = normalizeValue(key, value)\n }\n }\n\n return out\n}\n","/**\n * Build-time route loader for OpenAPI emit.\n *\n * Takes the G1 manifest (filePath + routePath + methods) and hydrates each\n * route's Zod schemas by dynamically importing the module. `defineRoute`\n * is an identity function, so the imported config exposes `body/query/\n * params/response` directly without any AST gymnastics.\n *\n * Supports both export shapes:\n * 1. `export const POST = defineRoute({...})` (per-method named exports)\n * 2. `export default defineRoute({...})` (single-export legacy shape)\n *\n * Per G2 plan v1.1 T2.2. Uses Vite's `ssrLoadModule` because route files\n * are TS at build time — Node's native loader doesn't transpile.\n */\nimport { resolve } from 'node:path'\n\nimport type { z } from 'zod'\n\nimport type { ManifestRoute } from '../../server/scan/manifest.js'\n\nimport type { OpenApiManifestRoute } from './emit.js'\n\ninterface RouteConfigShape {\n body?: z.ZodType\n query?: z.ZodType\n params?: z.ZodType\n response?: z.ZodType\n}\n\ninterface ViteLikeServer {\n ssrLoadModule: (id: string) => Promise<Record<string, unknown>>\n close: () => Promise<void>\n}\n\ninterface DefaultLoader {\n load: (absPath: string) => Promise<Record<string, unknown>>\n dispose: () => Promise<void>\n}\n\n/** Method names recognized as per-route named exports (UPPERCASE). */\nconst HTTP_METHOD_KEYS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const\n\nexport interface LoadRoutesOptions {\n serverDir: string\n routes: ManifestRoute[]\n /** Injectable for tests; defaults to a fresh Vite SSR dev server. */\n loadModule?: (absPath: string) => Promise<Record<string, unknown>>\n}\n\n/**\n * Hydrate manifest routes with Zod schemas extracted from their modules.\n *\n * Returns one `OpenApiManifestRoute` per (file × method) tuple. If a route\n * file declares multiple methods (`GET` + `POST`), each method gets its\n * own entry with the schemas from that method's `defineRoute()` call.\n *\n * Routes that fail to load are skipped with a console warning — the emit\n * should be best-effort, not a hard build failure.\n *\n * The default Vite loader is created once per call and disposed in the\n * `finally` block so the underlying server is released even when route\n * loading throws.\n */\nexport async function loadRoutesForOpenApi(\n options: LoadRoutesOptions,\n): Promise<OpenApiManifestRoute[]> {\n const { serverDir, routes } = options\n let loadModule = options.loadModule\n let dispose: (() => Promise<void>) | undefined\n if (loadModule === undefined) {\n const created = await createDefaultLoader(serverDir)\n loadModule = created.load\n dispose = created.dispose\n }\n\n const out: OpenApiManifestRoute[] = []\n try {\n for (const r of routes) {\n const abs = resolve(serverDir, r.filePath)\n let mod: Record<string, unknown>\n try {\n mod = await loadModule(abs)\n } catch (err) {\n console.warn(\n `[openapi-emit] Skipping ${r.filePath}: load failed (${(err as Error).message})`,\n )\n continue\n }\n\n const methods = r.methods ?? HTTP_METHOD_KEYS.filter((m) => mod[m] !== undefined)\n if (methods.length === 0) {\n // Fall back to default export when no method-named exports detected.\n const def = mod.default\n if (def !== undefined && def !== null) {\n out.push({ routePath: r.routePath, methods: ['GET'], ...extractSchemas(def) })\n }\n continue\n }\n\n for (const method of methods) {\n const handler = mod[method] ?? mod.default\n if (handler === undefined || handler === null) continue\n out.push({ routePath: r.routePath, methods: [method], ...extractSchemas(handler) })\n }\n }\n } finally {\n if (dispose !== undefined) {\n await dispose()\n }\n }\n return out\n}\n\nfunction extractSchemas(handlerExport: unknown): RouteConfigShape {\n if (typeof handlerExport !== 'object' || handlerExport === null) return {}\n const cfg = handlerExport as RouteConfigShape\n const out: RouteConfigShape = {}\n if (cfg.body !== undefined) out.body = cfg.body\n if (cfg.query !== undefined) out.query = cfg.query\n if (cfg.params !== undefined) out.params = cfg.params\n if (cfg.response !== undefined) out.response = cfg.response\n return out\n}\n\n/**\n * Default loader: spin up a minimal Vite SSR dev server (no HMR, no\n * middlewares) just to use its `ssrLoadModule`. Vite handles TS, ESM, and\n * import resolution for free.\n *\n * Returns `{load, dispose}` — the caller owns the lifecycle and MUST\n * call `dispose()` (typically in a `finally`) so the server is closed.\n */\nasync function createDefaultLoader(serverDir: string): Promise<DefaultLoader> {\n // Vite is a peerDep in build flows; import dynamically.\n const { createServer } = await import('vite')\n const server = (await createServer({\n root: serverDir,\n configFile: false,\n server: { middlewareMode: true },\n appType: 'custom',\n logLevel: 'silent',\n })) as unknown as ViteLikeServer\n\n const swallow = (): void => {\n /* eat close errors — best-effort cleanup */\n }\n return {\n load: async (absPath) => server.ssrLoadModule(absPath),\n dispose: async () => {\n await server.close().catch(swallow)\n },\n }\n}\n","/**\n * Dev-mode OpenAPI emit helper for `theokit dev`.\n *\n * Per P#3 plan v1.3 T1.1 (ADRs D3 + D4 + EC-8). Called once on `theokit dev`\n * boot AND on every chokidar 'change'/'add'/'unlink' watcher event for\n * route files when `config.openapi !== undefined`. Re-runs G2's\n * `emitOpenApi()` orchestrator to keep `<distDir>/openapi.json` always\n * fresh in dev.\n *\n * EC-8 absorbed (single-flight guard): if a previous invocation is still\n * awaiting `loadRoutesForOpenApi` (Vite SSR loader can hang on circular\n * imports or syntax errors), skip the new call and emit a `console.warn`\n * so watcher events don't pile up + dev server doesn't deadlock.\n *\n * Best-effort: ALL errors caught + warned. Never throws out of the\n * exported function (would crash Vite dev's chokidar handler).\n *\n * NEVER ship to runtime — dev-only artifact gated on `config.openapi`.\n */\nimport { generateManifest } from '../../server/scan/manifest.js'\n\nimport { emitOpenApi } from './emit.js'\nimport { loadRoutesForOpenApi } from './load-routes.js'\n\ninterface DevEmitConfig {\n servers: { url: string; description?: string }[]\n specVersion: '3.1.0' | '3.0.3'\n title: string\n version: string\n}\n\nlet inFlight = false\n\nexport async function reEmitOpenApi(\n serverDir: string,\n distDir: string,\n openApiConfig: DevEmitConfig,\n): Promise<void> {\n if (inFlight) {\n console.warn(\n '[openapi-emit] previous emit still running; skipping watcher event (EC-8 single-flight guard)',\n )\n return\n }\n inFlight = true\n try {\n const manifest = generateManifest(serverDir)\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n emitOpenApi({\n manifest: hydrated,\n config: { ...openApiConfig, outDir: distDir },\n })\n } catch (err) {\n console.warn(`[openapi-emit] re-emit failed: ${(err as Error).message}`)\n } finally {\n inFlight = false\n }\n}\n\n/** Test seam — resets the inFlight flag between tests. NOT for production use. */\nexport function _resetInFlightForTests(): void {\n inFlight = false\n}\n"],"mappings":";;;;;;;;AAsBA,SAAS,WAAW,qBAAqB;AACzC,SAAS,YAAY;;;ACZrB,SAAS,SAAS;AA8BX,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,SAAS,mBAAmB,QAAmB,UAA0B,CAAC,GAAkB;AACjG,QAAM,MAAkB,QAAQ,OAAO,EAAE,MAAM,oBAAI,IAAI,GAAG,YAAY,CAAC,EAAE;AAEzE,QAAM,OAAO,QAAQ;AACrB,MAAI,SAAS,QAAW;AACtB,QAAI,OAAO,UAAU,eAAe,KAAK,IAAI,YAAY,IAAI,GAAG;AAC9D,aAAO,EAAE,MAAM,wBAAwB,IAAI,GAAG;AAAA,IAChD;AACA,QAAI,KAAK,IAAI,QAAQ,IAAI;AACzB,QAAI,WAAW,IAAI,IAAI,CAAC;AACxB,UAAM,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0 @@
1
- {"version":3,"sources":["../src/devtools/shared.ts","../src/devtools/bridge/dispatcher.ts"],"sourcesContent":["/**\n * Devtools — shared types.\n *\n * NEVER use dangerouslySetInnerHTML in any devtools component — see plan EC-20.\n */\n\nexport type DevtoolsPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'\nexport type DevtoolsTab =\n | 'requests'\n | 'routes'\n | 'agents'\n | 'actions'\n | 'errors'\n | 'csrf-readiness'\n | 'settings'\nexport type DevtoolsTheme = 'light' | 'dark' | 'system'\n\nexport interface RequestRecord {\n id: string\n traceId: string\n method: string\n path: string\n status: number\n durationMs: number\n startedAt: number\n csrfWarn?: { code: string; docsUrl: string }\n headers?: Record<string, string>\n bodyPreview?: string\n bodyLength?: number\n bodyTruncated?: boolean\n}\n\nexport interface ErrorRecord {\n id: string\n type: 'console' | 'unhandled' | 'csrf.warn'\n message: string\n stack?: string\n code?: string\n docsUrl?: string\n timestamp: number\n}\n\nexport interface CsrfWarnPayload {\n event: 'csrf.warn'\n code: string\n docsUrl: string\n method: string\n path: string\n reason: string\n}\n\nexport interface RouteInfo {\n path: string\n absoluteFilePath: string\n layoutChain: string[]\n hasLoading: boolean\n hasError: boolean\n hasNotFound: boolean\n}\n\nexport interface RouteManifest {\n routes: RouteInfo[]\n}\n\n/**\n * Per-agent-run telemetry surfaced to the Agents devtools tab.\n *\n * Emitted by `trackAgentRun` (server-side) via the dispatcher in dev mode;\n * prod tree-shakes the entire wire (v1.1 EC-4 `__IS_DEV` IIFE guard).\n * Type lives here (devtools/shared) since both producer (server/cost) and\n * consumer (AgentsTab) need the shape; following architecture v3 ADR-0001\n * rule \"shared types in core/contracts\" is the canonical home — for this\n * one we keep it in devtools/shared to minimize churn in core/contracts/.\n */\nexport interface AgentRunRecord {\n id: string\n timestamp: number\n userId: string\n model: string\n tokensInput: number\n tokensOutput: number\n costUsd: number\n status: 'finished' | 'error' | 'aborted'\n}\n\n/**\n * T5.1 — Per-action-call telemetry surfaced to the Actions devtools tab.\n *\n * Emitted by `action-execute.ts` (server-side) via the dispatcher in dev\n * mode; prod tree-shakes the wire (mirrors AgentRunRecord pattern).\n * Field-level error pins consume `error.fields` directly when status='error'\n * (per plan ADR D6).\n */\nexport interface ActionCallRecord {\n id: string\n timestamp: number\n name: string\n input: unknown\n output?: unknown\n error?: {\n code: string\n message: string\n fields?: Record<string, string[]>\n issues?: unknown[]\n }\n durationMs: number\n status: 'success' | 'error'\n}\n\nexport interface DevtoolsState {\n open: boolean\n visible: boolean\n position: DevtoolsPosition\n theme: DevtoolsTheme\n activeTab: DevtoolsTab\n requests: RequestRecord[]\n errors: ErrorRecord[]\n agentRuns: AgentRunRecord[]\n actionCalls: ActionCallRecord[]\n routeManifest: RouteManifest | null\n activeRoutePath: string | null\n activeChain: string[]\n agentStreamEvents: AgentStreamRecord[]\n}\n\nexport type DevtoolsAction =\n | { type: 'TOGGLE_PANEL' }\n | { type: 'TOGGLE_VISIBLE' }\n | { type: 'SET_TAB'; tab: DevtoolsTab }\n | { type: 'SET_POSITION'; position: DevtoolsPosition }\n | { type: 'SET_THEME'; theme: DevtoolsTheme }\n | { type: 'REQUEST_ADD'; request: RequestRecord }\n | { type: 'ERROR_ADD'; error: ErrorRecord }\n | { type: 'CSRF_WARN'; payload: CsrfWarnPayload }\n | { type: 'MANIFEST_UPDATED'; manifest: RouteManifest }\n | { type: 'ROUTE_MATCHED'; path: string; chain: string[] }\n | { type: 'AGENT_RUN_ADD'; run: AgentRunRecord }\n | { type: 'ACTION_CALL_ADD'; record: ActionCallRecord }\n | { type: 'RESET_REQUESTS' }\n | { type: 'RESET_ERRORS' }\n | { type: 'RESET_AGENT_RUNS' }\n | { type: 'RESET_ACTION_CALLS' }\n | { type: 'AGENT_STREAM_EVENT'; event: AgentStreamRecord }\n | { type: 'RESET_AGENT_STREAM' }\n\nexport const RING_BUFFER_CAP = 50\nexport const MAX_QUEUE_SIZE = 100\nexport const STORAGE_VERSION = 2\n\nexport const initialState: DevtoolsState = {\n open: false,\n visible: true,\n position: 'bottom-right',\n theme: 'dark',\n activeTab: 'requests',\n requests: [],\n errors: [],\n agentRuns: [],\n actionCalls: [],\n routeManifest: null,\n activeRoutePath: null,\n activeChain: [],\n agentStreamEvents: [],\n}\n\nexport const CHANNEL_REQUEST = 'theo:devtools:request' as const\nexport const CHANNEL_ERROR = 'theo:devtools:error' as const\nexport const CHANNEL_CSRF_WARN = 'theo:devtools:csrf.warn' as const\nexport const CHANNEL_MANIFEST = 'theo:devtools:manifest' as const\nexport const CHANNEL_ROUTE_MATCHED = 'theo:devtools:route-matched' as const\nexport const CHANNEL_AGENT_RUN = 'theo:devtools:agent.run' as const\nexport const CHANNEL_ACTION_CALL = 'theo:devtools:action.call' as const\nexport const CHANNEL_AGENT_STREAM = 'theo:devtools:agent.stream' as const\n\nexport interface AgentStreamRecord {\n runId: string\n agentName: string\n type: string\n content?: string\n toolName?: string\n timestamp: number\n}\n","/**\n * T2.1 — Devtools dispatcher with pre-mount event queue.\n *\n * Pattern: events emitted from anywhere (server WS, browser console.error,\n * dispatcher.onCsrfWarn) can fire BEFORE the React tree mounts. Each call\n * either dispatches immediately (when `setDispatch` registered a dispatch\n * fn) or queues until React is ready, then flushes on first mount.\n *\n * EC-23: queue capped at MAX_QUEUE_SIZE (FIFO eviction).\n * EC-24: setDispatch is idempotent — flush only on NULL → non-null\n * transition (StrictMode re-mount safe).\n *\n * NEVER use dangerouslySetInnerHTML in any devtools component — see plan EC-20.\n */\nimport {\n type ActionCallRecord,\n type AgentRunRecord,\n type AgentStreamRecord,\n type CsrfWarnPayload,\n type DevtoolsAction,\n type ErrorRecord,\n MAX_QUEUE_SIZE,\n type RequestRecord,\n type RouteManifest,\n} from '../shared.js'\n\ntype Dispatch = (action: DevtoolsAction) => void\ntype QueuedItem = (d: Dispatch) => void\n\nlet _dispatch: Dispatch | null = null\nconst _queue: QueuedItem[] = []\n\nfunction queuable<Args extends unknown[]>(\n fn: (d: Dispatch, ...args: Args) => void,\n): (...args: Args) => void {\n return (...args: Args) => {\n if (_dispatch) {\n try {\n fn(_dispatch, ...args)\n } catch (err) {\n // EC-25: an error inside reducer-bound dispatch path MUST NOT bubble\n // to the original event source (e.g. logger / HMR callback / global\n // error handler). Log and continue.\n\n console.error('[theo devtools] dispatch failed', err)\n }\n } else {\n // EC-23: cap queue, FIFO-evict if full\n if (_queue.length >= MAX_QUEUE_SIZE) _queue.shift()\n _queue.push((d) => {\n fn(d, ...args)\n })\n }\n }\n}\n\nfunction flushQueue(): void {\n while (_queue.length) {\n const fn = _queue.shift()\n if (!fn || !_dispatch) break\n try {\n fn(_dispatch)\n } catch (err) {\n console.error('[theo devtools] queued event failed', err)\n }\n }\n}\n\nexport const dispatcher = {\n onRequest: queuable((d: Dispatch, req: RequestRecord) => {\n d({ type: 'REQUEST_ADD', request: req })\n }),\n onError: queuable((d: Dispatch, err: ErrorRecord) => {\n d({ type: 'ERROR_ADD', error: err })\n }),\n onCsrfWarn: queuable((d: Dispatch, payload: CsrfWarnPayload) => {\n d({ type: 'CSRF_WARN', payload })\n }),\n onManifestUpdated: queuable((d: Dispatch, manifest: RouteManifest) => {\n d({ type: 'MANIFEST_UPDATED', manifest })\n }),\n onRouteMatched: queuable((d: Dispatch, path: string, chain: string[]) => {\n d({ type: 'ROUTE_MATCHED', path, chain })\n }),\n onAgentRun: queuable((d: Dispatch, run: AgentRunRecord) => {\n d({ type: 'AGENT_RUN_ADD', run })\n }),\n onActionCall: queuable((d: Dispatch, record: ActionCallRecord) => {\n d({ type: 'ACTION_CALL_ADD', record })\n }),\n onAgentStreamEvent: queuable((d: Dispatch, event: AgentStreamRecord) => {\n d({ type: 'AGENT_STREAM_EVENT', event })\n }),\n\n /**\n * Wire React's dispatch function in. Idempotent (EC-24): only the\n * NULL → non-null transition flushes the queue; subsequent non-null\n * sets just replace the reference (used for StrictMode re-mount).\n */\n setDispatch(d: Dispatch | null): void {\n const prev = _dispatch\n _dispatch = d\n if (d && !prev) flushQueue()\n },\n\n /** Testing helper — clear queue + dispatch reference between tests. */\n _reset(): void {\n _dispatch = null\n _queue.length = 0\n },\n\n /** Testing helper — observe queue length. */\n _queueLength(): number {\n return _queue.length\n },\n}\n\nexport type Dispatcher = typeof dispatcher\n"],"mappings":";;;;AAkJO,IAAM,iBAAiB;;;ACrH9B,IAAI,YAA6B;AACjC,IAAM,SAAuB,CAAC;AAE9B,SAAS,SACP,IACyB;AACzB,SAAO,IAAI,SAAe;AACxB,QAAI,WAAW;AACb,UAAI;AACF,WAAG,WAAW,GAAG,IAAI;AAAA,MACvB,SAAS,KAAK;AAKZ,gBAAQ,MAAM,mCAAmC,GAAG;AAAA,MACtD;AAAA,IACF,OAAO;AAEL,UAAI,OAAO,UAAU,eAAgB,QAAO,MAAM;AAClD,aAAO,KAAK,CAAC,MAAM;AACjB,WAAG,GAAG,GAAG,IAAI;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,SAAS,aAAmB;AAC1B,SAAO,OAAO,QAAQ;AACpB,UAAM,KAAK,OAAO,MAAM;AACxB,QAAI,CAAC,MAAM,CAAC,UAAW;AACvB,QAAI;AACF,SAAG,SAAS;AAAA,IACd,SAAS,KAAK;AACZ,cAAQ,MAAM,uCAAuC,GAAG;AAAA,IAC1D;AAAA,EACF;AACF;AAEO,IAAM,aAAa;AAAA,EACxB,WAAW,SAAS,CAAC,GAAa,QAAuB;AACvD,MAAE,EAAE,MAAM,eAAe,SAAS,IAAI,CAAC;AAAA,EACzC,CAAC;AAAA,EACD,SAAS,SAAS,CAAC,GAAa,QAAqB;AACnD,MAAE,EAAE,MAAM,aAAa,OAAO,IAAI,CAAC;AAAA,EACrC,CAAC;AAAA,EACD,YAAY,SAAS,CAAC,GAAa,YAA6B;AAC9D,MAAE,EAAE,MAAM,aAAa,QAAQ,CAAC;AAAA,EAClC,CAAC;AAAA,EACD,mBAAmB,SAAS,CAAC,GAAa,aAA4B;AACpE,MAAE,EAAE,MAAM,oBAAoB,SAAS,CAAC;AAAA,EAC1C,CAAC;AAAA,EACD,gBAAgB,SAAS,CAAC,GAAa,MAAc,UAAoB;AACvE,MAAE,EAAE,MAAM,iBAAiB,MAAM,MAAM,CAAC;AAAA,EAC1C,CAAC;AAAA,EACD,YAAY,SAAS,CAAC,GAAa,QAAwB;AACzD,MAAE,EAAE,MAAM,iBAAiB,IAAI,CAAC;AAAA,EAClC,CAAC;AAAA,EACD,cAAc,SAAS,CAAC,GAAa,WAA6B;AAChE,MAAE,EAAE,MAAM,mBAAmB,OAAO,CAAC;AAAA,EACvC,CAAC;AAAA,EACD,oBAAoB,SAAS,CAAC,GAAa,UAA6B;AACtE,MAAE,EAAE,MAAM,sBAAsB,MAAM,CAAC;AAAA,EACzC,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOD,YAAY,GAA0B;AACpC,UAAM,OAAO;AACb,gBAAY;AACZ,QAAI,KAAK,CAAC,KAAM,YAAW;AAAA,EAC7B;AAAA;AAAA,EAGA,SAAe;AACb,gBAAY;AACZ,WAAO,SAAS;AAAA,EAClB;AAAA;AAAA,EAGA,eAAuB;AACrB,WAAO,OAAO;AAAA,EAChB;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/generate.ts","../src/cli/commands/generate-resource.ts","../src/cli/commands/generate-types.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { resolve, dirname } from 'node:path'\n\nimport { generateResource } from './generate-resource.js'\nimport {\n VALID_TYPES,\n type GeneratorType,\n type GenerateOptions,\n type GenerateStatus,\n type GenerateResult,\n} from './generate-types.js'\n\nexport {\n VALID_TYPES,\n type GeneratorType,\n type GenerateOptions,\n type GenerateStatus,\n type GenerateResult,\n}\n\nfunction toKebabCase(name: string): boolean {\n return /^[a-z][a-z0-9/-]*$/.test(name)\n}\n\n/**\n * Reserved JS identifier names that conflict with object prototype machinery\n * or would shadow built-in module shapes if used as action/route names.\n * Mirrors action-scan's RESERVED_NAMES (T1.4).\n */\nconst RESERVED_BASENAMES = new Set([\n 'index',\n 'constructor',\n '__proto__',\n 'prototype',\n 'hasOwnProperty',\n])\n\n/**\n * Validate that a name segment doesn't hit the reserved-identifier list.\n * Checks the BASENAME (last `/` segment) — nested `admin/constructor` still\n * rejected because the file `constructor.ts` would be the conflict.\n */\nfunction hasReservedSegment(name: string): boolean {\n const basename = name.includes('/') ? (name.split('/').pop() ?? name) : name\n return RESERVED_BASENAMES.has(basename)\n}\n\n/**\n * EC-4: validate that resolving `targetSubpath` under `cwd` stays inside `cwd`.\n * Returns `true` when path is safe (stays inside), `false` when it escapes via\n * `..`, absolute path, null byte, or similar traversal vector.\n */\nfunction isPathInside(cwd: string, targetSubpath: string): boolean {\n if (targetSubpath.includes('\\x00')) return false\n if (targetSubpath.startsWith('/') || targetSubpath.startsWith('\\\\')) return false\n const resolved = resolve(cwd, targetSubpath)\n const cwdResolved = resolve(cwd)\n const sep = process.platform === 'win32' ? '\\\\' : '/'\n return resolved === cwdResolved || resolved.startsWith(cwdResolved + sep)\n}\n\nfunction toPascalCase(name: string): string {\n return name\n .split(/[-/]/)\n .map((s) => s.charAt(0).toUpperCase() + s.slice(1))\n .join('')\n}\n\nfunction toCamelCase(name: string): string {\n const pascal = toPascalCase(name)\n return pascal.charAt(0).toLowerCase() + pascal.slice(1)\n}\n\nfunction generateRouteTemplate(name: string): string {\n return [\n `import { route } from 'theokit/server'`,\n `import { z } from 'zod'`,\n ``,\n `export const GET = route()`,\n ` .handler(({ ctx }) => {`,\n ` return { message: 'TODO: implement ${name} GET' }`,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateControllerTemplate(name: string): string {\n const className = toPascalCase(name) + 'Controller'\n const baseName = name.split('/').pop() ?? name\n return [\n `// AUTO-GENERATED by \\`theokit generate controller ${name}\\``,\n `import { Controller, Get } from '@theokit/http'`,\n ``,\n `@Controller('${baseName}')`,\n `export class ${className} {`,\n ` @Get()`,\n ` findAll(): string {`,\n ` return 'This action returns all ${baseName}'`,\n ` }`,\n `}`,\n ``,\n ].join('\\n')\n}\n\nfunction generateActionTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { action } from 'theokit/server'`,\n `import { z } from 'zod'`,\n ``,\n `export const ${camel} = action()`,\n ` .input(z.object({}))`,\n ` .handler(({ input, ctx }) => {`,\n ` return { message: 'TODO: implement ${name}' }`,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\n/**\n * Co-located test template for `theokit generate action <name>` (T5.2 +\n * plan Q4 cenário 1: roundtrip serialize). Skeleton uses vitest BDD shape\n * per testing.md.\n */\nfunction generateAgentTemplate(name: string): string {\n return [\n `import { agent } from '@theokit/agents'`,\n `import { z } from 'zod'`,\n ``,\n `// Zero-config: this file is auto-served at POST /api/agents/${name}.`,\n `// Add tools with tool('name')...build() and chain them via .tool(...).`,\n `export default agent()`,\n ` .input(z.object({ message: z.string() }))`,\n ` .model('openai/gpt-4o-mini')`,\n ` .system('You are a helpful ${name} assistant.')`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateToolboxTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { tool } from 'theokit/server'`,\n `import { z } from 'zod'`,\n ``,\n `export const ${camel}Hello = tool('${name}_hello')`,\n ` .describe('Say hello')`,\n ` .input(z.object({ name: z.string() }))`,\n ` .execute(({ name }) => \\`Hello, \\${name}!\\`)`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateWorkflowTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { Workflow, fn } from '@theokit/sdk/workflow'`,\n ``,\n `/**`,\n ` * A minimal workflow — a typed, multi-step pipeline (@theokit/sdk). Each \\`fn(...)\\` step is a pure`,\n ` * function; a step can also run an agent via \\`agentStep(name, agent, mapInput)\\`. Import + run it from`,\n ` * a route, action, cron job, or tool:`,\n ` *`,\n ` * const run = await ${camel}Workflow.run({ name: 'Ada' })`,\n ` * console.log(run.status, run.output) // 'completed' 'Hello, Ada!'`,\n ` */`,\n `export const ${camel}Workflow = Workflow.create({ name: '${name}' })`,\n ` .then(fn('normalize', (input: { name: string }) => ({ name: input.name.trim() })))`,\n ` .then(fn('greet', (step: { name: string }) => \\`Hello, \\${step.name}!\\`))`,\n ` .commit()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateEvalTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { Eval, Scorers } from '@theokit/sdk/eval'`,\n ``,\n `/**`,\n ` * An eval for your agent (@theokit/sdk) — runs the model over a dataset and scores each output.`,\n ` * To score the REAL agent, mirror its config: point \\`agent.model\\` (and, ideally, a \\`systemPrompt\\`)`,\n ` * at the same values your \\`agents/chat.ts\\` uses. Run it (needs a provider key in the environment):`,\n ` *`,\n ` * const run = await ${camel}Eval.run()`,\n ` * console.log(run.aggregate.meanScore)`,\n ` */`,\n `export const ${camel}Eval = Eval.create({`,\n ` name: '${name}',`,\n ` dataset: [{ input: 'Say ok', expected: 'ok' }],`,\n ` scorers: [Scorers.containsExpected({ caseSensitive: false })],`,\n ` // Mirror your agent: same model (+ systemPrompt) so this evaluates the agent your users talk to.`,\n ` agent: { apiKey: process.env.OPENROUTER_API_KEY ?? '', model: { id: 'openai/gpt-4o-mini' } },`,\n `})`,\n ``,\n ].join('\\n')\n}\n\nfunction generateSandboxTemplate(name: string): string {\n const camel = toCamelCase(name)\n const base = name.split('/').pop() ?? name\n const snake = base.replace(/-/g, '_')\n return [\n `import { tool } from 'theokit/server'`,\n `import { LocalSandbox } from '@theokit/sdk/sandbox'`,\n `import { z } from 'zod'`,\n ``,\n `/**`,\n ` * A sandbox-backed agent tool. \\`LocalSandbox\\` (@theokit/sdk) runs a shell command with a timeout +`,\n ` * output cap, isolated from your app process — so the agent can run commands SAFELY. This IS an agent`,\n ` * capability: connect it to your agent with \\`.tool(...)\\`:`,\n ` *`,\n ` * // agents/chat.ts`,\n ` * import { ${camel}Tool } from './sandbox/${base}.js'`,\n ` * agent().model(...).tool(${camel}Tool).build()`,\n ` */`,\n `export const ${camel}Tool = tool('${snake}')`,\n ` .describe('Run a shell command in an isolated sandbox and return its output.')`,\n ` .input(z.object({ command: z.string().describe('The shell command to run, e.g. \"ls -la\"') }))`,\n ` .execute(async ({ command }) => {`,\n ` const sandbox = new LocalSandbox({ timeoutMs: 5_000 })`,\n ` const { stdout, stderr, exitCode } = await sandbox.execute(command)`,\n ` return exitCode === 0 ? stdout : \\`exit \\${exitCode}: \\${stderr}\\``,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateScheduleTemplate(name: string): string {\n const base = name.split('/').pop() ?? name\n return [\n `import { defineCron } from 'theokit/server/cron'`,\n ``,\n `/**`,\n ` * A scheduled agent run — a first-class TheoKit cron. \\`theokit build\\` discovers it automatically and`,\n ` * translates the schedule to your deploy target's native cron (Vercel / Cloudflare / AWS). No manual`,\n ` * scheduler to start. The handler is where you invoke your agent — POST to \\`/api/agents/chat\\`, or use`,\n ` * \\`@theokit/sdk\\`'s \\`Agent\\` with the same model + system prompt as \\`agents/chat.ts\\`.`,\n ` *`,\n ` * Schedules are UTC (https://crontab.guru). \\`signal\\` aborts when the scheduler stops.`,\n ` */`,\n `export default defineCron('${base}', {`,\n ` schedule: '0 9 * * *', // every day at 09:00 UTC`,\n ` async handler({ traceId, scheduledAt, signal }) {`,\n ` void signal`,\n ` // Invoke your agent here — e.g. fetch your own \\`/api/agents/chat\\` endpoint, or call the SDK Agent.`,\n ` console.log(\\`[${base}] fired at \\${scheduledAt.toISOString()} (trace \\${traceId})\\`)`,\n ` },`,\n `})`,\n ``,\n ].join('\\n')\n}\n\nfunction generateMemoryTemplate(_name: string): string {\n return [\n `/**`,\n ` * Conversation memory — nothing to wire.`,\n ` *`,\n ` * Since @theokit/sdk 4.0, every agent session persists AUTOMATICALLY to a native Claude-shaped`,\n ` * transcript. TheoKit roots it at your app under \\`.data/agent-sessions/projects/<cwd>/<agentId>.jsonl\\`,`,\n ` * keyed by the conversation's session id — a same-session follow-up request resumes prior turns with`,\n ` * zero setup. There is no storage adapter to construct or pass to the agent anymore.`,\n ` *`,\n ` * Keep these transcripts out of git — add \\`.data/\\` to your \\`.gitignore\\`.`,\n ` *`,\n ` * Advanced: to change WHERE sessions are written (e.g. \\`~/.claude\\` so the Claude Code CLI can`,\n ` * \\`--continue\\` them), set the SDK's \\`local.baseDir\\` where you create the agent. Most apps never need to.`,\n ` */`,\n `export {}`,\n ``,\n ].join('\\n')\n}\n\nfunction resolveTemplate(\n cwd: string,\n type: GeneratorType,\n name: string,\n): { filePath: string; content: string } | null {\n switch (type) {\n // Agent-capability generators. These live UNDER `agents/` — they are facets of the agent domain,\n // not standalone top-level concerns — and the folder-semantic scanner treats each as composition\n // (never a phantom route). See docs/ARCHITECTURE.md.\n case 'workflow':\n return {\n filePath: resolve(cwd, 'agents/workflows', `${name}.ts`),\n content: generateWorkflowTemplate(name),\n }\n case 'eval':\n return {\n filePath: resolve(cwd, 'agents/evals', `${name}.ts`),\n content: generateEvalTemplate(name),\n }\n case 'sandbox':\n return {\n filePath: resolve(cwd, 'agents/sandbox', `${name}.ts`),\n content: generateSandboxTemplate(name),\n }\n case 'schedule':\n return {\n filePath: resolve(cwd, 'agents/schedules', `${name}.ts`),\n content: generateScheduleTemplate(name),\n }\n case 'memory':\n return {\n filePath: resolve(cwd, 'agents/memory', `${name}.ts`),\n content: generateMemoryTemplate(name),\n }\n case 'route':\n return {\n filePath: resolve(cwd, 'server/routes', `${name}.ts`),\n content: generateRouteTemplate(name),\n }\n case 'action':\n return {\n filePath: resolve(cwd, 'server/actions', `${name}.ts`),\n content: generateActionTemplate(name),\n }\n case 'page':\n return { filePath: resolve(cwd, `app/${name}/page.tsx`), content: generatePageTemplate(name) }\n case 'ws':\n return {\n filePath: resolve(cwd, 'server/ws', `${name}.ts`),\n content: generateWsTemplate(name),\n }\n case 'controller':\n return {\n filePath: resolve(cwd, 'server/controllers', `${name}.controller.ts`),\n content: generateControllerTemplate(name),\n }\n case 'agent':\n return {\n filePath: resolve(cwd, 'server/agents', `${name}.agent.ts`),\n content: generateAgentTemplate(name),\n }\n case 'toolbox':\n return {\n filePath: resolve(cwd, 'server/toolboxes', `${name}.tools.ts`),\n content: generateToolboxTemplate(name),\n }\n default:\n return null\n }\n}\n\nfunction generateActionTestTemplate(name: string): string {\n const camel = toCamelCase(name)\n return [\n `import { describe, it, expect } from 'vitest'`,\n ``,\n `import { ${camel} } from './${name.split('/').pop()}.js'`,\n ``,\n `describe('${name} action', () => {`,\n ` it('should accept a valid input shape', () => {`,\n ` expect(${camel}.input).toBeDefined()`,\n ` expect(typeof ${camel}.handler).toBe('function')`,\n ` })`,\n ``,\n ` it('should reject invalid input via zod schema', () => {`,\n ` const parsed = ${camel}.input.safeParse({ __invalid: true })`,\n ` // Empty object schema accepts {}; tighten this assertion when adding fields.`,\n ` expect(parsed.success).toBe(true)`,\n ` })`,\n `})`,\n ``,\n ].join('\\n')\n}\n\nfunction generatePageTemplate(name: string): string {\n const pascal = toPascalCase(name)\n return [`export default function ${pascal}Page() {`, ` return <h1>${pascal}</h1>`, `}`, ``].join(\n '\\n',\n )\n}\n\nfunction generateWsTemplate(_name: string): string {\n return [\n `import { defineWebSocket } from 'theokit/server'`,\n ``,\n `export default defineWebSocket({`,\n ` onMessage(ws, data) {`,\n ` ws.send(\\`echo: \\${data}\\`)`,\n ` },`,\n `})`,\n ``,\n ].join('\\n')\n}\n\n/**\n * Programmatic generate. Returns a structured result instead of throwing —\n * Studio (`theokit_generate` tool) consumes this directly. The CLI wrapper\n * below maps the structured result to console output + exit code semantics.\n */\n// eslint-disable-next-line @typescript-eslint/require-await\nexport async function generate(opts: GenerateOptions): Promise<GenerateResult> {\n const { cwd, type, name } = opts\n\n if (!existsSync(resolve(cwd, 'theo.config.ts')) && !existsSync(resolve(cwd, 'theo.config.js'))) {\n return {\n status: 'not_a_project',\n message: 'Not a Theo project. cwd has no theo.config.ts or theo.config.js',\n }\n }\n\n if (!VALID_TYPES.includes(type as GeneratorType)) {\n return {\n status: 'invalid_kind',\n message: `Invalid generator type \"${type}\". Available: ${VALID_TYPES.join(', ')}`,\n }\n }\n\n if (!name || !toKebabCase(name)) {\n return {\n status: 'invalid_name',\n message: `Invalid name \"${name}\". Use kebab-case: lowercase letters, numbers, hyphens.`,\n }\n }\n\n // EC-2-related: reject reserved JS identifier basenames (would shadow\n // built-in prototype machinery in virtual module emit or scan).\n if (hasReservedSegment(name)) {\n return {\n status: 'invalid_name',\n message: `Reserved name \"${name}\" — basename collides with built-in identifier (index/constructor/__proto__/prototype/hasOwnProperty).`,\n }\n }\n\n // Resource generates multiple files — handle separately\n if (type === 'resource') {\n return generateResource(cwd, name, opts.fields ?? [])\n }\n\n const resolved = resolveTemplate(cwd, type as GeneratorType, name)\n if (resolved === null) {\n return { status: 'invalid_kind', message: `Unknown type: ${type}` }\n }\n const { filePath, content } = resolved\n\n // EC-4: confirm the resolved filePath stays inside cwd. `toKebabCase`\n // already rejects most traversal vectors but a defense-in-depth check\n // against `..` slipping in via valid-looking segments is cheap.\n const relativeFromCwd = filePath.startsWith(resolve(cwd))\n ? filePath.slice(resolve(cwd).length + 1)\n : filePath\n if (!isPathInside(cwd, relativeFromCwd)) {\n return {\n status: 'invalid_name',\n message: `Path traversal denied: \"${name}\" would escape project root.`,\n }\n }\n\n if (existsSync(filePath)) {\n return { status: 'already_exists', filePath, kind: type as GeneratorType, name }\n }\n\n mkdirSync(dirname(filePath), { recursive: true })\n writeFileSync(filePath, content)\n\n // T5.2 + plan Q4: emit co-located test file alongside actions (only\n // for action type; routes/pages/ws keep prior single-file behavior).\n // Skip if existing test file present (preserve user-customized tests).\n if (type === 'action') {\n const testPath = filePath.replace(/\\.ts$/, '.test.ts')\n if (!existsSync(testPath)) {\n writeFileSync(testPath, generateActionTestTemplate(name))\n }\n }\n\n return { status: 'created', filePath, kind: type as GeneratorType, name }\n}\n\n/**\n * CLI entry point — preserves the original surface (throws + console.log).\n * Wraps the programmatic `generate` function.\n */\nexport async function generateCommand(\n type: string,\n name: string,\n fields?: string[],\n): Promise<void> {\n const result = await generate({ cwd: process.cwd(), type, name, fields })\n switch (result.status) {\n case 'not_a_project':\n throw new Error('Not a Theo project. Run this from a project root with theo.config.ts')\n case 'invalid_kind':\n throw new Error(result.message ?? 'Invalid kind')\n case 'invalid_name':\n throw new Error(\n `Invalid name \"${name}\". Use kebab-case: lowercase letters, numbers, hyphens. Example: my-route`,\n )\n case 'already_exists':\n console.log(`\\n ⚠ ${result.filePath} already exists. Skipping.\\n`)\n return\n case 'created':\n console.log(`\\n ✓ Created ${type}: ${result.filePath}\\n`)\n return\n }\n}\n","import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve, dirname } from 'node:path'\n\nimport type { GenerateResult } from './generate-types.js'\n\n// --- Field parsing ---\n\nconst ALLOWED_FIELD_TYPES = new Set(['string', 'text', 'number', 'boolean'])\nconst RESERVED_FIELDS = new Set(['id', 'createdAt', 'created_at'])\n\nexport interface ResourceField {\n name: string\n type: 'string' | 'text' | 'number' | 'boolean'\n drizzleColumn: string\n zodType: string\n}\n\nexport function parseResourceFields(args: string[]): ResourceField[] {\n if (args.length === 0) {\n throw new Error(\n 'Resource requires at least one field. Example: theokit generate resource posts title:string',\n )\n }\n return args.map((arg) => {\n const parts = arg.split(':')\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Error(`Invalid field \"${arg}\". Use name:type format (e.g. title:string)`)\n }\n const [name, type] = parts\n if (!ALLOWED_FIELD_TYPES.has(type)) {\n throw new Error(\n `Unknown field type \"${type}\" in \"${arg}\". Valid types: ${[...ALLOWED_FIELD_TYPES].join(', ')}`,\n )\n }\n if (RESERVED_FIELDS.has(name)) {\n throw new Error(`Field \"${name}\" is reserved (auto-generated by the framework)`)\n }\n const fieldType = type as ResourceField['type']\n return {\n name,\n type: fieldType,\n drizzleColumn: mapDrizzleColumn(name, fieldType),\n zodType: mapZodType(fieldType),\n }\n })\n}\n\n// --- Column / type mapping ---\n\nfunction mapDrizzleColumn(name: string, type: ResourceField['type']): string {\n switch (type) {\n case 'string':\n case 'text':\n return `text('${name}').notNull()`\n case 'number':\n return `integer('${name}').notNull()`\n case 'boolean':\n return `integer('${name}', { mode: 'boolean' }).notNull().default(false)`\n }\n}\n\nfunction mapZodType(type: ResourceField['type']): string {\n switch (type) {\n case 'string':\n case 'text':\n return 'z.string()'\n case 'number':\n return 'z.number()'\n case 'boolean':\n return 'z.boolean()'\n }\n}\n\n// --- Template generators ---\n\nfunction generateSchemaEntry(resourceName: string, fields: ResourceField[]): string {\n const cols = [\n ` id: integer('id').primaryKey({ autoIncrement: true }),`,\n ...fields.map((f) => ` ${f.name}: ${f.drizzleColumn},`),\n ` createdAt: text('created_at')`,\n ` .notNull()`,\n ` .$defaultFn(() => new Date().toISOString().split('T')[0]),`,\n ]\n return [\n ``,\n `export const ${resourceName} = sqliteTable('${resourceName}', {`,\n ...cols,\n `})`,\n ``,\n ].join('\\n')\n}\n\nfunction generateRouteIndex(resourceName: string, fields: ResourceField[]): string {\n const bodyFields = fields.map((f) => ` ${f.name}: ${f.zodType},`).join('\\n')\n return [\n `import { route } from 'theokit/server/define'`,\n `import { z } from 'zod'`,\n `import { db } from '../../db/index.js'`,\n `import { ${resourceName} } from '../../db/schema.js'`,\n ``,\n `export const GET = route()`,\n ` .handler(() => db.select().from(${resourceName}).all())`,\n ` .build()`,\n ``,\n `export const POST = route()`,\n ` .body(`,\n ` z.object({`,\n bodyFields,\n ` }),`,\n ` )`,\n ` .status(201)`,\n ` .handler(({ body }) => {`,\n ` const result = db.insert(${resourceName}).values(body).returning().get()`,\n ` return result`,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateRouteId(resourceName: string, fields: ResourceField[]): string {\n const updateFields = fields.map((f) => ` ${f.name}: ${f.zodType}.optional(),`).join('\\n')\n return [\n `import { route } from 'theokit/server/define'`,\n `import { z } from 'zod'`,\n `import { db } from '../../db/index.js'`,\n `import { ${resourceName} } from '../../db/schema.js'`,\n `import { eq } from 'drizzle-orm'`,\n ``,\n `export const GET = route()`,\n ` .params(z.object({ id: z.coerce.number() }))`,\n ` .handler(({ params }) => {`,\n ` const item = db.select().from(${resourceName}).where(eq(${resourceName}.id, params.id)).get()`,\n ` if (!item) return new Response(JSON.stringify({ error: 'Not found' }), { status: 404 })`,\n ` return item`,\n ` })`,\n ` .build()`,\n ``,\n `export const PUT = route()`,\n ` .params(z.object({ id: z.coerce.number() }))`,\n ` .body(`,\n ` z.object({`,\n updateFields,\n ` }),`,\n ` )`,\n ` .handler(({ params, body }) => {`,\n ` const result = db.update(${resourceName}).set(body).where(eq(${resourceName}.id, params.id)).returning().get()`,\n ` if (!result) return new Response(JSON.stringify({ error: 'Not found' }), { status: 404 })`,\n ` return result`,\n ` })`,\n ` .build()`,\n ``,\n `export const DELETE = route()`,\n ` .params(z.object({ id: z.coerce.number() }))`,\n ` .status(204)`,\n ` .handler(({ params }) => {`,\n ` db.delete(${resourceName}).where(eq(${resourceName}.id, params.id)).run()`,\n ` })`,\n ` .build()`,\n ``,\n ].join('\\n')\n}\n\nfunction generateTestTemplate(resourceName: string): string {\n return [\n `import { describe, it, expect } from 'vitest'`,\n ``,\n `describe('${resourceName} API', () => {`,\n ` it('should have a schema defined', async () => {`,\n ` const schema = await import('../server/db/schema.js')`,\n ` expect(schema.${resourceName}).toBeDefined()`,\n ` })`,\n ``,\n ` it('should have route handlers', async () => {`,\n ` const index = await import('../server/routes/${resourceName}/index.js')`,\n ` expect(index.GET).toBeDefined()`,\n ` expect(index.POST).toBeDefined()`,\n ` })`,\n `})`,\n ``,\n ].join('\\n')\n}\n\n// --- Orchestrator ---\n\nexport function generateResource(cwd: string, name: string, fieldArgs: string[]): GenerateResult {\n let fields: ResourceField[]\n try {\n fields = parseResourceFields(fieldArgs)\n } catch (err) {\n return { status: 'invalid_name', message: err instanceof Error ? err.message : String(err) }\n }\n\n const schemaPath = resolve(cwd, 'server/db/schema.ts')\n const routeIndexPath = resolve(cwd, `server/routes/${name}/index.ts`)\n const routeIdPath = resolve(cwd, `server/routes/${name}/[id].ts`)\n const testPath = resolve(cwd, `tests/${name}.test.ts`)\n\n if (!existsSync(schemaPath)) {\n return {\n status: 'not_a_project',\n message:\n 'server/db/schema.ts not found. Run this from a TheoKit project with database setup.',\n }\n }\n\n if (existsSync(routeIndexPath)) {\n return { status: 'already_exists', filePath: routeIndexPath, kind: 'resource', name }\n }\n\n const existingSchema = readFileSync(schemaPath, 'utf-8')\n if (existingSchema.includes(`export const ${name} =`)) {\n return {\n status: 'already_exists',\n filePath: schemaPath,\n kind: 'resource',\n name,\n message: `Table \"${name}\" already exists in schema.ts`,\n }\n }\n\n // 1. Append schema entry\n appendFileSync(schemaPath, generateSchemaEntry(name, fields))\n\n // 2. Create route files\n mkdirSync(dirname(routeIndexPath), { recursive: true })\n writeFileSync(routeIndexPath, generateRouteIndex(name, fields))\n writeFileSync(routeIdPath, generateRouteId(name, fields))\n\n // 3. Create test file\n mkdirSync(dirname(testPath), { recursive: true })\n if (!existsSync(testPath)) {\n writeFileSync(testPath, generateTestTemplate(name))\n }\n\n return { status: 'created', filePath: routeIndexPath, kind: 'resource', name }\n}\n","/**\n * Shared types for the `theokit generate` CLI command family.\n *\n * Extracted to break the circular dependency between generate.ts ↔ generate-resource.ts\n * (architecture-remediation plan T1.1, 2026-06-12).\n */\n\nexport const VALID_TYPES = [\n 'route',\n 'action',\n 'page',\n 'ws',\n 'controller',\n 'agent',\n 'toolbox',\n 'workflow',\n 'eval',\n 'sandbox',\n 'schedule',\n 'memory',\n 'resource',\n] as const\nexport type GeneratorType = (typeof VALID_TYPES)[number]\n\nexport interface GenerateOptions {\n cwd: string\n type: string\n name: string\n fields?: string[]\n}\n\nexport type GenerateStatus =\n | 'created'\n | 'already_exists'\n | 'invalid_kind'\n | 'invalid_name'\n | 'not_a_project'\n\nexport interface GenerateResult {\n status: GenerateStatus\n filePath?: string\n kind?: GeneratorType\n name?: string\n message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AAQ,GAAG,EAAE,WAAW,KAAK,CAAC;AAChD,EAAAC,eAAc,UAAU,OAAO;AAK/B,MAAI,SAAS,UAAU;AACrB,UAAM,WAAW,SAAS,QAAQ,SAAS,UAAU;AACrD,QAAI,CAACH,YAAW,QAAQ,GAAG;AACzB,MAAAG,eAAc,UAAU,2BAA2B,IAAI,CAAC;AAAA,IAC1D;AAAA,EACF;AAEA,SAAO,EAAE,QAAQ,WAAW,UAAU,MAAM,MAAuB,KAAK;AAC1E;AAMA,eAAsB,gBACpB,MACA,MACA,QACe;AACf,QAAM,SAAS,MAAM,SAAS,EAAE,KAAK,QAAQ,IAAI,GAAG,MAAM,MAAM,OAAO,CAAC;AACxE,UAAQ,OAAO,QAAQ;AAAA,IACrB,KAAK;AACH,YAAM,IAAI,MAAM,sEAAsE;AAAA,IACxF,KAAK;AACH,YAAM,IAAI,MAAM,OAAO,WAAW,cAAc;AAAA,IAClD,KAAK;AACH,YAAM,IAAI;AAAA,QACR,iBAAiB,IAAI;AAAA,MACvB;AAAA,IACF,KAAK;AACH,cAAQ,IAAI;AAAA,WAAS,OAAO,QAAQ;AAAA,CAA8B;AAClE;AAAA,IACF,KAAK;AACH,cAAQ,IAAI;AAAA,mBAAiB,IAAI,KAAK,OAAO,QAAQ;AAAA,CAAI;AACzD;AAAA,EACJ;AACF;","names":["existsSync","mkdirSync","writeFileSync","resolve","dirname","resolve","existsSync","mkdirSync","dirname","writeFileSync"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/info.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * CLI `theo info` reader. Reads `package.json`, `theo.config.*`, lock\n * files under the user's `cwd`. Read-only build-time tool. No HTTP input.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { scanRoutes } from '../../router/scan.js'\n\nexport interface RuntimeInfo {\n name: 'node' | 'bun' | 'deno' | 'unknown'\n version: string\n}\n\nexport interface PackageJsonMinimal {\n name?: string\n version?: string\n}\n\nexport interface ConfigSummary {\n ok: boolean\n summary: string\n}\n\nexport interface BuildInfoDeps {\n cwd: string\n readPackageJson?: () => PackageJsonMinimal | null\n detectRuntime?: () => RuntimeInfo\n loadConfig?: () => Promise<ConfigSummary>\n countRoutes?: () => number\n}\n\nfunction defaultDetectRuntime(): RuntimeInfo {\n const g = globalThis as { Bun?: { version: string }; Deno?: { version: { deno: string } } }\n if (g.Bun?.version) {\n return { name: 'bun', version: g.Bun.version }\n }\n if (g.Deno?.version) {\n return { name: 'deno', version: g.Deno.version.deno }\n }\n if (typeof process !== 'undefined' && process.versions.node) {\n return { name: 'node', version: process.versions.node }\n }\n return { name: 'unknown', version: '?' }\n}\n\nfunction defaultReadPackageJson(cwd: string): PackageJsonMinimal | null {\n const path = resolve(cwd, 'package.json')\n if (!existsSync(path)) return null\n try {\n const raw = readFileSync(path, 'utf-8')\n const parsed = JSON.parse(raw) as PackageJsonMinimal\n return parsed\n } catch {\n return null\n }\n}\n\nasync function defaultLoadConfig(cwd: string): Promise<ConfigSummary> {\n try {\n await loadConfig(cwd)\n return { ok: true, summary: 'config OK' }\n } catch (err) {\n return { ok: false, summary: (err as Error).message }\n }\n}\n\nfunction defaultCountRoutes(cwd: string): number {\n const appDir = resolve(cwd, 'app')\n if (!existsSync(appDir)) return 0\n const tree = scanRoutes(appDir)\n let count = 0\n function walk(node: { page?: string; children: { page?: string; children: unknown[] }[] }): void {\n if (node.page) count++\n for (const child of node.children) walk(child as never)\n }\n walk(tree)\n return count\n}\n\nexport async function buildInfo(deps: BuildInfoDeps): Promise<string> {\n const cwd = deps.cwd\n const readPkg = deps.readPackageJson ?? (() => defaultReadPackageJson(cwd))\n const runtime = (deps.detectRuntime ?? defaultDetectRuntime)()\n const loadCfg = deps.loadConfig ?? (() => defaultLoadConfig(cwd))\n const countRts = deps.countRoutes ?? (() => defaultCountRoutes(cwd))\n\n const pkg = readPkg()\n const config = await loadCfg()\n\n let routesCount = 0\n let scanError: string | null = null\n try {\n routesCount = countRts()\n } catch (err) {\n scanError = (err as Error).message\n }\n\n const projectLine = pkg?.name ? `${pkg.name}@${pkg.version ?? '?'}` : '(missing)'\n\n const configLine = config.ok ? 'OK' : `INVALID — ${config.summary}`\n\n const routesLine = scanError ? `Scan failed: ${scanError}` : `Routes: ${routesCount}`\n\n return [\n `# Theo info`,\n ``,\n `## Project`,\n `Project: ${projectLine}`,\n ``,\n `## Runtime`,\n `${runtime.name} ${runtime.version}`,\n ``,\n `## Config`,\n `Config: ${configLine}`,\n ``,\n `## App`,\n routesLine,\n ``,\n ].join('\\n')\n}\n\nexport async function infoCommand(): Promise<void> {\n const cwd = process.cwd()\n const output = await buildInfo({ cwd })\n console.log(output)\n}\n"],"mappings":";;;;;;;;;;;;;AAIA,SAAS,YAAY,oBAAoB;AACzC,SAAS,eAAe;AA4BxB,SAAS,uBAAoC;AAC3C,QAAM,IAAI;AACV,MAAI,EAAE,KAAK,SAAS;AAClB,WAAO,EAAE,MAAM,OAAO,SAAS,EAAE,IAAI,QAAQ;AAAA,EAC/C;AACA,MAAI,EAAE,MAAM,SAAS;AACnB,WAAO,EAAE,MAAM,QAAQ,SAAS,EAAE,KAAK,QAAQ,KAAK;AAAA,EACtD;AACA,MAAI,OAAO,YAAY,eAAe,QAAQ,SAAS,MAAM;AAC3D,WAAO,EAAE,MAAM,QAAQ,SAAS,QAAQ,SAAS,KAAK;AAAA,EACxD;AACA,SAAO,EAAE,MAAM,WAAW,SAAS,IAAI;AACzC;AAEA,SAAS,uBAAuB,KAAwC;AACtE,QAAM,OAAO,QAAQ,KAAK,cAAc;AACxC,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO;AAC9B,MAAI;AACF,UAAM,MAAM,aAAa,MAAM,OAAO;AACtC,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe,kBAAkB,KAA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;AAAA,IAClC;AAAA,IACA;AAAA,IACA,WAAW,UAAU;AAAA,IACrB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,eAAsB,cAA6B;AACjD,QAAM,MAAM,QAAQ,IAAI;AACxB,QAAM,SAAS,MAAM,UAAU,EAAE,IAAI,CAAC;AACtC,UAAQ,IAAI,MAAM;AACpB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/mcp.ts","../src/server/agent/mcp-stdio.ts"],"sourcesContent":["/**\n * `theokit mcp <agent>` — expose a scanned agent as an MCP server over stdio.\n *\n * The stdio sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`): a desktop MCP client\n * (e.g. Claude Desktop) spawns this command and speaks newline-delimited JSON-RPC over the pipe.\n * It reuses the framework's OWN `serveMcpStdio` / `handleMcpJsonRpc` (no LLM call, no runtime — a\n * TRANSPORT, like the HTTP route). `deps` is injectable so the routing is tested without Vite/stdin.\n */\nimport { createInterface } from 'node:readline'\n\nimport { extractAppResources } from '../../server/agent/mcp-app-resources.js'\nimport { type StdioStreams, serveMcpStdio } from '../../server/agent/mcp-stdio.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\n\nimport { createAgentSsrLoader } from './agent.js'\n\nexport interface McpCommandDeps {\n projectRoot?: string\n /** Load a TS agent module; defaults to the framework's Vite SSR loader (same transpile as dev). */\n loadModule?: (filePath: string) => Promise<Record<string, unknown>>\n /** stdio streams; defaults to `readline(process.stdin)` + `process.stdout`. Injected in tests. */\n streams?: StdioStreams\n /** Agents dir name (config `agentsDir`); defaults to the loaded config's value (\"agents\"). Tests inject it. */\n agentsDir?: string\n}\n\nexport async function mcpCommand(name: string, deps: McpCommandDeps = {}): Promise<void> {\n const projectRoot = deps.projectRoot ?? process.cwd()\n // #95 follow-up — resolve agents dir from config (default \"agents\") so `agentsDir` is honored here too.\n const agentsDir =\n deps.agentsDir ??\n (await (await import('../../config/load-config.js')).loadConfig(projectRoot)).agentsDir\n const agent = scanAgents(projectRoot, agentsDir).find((a) => a.name === name)\n if (!agent) {\n const names = scanAgents(projectRoot, agentsDir)\n .map((a) => a.name)\n .join(', ')\n throw new Error(\n `theokit mcp: agent '${name}' not found. Available: ${names || '(none in agents/)'}`,\n )\n }\n\n let loadModule = deps.loadModule\n let dispose: (() => Promise<void>) | undefined\n if (!loadModule) {\n const loader = await createAgentSsrLoader(projectRoot)\n loadModule = loader.load\n dispose = loader.dispose\n }\n\n const streams =\n deps.streams ??\n ({\n lines: createInterface({ input: process.stdin }),\n write: (line: string) => process.stdout.write(line),\n } satisfies StdioStreams)\n\n try {\n const mod = await loadModule(agent.filePath)\n await serveMcpStdio(mod, agent.name, extractAppResources(mod), streams)\n } finally {\n if (dispose) await dispose()\n }\n}\n","/**\n * MCP stdio transport (M16 follow-up) — expose a TheoKit agent as an MCP server over stdin/stdout,\n * the sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`). A desktop MCP client (e.g.\n * Claude Desktop) spawns `theokit mcp <agent>` and speaks newline-delimited JSON-RPC over the pipe.\n *\n * This is a TRANSPORT over the framework's OWN {@link handleMcpJsonRpc} — it reuses the exact handler\n * the HTTP route uses; it calls no LLM, spawns no MCP client, and reimplements no runtime (G2 /\n * sdk-runtime.md). Distinct from the SDK's MCP CLIENT stdio (which spawns external MCP servers via\n * `mcpServers` command/args) — that stays SDK-side. Here TheoKit is the SERVER. The framework-side\n * placement of this server-exposure transport is recorded in ADR-0042 (refining ADR-0040's M16 note).\n */\nimport type { AppResource } from './mcp-app-resources.js'\nimport { handleMcpJsonRpc } from './mcp-handler.js'\n\n/**\n * Handle one newline-delimited JSON-RPC line. Returns the response line to write to stdout, or\n * `null` for a blank line (nothing to emit). A malformed JSON line yields a `-32700` (Parse error)\n * envelope — never throws, so the stdio loop never dies on bad input.\n */\nexport async function handleMcpStdioLine(\n line: string,\n mod: unknown,\n name: string,\n appResources: readonly AppResource[] = [],\n): Promise<string | null> {\n const trimmed = line.trim()\n if (trimmed.length === 0) return null\n let body: unknown\n try {\n body = JSON.parse(trimmed)\n } catch {\n return JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error' },\n })\n }\n const response = await handleMcpJsonRpc(mod, name, body, appResources)\n const payload: unknown = await response.json()\n return JSON.stringify(payload)\n}\n\n/** A minimal readable line source (an async iterable of lines) + a writable sink. */\nexport interface StdioStreams {\n /** Async iterable of newline-delimited input lines (e.g. `readline.createInterface({ input })`). */\n lines: AsyncIterable<string>\n /** Write a response line (the caller appends no newline). */\n write: (line: string) => void\n}\n\n/**\n * Drive the MCP stdio server loop: for each input line, dispatch via {@link handleMcpStdioLine} and\n * write the response line (with a trailing `\\n`). Returns when the input stream ends (EOF).\n */\nexport async function serveMcpStdio(\n mod: unknown,\n name: string,\n appResources: readonly AppResource[],\n streams: StdioStreams,\n): Promise<void> {\n for await (const line of streams.lines) {\n const out = await handleMcpStdioLine(line, mod, name, appResources)\n if (out !== null) streams.write(`${out}\\n`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAQA,SAAS,uBAAuB;;;ACWhC,eAAsB,mBACpB,MACA,KACA,MACA,eAAuC,CAAC,GAChB;AACxB,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAO,KAAK,UAAU;AAAA,MACpB,SAAS;AAAA,MACT,IAAI;AAAA,MACJ,OAAO,EAAE,MAAM,QAAQ,SAAS,cAAc;AAAA,IAChD,CAAC;AAAA,EACH;AACA,QAAM,WAAW,MAAM,iBAAiB,KAAK,MAAM,MAAM,YAAY;AACrE,QAAM,UAAmB,MAAM,SAAS,KAAK;AAC7C,SAAO,KAAK,UAAU,OAAO;AAC/B;AAcA,eAAsB,cACpB,KACA,MACA,cACA,SACe;AACf,mBAAiB,QAAQ,QAAQ,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
8
- nodeAdapter
9
- };
10
- //# sourceMappingURL=node-BPJ3Z4DT.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/openapi.ts"],"sourcesContent":["/**\n * `theokit openapi` — regenerate `<distDir>/openapi.json` standalone.\n *\n * Mirrors trpc-openapi's `pnpm codegen` script. Useful in dev workflows\n * when only schemas changed and a full `theokit build` would be\n * overkill.\n *\n * Per G2 plan v1.1 T2.3. Single output (dev location only) — for the\n * dist artifact, run `theokit build`.\n *\n * Flags:\n * --dry-run Validate + print the document to stdout; skip the\n * filesystem write (EC-3 absorbed).\n */\nimport { mkdtempSync, rmSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { generateManifest } from '../../server/scan/manifest.js'\nimport { emitOpenApi } from '../../vite-plugin/openapi-emit/emit.js'\nimport { loadRoutesForOpenApi } from '../../vite-plugin/openapi-emit/load-routes.js'\n\nconst MIGRATION_GUIDE_URL = 'docs/concepts/openapi.md'\n\nexport interface OpenApiCommandOptions {\n /** Project root (defaults to `process.cwd()`). */\n cwd?: string\n /** Skip the filesystem write; print the document to stdout (EC-3). */\n dryRun?: boolean\n}\n\nexport async function openapiCommand(options: OpenApiCommandOptions = {}): Promise<void> {\n const cwd = options.cwd ?? process.cwd()\n const config = await loadConfig(cwd)\n\n if (config.openapi === undefined) {\n console.error(\n `\\n ✗ openapi: not configured in theo.config.ts\\n\\n` +\n ` Add the \\`openapi\\` block to opt in:\\n\\n` +\n ` export default defineConfig({\\n` +\n ` openapi: {\\n` +\n ` title: 'My App',\\n` +\n ` version: '1.0.0',\\n` +\n ` },\\n` +\n ` })\\n\\n` +\n ` See ${MIGRATION_GUIDE_URL} for the full reference.\\n`,\n )\n process.exit(1)\n return\n }\n\n const serverDir = resolve(cwd, config.serverDir)\n const manifest = generateManifest(serverDir)\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n\n if (options.dryRun) {\n // Build the document without writing — for the dry-run we still want a\n // valid emit pass, but with an in-memory output dir we never touch disk.\n const result = emitOpenApiInMemory(hydrated, config.openapi)\n console.log(`\\n ✓ openapi.json (dry-run): ${String(hydrated.length)} ops`)\n console.log(JSON.stringify(result.document, null, 2))\n console.log(`\\n Docs: ${MIGRATION_GUIDE_URL}\\n`)\n return\n }\n\n const distDir = resolve(cwd, config.distDir)\n const result = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distDir },\n })\n console.log(\n `\\n ✓ openapi.json: ${String(hydrated.length)} ops → ${result.path}\\n` +\n ` Docs: ${MIGRATION_GUIDE_URL}\\n`,\n )\n}\n\n/**\n * Dry-run helper: build the OpenAPI doc without writing. Routes through\n * the same `emitOpenApi` but discards the side-effecting write by\n * targeting a temp directory we immediately ignore.\n *\n * Honest tradeoff: this still calls `mkdirSync` (no-op on existing tmpdir)\n * + a synchronous write to a discardable tempfile. Cost is < 1ms and the\n * code stays the single transformation. A pure no-write helper would\n * duplicate the orchestration in `emit.ts` — KISS prefers reuse.\n */\nfunction emitOpenApiInMemory(\n manifest: Parameters<typeof emitOpenApi>[0]['manifest'],\n config: Omit<Parameters<typeof emitOpenApi>[0]['config'], 'outDir'>,\n): { document: unknown } {\n const tmp = mkdtempSync(join(tmpdir(), 'theokit-openapi-dryrun-'))\n try {\n const result = emitOpenApi({ manifest, config: { ...config, outDir: tmp } })\n return { document: result.document }\n } finally {\n rmSync(tmp, { recursive: true, force: true })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAcA,SAAS,aAAa,cAAc;AACpC,SAAS,cAAc;AACvB,SAAS,MAAM,eAAe;AAO9B,IAAM,sBAAsB;AAS5B,eAAsB,eAAe,UAAiC,CAAC,GAAkB;AACvF,QAAM,MAAM,QAAQ,OAAO,QAAQ,IAAI;AACvC,QAAM,SAAS,MAAM,WAAW,GAAG;AAEnC,MAAI,OAAO,YAAY,QAAW;AAChC,YAAQ;AAAA,MACN;AAAA;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/registry.ts
5
- var adapterRegistry = {
6
- node: async () => (await import("./node-BPJ3Z4DT.js")).nodeAdapter,
7
- vercel: async () => (await import("./vercel-J6G7ZHYQ.js")).vercelAdapter,
8
- cloudflare: async () => (await import("./cloudflare-C6E5SPAE.js")).cloudflareAdapter,
9
- static: async () => (await import("./static-MB2CD5Y3.js")).staticAdapter,
10
- bun: async () => (await import("./bun-KP2KES6S.js")).bunAdapter,
11
- "deno-deploy": async () => (await import("./deno-deploy-RFZN56X4.js")).denoDeployAdapter,
12
- netlify: async () => (await import("./netlify-PMLHVPN4.js")).netlifyAdapter,
13
- "aws-lambda": async () => (await import("./aws-lambda-7GSCNLPY.js")).awsLambdaAdapter,
14
- "theo-cloud": async () => (await import("./theo-cloud-DQRP6S6M.js")).theoCloudAdapter
15
- };
16
- async function resolveAdapter(target) {
17
- const factory = adapterRegistry[target];
18
- return factory();
19
- }
20
- export {
21
- adapterRegistry,
22
- resolveAdapter
23
- };
24
- //# sourceMappingURL=registry-FKPH7XEL.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/registry.ts"],"sourcesContent":["/**\n * Adapter Registry (T1.1 of architecture-medium-deferrals plan, ADR D1).\n *\n * Replaces the 9-case `switch (target)` in `cli/commands/build.ts` with a\n * declarative `Record<BuildTarget, () => Promise<DeployAdapter>>` map.\n *\n * Why a registry?\n * - **OCP** — adding a new adapter is now 1 line in this map + 1 string in\n * `VALID_TARGETS`. The CLI does not change.\n * - **Lazy import preserved** — each factory is `async () => (await import(...))`\n * so deps load only when the matching target is built.\n * - **TypeScript exhaustiveness** — `Record<BuildTarget, ...>` forces every\n * target in the union to have a registered factory. Adding a new target\n * without registering it is a compile error.\n *\n * The registry is the single source of truth for runtime adapter dispatch.\n * The string list `VALID_TARGETS` (in `./types.js`) is the source of truth\n * for CLI flag validation. A test (`test_valid_targets_matches_registry_keys`)\n * pins both lists to the same `BuildTarget` union to prevent drift.\n */\n\nimport type { BuildTarget, DeployAdapter } from './types.js'\n\nexport const adapterRegistry: Record<BuildTarget, () => Promise<DeployAdapter>> = {\n node: async () => (await import('./node.js')).nodeAdapter,\n vercel: async () => (await import('./vercel.js')).vercelAdapter,\n cloudflare: async () => (await import('./cloudflare.js')).cloudflareAdapter,\n static: async () => (await import('./static.js')).staticAdapter,\n bun: async () => (await import('./bun.js')).bunAdapter,\n 'deno-deploy': async () => (await import('./deno-deploy.js')).denoDeployAdapter,\n netlify: async () => (await import('./netlify.js')).netlifyAdapter,\n 'aws-lambda': async () => (await import('./aws-lambda.js')).awsLambdaAdapter,\n 'theo-cloud': async () => (await import('./theo-cloud.js')).theoCloudAdapter,\n}\n\n/**\n * Resolve a `DeployAdapter` for the given target. Throws actionable error\n * if the target is not registered (should be unreachable when callers use\n * the typed `BuildTarget` union, but guards against runtime drift).\n */\nexport async function resolveAdapter(target: BuildTarget): Promise<DeployAdapter> {\n // BuildTarget union guarantees the key exists at compile time. The runtime\n // accessor still returns the typed factory; we call it directly.\n const factory = adapterRegistry[target]\n return factory()\n}\n"],"mappings":";;;;AAuBO,IAAM,kBAAqE;AAAA,EAChF,MAAM,aAAa,MAAM,OAAO,oBAAW,GAAG;AAAA,EAC9C,QAAQ,aAAa,MAAM,OAAO,sBAAa,GAAG;AAAA,EAClD,YAAY,aAAa,MAAM,OAAO,0BAAiB,GAAG;AAAA,EAC1D,QAAQ,aAAa,MAAM,OAAO,sBAAa,GAAG;AAAA,EAClD,KAAK,aAAa,MAAM,OAAO,mBAAU,GAAG;AAAA,EAC5C,eAAe,aAAa,MAAM,OAAO,2BAAkB,GAAG;AAAA,EAC9D,SAAS,aAAa,MAAM,OAAO,uBAAc,GAAG;AAAA,EACpD,cAAc,aAAa,MAAM,OAAO,0BAAiB,GAAG;AAAA,EAC5D,cAAc,aAAa,MAAM,OAAO,0BAAiB,GAAG;AAC9D;AAOA,eAAsB,eAAe,QAA6C;AAGhF,QAAM,UAAU,gBAAgB,MAAM;AACtC,SAAO,QAAQ;AACjB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/migrate/router.ts","../src/cli/commands/migrate/router-codemod.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time codemod: derives all FS paths from the user's `<routesDir>`\n * argument (defaults to `<cwd>/server/routes`). No HTTP input reaches\n * these fs calls. Operator runs this manually via `theokit migrate router`.\n */\n/**\n * G6 T2.1 — `theokit migrate router` CLI subcommand.\n *\n * Plan: .claude/knowledge-base/plans/g6-router-convention-plan.md v1.1\n *\n * Wraps the pure `planRouterMigration` with side effects:\n * - EC-2: pre-flight `isPortInUse(3000|3100)` warning to prevent the\n * dev-server HMR cascade described in the edge-case review.\n * - EC-7: partial failure produces a typed `RouterMigrationPartialFailure`\n * with `filesAlreadyMigrated` so a re-run can continue from where it\n * stopped (idempotent by virtue of `planRouterMigration`).\n * - Prefers `git mv $from $to` so the rename appears as a single\n * history entry; falls back to `mkdir -p $(dirname $to) && fs.rename`\n * when not in a git repo or git mv fails.\n */\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { createServer } from 'node:net'\nimport { dirname, resolve } from 'node:path'\n\nimport {\n computeDepthDelta,\n planRouterMigration,\n rewriteRelativeImports,\n type RouterMigrationPlanItem,\n} from './router-codemod.js'\n\nexport interface RouterMigrateOptions {\n /** Absolute path to `<project>/server/routes`. Defaults to `<cwd>/server/routes`. */\n routesDir?: string\n /**\n * Skip the EC-2 dev-server port pre-flight check (CI / non-TTY).\n * Default: false.\n */\n force?: boolean\n /** When true, prints the plan but performs no renames (dry-run). */\n dryRun?: boolean\n /** When true, suppresses stdout (used in tests). */\n silent?: boolean\n}\n\n/**\n * Thrown when the codemod completes with at least one successful rename\n * AND at least one failure — caller can re-run safely (idempotent) and\n * the second pass will skip already-migrated files.\n */\nexport class RouterMigrationPartialFailure extends Error {\n override readonly name = 'RouterMigrationPartialFailure'\n readonly filesAlreadyMigrated: string[]\n readonly failedFile: string\n readonly causeMessage: string\n constructor(filesAlreadyMigrated: string[], failedFile: string, causeMessage: string) {\n super(\n `Router migration partial failure: ${filesAlreadyMigrated.length} files migrated successfully, then failed on ${failedFile}: ${causeMessage}. Re-run \\`theokit migrate router\\` to retry — already-migrated files will be skipped.`,\n )\n this.filesAlreadyMigrated = filesAlreadyMigrated\n this.failedFile = failedFile\n this.causeMessage = causeMessage\n }\n}\n\n/**\n * EC-2: dev-server detection. Returns true if the port is in use (someone\n * is already listening on localhost:<port>). Uses Node's `node:net` —\n * zero new deps.\n */\nexport async function isPortInUse(port: number): Promise<boolean> {\n return await new Promise<boolean>((resolve) => {\n const probe = createServer()\n probe.once('error', (err: NodeJS.ErrnoException) => {\n probe.close(() => {\n resolve(err.code === 'EADDRINUSE')\n })\n })\n probe.once('listening', () => {\n probe.close(() => {\n resolve(false)\n })\n })\n probe.listen(port, '127.0.0.1')\n })\n}\n\n/**\n * EC-2 pre-flight: returns the first port in use among the typical\n * theokit dev ports (3000 + 3100) so the caller can warn the user.\n */\nexport async function findRunningDevServerPort(): Promise<number | null> {\n for (const port of [3000, 3100]) {\n if (await isPortInUse(port)) return port\n }\n return null\n}\n\nfunction tryGitMv(from: string, to: string): boolean {\n try {\n mkdirSync(dirname(to), { recursive: true })\n // Arguments are absolute paths from a recursive walk of <routesDir>.\n // Pass as argv to avoid shell parsing entirely (no `shell: true`).\n // `git` is resolved via the operator's PATH (same security model as\n // every other CLI tool — `theokit dev`, `pnpm install`, etc.).\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n execFileSync('git', ['mv', from, to], { stdio: 'pipe' })\n return true\n } catch {\n return false\n }\n}\n\nfunction fallbackRename(from: string, to: string): void {\n mkdirSync(dirname(to), { recursive: true })\n renameSync(from, to)\n}\n\nfunction applyRename(item: RouterMigrationPlanItem): void {\n if (!existsSync(item.from)) {\n // Idempotency: already migrated — skip silently\n return\n }\n if (existsSync(item.to)) {\n // The plan() phase would have thrown CollisionError if we knew about\n // it at plan time. This branch covers a race condition where the\n // target was created between plan and apply.\n throw new Error(\n `Refusing to overwrite existing file at ${item.to} during migration of ${item.from}`,\n )\n }\n if (!tryGitMv(item.from, item.to)) {\n fallbackRename(item.from, item.to)\n }\n}\n\n/**\n * Adjust relative imports inside the renamed file to compensate for the\n * extra nesting depth. Without this, `import { foo } from './chat'` inside\n * a file moved from `routes/admin.sdk-config.ts` → `routes/admin/sdk-config.ts`\n * would fail to resolve at typecheck/runtime — the import needs `../chat`\n * now that the file lives one level deeper.\n */\nfunction applyImportRewrite(item: RouterMigrationPlanItem, routesDir: string): void {\n const delta = computeDepthDelta(item.from, item.to, routesDir)\n if (delta <= 0) return\n const source = readFileSync(item.to, 'utf8')\n const rewritten = rewriteRelativeImports(source, delta)\n if (rewritten !== source) {\n writeFileSync(item.to, rewritten, 'utf8')\n }\n}\n\nexport interface RouterMigrateResult {\n /** Successfully renamed (from, to) pairs. */\n migrated: RouterMigrationPlanItem[]\n /** Plan was empty — nothing to do (already-nested). */\n alreadyClean: boolean\n}\n\ntype LogFn = (msg: string) => void\n\nfunction makeLog(silent: boolean | undefined): LogFn {\n if (silent) {\n return (_msg: string) => {\n // intentionally silent\n }\n }\n return (msg: string) => {\n console.log(msg)\n }\n}\n\nasync function assertNoRunningDevServer(opts: RouterMigrateOptions): Promise<void> {\n if (opts.force) return\n const runningPort = await findRunningDevServerPort()\n if (runningPort !== null) {\n throw new Error(\n `Detected theokit dev server running on port ${runningPort}. STOP it before running migration to avoid HMR cascade (see EC-2). Re-run with --force to override.`,\n )\n }\n}\n\nfunction executeRenames(\n plan: readonly RouterMigrationPlanItem[],\n routesDir: string,\n log: LogFn,\n): RouterMigrationPlanItem[] {\n const migrated: RouterMigrationPlanItem[] = []\n for (const item of plan) {\n try {\n applyRename(item)\n applyImportRewrite(item, routesDir)\n migrated.push(item)\n log(` ✓ ${item.from} → ${item.to}`)\n } catch (err) {\n // EC-7: partial failure observability — emit structured error with\n // the list of already-migrated files so a re-run can recover.\n const causeMessage = err instanceof Error ? err.message : String(err)\n throw new RouterMigrationPartialFailure(\n migrated.map((m) => m.from),\n item.from,\n causeMessage,\n )\n }\n }\n return migrated\n}\n\nexport async function routerMigrateCommand(\n opts: RouterMigrateOptions = {},\n): Promise<RouterMigrateResult> {\n const routesDir = opts.routesDir ?? resolve(process.cwd(), 'server', 'routes')\n const log = makeLog(opts.silent)\n\n await assertNoRunningDevServer(opts)\n\n const plan = planRouterMigration(routesDir)\n if (plan.length === 0) {\n log(' ✓ Router already uses directory-nested convention. Nothing to do.')\n return { migrated: [], alreadyClean: true }\n }\n\n log(` → Migrating ${plan.length} dotted route(s) to directory-nested form...`)\n\n if (opts.dryRun) {\n for (const item of plan) {\n log(` [dry-run] ${item.from} → ${item.to}`)\n }\n return { migrated: [], alreadyClean: false }\n }\n\n const migrated = executeRenames(plan, routesDir, log)\n log(` ✓ Migrated ${migrated.length} route(s).`)\n return { migrated, alreadyClean: false }\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time codemod: walks `<routesDir>` derived from the operator's\n * cwd via `theokit migrate router`. No HTTP input reaches these fs calls.\n */\n/**\n * G6 T2.1 — Pure codemod core for `theokit migrate router`.\n *\n * Plan: .claude/knowledge-base/plans/g6-router-convention-plan.md v1.1\n *\n * `planRouterMigration` walks `<routesDir>` recursively and returns the\n * set of (from, to) renames required to convert legacy dotted-basename\n * routes (`auth.[provider].login.ts`) into the directory-nested form\n * (`auth/[provider]/login.ts`). The function is PURE — it does NOT\n * touch the filesystem beyond `readdirSync`/`statSync`. The CLI subcommand\n * (`router.ts`) is responsible for executing the renames via `git mv`\n * or `fs.rename` with the appropriate error handling.\n *\n * Edge cases covered:\n * - EC-4: co-located `*.test.[jt]sx?` / `*.spec.[jt]sx?` files are\n * silently skipped (same filter as the scanner).\n * - EC-5: target collision detection is CASE-INSENSITIVE so a\n * macOS/Windows dev doesn't silently overwrite a sibling file that\n * differs only in case.\n * - Idempotent: invoked twice on the same tree, the second pass is empty.\n */\nimport { readdirSync, statSync } from 'node:fs'\nimport { extname, join, relative, sep } from 'node:path'\n\nconst ROUTE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst TEST_OR_SPEC_RE = /\\.(test|spec)\\.[jt]sx?$/\n\n/**\n * One pending rename emitted by `planRouterMigration`.\n */\nexport interface RouterMigrationPlanItem {\n /** Absolute path of the offending dotted-basename file. */\n from: string\n /** Absolute path of the proposed directory-nested replacement. */\n to: string\n}\n\n/**\n * `RouterMigrationCollisionError` is thrown when migrating a dotted file\n * would overwrite an existing file (case-insensitive). The caller MUST\n * resolve the conflict manually before re-running the codemod.\n */\nexport class RouterMigrationCollisionError extends Error {\n override readonly name = 'RouterMigrationCollisionError'\n readonly from: string\n readonly to: string\n constructor(from: string, to: string) {\n super(\n `Router migration collision: ${from} would rename to ${to}, but that file already exists (case-insensitive match). Resolve manually.`,\n )\n this.from = from\n this.to = to\n }\n}\n\n/**\n * Compute the depth delta (number of extra `..` levels needed) between\n * the original (dotted) path and the migrated (nested) path, relative\n * to a common `routesDir` ancestor.\n *\n * - `admin.sdk-config.ts` (depth 0) → `admin/sdk-config.ts` (depth 1): delta = 1\n * - `debug.stability.last.ts` (depth 0) → `debug/stability/last.ts` (depth 2): delta = 2\n * - `canvas/artifacts.[id].ts` (depth 1) → `canvas/artifacts/[id].ts` (depth 2): delta = 1\n */\nexport function computeDepthDelta(from: string, to: string, routesDir: string): number {\n const depthOf = (p: string): number => {\n const rel = relative(routesDir, p).replace(/\\\\/g, '/')\n // depth = number of `/` separators in the relative path\n return rel.split('/').length - 1\n }\n return depthOf(to) - depthOf(from)\n}\n\n/**\n * Rewrite all relative imports in `source` by prepending `../` × `delta`\n * to every `./X` or `../X` specifier. Absolute / package specifiers\n * (`theokit/server`, `zod`, `node:fs`) are untouched.\n *\n * Handles three import shapes:\n * - `import ... from './foo'`\n * - `import('./foo')` (dynamic)\n * - `import './foo'` (side-effect only)\n * - `export ... from './foo'` (re-exports)\n *\n * Pure: returns the new source; does NOT touch disk.\n */\nexport function rewriteRelativeImports(source: string, delta: number): string {\n if (delta <= 0) return source\n\n const prefix = '../'.repeat(delta)\n\n // Rewrites a captured relative specifier: `./foo` → `<prefix>foo`,\n // `../foo` → `<prefix>../foo`. Single source of truth for the algorithm\n // shared by all three import-shape regexes below.\n const transformSpecifier = (specifier: string): string => {\n if (specifier.startsWith('./')) return `${prefix}${specifier.slice(2)}`\n return `${prefix}${specifier}`\n }\n\n // Three narrow regexes keep us out of catastrophic-backtracking territory.\n // Each is anchored on a keyword (`from`, `import`) and uses a possessive\n // character class (`[^'\"]+`) for the specifier, so backtracking is bounded.\n const fromRe = /\\bfrom\\s+(['\"])(\\.{1,2}\\/[^'\"]+)\\1/g\n const dynRe = /\\bimport\\s*\\(\\s*(['\"])(\\.{1,2}\\/[^'\"]+)\\1\\s*\\)/g\n const sideRe = /\\bimport\\s+(['\"])(\\.{1,2}\\/[^'\"]+)\\1/g\n\n const fromSub = (_m: string, q: string, spec: string): string =>\n `from ${q}${transformSpecifier(spec)}${q}`\n const dynSub = (_m: string, q: string, spec: string): string =>\n `import(${q}${transformSpecifier(spec)}${q})`\n const sideSub = (_m: string, q: string, spec: string): string =>\n `import ${q}${transformSpecifier(spec)}${q}`\n\n // `from` covers both `import ... from '...'` and `export ... from '...'`\n // (the `\\bfrom\\s+` anchor matches the keyword position in both shapes).\n // `dynRe` handles `import('...')`. `sideRe` handles bare `import '...'`.\n // No overlap — `sideRe` requires `import` followed by whitespace then\n // a quote (vs. `import(` for dynRe and `import ... from` for fromRe).\n return source.replace(fromRe, fromSub).replace(dynRe, dynSub).replace(sideRe, sideSub)\n}\n\nfunction isTestOrSpecFile(filePath: string): boolean {\n return TEST_OR_SPEC_RE.test(filePath)\n}\n\nfunction hasDotOutsideBrackets(segment: string): boolean {\n let depth = 0\n for (const ch of segment) {\n if (ch === '[') depth++\n else if (ch === ']') depth--\n else if (ch === '.' && depth === 0) return true\n }\n return false\n}\n\nfunction splitDottedSegmentOutsideBrackets(segment: string): string[] {\n const parts: string[] = []\n let current = ''\n let depth = 0\n for (const ch of segment) {\n if (ch === '[') {\n depth++\n current += ch\n } else if (ch === ']') {\n depth--\n current += ch\n } else if (ch === '.' && depth === 0) {\n if (current) parts.push(current)\n current = ''\n } else {\n current += ch\n }\n }\n if (current) parts.push(current)\n return parts\n}\n\nfunction toDirectoryNestedPath(filePath: string, routesDir: string): string {\n const rel = relative(routesDir, filePath).replace(/\\\\/g, '/')\n const ext = extname(rel)\n const withoutExt = rel.slice(0, -ext.length)\n const flattened = withoutExt.split('/').flatMap(splitDottedSegmentOutsideBrackets)\n return join(routesDir, `${flattened.join(sep)}${ext}`)\n}\n\nfunction walkRoutes(root: string, onFile: (absPath: string) => void): void {\n let entries\n try {\n entries = readdirSync(root, { withFileTypes: true })\n } catch {\n return\n }\n for (const entry of entries) {\n if (entry.name.startsWith('_') || entry.name.startsWith('.')) continue\n const full = join(root, entry.name)\n if (entry.isDirectory()) {\n walkRoutes(full, onFile)\n } else if (entry.isFile() && ROUTE_EXTENSIONS.has(extname(entry.name))) {\n onFile(full)\n }\n }\n}\n\nfunction isDottedRouteFile(filePath: string, routesDir: string): boolean {\n const rel = relative(routesDir, filePath).replace(/\\\\/g, '/')\n const ext = extname(rel)\n const withoutExt = rel.slice(0, -ext.length)\n return withoutExt.split('/').some(hasDotOutsideBrackets)\n}\n\n/**\n * Compute the migration plan for a `<server>/routes` tree.\n *\n * Pure: does NOT mutate the filesystem.\n *\n * @throws RouterMigrationCollisionError when a target collides with an\n * existing file (case-insensitive).\n */\nexport function planRouterMigration(routesDir: string): RouterMigrationPlanItem[] {\n const plan: RouterMigrationPlanItem[] = []\n const existingPathsLowercase = new Set<string>()\n\n walkRoutes(routesDir, (absPath) => {\n existingPathsLowercase.add(absPath.toLowerCase())\n })\n\n walkRoutes(routesDir, (absPath) => {\n if (isTestOrSpecFile(absPath)) return\n if (!isDottedRouteFile(absPath, routesDir)) return\n\n const to = toDirectoryNestedPath(absPath, routesDir)\n\n // EC-5: case-insensitive collision check — macOS HFS+/APFS default\n // and Windows NTFS treat case-only differences as the same path. If\n // any pre-existing file at a case-insensitive match exists, the codemod\n // would silently overwrite on those platforms; we bail explicitly.\n const targetLower = to.toLowerCase()\n if (existingPathsLowercase.has(targetLower) && targetLower !== absPath.toLowerCase()) {\n throw new RouterMigrationCollisionError(absPath, to)\n }\n // Also guard against statSync race using an explicit existence check.\n try {\n if (statSync(to).isFile()) {\n throw new RouterMigrationCollisionError(absPath, to)\n }\n } catch (err) {\n if (err instanceof RouterMigrationCollisionError) throw err\n // ENOENT — fine, target does not exist\n }\n\n plan.push({ from: absPath, to })\n })\n\n return plan\n}\n"],"mappings":";;;;AAoBA,SAAS,oBAAoB;AAC7B,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,oBAAoB;AAC7B,SAAS,SAAS,eAAe;;;ACEjC,SAAS,aAAa,gBAAgB;AACtC,SAAS,SAAS,MAAM,UAAU,WAAW;AAE7C,IAAM,mBAAmB,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAC/D,IAAM,kBAAkB;AAiBjB,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACrC,OAAO;AAAA,EAChB;AAAA,EACA;AAAA,EACT,YAAY,MAAc,IAAY;AACpC;AAAA,MACE,+BAA+B,IAAI,oBAAoB,EAAE;AAAA,IAC3D;AACA,SAAK,OAAO;AACZ,SAAK,KAAK;AAAA,EACZ;AACF;AAWO,SAAS,kBAAkB,MAAc,IAAY,WAA2B;AACrF,QAAM,UAAU,CAAC,MAAsB;AACrC,UAAM,MAAM,SAAS,WAAW,CAAC,EAAE,QAAQ,OAAO,GAAG;AAErD,WAAO,IAAI,MAAM,GAAG,EAAE,SAAS;AAAA,EACjC;AACA,SAAO,QAAQ,EAAE,IAAI,QAAQ,IAAI;AACnC;AAeO,SAAS,uBAAuB,QAAgB,OAAuB;AAC5E,MAAI,SAAS,EAAG,QAAO;AAEvB,QA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AG;AACpD,MAAI,qBAAgB,SAAS,MAAM,YAAY;AAC/C,SAAO,EAAE,UAAU,cAAc,MAAM;AACzC;","names":["resolve"]}
@@ -1,30 +0,0 @@
1
- #!/usr/bin/env node
2
- import "tsx/esm";
3
- import {
4
- cacheSchema,
5
- corsSchema,
6
- disallowedConfigSchema,
7
- headerSafeString,
8
- loggingSchema,
9
- rateLimitSchema,
10
- securityHeadersSchema,
11
- securitySchema,
12
- storageSchema,
13
- theoConfigSchema,
14
- uploadSchema
15
- } from "./chunk-GSO77FSM.js";
16
- import "./chunk-45C3WUQ7.js";
17
- export {
18
- cacheSchema,
19
- corsSchema,
20
- disallowedConfigSchema,
21
- headerSafeString,
22
- loggingSchema,
23
- rateLimitSchema,
24
- securityHeadersSchema,
25
- securitySchema,
26
- storageSchema,
27
- theoConfigSchema,
28
- uploadSchema
29
- };
30
- //# sourceMappingURL=schema-LYOLNHZ7.js.map