theokit 0.43.7 → 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 (230) hide show
  1. package/dist/{actions-virtual-module-N7GKUS3D.js → actions-virtual-module-HG66SZ7T.js} +8 -8
  2. package/dist/actions-virtual-module-HG66SZ7T.js.map +1 -0
  3. package/dist/{actions-virtual-module-LD3YKWIX.js → actions-virtual-module-RSFRPJQZ.js} +7 -7
  4. package/dist/actions-virtual-module-RSFRPJQZ.js.map +1 -0
  5. package/dist/{add-W6FNTAFS.js → add-3VLFUPF4.js} +1 -1
  6. package/dist/add-3VLFUPF4.js.map +1 -0
  7. package/dist/{agent-U35G3WNE.js → agent-OXRRKB55.js} +5 -5
  8. package/dist/{agents-typed-client-NJ73Z6XY.js → agents-typed-client-X56CQ6FX.js} +1 -1
  9. package/dist/agents-typed-client-X56CQ6FX.js.map +1 -0
  10. package/dist/{agents-typed-client-CHMVW7MK.js → agents-typed-client-ZP7BKJB3.js} +1 -1
  11. package/dist/agents-typed-client-ZP7BKJB3.js.map +1 -0
  12. package/dist/{app-typed-client-6YZRDAPY.js → app-typed-client-GDF2OMJ2.js} +8 -8
  13. package/dist/app-typed-client-GDF2OMJ2.js.map +1 -0
  14. package/dist/{app-typed-client-V77SVU2O.js → app-typed-client-USLAMN7X.js} +7 -7
  15. package/dist/app-typed-client-USLAMN7X.js.map +1 -0
  16. package/dist/{aws-lambda-7GSCNLPY.js → aws-lambda-473QCOL6.js} +3 -3
  17. package/dist/{body-parser-web-MUWBKZ3F.js → body-parser-web-NNEJGX6Y.js} +1 -1
  18. package/dist/body-parser-web-NNEJGX6Y.js.map +1 -0
  19. package/dist/{body-parser-web-FV5HWCY3.js → body-parser-web-TIOTXPDW.js} +1 -1
  20. package/dist/body-parser-web-TIOTXPDW.js.map +1 -0
  21. package/dist/{build-BYLQZJT2.js → build-MQHIJROR.js} +11 -11
  22. package/dist/{build-BYLQZJT2.js.map → build-MQHIJROR.js.map} +1 -1
  23. package/dist/{build-request-body-preview-EOP2Y4F3.js → build-request-body-preview-FVBQ7LCE.js} +1 -1
  24. package/dist/build-request-body-preview-FVBQ7LCE.js.map +1 -0
  25. package/dist/{build-request-body-preview-QMWD2IXK.js → build-request-body-preview-XPZ2GYMG.js} +1 -1
  26. package/dist/build-request-body-preview-XPZ2GYMG.js.map +1 -0
  27. package/dist/{bun-KP2KES6S.js → bun-OQUCL3XW.js} +3 -3
  28. package/dist/{check-PD2FTKMM.js → check-45NKUVSQ.js} +1 -1
  29. package/dist/check-45NKUVSQ.js.map +1 -0
  30. package/dist/{chunk-FRUEDJFX.js → chunk-226KMIGZ.js} +3 -3
  31. package/dist/{chunk-FRUEDJFX.js.map → chunk-226KMIGZ.js.map} +1 -1
  32. package/dist/{chunk-U3NTEK46.js → chunk-26ECIX74.js} +2 -2
  33. package/dist/{chunk-FEDSPOY6.js → chunk-2WH6SD3C.js} +6 -6
  34. package/dist/chunk-2WH6SD3C.js.map +1 -0
  35. package/dist/{chunk-JAIKGP3Q.js → chunk-47VNWTL4.js} +1 -1
  36. package/dist/chunk-47VNWTL4.js.map +1 -0
  37. package/dist/{chunk-D7ZH7DTG.js → chunk-4B2ZMX45.js} +1 -1
  38. package/dist/chunk-4B2ZMX45.js.map +1 -0
  39. package/dist/{chunk-IHJZPQEF.js → chunk-4HAU7AJM.js} +3 -3
  40. package/dist/chunk-4HAU7AJM.js.map +1 -0
  41. package/dist/{chunk-IPC5UREF.js → chunk-575PAX5L.js} +17 -17
  42. package/dist/chunk-575PAX5L.js.map +1 -0
  43. package/dist/{chunk-X2VVCJ4V.js → chunk-65EFIUDD.js} +1 -1
  44. package/dist/chunk-65EFIUDD.js.map +1 -0
  45. package/dist/{chunk-GY5Q27BJ.js → chunk-6FK7FKY6.js} +1 -1
  46. package/dist/{chunk-GY5Q27BJ.js.map → chunk-6FK7FKY6.js.map} +1 -1
  47. package/dist/{chunk-GSO77FSM.js → chunk-6OXCZMW3.js} +45 -47
  48. package/dist/chunk-6OXCZMW3.js.map +1 -0
  49. package/dist/{chunk-P37RZRFV.js → chunk-A7JBF5FO.js} +1 -1
  50. package/dist/chunk-A7JBF5FO.js.map +1 -0
  51. package/dist/{chunk-AFVTEAES.js → chunk-CJNMJUHE.js} +2 -2
  52. package/dist/{chunk-AXVFVMLM.js → chunk-DJFMAWH5.js} +8 -4
  53. package/dist/chunk-DJFMAWH5.js.map +1 -0
  54. package/dist/{chunk-2ZX4J4SX.js → chunk-DQVBL2G4.js} +58 -56
  55. package/dist/chunk-DQVBL2G4.js.map +1 -0
  56. package/dist/{chunk-GW5H4KB4.js → chunk-FX72VHAE.js} +3 -3
  57. package/dist/{chunk-5AVPWHUE.js → chunk-HGUZWG2C.js} +7 -4
  58. package/dist/chunk-HGUZWG2C.js.map +1 -0
  59. package/dist/{chunk-UNLG36Z5.js → chunk-IE6C4KZX.js} +10 -5
  60. package/dist/chunk-IE6C4KZX.js.map +1 -0
  61. package/dist/{chunk-QWBXUZAX.js → chunk-JIL74SFK.js} +4 -4
  62. package/dist/chunk-JIL74SFK.js.map +1 -0
  63. package/dist/{chunk-KI7OWQUX.js → chunk-L2S2R3TI.js} +63 -20
  64. package/dist/chunk-L2S2R3TI.js.map +1 -0
  65. package/dist/{chunk-L4GCEMNW.js → chunk-LNVMHQ2Z.js} +2 -2
  66. package/dist/{chunk-SPJNVWOK.js → chunk-N2D5AVRR.js} +2 -3
  67. package/dist/chunk-N2D5AVRR.js.map +1 -0
  68. package/dist/{chunk-UO7WS32S.js → chunk-OI6DK6ZJ.js} +3 -3
  69. package/dist/chunk-OI6DK6ZJ.js.map +1 -0
  70. package/dist/{chunk-RMU7EBRO.js → chunk-OP7QCTR5.js} +2 -2
  71. package/dist/{chunk-RMU7EBRO.js.map → chunk-OP7QCTR5.js.map} +1 -1
  72. package/dist/{chunk-GUUWDMR2.js → chunk-OVHW23YC.js} +2 -2
  73. package/dist/{chunk-NQRNDPZJ.js → chunk-OXCALO3W.js} +3 -3
  74. package/dist/{chunk-45C3WUQ7.js → chunk-QPVXGC7O.js} +1 -1
  75. package/dist/chunk-QPVXGC7O.js.map +1 -0
  76. package/dist/{chunk-FOZIR3TG.js → chunk-SMP2T335.js} +2 -2
  77. package/dist/{chunk-M6NMS5LR.js → chunk-TDNNBLGW.js} +1 -1
  78. package/dist/chunk-TDNNBLGW.js.map +1 -0
  79. package/dist/{chunk-WFNLNIJX.js → chunk-VPISAMXU.js} +2 -2
  80. package/dist/{chunk-5PU65T5W.js → chunk-XZ6B2Y2R.js} +1 -1
  81. package/dist/chunk-XZ6B2Y2R.js.map +1 -0
  82. package/dist/cli/index.js +15 -15
  83. package/dist/client/index.d.ts +1 -1
  84. package/dist/client/index.js +20 -25
  85. package/dist/client/index.js.map +1 -1
  86. package/dist/{cloudflare-C6E5SPAE.js → cloudflare-4YT5CK3P.js} +3 -3
  87. package/dist/{controller-swc-transform-URELVCBM.js → controller-swc-transform-JJRMTSDY.js} +1 -1
  88. package/dist/controller-swc-transform-JJRMTSDY.js.map +1 -0
  89. package/dist/{controller-swc-transform-XV3ETSE3.js → controller-swc-transform-LUJ4VAZJ.js} +1 -1
  90. package/dist/controller-swc-transform-LUJ4VAZJ.js.map +1 -0
  91. package/dist/{db-3UNAMSFK.js → db-IVVCQE5Z.js} +1 -2
  92. package/dist/db-IVVCQE5Z.js.map +1 -0
  93. package/dist/{deno-deploy-RFZN56X4.js → deno-deploy-YYN6BNLF.js} +3 -3
  94. package/dist/{dev-PS2NGT6I.js → dev-WQ4LWCAW.js} +13 -13
  95. package/dist/{dev-emit-2DL3MCLM.js → dev-emit-HLGJK3PP.js} +3 -3
  96. package/dist/dev-emit-HLGJK3PP.js.map +1 -0
  97. package/dist/{dev-emit-XVTJXZGA.js → dev-emit-J7V6GWSK.js} +6 -6
  98. package/dist/devtools/entry.js +43 -15
  99. package/dist/devtools/entry.js.map +1 -1
  100. package/dist/{dispatcher-63LBXYLE.js → dispatcher-DLKIXYNO.js} +2 -2
  101. package/dist/{dispatcher-EJHL6JMJ.js → dispatcher-KMZBGMM5.js} +1 -1
  102. package/dist/dispatcher-KMZBGMM5.js.map +1 -0
  103. package/dist/{generate-5X4LG77M.js → generate-GXWPUVS7.js} +4 -5
  104. package/dist/generate-GXWPUVS7.js.map +1 -0
  105. package/dist/index.js +9 -9
  106. package/dist/{info-2OOXFTJX.js → info-75U6GCMD.js} +4 -4
  107. package/dist/info-75U6GCMD.js.map +1 -0
  108. package/dist/{internal-api-LFW7R65K.js → internal-api-DV3H5NNV.js} +7 -9
  109. package/dist/{internal-api-FBFV265J.js → internal-api-JFORKYLR.js} +8 -10
  110. package/dist/{load-config-3EAQTXPH.js → load-config-XP7NSSA7.js} +4 -4
  111. package/dist/{mcp-ML4QK5ON.js → mcp-FF3NTCHB.js} +6 -6
  112. package/dist/mcp-FF3NTCHB.js.map +1 -0
  113. package/dist/{netlify-PMLHVPN4.js → netlify-2WZUQYI3.js} +3 -3
  114. package/dist/node-CMAYKDCM.js +10 -0
  115. package/dist/{openapi-2HVGJMSN.js → openapi-ZPXYRAM2.js} +9 -9
  116. package/dist/openapi-ZPXYRAM2.js.map +1 -0
  117. package/dist/registry-72YH7ZJM.js +23 -0
  118. package/dist/registry-72YH7ZJM.js.map +1 -0
  119. package/dist/{router-TLEAOFID.js → router-6MAACS25.js} +1 -2
  120. package/dist/router-6MAACS25.js.map +1 -0
  121. package/dist/{routes-XNS3UM3B.js → routes-ZVDKABXZ.js} +6 -6
  122. package/dist/schema-FBOTN46F.js +22 -0
  123. package/dist/server/agent/index.js +1 -1
  124. package/dist/server/cost/index.js +1 -1
  125. package/dist/server/cron/index.js +2 -2
  126. package/dist/server/http/index.js +3 -3
  127. package/dist/server/index.js +11 -11
  128. package/dist/server/jobs/index.js +3 -3
  129. package/dist/server/observability/index.d.ts +1 -38
  130. package/dist/server/observability/index.js +2 -2
  131. package/dist/server/scan/index.js +2 -2
  132. package/dist/{server-routes-hmr-VZXOP5YT.js → server-routes-hmr-4W5L2MKN.js} +1 -1
  133. package/dist/server-routes-hmr-4W5L2MKN.js.map +1 -0
  134. package/dist/{server-routes-hmr-PBHSKCQJ.js → server-routes-hmr-RI7SYNT2.js} +1 -1
  135. package/dist/server-routes-hmr-RI7SYNT2.js.map +1 -0
  136. package/dist/{services-json-Y3XODNB5.js → services-json-7ZXJ4CIS.js} +1 -1
  137. package/dist/services-json-7ZXJ4CIS.js.map +1 -0
  138. package/dist/{services-typed-client-IETY2SAK.js → services-typed-client-AU6DKXAO.js} +2 -2
  139. package/dist/services-typed-client-AU6DKXAO.js.map +1 -0
  140. package/dist/{services-typed-client-32KMTTXR.js → services-typed-client-EO4RFNTZ.js} +2 -2
  141. package/dist/services-typed-client-EO4RFNTZ.js.map +1 -0
  142. package/dist/{start-YLR2SFHU.js → start-2U3FUCJX.js} +12 -12
  143. package/dist/start-2U3FUCJX.js.map +1 -0
  144. package/dist/{static-MB2CD5Y3.js → static-25H5K42R.js} +3 -3
  145. package/dist/{static-MB2CD5Y3.js.map → static-25H5K42R.js.map} +1 -1
  146. package/dist/{theo-cloud-DQRP6S6M.js → theo-cloud-JL2KXHIS.js} +2 -2
  147. package/dist/{upgrade-readiness-ACGW44JC.js → upgrade-readiness-77P6VNB4.js} +1 -1
  148. package/dist/upgrade-readiness-77P6VNB4.js.map +1 -0
  149. package/dist/{vercel-J6G7ZHYQ.js → vercel-FP3C6LN6.js} +3 -3
  150. package/dist/vite-plugin/index.js +9 -9
  151. package/dist/{vite-plugin-6VVU6PPC.js → vite-plugin-D2NTPZNC.js} +13 -13
  152. package/package.json +4 -7
  153. package/dist/actions-virtual-module-LD3YKWIX.js.map +0 -1
  154. package/dist/actions-virtual-module-N7GKUS3D.js.map +0 -1
  155. package/dist/add-W6FNTAFS.js.map +0 -1
  156. package/dist/agents-typed-client-CHMVW7MK.js.map +0 -1
  157. package/dist/agents-typed-client-NJ73Z6XY.js.map +0 -1
  158. package/dist/app-typed-client-6YZRDAPY.js.map +0 -1
  159. package/dist/app-typed-client-V77SVU2O.js.map +0 -1
  160. package/dist/body-parser-web-FV5HWCY3.js.map +0 -1
  161. package/dist/body-parser-web-MUWBKZ3F.js.map +0 -1
  162. package/dist/build-request-body-preview-EOP2Y4F3.js.map +0 -1
  163. package/dist/build-request-body-preview-QMWD2IXK.js.map +0 -1
  164. package/dist/check-PD2FTKMM.js.map +0 -1
  165. package/dist/chunk-2ZX4J4SX.js.map +0 -1
  166. package/dist/chunk-45C3WUQ7.js.map +0 -1
  167. package/dist/chunk-5AVPWHUE.js.map +0 -1
  168. package/dist/chunk-5PU65T5W.js.map +0 -1
  169. package/dist/chunk-AXVFVMLM.js.map +0 -1
  170. package/dist/chunk-D7ZH7DTG.js.map +0 -1
  171. package/dist/chunk-FEDSPOY6.js.map +0 -1
  172. package/dist/chunk-GSO77FSM.js.map +0 -1
  173. package/dist/chunk-IHJZPQEF.js.map +0 -1
  174. package/dist/chunk-IPC5UREF.js.map +0 -1
  175. package/dist/chunk-JAIKGP3Q.js.map +0 -1
  176. package/dist/chunk-KI7OWQUX.js.map +0 -1
  177. package/dist/chunk-M6NMS5LR.js.map +0 -1
  178. package/dist/chunk-P37RZRFV.js.map +0 -1
  179. package/dist/chunk-QWBXUZAX.js.map +0 -1
  180. package/dist/chunk-SPJNVWOK.js.map +0 -1
  181. package/dist/chunk-UNLG36Z5.js.map +0 -1
  182. package/dist/chunk-UO7WS32S.js.map +0 -1
  183. package/dist/chunk-X2VVCJ4V.js.map +0 -1
  184. package/dist/controller-swc-transform-URELVCBM.js.map +0 -1
  185. package/dist/controller-swc-transform-XV3ETSE3.js.map +0 -1
  186. package/dist/db-3UNAMSFK.js.map +0 -1
  187. package/dist/dev-emit-2DL3MCLM.js.map +0 -1
  188. package/dist/dispatcher-EJHL6JMJ.js.map +0 -1
  189. package/dist/generate-5X4LG77M.js.map +0 -1
  190. package/dist/info-2OOXFTJX.js.map +0 -1
  191. package/dist/mcp-ML4QK5ON.js.map +0 -1
  192. package/dist/node-BPJ3Z4DT.js +0 -10
  193. package/dist/openapi-2HVGJMSN.js.map +0 -1
  194. package/dist/registry-FKPH7XEL.js +0 -24
  195. package/dist/registry-FKPH7XEL.js.map +0 -1
  196. package/dist/router-TLEAOFID.js.map +0 -1
  197. package/dist/schema-LYOLNHZ7.js +0 -30
  198. package/dist/server-routes-hmr-PBHSKCQJ.js.map +0 -1
  199. package/dist/server-routes-hmr-VZXOP5YT.js.map +0 -1
  200. package/dist/services-json-Y3XODNB5.js.map +0 -1
  201. package/dist/services-typed-client-32KMTTXR.js.map +0 -1
  202. package/dist/services-typed-client-IETY2SAK.js.map +0 -1
  203. package/dist/start-YLR2SFHU.js.map +0 -1
  204. package/dist/upgrade-readiness-ACGW44JC.js.map +0 -1
  205. /package/dist/{agent-U35G3WNE.js.map → agent-OXRRKB55.js.map} +0 -0
  206. /package/dist/{aws-lambda-7GSCNLPY.js.map → aws-lambda-473QCOL6.js.map} +0 -0
  207. /package/dist/{bun-KP2KES6S.js.map → bun-OQUCL3XW.js.map} +0 -0
  208. /package/dist/{chunk-U3NTEK46.js.map → chunk-26ECIX74.js.map} +0 -0
  209. /package/dist/{chunk-AFVTEAES.js.map → chunk-CJNMJUHE.js.map} +0 -0
  210. /package/dist/{chunk-GW5H4KB4.js.map → chunk-FX72VHAE.js.map} +0 -0
  211. /package/dist/{chunk-L4GCEMNW.js.map → chunk-LNVMHQ2Z.js.map} +0 -0
  212. /package/dist/{chunk-GUUWDMR2.js.map → chunk-OVHW23YC.js.map} +0 -0
  213. /package/dist/{chunk-NQRNDPZJ.js.map → chunk-OXCALO3W.js.map} +0 -0
  214. /package/dist/{chunk-FOZIR3TG.js.map → chunk-SMP2T335.js.map} +0 -0
  215. /package/dist/{chunk-WFNLNIJX.js.map → chunk-VPISAMXU.js.map} +0 -0
  216. /package/dist/{cloudflare-C6E5SPAE.js.map → cloudflare-4YT5CK3P.js.map} +0 -0
  217. /package/dist/{deno-deploy-RFZN56X4.js.map → deno-deploy-YYN6BNLF.js.map} +0 -0
  218. /package/dist/{dev-PS2NGT6I.js.map → dev-WQ4LWCAW.js.map} +0 -0
  219. /package/dist/{dev-emit-XVTJXZGA.js.map → dev-emit-J7V6GWSK.js.map} +0 -0
  220. /package/dist/{dispatcher-63LBXYLE.js.map → dispatcher-DLKIXYNO.js.map} +0 -0
  221. /package/dist/{internal-api-FBFV265J.js.map → internal-api-DV3H5NNV.js.map} +0 -0
  222. /package/dist/{internal-api-LFW7R65K.js.map → internal-api-JFORKYLR.js.map} +0 -0
  223. /package/dist/{load-config-3EAQTXPH.js.map → load-config-XP7NSSA7.js.map} +0 -0
  224. /package/dist/{netlify-PMLHVPN4.js.map → netlify-2WZUQYI3.js.map} +0 -0
  225. /package/dist/{node-BPJ3Z4DT.js.map → node-CMAYKDCM.js.map} +0 -0
  226. /package/dist/{routes-XNS3UM3B.js.map → routes-ZVDKABXZ.js.map} +0 -0
  227. /package/dist/{schema-LYOLNHZ7.js.map → schema-FBOTN46F.js.map} +0 -0
  228. /package/dist/{theo-cloud-DQRP6S6M.js.map → theo-cloud-JL2KXHIS.js.map} +0 -0
  229. /package/dist/{vercel-J6G7ZHYQ.js.map → vercel-FP3C6LN6.js.map} +0 -0
  230. /package/dist/{vite-plugin-6VVU6PPC.js.map → vite-plugin-D2NTPZNC.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/start/index.ts","../src/server/define/health-route.ts","../src/cli/commands/start/assert-sdk-compatible.ts","../src/server/agent/sdk-compat.ts","../src/cli/commands/start/bootstrap-stages.ts","../src/cli/commands/start/graceful-shutdown.ts","../src/cli/commands/start/manifest-loader.ts","../src/cli/commands/start/request-handler.ts","../src/cli/commands/start/handlers.ts","../src/server/http/static.ts","../src/cli/commands/start/ssr-setup.ts","../src/cli/commands/start/websocket-handler.ts"],"sourcesContent":["/**\n * theokit start — production server orchestration spine.\n *\n * T4.2 (architecture-cleanup, ADR-0017): stages extracted to sibling modules.\n * - start-bootstrap-stages.ts — config/registry/storage bootstrap + resolveSsrEntry\n * - start-manifest-loader.ts — manifest.json or scan fallback\n * - start-ssr-setup.ts — SSR entry-server + HTML template split\n * - start-handlers.ts — branch handlers (action/route/static/404)\n * - start-request-handler.ts — request lifecycle wiring\n * - start-websocket-handler.ts — WS upgrade (opt-in)\n * - start-graceful-shutdown.ts — SIGTERM/SIGINT drain\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { createServer } from 'node:http'\nimport { join, resolve } from 'node:path'\n\nimport { loadConfig } from '../../../config/load-config.js'\nimport { loadEnv } from '../../../config/load-env.js'\nimport { defineHealthRoute } from '../../../server/define/health-route.js'\nimport { createPluginRunnerFromConfig } from '../../../server/plugins/load-plugins.js'\nimport { createRateLimiter } from '../../../server/rate-limit/rate-limit.js'\nimport { createProductionLoader } from '../../../server/scan/module-loader.js'\nimport { resolveTransformer } from '../../../server/transformer.js'\nimport { preflightNodeAndBindings } from '../../preflight-node-version.js'\n\nimport { assertSdkCompatible } from './assert-sdk-compatible.js'\nimport {\n configureAgentRegistryFromConfig,\n configureStorageManagerFromConfig,\n} from './bootstrap-stages.js'\nimport { installGracefulShutdown } from './graceful-shutdown.js'\nimport type { RequestHandlerCtx } from './handlers.js'\nimport { loadRoutesAndActions } from './manifest-loader.js'\nimport { createRequestHandler } from './request-handler.js'\nimport { setupSsr } from './ssr-setup.js'\nimport { attachWebSocketHandler } from './websocket-handler.js'\n\n// Backwards-compat: external test fixtures may import resolveSsrEntry from here.\nexport { resolveSsrEntry } from './bootstrap-stages.js'\n\ninterface StartOptions {\n port?: number\n}\n\nexport async function startCommand(options: StartOptions): Promise<void> {\n const cwd = process.cwd()\n // Preflight (FIRST — BEFORE anything that touches native bindings).\n preflightNodeAndBindings(cwd)\n loadEnv({ cwd, mode: 'production' })\n const config = await loadConfig(cwd)\n\n // M48 — fail fast if the installed @theokit/sdk is present but incompatible (before serving any\n // request). Absent SDK stays silent here (an api-only app is valid); the request path guards it lazily.\n assertSdkCompatible()\n\n await configureAgentRegistryFromConfig(config.agents?.registry)\n await configureStorageManagerFromConfig(config.storage)\n\n const distDir = resolve(cwd, '.theokit')\n const clientDir = resolve(distDir, 'client')\n // #95 — honor config `serverDir` (default \"server\") in production start, matching dev.\n const serverDir = resolve(cwd, config.serverDir)\n\n if (!existsSync(clientDir)) {\n throw new Error('No build found. Run `theo build` first.')\n }\n\n const indexHtml = readFileSync(join(clientDir, 'index.html'), 'utf-8')\n const loadModule = createProductionLoader()\n const port = options.port ?? config.port\n const pluginRunner = await createPluginRunnerFromConfig(config.plugins)\n const transformer = resolveTransformer(config.serialization)\n\n const custom404Path = join(clientDir, '404.html')\n const custom500Path = join(clientDir, '500.html')\n const custom404Html = existsSync(custom404Path) ? readFileSync(custom404Path, 'utf-8') : null\n const custom500Html = existsSync(custom500Path) ? readFileSync(custom500Path, 'utf-8') : null\n\n const {\n routes: cachedRoutes,\n actions: cachedActions,\n wsRoutes: cachedWsRoutes,\n agents: cachedAgents,\n } = loadRoutesAndActions(distDir, serverDir, config.agentsDir)\n\n // Rate limiter (legacy flat form only — per-route variant is handled in\n // api-middleware integration path, not this fallback).\n const flatRateLimit =\n config.rateLimit && 'windowMs' in config.rateLimit && 'max' in config.rateLimit\n ? config.rateLimit\n : undefined\n const rateLimiter = flatRateLimit ? createRateLimiter(flatRateLimit) : null\n\n const ssr = await setupSsr({\n distDir,\n indexHtml,\n ssrConfigEnabled: config.ssr,\n ssrStreamingConfig: config.ssrStreaming,\n })\n\n const server = createServer(\n createRequestHandler({\n buildCtx: (req, res, requestId, startTime): RequestHandlerCtx => ({\n req,\n res,\n url: req.url ?? '/',\n requestId,\n startTime,\n clientDir,\n custom404Html,\n cachedRoutes,\n cachedActions,\n cachedAgents,\n loadModule,\n serverDir,\n projectRoot: cwd,\n pluginRunner,\n transformer,\n csrfMode: config.security?.csrf ?? 'strict',\n disallowed: config.security?.disallowed,\n rateLimiter,\n }),\n securityHeadersConfig: config.security?.headers ?? {},\n ssrRender: ssr.render,\n ssrRenderStreaming: ssr.renderStreaming,\n ssrStreamingEnabled: ssr.streamingEnabled,\n htmlHead: ssr.htmlHead,\n htmlTail: ssr.htmlTail,\n indexHtml,\n custom500Html,\n // M7-2: serve a built-in liveness route on the Node listener. Readiness\n // probe wiring from theo.config.ts is a documented follow-up (see the M7\n // implementation summary § Scope note).\n reservedRoutes: { health: defineHealthRoute() },\n }),\n )\n\n await attachWebSocketHandler(server, cachedWsRoutes, loadModule)\n\n server.listen(port, () => {\n console.log(`\\n Theo production server`)\n console.log(` → http://localhost:${String(port)}\\n`)\n })\n\n installGracefulShutdown(server)\n}\n","/**\n * M7-2 — health/ready reserved routes for the convention/filesystem-route\n * server. Liveness (`/__theo/health`, always 200) and readiness\n * (`/__theo/ready`, 200/503 from a probe) are registered on a reserved\n * namespace BEFORE the user-route catch-all + 404 branch — mirroring nitro's\n * `/_nitro/*` reserved-namespace pattern (knowledge-base/references/nitro/src/\n * runtime/internal/routes/dev-tasks.ts). Liveness and readiness are kept\n * separate by design: liveness says \"the process is up\", readiness says\n * \"dependencies are up\".\n *\n * @public\n */\n\n/** Reserved path for the liveness endpoint. */\nexport const HEALTH_PATH = '/__theo/health'\n/** Reserved path for the readiness endpoint. */\nexport const READY_PATH = '/__theo/ready'\n\n/** Config produced by {@link defineHealthRoute}. */\nexport interface HealthRouteConfig {\n readonly kind: 'health'\n /** Returns the liveness body (auto-serialized to JSON). Default: `{ status: 'ok' }`. */\n readonly handler: () => unknown\n}\n\n/** Config produced by {@link defineReadyRoute}. */\nexport interface ReadyRouteConfig {\n readonly kind: 'ready'\n /** Resolves `true` when dependencies are ready. A throw/reject is treated as not-ready (503). */\n readonly probe: () => boolean | Promise<boolean>\n}\n\n/** The reserved-route registry consulted by {@link serveReservedRoute}. */\nexport interface ReservedRoutes {\n readonly health?: HealthRouteConfig\n readonly ready?: ReadyRouteConfig\n}\n\n/** A reserved-route response: an HTTP status + a JSON-serializable body. */\nexport interface ReservedResponse {\n readonly status: number\n readonly body: unknown\n}\n\n/**\n * Define the liveness route. The default handler returns `{ status: 'ok' }`.\n * Liveness is always 200 — it asserts the process is up, not that dependencies are.\n */\nexport function defineHealthRoute(\n handler: () => unknown = () => ({ status: 'ok' }),\n): HealthRouteConfig {\n return { kind: 'health', handler }\n}\n\n/**\n * Define the readiness route. The `probe` decides 200 (ready) vs 503 (not-ready).\n * A probe that throws/rejects is treated as not-ready (503) — never a 500 crash.\n */\nexport function defineReadyRoute(probe: () => boolean | Promise<boolean>): ReadyRouteConfig {\n return { kind: 'ready', probe }\n}\n\n/**\n * Pure dispatcher: map a request pathname to a reserved-route response, or\n * `null` when the path is not reserved (so the user catch-all + 404 take over).\n * Liveness defaults to 200 `{status:'ok'}`; readiness without a probe is\n * trivially ready (200). Registered BEFORE the user catch-all by the caller.\n */\nexport async function serveReservedRoute(\n pathname: string,\n routes: ReservedRoutes = {},\n): Promise<ReservedResponse | null> {\n if (pathname === HEALTH_PATH) {\n const handler = routes.health?.handler ?? (() => ({ status: 'ok' }))\n return { status: 200, body: handler() }\n }\n if (pathname === READY_PATH) {\n const probe = routes.ready?.probe\n if (probe === undefined) {\n return { status: 200, body: { status: 'ready' } }\n }\n try {\n const ready = await probe()\n return ready\n ? { status: 200, body: { status: 'ready' } }\n : { status: 503, body: { status: 'not-ready' } }\n } catch (err) {\n // 503 (the dependency is not ready) but NEVER swallow the cause — a\n // readiness probe failing silently is invisible to ops (project rule:\n // \"NUNCA engula exceções\"). Log the cause, keep the 503 contract.\n console.error('[theo] readiness probe threw — treating as not-ready', err)\n return { status: 503, body: { status: 'not-ready' } }\n }\n }\n return null\n}\n","/**\n * M48 (ecosystem-integration-guarantee) T3.2 — boot-time SDK compatibility fail-fast.\n *\n * The agent runtime is `@theokit/sdk` (G2). Today a missing / mis-versioned SDK is invisible until\n * the FIRST agent request, where `sdk-adapter.ts` yields a lazy `SDK_NOT_INSTALLED` stream event.\n * This runs at `theokit start` boot instead: if the installed SDK is present but outside the\n * supported range it throws a typed error naming found-vs-required; if it is absent (a legitimately\n * api-only app — the SDK is an OPTIONAL peer) it stays silent unless the caller marks it required.\n *\n * CLI/adapter layer → `node:*` is allowed here (unlike `server/`). The version range check itself is\n * the pure `server/agent/sdk-compat.ts` helper (one source of truth with the contract-test drift guard).\n */\nimport { readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\n\nimport { SUPPORTED_SDK_RANGE, satisfiesSdkRange } from '../../../server/agent/sdk-compat.js'\n\n/** Typed error surfaced at boot when the installed `@theokit/sdk` is incompatible or absent-but-required. */\nexport class SdkIncompatibleError extends Error {\n readonly code = 'SDK_INCOMPATIBLE' as const\n readonly found: string | undefined\n readonly required: string\n constructor(found: string | undefined, required: string) {\n super(\n found === undefined\n ? `@theokit/sdk is required but not installed — run: pnpm add @theokit/sdk@${required}`\n : `@theokit/sdk ${found} does not satisfy the required range ${required} — run: pnpm add @theokit/sdk@${required}`,\n )\n this.name = 'SdkIncompatibleError'\n this.found = found\n this.required = required\n }\n}\n\n/** Resolve the version of the ACTUALLY-installed `@theokit/sdk`, or `undefined` when absent. */\nfunction defaultResolveSdkVersion(): string | undefined {\n try {\n const require = createRequire(import.meta.url)\n const pkgPath = require.resolve('@theokit/sdk/package.json')\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { version?: string }\n return typeof pkg.version === 'string' ? pkg.version : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Fail fast at boot when the installed `@theokit/sdk` is incompatible.\n *\n * - present + in range → returns (silent)\n * - present + out of range → throws {@link SdkIncompatibleError} (found + required)\n * - absent + `required !== true` → returns (api-only app; the request path still guards lazily)\n * - absent + `required === true` → throws {@link SdkIncompatibleError}\n *\n * `resolveVersion` is injectable for tests (DIP); production uses {@link defaultResolveSdkVersion}.\n */\nexport function assertSdkCompatible(opts?: {\n required?: boolean\n resolveVersion?: () => string | undefined\n}): void {\n const version = (opts?.resolveVersion ?? defaultResolveSdkVersion)()\n if (version === undefined) {\n if (opts?.required === true) throw new SdkIncompatibleError(undefined, SUPPORTED_SDK_RANGE)\n return\n }\n if (!satisfiesSdkRange(version, SUPPORTED_SDK_RANGE)) {\n throw new SdkIncompatibleError(version, SUPPORTED_SDK_RANGE)\n }\n}\n","/**\n * M48 (ecosystem-integration-guarantee) — the supported `@theokit/sdk` version range + a pure,\n * dependency-free `||`-aware caret semver check. Shared by the contract test's version-drift guard\n * (`tests/integration/contract-sdk-seam.test.ts`) and the boot-time fail-fast\n * (`cli/commands/start/assert-sdk-compatible.ts`) — one source of truth for \"which SDK theokit runs on\".\n *\n * Web-Standards discipline (G8/R3a): `server/` code uses no `node:*`. This is pure string logic.\n * Rule 9 (Don't Reinvent) trade-off (ADR D1): a small inline caret checker instead of a `semver`\n * dependency, matching the theo-ui seam's existing precedent (`contract-usetheo-ui-vite-plugin.test.ts`).\n */\n\n/** The single source of truth for the supported SDK range. Mirrors the `package.json` peer floor. */\nexport const SUPPORTED_SDK_RANGE = '^4.0.1'\n\n// Bounded semver: three `\\d+` tuples + an optional `-tag.N` prerelease. No nested quantifiers →\n// no catastrophic backtracking; the security/detect-unsafe-regex heuristic false-positives here.\n// eslint-disable-next-line security/detect-unsafe-regex -- bounded \\d+ groups anchored by `.`/`$`, no backtracking\nconst SEMVER_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([a-z]+)\\.(\\d+))?$/\n\ninterface Semver {\n major: string\n minor: string\n patch: string\n tag: string | undefined\n pre: string | undefined\n}\n\nfunction parseSemver(value: string): Semver | null {\n const m = SEMVER_RE.exec(value)\n if (!m) return null\n return { major: m[1], minor: m[2], patch: m[3], tag: m[4], pre: m[5] }\n}\n\n/**\n * Return `true` when `version` satisfies `range`, where `range` is a `||`-joined series of caret\n * pins (e.g. `^4.0.1` or `^0.14.0 || ^1.0.0`). A version satisfies the range when it satisfies ANY\n * clause. Covers the semver subset the monorepo uses (caret pins, optional `-tag.N` prerelease);\n * no range-sets or build metadata.\n */\nexport function satisfiesSdkRange(version: string, range: string): boolean {\n return range\n .split('||')\n .map((clause) => clause.trim())\n .some((clause) => satisfiesSingleCaret(version, clause))\n}\n\nfunction satisfiesSingleCaret(version: string, range: string): boolean {\n if (!range.startsWith('^')) return false\n const pin = parseSemver(range.slice(1))\n const ver = parseSemver(version)\n if (!pin || !ver) return false\n if (pin.tag !== undefined) return satisfiesPrereleaseCaret(ver, pin)\n if (ver.tag !== undefined) return false // a prerelease never satisfies a stable caret pin\n return satisfiesStableCaret(ver, pin)\n}\n\nfunction satisfiesPrereleaseCaret(ver: Semver, pin: Semver): boolean {\n // Prerelease pin: same X.Y.Z + same tag + prerelease number >= pin's.\n if (pin.major !== ver.major || pin.minor !== ver.minor || pin.patch !== ver.patch) return false\n if (ver.tag !== pin.tag) return false\n return Number(ver.pre ?? '0') >= Number(pin.pre ?? '0')\n}\n\nfunction satisfiesStableCaret(ver: Semver, pin: Semver): boolean {\n if (pin.major !== ver.major) return false\n if (pin.major === '0') {\n // 0.X.Y caret: minor must match exactly; patch can be >=.\n if (pin.minor !== ver.minor) return false\n return Number(ver.patch) >= Number(pin.patch)\n }\n // >= 1.0.0 caret: minor can be >=, patch anything within the same/greater minor.\n if (Number(ver.minor) > Number(pin.minor)) return true\n if (Number(ver.minor) === Number(pin.minor)) return Number(ver.patch) >= Number(pin.patch)\n return false\n}\n","/**\n * Bootstrap stages extracted from `start.ts` per T4.2 (architecture-cleanup, ADR-0017).\n *\n * The full goal of T4.2 is a ≤30-LOC `startCommand` spine + 6-8 stage files. This\n * file ships the first batch: the configure-from-config bootstrap helpers + the\n * SSR entry resolver. They are stand-alone, side-effect-free at module load, and\n * already individually testable.\n *\n * Remaining stages (request-handler extraction, graceful-shutdown extraction,\n * signal-handlers extraction) are deferred to a follow-up sprint — see plan\n * `docs/plans/architecture-cleanup-plan.md` T4.2 Deferred sub-tasks.\n */\n\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\n\ninterface SdkAgentRegistry {\n configure?: (opts: { maxAgents?: number; idleTimeoutMs?: number }) => void\n}\ninterface SdkModule {\n Agent?: { registry?: SdkAgentRegistry }\n}\n\n/**\n * Configure SDK's Agent.registry from `theo.config.ts > agents.registry`.\n * Lazy at boot; EC-3 sync flag flip prevents race under concurrent boot.\n * Silent no-op when registry config is absent or SDK is uninstalled.\n */\nexport async function configureAgentRegistryFromConfig(\n registryConfig: { maxAgents: number; idleTimeoutMs: number } | undefined,\n): Promise<void> {\n if (registryConfig === undefined) return\n try {\n const sdk = (await import('@theokit/sdk').catch(() => null)) as SdkModule | null\n const sdkConfigure = sdk?.Agent?.registry?.configure\n if (sdkConfigure === undefined) return\n const { configureAgentRegistryOnce } =\n await import('../../../server/agent/configure-agent-registry.js')\n configureAgentRegistryOnce(\n {\n configure: (opts) => {\n sdkConfigure(opts)\n },\n },\n registryConfig,\n )\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.agent_registry_skip', {\n event: 'bootstrap.agent_registry_skip',\n message: msg,\n })\n }\n}\n\n/**\n * Configure the StorageManager from `theo.config.ts > storage` (ADR-0007).\n * Manager enforces configure-once internally (D3); this helper bridges the\n * config to the singleton with actionable error handling.\n */\nexport async function configureStorageManagerFromConfig(storageConfig: unknown): Promise<void> {\n if (storageConfig === undefined || storageConfig === null) return\n try {\n const { getStorageManager } = await import('../../../server/storage/storage-manager.js')\n const { storageSchema } = await import('../../../config/schema.js')\n // Re-validate at boot so a malformed config from a non-Zod source\n // (test fixtures, dynamic configs) surfaces a clear error early.\n const parsed = storageSchema.parse(storageConfig)\n getStorageManager().configure(parsed)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.storage_skip', {\n event: 'bootstrap.storage_skip',\n message: msg,\n })\n }\n}\n\nconst SSR_EXTENSIONS = ['.mjs', '.js'] as const\n\n/**\n * Resolve the SSR entry-server module path. tsup may emit `.mjs` or `.js`\n * depending on output format. Try `.mjs` first (modern default) then fall\n * back to `.js`. Returns null when neither exists — SSR stays disabled.\n *\n * Exported so unit tests can pin the resolution order without booting the\n * full CLI.\n */\nexport function resolveSsrEntry(distDir: string): string | null {\n for (const ext of SSR_EXTENSIONS) {\n const path = resolve(distDir, `server/entry-server${ext}`)\n\n if (existsSync(path)) return path\n }\n return null\n}\n","/**\n * Graceful shutdown stage for `theokit start` (T4.2 architecture-cleanup,\n * ADR-0007 D6 — SIGTERM evicts agents + drains StorageManager).\n *\n * EC-13: SIGTERM evicts agents IMMEDIATELY (no per-request drain). In-flight\n * requests get aborted mid-stream — acceptable because the platform LB\n * removed this pod from rotation BEFORE sending SIGTERM (K8s preStop hook +\n * terminationGracePeriodSeconds; same on Vercel/CF/Render).\n *\n * Re-entry guard: multiple SIGTERMs in quick succession run shutdown ONCE.\n */\n\nimport type { Server as HttpServer } from 'node:http'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\n\nexport function installGracefulShutdown(server: HttpServer): void {\n let shuttingDown = false\n const shutdown = (signal: NodeJS.Signals): void => {\n if (shuttingDown) return\n shuttingDown = true\n console.log(`\\n [theokit] ${signal} received — evicting agents`)\n void (async () => {\n // Lazy-import SDK only at shutdown time to avoid forcing the dep on\n // apps that don't use agents at all.\n try {\n const sdk = (await import('@theokit/sdk').catch(() => null)) as {\n Agent?: { registry?: { evictAll?: () => Promise<void> } }\n } | null\n if (sdk?.Agent?.registry?.evictAll !== undefined) {\n await sdk.Agent.registry.evictAll()\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('shutdown.evict_error', {\n event: 'shutdown.evict_error',\n message: msg,\n })\n }\n // T3.1 — drain the StorageManager AFTER agent eviction. Order matters:\n // agents may still hold open pool refs while evicting; closing pools\n // first would break in-flight queries.\n try {\n const { getStorageManager } = await import('../../../server/storage/storage-manager.js')\n const manager = getStorageManager()\n await manager.dispose()\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('shutdown.dispose_error', {\n event: 'shutdown.dispose_error',\n message: msg,\n })\n }\n console.log(` [theokit] shutdown complete`)\n server.close(() => {\n process.exit(0)\n })\n setTimeout(() => {\n warnOnce('shutdown.forced_exit', {\n event: 'shutdown.forced_exit',\n message: 'forced exit after 25s timeout',\n })\n process.exit(0)\n }, 25_000).unref()\n })()\n }\n process.on('SIGTERM', () => {\n shutdown('SIGTERM')\n })\n process.on('SIGINT', () => {\n shutdown('SIGINT')\n })\n}\n","/**\n * Manifest loading stage for `theokit start` (T4.2 architecture-cleanup).\n *\n * Loads pre-built manifest from `.theokit/manifest.json` if present; otherwise\n * scans server/ for routes/actions/ws at startup with a structured warn.\n */\n\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { dirname } from 'node:path'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\nimport type { ActionNode } from '../../../server/scan/action-scan.js'\nimport { scanServerActions } from '../../../server/scan/action-scan.js'\nimport type { AgentNode } from '../../../server/scan/agent-scan.js'\nimport { scanAgents } from '../../../server/scan/agent-scan.js'\nimport { loadManifest } from '../../../server/scan/manifest.js'\nimport type { ServerRouteNode } from '../../../server/scan/match.js'\nimport { scanServerRoutes } from '../../../server/scan/scan.js'\nimport type { WebSocketRouteNode } from '../../../server/scan/ws-scan.js'\nimport { scanWebSocketRoutes } from '../../../server/scan/ws-scan.js'\n\ninterface LoadedRoutes {\n routes: ServerRouteNode[]\n actions: ActionNode[]\n wsRoutes: WebSocketRouteNode[]\n agents: AgentNode[]\n}\n\nexport function loadRoutesAndActions(\n distDir: string,\n serverDir: string,\n // #95 follow-up — agents dir name (config `agentsDir`, default \"agents\") for the live-scan fallback.\n agentsDir = 'agents',\n): LoadedRoutes {\n const manifestPath = join(distDir, 'manifest.json')\n\n if (existsSync(manifestPath)) {\n const manifest = loadManifest(distDir, serverDir)\n return {\n routes: manifest.routes,\n actions: manifest.actions,\n wsRoutes: manifest.websockets,\n agents: manifest.agents,\n }\n }\n warnOnce('bootstrap.manifest_not_found', {\n event: 'bootstrap.manifest_not_found',\n message:\n 'No manifest found, scanning routes at startup. Run \"theo build\" to generate manifest.',\n serverDir,\n })\n return {\n routes: scanServerRoutes(serverDir),\n actions: scanServerActions(serverDir),\n wsRoutes: scanWebSocketRoutes(serverDir),\n // Agents live at <projectRoot>/<agentsDir>; projectRoot = serverDir's parent for the canonical layout.\n agents: scanAgents(dirname(serverDir), agentsDir),\n }\n}\n","/**\n * Inline request handler for `theokit start` (T4.2 architecture-cleanup).\n *\n * Wires the per-request flow: security headers → action/route/static branches\n * → SSR fallback → CSR fallback → 500 page.\n *\n * Refactored: CC reduced from 33 to ≤10 per function\n * (architecture-remediation T2.1, 2026-06-12).\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { generateNonce } from '../../../server/auth/nonce.js'\nimport { type ReservedRoutes, serveReservedRoute } from '../../../server/define/health-route.js'\nimport { sendError } from '../../../server/http/send-response.js'\nimport { buildSecurityHeaders } from '../../../server/security/security-headers.js'\n\nimport {\n tryServeAction,\n tryServeAgent,\n tryServeAgentAux,\n tryServeApiRoute,\n tryServeCustom404,\n tryServeStatic,\n type RequestHandlerCtx,\n} from './handlers.js'\nimport {\n isSsrRenderResult,\n type SsrRender,\n type SsrRenderResult,\n type SsrRenderStreaming,\n} from './ssr-setup.js'\n\ninterface RequestHandlerContext {\n buildCtx: (\n req: IncomingMessage,\n res: ServerResponse,\n requestId: string,\n startTime: number,\n ) => RequestHandlerCtx\n securityHeadersConfig: Parameters<typeof buildSecurityHeaders>[0]\n ssrRender: SsrRender | null\n ssrRenderStreaming: SsrRenderStreaming | null\n ssrStreamingEnabled: boolean\n htmlHead: string\n htmlTail: string\n indexHtml: string\n custom500Html: string | null\n /** M7-2: reserved health/ready routes served before the user catch-all. */\n reservedRoutes?: ReservedRoutes\n}\n\n/**\n * M7-2: serve a reserved `/__theo/*` route (health/ready) before any user\n * branch. Returns true when the request was handled.\n */\nasync function tryServeReserved(\n ctx: RequestHandlerContext,\n url: string,\n res: ServerResponse,\n): Promise<boolean> {\n const pathname = new URL(url, 'http://localhost').pathname\n const reserved = await serveReservedRoute(pathname, ctx.reservedRoutes ?? {})\n if (reserved === null) return false\n const payload = JSON.stringify(reserved.body)\n res.writeHead(reserved.status, {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(payload),\n })\n res.end(payload)\n return true\n}\n\nfunction asSsrRenderResult(value: SsrRenderResult): SsrRenderResult {\n return value\n}\n\nfunction isRedirectResult(result: unknown): result is { redirect: Response } {\n return result !== null && typeof result === 'object' && 'redirect' in result\n}\n\nfunction sendRedirect(res: ServerResponse, result: { redirect: Response }): void {\n res.writeHead(302, { Location: result.redirect.headers.get('location') ?? '/' })\n res.end()\n}\n\nfunction send500(res: ServerResponse, custom500Html: string | null): void {\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/html' })\n }\n if (!res.writableEnded) {\n res.end(custom500Html ?? '<h1>500 — Server Error</h1>')\n }\n}\n\nfunction buildSsrHtml(\n ctx: RequestHandlerContext,\n result: string | SsrRenderResult,\n nonce: string,\n): string {\n if (typeof result === 'string') {\n return ctx.htmlHead + result + ctx.htmlTail\n }\n if (isSsrRenderResult(result)) {\n const rendered = asSsrRenderResult(result)\n const dataJson = JSON.stringify(rendered.hydrationData).replace(/</g, '\\\\u003c')\n const hydrationScript = `<script${\n nonce ? ` nonce=\"${nonce}\"` : ''\n }>window.__staticRouterHydrationData=${dataJson}</script>`\n return ctx.htmlHead + rendered.html + hydrationScript + ctx.htmlTail\n }\n return ctx.htmlHead + ctx.htmlTail\n}\n\nasync function handleSsrStreaming(\n ctx: RequestHandlerContext,\n req: IncomingMessage,\n res: ServerResponse,\n url: string,\n nonce: string,\n): Promise<boolean> {\n if (!ctx.ssrStreamingEnabled || !ctx.ssrRenderStreaming) return false\n\n const controller = new AbortController()\n const onClose = (): void => {\n controller.abort()\n }\n req.on('close', onClose)\n try {\n const result = await ctx.ssrRenderStreaming(url, res, {\n signal: controller.signal,\n nonce,\n })\n if (isRedirectResult(result)) sendRedirect(res, result)\n return true\n } catch (streamErr) {\n console.error('[SSR Stream Error]', (streamErr as Error).message)\n send500(res, ctx.custom500Html)\n return true\n } finally {\n req.removeListener('close', onClose)\n }\n}\n\nasync function handleSsrSync(\n ctx: RequestHandlerContext,\n res: ServerResponse,\n url: string,\n nonce: string,\n): Promise<boolean> {\n if (!ctx.ssrRender) return false\n\n try {\n const result = await ctx.ssrRender(url, { nonce })\n if (isRedirectResult(result)) {\n sendRedirect(res, result)\n return true\n }\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(buildSsrHtml(ctx, result, nonce))\n return true\n } catch (ssrErr) {\n console.error('[SSR Error] Falling back to CSR:', (ssrErr as Error).message)\n return false\n }\n}\n\nfunction handleFatalError(ctx: RequestHandlerContext, res: ServerResponse, err: unknown): void {\n if (ctx.custom500Html && !res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/html' })\n res.end(ctx.custom500Html)\n } else if (!res.headersSent) {\n sendError(res, 'INTERNAL_ERROR', (err as Error).message, 500)\n } else {\n res.end()\n }\n}\n\nexport function createRequestHandler(\n ctx: RequestHandlerContext,\n): (req: IncomingMessage, res: ServerResponse) => void {\n return (req: IncomingMessage, res: ServerResponse) => {\n void (async () => {\n const url = req.url ?? '/'\n const requestId = randomUUID()\n const start = Date.now()\n\n const nonce = generateNonce()\n const securityHeaders = buildSecurityHeaders(\n ctx.securityHeadersConfig,\n { production: true },\n { nonce },\n )\n for (const [k, v] of Object.entries(securityHeaders)) {\n res.setHeader(k, v)\n }\n\n const handlerCtx = ctx.buildCtx(req, res, requestId, start)\n\n try {\n if (await tryServeReserved(ctx, url, res)) return\n if (await tryServeAction(handlerCtx)) return\n if (await tryServeAgentAux(handlerCtx)) return\n if (await tryServeAgent(handlerCtx)) return\n if (await tryServeApiRoute(handlerCtx)) return\n if (tryServeStatic(handlerCtx)) return\n if (tryServeCustom404(handlerCtx)) return\n\n if (await handleSsrStreaming(ctx, req, res, url, nonce)) return\n if (await handleSsrSync(ctx, res, url, nonce)) return\n\n // CSR fallback\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(ctx.indexHtml)\n } catch (err) {\n handleFatalError(ctx, res, err)\n }\n })()\n }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { extname } from 'node:path'\n\nimport { getApprovalRegistry } from '../../../server/agent/approval-registry.js'\nimport { handleAgentApproval, isApprovalPath } from '../../../server/agent/approve-agent.js'\nimport { mountAgent } from '../../../server/agent/mount-agent.js'\nimport { resolveProvider } from '../../../server/agent/provider-resolver.js'\nimport { serveAgentAuxRoute } from '../../../server/agent/serve-aux-routes.js'\nimport { executeAction } from '../../../server/http/action-execute.js'\nimport { executeRoute } from '../../../server/http/execute.js'\nimport {\n incomingMessageToWebRequest,\n writeWebResponseToServerResponse,\n} from '../../../server/http/node-web-adapter.js'\nimport { sendError } from '../../../server/http/send-response.js'\nimport { serveStaticFile } from '../../../server/http/static.js'\nimport { logRequest } from '../../../server/observability/logger.js'\nimport { findSuggestion } from '../../../server/observability/suggest.js'\nimport type { PluginRunner } from '../../../server/plugins/plugin-runner.js'\nimport type { ActionNode } from '../../../server/scan/action-scan.js'\nimport type { AgentNode } from '../../../server/scan/agent-scan.js'\nimport { matchRoute } from '../../../server/scan/match.js'\nimport type { ServerRouteNode } from '../../../server/scan/match.js'\nimport type { LoadModule } from '../../../server/scan/module-loader.js'\nimport type { CsrfMode, DisallowedConfig } from '../../../server/security/csrf.js'\nimport type { TheoTransformer } from '../../../server/transformer.js'\n\n/** Response header carrying the per-request correlation id. */\nconst X_REQUEST_ID = 'x-request-id'\n\n/**\n * T6.1 (PV-7 SRP): start.ts request orchestrator decomposed into 5 focused\n * per-branch handlers. Each handler returns `true` if it handled the\n * request (response sent) so the orchestrator can stop iterating.\n *\n * The original 455-LOC monolith closed over 14+ locals; the shared shape\n * `RequestHandlerCtx` makes the dependencies explicit + reviewable.\n */\nexport interface RequestHandlerCtx {\n req: IncomingMessage\n res: ServerResponse\n url: string\n requestId: string\n startTime: number\n // Pre-loaded build artifacts\n clientDir: string\n custom404Html: string | null\n // Manifest-resolved tables\n cachedRoutes: ServerRouteNode[]\n cachedActions: ActionNode[]\n cachedAgents: AgentNode[]\n // Runtime infra\n loadModule: LoadModule\n serverDir: string\n /** App root (= `process.cwd()` at `theokit start`); mountAgent points `.theokit/` discovery here. */\n projectRoot: string\n pluginRunner: PluginRunner | undefined\n transformer: TheoTransformer | undefined\n csrfMode: CsrfMode\n disallowed: DisallowedConfig | undefined\n rateLimiter:\n | ((req: IncomingMessage) => { limited: boolean; headers: Record<string, string> })\n | null\n}\n\n/** Apply rate limit; return true if request was limited (response sent). */\nfunction applyRateLimit(c: RequestHandlerCtx, method: string): boolean {\n if (!c.rateLimiter) return false\n const check = c.rateLimiter(c.req)\n for (const [k, v] of Object.entries(check.headers)) c.res.setHeader(k, v)\n if (check.limited) {\n sendError(c.res, 'RATE_LIMITED', 'Too many requests', 429, undefined, c.requestId)\n logRequest({\n method,\n url: c.url,\n status: 429,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n return false\n}\n\n/** Branch 1: action routes (`/api/__actions/{file}/{exportName}`). */\nexport async function tryServeAction(c: RequestHandlerCtx): Promise<boolean> {\n if (!c.url.startsWith('/api/__actions/')) return false\n c.res.setHeader(X_REQUEST_ID, c.requestId)\n\n if (applyRateLimit(c, c.req.method ?? 'POST')) return true\n\n const pathAfterPrefix = c.url.slice('/api/__actions/'.length).split('?')[0]\n const segments = pathAfterPrefix.split('/').filter(Boolean)\n if (segments.length < 2) {\n sendError(\n c.res,\n 'BAD_REQUEST',\n 'Action URL must be /api/__actions/{file}/{exportName}',\n 400,\n undefined,\n c.requestId,\n )\n logRequest({\n method: c.req.method ?? 'POST',\n url: c.url,\n status: 400,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n const exportName = segments[segments.length - 1]\n const actionPath = segments.slice(0, -1).join('/')\n const action = c.cachedActions.find((a) => a.actionPath === actionPath)\n if (!action) {\n const actionPaths = c.cachedActions.map((a) => a.actionPath)\n const suggestion = findSuggestion(actionPath, actionPaths)\n const msg = suggestion\n ? `Action \"${actionPath}\" not found. Did you mean: ${suggestion}?`\n : `Action \"${actionPath}\" not found`\n sendError(c.res, 'NOT_FOUND', msg, 404, undefined, c.requestId)\n logRequest({\n method: c.req.method ?? 'POST',\n url: c.url,\n status: 404,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n await executeAction(\n action.filePath,\n exportName,\n c.req,\n c.res,\n c.loadModule,\n c.serverDir,\n c.requestId,\n c.pluginRunner,\n c.csrfMode,\n c.disallowed,\n )\n logRequest({\n method: c.req.method ?? 'POST',\n url: c.url,\n status: c.res.statusCode,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n}\n\n/**\n * Branch 1.4: agent AUXILIARY routes served identically in dev + prod (M15/M16 follow-up) —\n * agent cards (`/.well-known/<name>/agent-card.json`), MCP (`/api/agents/<name>/mcp`), and the\n * pending-approvals listing (`/api/agents/<name>/approvals`). Before this, they were dev-only, so a\n * built/deployed app 404'd them. Delegates to the shared `serveAgentAuxRoute` dispatcher (DRY).\n */\nexport async function tryServeAgentAux(c: RequestHandlerCtx): Promise<boolean> {\n const urlPath = c.url.split('?')[0]\n const baseUrl = `http://${c.req.headers.host ?? 'localhost'}`\n const request = incomingMessageToWebRequest(c.req)\n const response = await serveAgentAuxRoute(request, urlPath, {\n agents: c.cachedAgents,\n loadModule: c.loadModule,\n baseUrl,\n // M34 (#97) — the MCP aux route drives the agent (spends tokens); enforce CSRF like the run route.\n csrfMode: c.csrfMode,\n // M39 — the thread follow-up route drives the agent; resolve the key on demand.\n resolveApiKey: () => resolveProvider().apiKey,\n })\n if (response === null) return false\n c.res.setHeader(X_REQUEST_ID, c.requestId)\n await writeWebResponseToServerResponse(response, c.res)\n logRequest({\n method: (c.req.method ?? 'GET').toUpperCase(),\n url: c.url,\n status: c.res.statusCode,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n}\n\n/**\n * Branch 1.5: agent convention routes (`/api/agents/<name>`, M2). Runs BEFORE the generic `/api/*`\n * branch so a scanned `agents/<name>.ts` owns its path (parity with dev). Loads the module, resolves\n * the provider apiKey (fail-fast), and streams the M0/M1 UIMessageStream via `mountAgent`.\n */\nexport async function tryServeAgent(c: RequestHandlerCtx): Promise<boolean> {\n if (!c.url.startsWith('/api/agents/')) return false\n const urlPath = c.url.split('?')[0]\n\n // HITL approve route (`/api/agents/<name>/approve/<id>`, M4) — resolve the pending approval.\n // Handled BEFORE the agent-path exact match (the approve path never equals an `agentPath`).\n if (isApprovalPath(urlPath)) {\n c.res.setHeader(X_REQUEST_ID, c.requestId)\n if (applyRateLimit(c, c.req.method ?? 'POST')) return true\n const method = (c.req.method ?? 'POST').toUpperCase()\n if (method !== 'POST') {\n sendError(\n c.res,\n 'METHOD_NOT_ALLOWED',\n 'Approve endpoints accept POST',\n 405,\n undefined,\n c.requestId,\n )\n logRequest({\n method,\n url: c.url,\n status: 405,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n try {\n const request = incomingMessageToWebRequest(c.req)\n const response = await handleAgentApproval(\n request,\n urlPath,\n getApprovalRegistry(),\n c.csrfMode,\n )\n await writeWebResponseToServerResponse(response, c.res)\n } catch (err) {\n sendError(\n c.res,\n 'INTERNAL',\n err instanceof Error ? err.message : 'Approve handler failed',\n 500,\n undefined,\n c.requestId,\n )\n }\n logRequest({\n method,\n url: c.url,\n status: c.res.statusCode,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n\n const agent = c.cachedAgents.find((a) => a.agentPath === urlPath)\n if (!agent) return false // fall through to the generic /api/* branch (may 404 there)\n\n c.res.setHeader(X_REQUEST_ID, c.requestId)\n if (applyRateLimit(c, c.req.method ?? 'POST')) return true\n\n const method = (c.req.method ?? 'POST').toUpperCase()\n if (method !== 'POST') {\n sendError(\n c.res,\n 'METHOD_NOT_ALLOWED',\n 'Agent endpoints accept POST',\n 405,\n undefined,\n c.requestId,\n )\n logRequest({\n method,\n url: c.url,\n status: 405,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n\n try {\n const mod = await c.loadModule(agent.filePath)\n const apiKey = resolveProvider().apiKey\n const request = incomingMessageToWebRequest(c.req)\n const response = await mountAgent(mod, request, apiKey, {\n source: agent.filePath,\n csrfMode: c.csrfMode,\n projectRoot: c.projectRoot,\n })\n await writeWebResponseToServerResponse(response, c.res)\n } catch (err) {\n sendError(\n c.res,\n 'INTERNAL',\n err instanceof Error ? err.message : 'Agent handler failed',\n 500,\n undefined,\n c.requestId,\n )\n }\n logRequest({\n method,\n url: c.url,\n status: c.res.statusCode,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n}\n\n/** Branch 2: API routes (`/api/*` excluding actions). */\nexport async function tryServeApiRoute(c: RequestHandlerCtx): Promise<boolean> {\n if (!c.url.startsWith('/api/')) return false\n c.res.setHeader(X_REQUEST_ID, c.requestId)\n\n if (applyRateLimit(c, c.req.method ?? 'GET')) return true\n\n const match = matchRoute(c.url, c.cachedRoutes)\n if (!match) {\n const urlPath = c.url.split('?')[0]\n const routePaths = c.cachedRoutes.map((r) => r.routePath)\n const suggestion = findSuggestion(urlPath, routePaths)\n const msg = suggestion\n ? `API route not found: ${urlPath}. Did you mean: ${suggestion}?`\n : 'API route not found'\n sendError(c.res, 'NOT_FOUND', msg, 404, undefined, c.requestId)\n logRequest({\n method: c.req.method ?? 'GET',\n url: c.url,\n status: 404,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n const method = (c.req.method ?? 'GET').toUpperCase()\n // T3.1 (ADR-0016) — context object replaces 12 positional args\n await executeRoute({\n route: match.route,\n method,\n params: match.params,\n req: c.req,\n res: c.res,\n loadModule: c.loadModule,\n serverDir: c.serverDir,\n requestId: c.requestId,\n pluginRunner: c.pluginRunner,\n transformer: c.transformer,\n csrfMode: c.csrfMode,\n disallowed: c.disallowed,\n })\n logRequest({\n method,\n url: c.url,\n status: c.res.statusCode,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n}\n\n/** Branch 3: static files (returns true if a static asset was served). */\nexport function tryServeStatic(c: RequestHandlerCtx): boolean {\n return serveStaticFile(c.req, c.res, c.clientDir)\n}\n\n/** Branch 4: custom 404 for URLs that look like missing assets. */\nexport function tryServeCustom404(c: RequestHandlerCtx): boolean {\n const urlPath = c.url.split('?')[0]\n if (c.custom404Html && extname(urlPath)) {\n c.res.writeHead(404, { 'Content-Type': 'text/html' })\n c.res.end(c.custom404Html)\n return true\n }\n return false\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Static-file server. The URL path IS user-controlled, BUT before any fs\n * call we resolve to absolute and reject with 403 if the resolved path\n * escapes `clientDir` (see EC-1 guard at line below). The guard is\n * authoritative; the rule cannot see it.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { resolve, extname } from 'node:path'\n\nconst MIME_TYPES: Record<string, string> = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.txt': 'text/plain',\n '.map': 'application/json',\n}\n\nexport function serveStaticFile(\n req: IncomingMessage,\n res: ServerResponse,\n clientDir: string,\n): boolean {\n const urlPath = (req.url ?? '/').split('?')[0]\n\n // Path traversal prevention (EC-1)\n const filePath = resolve(clientDir, '.' + urlPath)\n if (!filePath.startsWith(clientDir)) {\n res.writeHead(403)\n res.end('Forbidden')\n return true\n }\n\n if (!existsSync(filePath)) return false\n\n const stat = statSync(filePath)\n if (!stat.isFile()) return false\n\n const ext = extname(filePath)\n const contentType = MIME_TYPES[ext] ?? 'application/octet-stream'\n const content = readFileSync(filePath)\n\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': content.length,\n })\n res.end(content)\n return true\n}\n","/**\n * SSR setup stage for `theokit start` (T4.2 architecture-cleanup).\n *\n * Loads the SSR entry-server module if configured + builds template split\n * around the React root div. Returns null renderers when SSR is disabled.\n */\n\nimport type { ServerResponse } from 'node:http'\n\nimport { resolveSsrEntry } from './bootstrap-stages.js'\n\nexport interface SsrRenderResult {\n html: string\n hydrationData: {\n loaderData?: unknown\n actionData?: unknown\n errors?: unknown\n }\n}\n\nexport type RenderStreamingResult = { redirect: Response } | { streaming: true } | undefined\n\nexport type SsrRender = (\n url: string,\n options?: { nonce?: string },\n) => Promise<SsrRenderResult | { redirect: Response } | string>\n\nexport type SsrRenderStreaming = (\n url: string,\n response: ServerResponse,\n options?: { signal?: AbortSignal; nonce?: string },\n) => Promise<RenderStreamingResult>\n\ninterface SsrSetupResult {\n enabled: boolean\n streamingEnabled: boolean\n render: SsrRender | null\n renderStreaming: SsrRenderStreaming | null\n htmlHead: string\n htmlTail: string\n}\n\nexport function isSsrRenderResult(value: unknown): value is SsrRenderResult {\n if (typeof value !== 'object' || value === null) return false\n if (!('html' in value)) return false\n const html = (value as Record<string, unknown>).html\n if (typeof html !== 'string') return false\n return true\n}\n\ninterface SsrEntryServer {\n render: SsrRender\n renderStreaming?: SsrRenderStreaming\n}\n\nexport async function setupSsr(opts: {\n distDir: string\n indexHtml: string\n ssrConfigEnabled: boolean\n ssrStreamingConfig: boolean | undefined\n}): Promise<SsrSetupResult> {\n const ssrServerPath: string | null = opts.ssrConfigEnabled ? resolveSsrEntry(opts.distDir) : null\n const enabled = ssrServerPath !== null\n const streamingEnabled = enabled && Boolean(opts.ssrStreamingConfig)\n\n if (ssrServerPath === null) {\n return {\n enabled: false,\n streamingEnabled: false,\n render: null,\n renderStreaming: null,\n htmlHead: '',\n htmlTail: '',\n }\n }\n\n const mod = (await import(ssrServerPath)) as SsrEntryServer\n const render = mod.render\n const renderStreaming = typeof mod.renderStreaming === 'function' ? mod.renderStreaming : null\n\n // Split HTML template on root div\n let htmlHead = ''\n let htmlTail = ''\n const rootDivMatch = /<div id=[\"']root[\"'][^>]*>/.exec(opts.indexHtml)\n if (rootDivMatch) {\n const splitIdx = opts.indexHtml.indexOf(rootDivMatch[0]) + rootDivMatch[0].length\n htmlHead = opts.indexHtml.slice(0, splitIdx)\n htmlTail = opts.indexHtml.slice(splitIdx)\n }\n\n return { enabled, streamingEnabled, render, renderStreaming, htmlHead, htmlTail }\n}\n","/**\n * WebSocket upgrade handler for `theokit start` (T4.2 architecture-cleanup).\n *\n * Wires `server.on('upgrade')` for declared WS routes. Opt-in: only attached\n * when `wsRoutes.length > 0`. Lazy-imports `ws` package — throws an actionable\n * error when wsRoutes declared but `ws` not installed.\n */\n\nimport type { Server as HttpServer } from 'node:http'\n\nimport type * as WsLib from 'ws'\n\nimport type { WebSocketHandler } from '../../../server/define/define-websocket.js'\nimport type { LoadModule } from '../../../server/scan/module-loader.js'\nimport type { WebSocketRouteNode } from '../../../server/scan/ws-scan.js'\n\nexport async function attachWebSocketHandler(\n server: HttpServer,\n wsRoutes: WebSocketRouteNode[],\n loadModule: LoadModule,\n): Promise<void> {\n if (wsRoutes.length === 0) return\n\n let WebSocketServerCtor: typeof WsLib.WebSocketServer\n try {\n const wsModule = await import('ws')\n WebSocketServerCtor = wsModule.WebSocketServer\n } catch {\n throw new Error('WebSocket routes found but \"ws\" package is not installed. Run: npm install ws')\n }\n\n const wss = new WebSocketServerCtor({ noServer: true })\n\n server.on('upgrade', (request, socket, head) => {\n void (async () => {\n const url = request.url ?? '/'\n if (!url.startsWith('/ws/')) {\n socket.destroy()\n return\n }\n\n const wsPath = url.split('?')[0]\n const match = wsRoutes.find((r) => r.wsPath === wsPath)\n if (!match) {\n socket.destroy()\n return\n }\n\n try {\n const mod = await loadModule(match.filePath)\n const handler = ((mod as { default?: unknown }).default ?? mod) as WebSocketHandler\n\n wss.handleUpgrade(request, socket, head, (ws) => {\n handler.onOpen?.(ws, request)\n ws.on('message', (data: Buffer) => {\n handler.onMessage?.(ws, data.toString())\n })\n ws.on('close', (code: number, reason: Buffer) => {\n handler.onClose?.(ws, code, reason)\n })\n ws.on('error', (err: Error) => {\n handler.onError?.(ws, err)\n })\n })\n } catch {\n socket.destroy()\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,oBAAoB;AAC7B,SAAS,QAAAC,OAAM,WAAAC,gBAAe;;;ACDvB,IAAM,cAAc;AAEpB,IAAM,aAAa;AAgCnB,SAAS,kBACd,UAAyB,OAAO,EAAE,QAAQ,KAAK,IAC5B;AACnB,SAAO,EAAE,MAAM,UAAU,QAAQ;AACnC;AAgBA,eAAsB,mBACpB,UACA,SAAyB,CAAC,GACQ;AAClC,MAAI,aAAa,aAAa;AAC5B,UAAM,UAAU,OAAO,QAAQ,YAAY,OAAO,EAAE,QAAQ,KAAK;AACjE,WAAO,EAAE,QAAQ,KAAK,MAAM,QAAQ,EAAE;AAAA,EACxC;AACA,MAAI,aAAa,YAAY;AAC3B,UAAM,QAAQ,OAAO,OAAO;AAC5B,QAAI,UAAU,QAAW;AACvB,aAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,QAAQ,QAAQ,EAAE;AAAA,IAClD;AACA,QAAI;AACF,YAAM,QAAQ,MAAM,MAAM;AAC1B,aAAO,QACH,EAAE,QAAQ,KAAK,MAAM,EAAE,QAAQ,QAAQ,EAAE,IACzC,EAAE,QAAQ,KAAK,MAAM,EAAE,QAAQ,YAAY,EAAE;AAAA,IACnD,SAAS,KAAK;AAIZ,cAAQ,MAAM,6DAAwD,GAAG;AACzE,aAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,QAAQ,YAAY,EAAE;AAAA,IAC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AA,yBAA4B;AACxC,YAAQ,IAAI,6BAAwB,OAAO,IAAI,CAAC;AAAA,CAAI;AAAA,EACtD,CAAC;AAED,0BAAwB,MAAM;AAChC;","names":["existsSync","readFileSync","join","resolve","require","existsSync","existsSync","extname","existsSync","readFileSync","resolve","method","extname","resolve","existsSync","readFileSync","join"]}
@@ -2,14 +2,14 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  nodeAdapter
5
- } from "./chunk-FOZIR3TG.js";
5
+ } from "./chunk-SMP2T335.js";
6
6
  import {
7
7
  scanRoutes
8
8
  } from "./chunk-IEES3CHD.js";
9
9
  import {
10
10
  assertServicesUnsupported,
11
11
  readManifest
12
- } from "./chunk-45C3WUQ7.js";
12
+ } from "./chunk-QPVXGC7O.js";
13
13
 
14
14
  // src/adapters/static.ts
15
15
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "fs";
@@ -225,4 +225,4 @@ export {
225
225
  detectApiRoutes,
226
226
  staticAdapter
227
227
  };
228
- //# sourceMappingURL=static-MB2CD5Y3.js.map
228
+ //# sourceMappingURL=static-25H5K42R.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapters/static.ts","../src/adapters/static-paths.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * All filesystem inputs in this file are derived from:\n * - `process.cwd()` resolved at build time, OR\n * - directory tree walks rooted in `serverDir`/`appDir` (themselves\n * resolved from cwd), OR\n * - file paths produced by `collectStaticPaths` (a controlled router\n * scanner).\n * No path here originates from HTTP input, environment variables, or\n * deserialized user data. The path-traversal vector the rule guards\n * against does not apply — this is a build-time tool, not a request\n * handler.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname, resolve, relative } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { scanRoutes } from '../router/scan.js'\nimport type { RouteNode } from '../router/types.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { nodeAdapter } from './node.js'\nimport {\n collectStaticPaths,\n type CollectOptions,\n type LoadStaticPaths,\n type ResolvedPath,\n} from './static-paths.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport class StaticApiRoutesDetectedError extends Error {\n constructor(routes: string[]) {\n super(\n `Static adapter cannot build a project with API routes. Found: ${routes.join(\n ', ',\n )}. Use 'node', 'vercel', 'cloudflare' or another runtime adapter.`,\n )\n this.name = 'StaticApiRoutesDetectedError'\n }\n}\n\nexport class StaticRenderError extends Error {\n constructor(url: string, cause: unknown) {\n const causeMsg = cause instanceof Error ? cause.message : String(cause)\n super(`SSR render failed for ${url}: ${causeMsg}`)\n this.name = 'StaticRenderError'\n if (cause instanceof Error) {\n this.cause = cause\n }\n }\n}\n\nexport interface StaticBuildDeps {\n detectApiRoutes?: (serverDir: string) => string[]\n scanAppRoutes?: (appDir: string) => RouteNode\n collectPaths?: (tree: RouteNode, options: CollectOptions) => Promise<ResolvedPath[]>\n loadStaticPaths?: LoadStaticPaths\n renderHtml?: (url: string, cwd: string) => Promise<string>\n ensureDir?: (path: string) => Promise<void>\n writeFile?: (path: string, content: string) => Promise<void>\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n}\n\nexport function detectApiRoutes(serverDir: string): string[] {\n const routesDir = resolve(serverDir, 'routes')\n if (!existsSync(routesDir)) return []\n if (!statSync(routesDir).isDirectory()) return []\n\n const out: string[] = []\n walkRoutes(routesDir, routesDir, out)\n return out\n}\n\nfunction walkRoutes(root: string, dir: string, out: string[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name.startsWith('.') || entry.name.startsWith('_')) continue\n const full = resolve(dir, entry.name)\n if (entry.isDirectory()) {\n walkRoutes(root, full, out)\n } else if (entry.isFile() && /\\.(ts|tsx|js|jsx|mjs)$/.test(entry.name)) {\n const rel = relative(root, full).split(/[\\\\/]/).join('/')\n out.push(rel)\n }\n }\n}\n\n/* eslint-disable @typescript-eslint/require-await -- DI contract is async; default impl uses sync fs */\n\n// The DI surface exposes async helpers (so consumers can override with\n// real async IO — e.g. S3 uploads). The defaults use sync fs because\n// every caller awaits the result anyway.\nconst defaultEnsureDir = async (path: string): Promise<void> => {\n mkdirSync(path, { recursive: true })\n}\n\nconst defaultWriteFile = async (path: string, content: string): Promise<void> => {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, content)\n}\n\n/* eslint-enable @typescript-eslint/require-await */\n\n/**\n * Default loader: dynamic-imports the file at `paramsFilePath` and invokes\n * its default export. Returns null if the file does not exist (the caller\n * will throw StaticPathsRequiredError with a clear message in that case).\n */\nconst defaultLoadStaticPaths: LoadStaticPaths = async (paramsFilePath) => {\n if (!existsSync(paramsFilePath)) return null\n try {\n const mod = (await import(pathToFileURL(paramsFilePath).href)) as {\n default?: LoadStaticPaths | (() => Awaited<ReturnType<LoadStaticPaths>>)\n }\n if (typeof mod.default !== 'function') return null\n // The user's `static-paths.ts` may export `default` as either sync or\n // async — `await` accepts both, but ESLint's `await-thenable` cannot\n // see through the union.\n const value = mod.default(paramsFilePath)\n const result = value instanceof Promise ? await value : value\n return result ?? null\n } catch {\n return null\n }\n}\n\n/**\n * Default renderer: loads the built SSR entry (`.theokit/server/entry-server.js`)\n * and calls its `render(url)` export, wrapping the result in the client\n * `index.html` template. Falls back to a minimal HTML shell when no SSR build\n * is present (so the static adapter still emits something usable even without\n * SSR enabled).\n */\nfunction createDefaultRenderHtml(cwd: string): (url: string) => Promise<string> {\n return async (url: string): Promise<string> => {\n const clientDir = resolve(cwd, '.theokit/client')\n const indexPath = resolve(clientDir, 'index.html')\n const ssrEntryPath = resolve(cwd, '.theokit/server/entry-server.js')\n\n let baseHtml = '<!doctype html><html><body><div id=\"root\"></div></body></html>'\n if (existsSync(indexPath)) {\n baseHtml = readFileSync(indexPath, 'utf-8')\n }\n\n if (!existsSync(ssrEntryPath)) {\n // No SSR build — emit the client shell. Hydration on the client will\n // render the route once JS loads. Acceptable degradation when the user\n // chose static + ssr: false.\n return baseHtml\n }\n\n try {\n const mod = (await import(pathToFileURL(ssrEntryPath).href)) as {\n render?: (u: string) => Promise<string | { redirect: Response }>\n }\n if (typeof mod.render !== 'function') return baseHtml\n const result = await mod.render(url)\n if (typeof result === 'string') {\n const rootMatch = /<div id=[\"']root[\"'][^>]*>/.exec(baseHtml)\n if (rootMatch) {\n const splitIdx = baseHtml.indexOf(rootMatch[0]) + rootMatch[0].length\n return baseHtml.slice(0, splitIdx) + result + baseHtml.slice(splitIdx)\n }\n return baseHtml.replace('</body>', result + '</body>')\n }\n // redirect — emit a meta refresh fallback for static export\n return `<!doctype html><meta http-equiv=\"refresh\" content=\"0; url=/\" />`\n } catch (err) {\n throw new StaticRenderError(url, err)\n }\n }\n}\n\nexport async function buildStatic(\n config: TheoConfig,\n cwd: string,\n deps: StaticBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('static', readManifest(cwd))\n\n const detect = deps.detectApiRoutes ?? detectApiRoutes\n const apiRoutes = detect(resolve(cwd, 'server'))\n if (apiRoutes.length > 0) {\n throw new StaticApiRoutesDetectedError(apiRoutes)\n }\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const scan = deps.scanAppRoutes ?? scanRoutes\n // #95 — honor config `appDir` (default \"app\") so `--target static` prerenders a custom frontend dir.\n // `config` is a fully-loaded TheoConfig (loadConfig applied the schema default), so appDir is present.\n const appDir = resolve(cwd, config.appDir)\n const tree = scan(appDir)\n\n const loadStaticPaths = deps.loadStaticPaths ?? defaultLoadStaticPaths\n const collect = deps.collectPaths ?? collectStaticPaths\n const paths = await collect(tree, { appDir, loadStaticPaths })\n\n if (paths.length === 0) return\n\n const renderHtml = deps.renderHtml ?? createDefaultRenderHtml(cwd)\n const ensureDir = deps.ensureDir ?? defaultEnsureDir\n const writeFile = deps.writeFile ?? defaultWriteFile\n\n const outDir = resolve(cwd, '.theokit/static')\n await ensureDir(outDir)\n\n for (const path of paths) {\n let html: string\n try {\n html = await renderHtml(path.url, cwd)\n } catch (err) {\n throw new StaticRenderError(path.url, err)\n }\n const outPath = resolve(outDir, path.filename)\n await writeFile(outPath, html)\n }\n}\n\nexport const staticAdapter: DeployAdapter = {\n name: 'static',\n build(config, cwd, ctx) {\n return buildStatic(config, cwd, {}, ctx)\n },\n}\n","import type { RouteNode } from '../router/types.js'\n\nexport interface ResolvedPath {\n /** URL path to render, e.g. '/blog/123' */\n url: string\n /** Output file path relative to .theokit/static/, e.g. 'blog/123.html' */\n filename: string\n}\n\nexport type StaticPathParams = Record<string, string | string[]>\n\nexport type LoadStaticPaths = (paramsFilePath: string) => Promise<StaticPathParams[] | null>\n\nexport class StaticPathsRequiredError extends Error {\n constructor(routePath: string, paramsFile: string) {\n super(\n `Route ${routePath} has dynamic segments and requires ${paramsFile}. ` +\n `Export default function returning Array<{ <param>: string | string[] }>.`,\n )\n this.name = 'StaticPathsRequiredError'\n }\n}\n\nexport interface CollectOptions {\n appDir: string\n loadStaticPaths: LoadStaticPaths\n}\n\nexport type ParsedSegment =\n | { kind: 'static' }\n | { kind: 'param'; name: string }\n | { kind: 'catch-all'; name: string }\n\nconst CATCH_ALL = /^\\[\\.\\.\\.(.+)\\]$/\nconst PARAM = /^\\[(.+)\\]$/\n\nexport function parseSegment(segment: string): ParsedSegment {\n const catchAll = CATCH_ALL.exec(segment)\n if (catchAll) return { kind: 'catch-all', name: catchAll[1] }\n const param = PARAM.exec(segment)\n if (param) return { kind: 'param', name: param[1] }\n return { kind: 'static' }\n}\n\nexport async function collectStaticPaths(\n tree: RouteNode,\n options: CollectOptions,\n): Promise<ResolvedPath[]> {\n const out: ResolvedPath[] = []\n await walk(tree, [], out, options)\n return out\n}\n\nasync function walk(\n node: RouteNode,\n parentSegments: string[],\n out: ResolvedPath[],\n options: CollectOptions,\n): Promise<void> {\n const segments = node.segment === '' ? parentSegments : [...parentSegments, node.segment]\n\n if (node.page) {\n const resolved = await resolveNodePaths(segments, options)\n out.push(...resolved)\n }\n\n for (const child of node.children) {\n await walk(child, segments, out, options)\n }\n}\n\nasync function resolveNodePaths(\n segments: string[],\n options: CollectOptions,\n): Promise<ResolvedPath[]> {\n if (segments.length === 0) {\n return [{ url: '/', filename: 'index.html' }]\n }\n\n const parsed = segments.map(parseSegment)\n const hasDynamic = parsed.some((p) => p.kind !== 'static')\n\n if (!hasDynamic) {\n const joined = segments.join('/')\n return [{ url: '/' + joined, filename: joined + '.html' }]\n }\n\n let lastDynamicIdx = 0\n for (let i = 0; i < parsed.length; i++) {\n if (parsed[i].kind !== 'static') lastDynamicIdx = i\n }\n\n const dirSegments = segments.slice(0, lastDynamicIdx + 1)\n const paramsFile = `${options.appDir}/${dirSegments.join('/')}/static-paths.ts`\n const params = await options.loadStaticPaths(paramsFile)\n\n if (!params) {\n const routePath = '/' + segments.join('/')\n throw new StaticPathsRequiredError(routePath, paramsFile)\n }\n\n return params.map((paramSet) => {\n const filled: string[] = []\n for (let i = 0; i < segments.length; i++) {\n const p = parsed[i]\n if (p.kind === 'static') {\n filled.push(segments[i])\n } else {\n const value = paramSet[p.name]\n if (Array.isArray(value)) {\n filled.push(...value)\n } else {\n filled.push(value)\n }\n }\n }\n const joined = filled.join('/')\n return { url: '/' + joined, filename: joined + '.html' }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAYA,SAAS,YAAY,WAAW,aAAa,cAAc,UAAU,qBAAqB;AAC1F,SAAS,SAAS,SAAS,gBAAgB;AAC3C,SAAS,qBAAqB;;;ACDvB,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAClD,YAAY,WAAmB,YAAoB;AACjD;AAAA,MACE,SAAS,SAAS,sCAAsC,UAAU;AAAA,IAEpE;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAYA,IAAM,YAAY;AAClB,IAAM,QAA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AAM,OAAO,KAAK,iBAAiB;AAGnC,QAAM,SAAS,QAAQ,KAAK,OAAO,MAAM;AACzC,QAAM,OAAO,KAAK,MAAM;AAExB,QAAM,kBAAkB,KAAK,mBAAmB;AAChD,QAAM,UAAU,KAAK,gBAAgB;AACrC,QAAM,QAAQ,MAAM,QAAQ,MAAM,EAAE,QAAQ,gBAAgB,CAAC;AAE7D,MAAI,MAAM,WAAW,EAAG;AAExB,QAAM,aAAa,KAAK,cAAc,wBAAwB,GAAG;AACjE,QAAM,YAAY,KAAK,aAAa;AACpC,QAAM,YAAY,KAAK,aAAa;AAEpC,QAAM,SAAS,QAAQ,KAAK,iBAAiB;AAC7C,QAAM,UAAU,MAAM;AAEtB,aAAW,QAAQ,OAAO;AACxB,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,WAAW,KAAK,KAAK,GAAG;AAAA,IACvC,SAAS,KAAK;AACZ,YAAM,IAAI,kBAAkB,KAAK,KAAK,GAAG;AAAA,IAC3C;AACA,UAAM,UAAU,QAAQ,QAAQ,KAAK,QAAQ;AAC7C,UAAM,UAAU,SAAS,IAAI;AAAA,EAC/B;AACF;AAEO,IAAM,gBAA+B;AAAA,EAC1C,MAAM;AAAA,EACN,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,YAAY,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EACzC;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/adapters/static.ts","../src/adapters/static-paths.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * All filesystem inputs in this file are derived from:\n * - `process.cwd()` resolved at build time, OR\n * - directory tree walks rooted in `serverDir`/`appDir` (themselves\n * resolved from cwd), OR\n * - file paths produced by `collectStaticPaths` (a controlled router\n * scanner).\n * No path here originates from HTTP input, environment variables, or\n * deserialized user data. The path-traversal vector the rule guards\n * against does not apply — this is a build-time tool, not a request\n * handler.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname, resolve, relative } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { scanRoutes } from '../router/scan.js'\nimport type { RouteNode } from '../router/types.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { nodeAdapter } from './node.js'\nimport {\n collectStaticPaths,\n type CollectOptions,\n type LoadStaticPaths,\n type ResolvedPath,\n} from './static-paths.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport class StaticApiRoutesDetectedError extends Error {\n constructor(routes: string[]) {\n super(\n `Static adapter cannot build a project with API routes. Found: ${routes.join(\n ', ',\n )}. Use 'node', 'vercel', 'cloudflare' or another runtime adapter.`,\n )\n this.name = 'StaticApiRoutesDetectedError'\n }\n}\n\nexport class StaticRenderError extends Error {\n constructor(url: string, cause: unknown) {\n const causeMsg = cause instanceof Error ? cause.message : String(cause)\n super(`SSR render failed for ${url}: ${causeMsg}`)\n this.name = 'StaticRenderError'\n if (cause instanceof Error) {\n this.cause = cause\n }\n }\n}\n\nexport interface StaticBuildDeps {\n detectApiRoutes?: (serverDir: string) => string[]\n scanAppRoutes?: (appDir: string) => RouteNode\n collectPaths?: (tree: RouteNode, options: CollectOptions) => Promise<ResolvedPath[]>\n loadStaticPaths?: LoadStaticPaths\n renderHtml?: (url: string, cwd: string) => Promise<string>\n ensureDir?: (path: string) => Promise<void>\n writeFile?: (path: string, content: string) => Promise<void>\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n}\n\nexport function detectApiRoutes(serverDir: string): string[] {\n const routesDir = resolve(serverDir, 'routes')\n if (!existsSync(routesDir)) return []\n if (!statSync(routesDir).isDirectory()) return []\n\n const out: string[] = []\n walkRoutes(routesDir, routesDir, out)\n return out\n}\n\nfunction walkRoutes(root: string, dir: string, out: string[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name.startsWith('.') || entry.name.startsWith('_')) continue\n const full = resolve(dir, entry.name)\n if (entry.isDirectory()) {\n walkRoutes(root, full, out)\n } else if (entry.isFile() && /\\.(ts|tsx|js|jsx|mjs)$/.test(entry.name)) {\n const rel = relative(root, full).split(/[\\\\/]/).join('/')\n out.push(rel)\n }\n }\n}\n\n/* eslint-disable @typescript-eslint/require-await -- DI contract is async; default impl uses sync fs */\n\n// The DI surface exposes async helpers (so consumers can override with\n// real async IO — e.g. S3 uploads). The defaults use sync fs because\n// every caller awaits the result anyway.\nconst defaultEnsureDir = async (path: string): Promise<void> => {\n mkdirSync(path, { recursive: true })\n}\n\nconst defaultWriteFile = async (path: string, content: string): Promise<void> => {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, content)\n}\n\n/* eslint-enable @typescript-eslint/require-await */\n\n/**\n * Default loader: dynamic-imports the file at `paramsFilePath` and invokes\n * its default export. Returns null if the file does not exist (the caller\n * will throw StaticPathsRequiredError with a clear message in that case).\n */\nconst defaultLoadStaticPaths: LoadStaticPaths = async (paramsFilePath) => {\n if (!existsSync(paramsFilePath)) return null\n try {\n const mod = (await import(pathToFileURL(paramsFilePath).href)) as {\n default?: LoadStaticPaths | (() => Awaited<ReturnType<LoadStaticPaths>>)\n }\n if (typeof mod.default !== 'function') return null\n // The user's `static-paths.ts` may export `default` as either sync or\n // async — `await` accepts both, but ESLint's `await-thenable` cannot\n // see through the union.\n const value = mod.default(paramsFilePath)\n const result = value instanceof Promise ? await value : value\n return result ?? null\n } catch {\n return null\n }\n}\n\n/**\n * Default renderer: loads the built SSR entry (`.theokit/server/entry-server.js`)\n * and calls its `render(url)` export, wrapping the result in the client\n * `index.html` template. Falls back to a minimal HTML shell when no SSR build\n * is present (so the static adapter still emits something usable even without\n * SSR enabled).\n */\nfunction createDefaultRenderHtml(cwd: string): (url: string) => Promise<string> {\n return async (url: string): Promise<string> => {\n const clientDir = resolve(cwd, '.theokit/client')\n const indexPath = resolve(clientDir, 'index.html')\n const ssrEntryPath = resolve(cwd, '.theokit/server/entry-server.js')\n\n let baseHtml = '<!doctype html><html><body><div id=\"root\"></div></body></html>'\n if (existsSync(indexPath)) {\n baseHtml = readFileSync(indexPath, 'utf-8')\n }\n\n if (!existsSync(ssrEntryPath)) {\n // No SSR build — emit the client shell. Hydration on the client will\n // render the route once JS loads. Acceptable degradation when the user\n // chose static + ssr: false.\n return baseHtml\n }\n\n try {\n const mod = (await import(pathToFileURL(ssrEntryPath).href)) as {\n render?: (u: string) => Promise<string | { redirect: Response }>\n }\n if (typeof mod.render !== 'function') return baseHtml\n const result = await mod.render(url)\n if (typeof result === 'string') {\n const rootMatch = /<div id=[\"']root[\"'][^>]*>/.exec(baseHtml)\n if (rootMatch) {\n const splitIdx = baseHtml.indexOf(rootMatch[0]) + rootMatch[0].length\n return baseHtml.slice(0, splitIdx) + result + baseHtml.slice(splitIdx)\n }\n return baseHtml.replace('</body>', result + '</body>')\n }\n // redirect — emit a meta refresh fallback for static export\n return `<!doctype html><meta http-equiv=\"refresh\" content=\"0; url=/\" />`\n } catch (err) {\n throw new StaticRenderError(url, err)\n }\n }\n}\n\nexport async function buildStatic(\n config: TheoConfig,\n cwd: string,\n deps: StaticBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('static', readManifest(cwd))\n\n const detect = deps.detectApiRoutes ?? detectApiRoutes\n const apiRoutes = detect(resolve(cwd, 'server'))\n if (apiRoutes.length > 0) {\n throw new StaticApiRoutesDetectedError(apiRoutes)\n }\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const scan = deps.scanAppRoutes ?? scanRoutes\n // #95 — honor config `appDir` (default \"app\") so `--target static` prerenders a custom frontend dir.\n // `config` is a fully-loaded TheoConfig (loadConfig applied the schema default), so appDir is present.\n const appDir = resolve(cwd, config.appDir)\n const tree = scan(appDir)\n\n const loadStaticPaths = deps.loadStaticPaths ?? defaultLoadStaticPaths\n const collect = deps.collectPaths ?? collectStaticPaths\n const paths = await collect(tree, { appDir, loadStaticPaths })\n\n if (paths.length === 0) return\n\n const renderHtml = deps.renderHtml ?? createDefaultRenderHtml(cwd)\n const ensureDir = deps.ensureDir ?? defaultEnsureDir\n const writeFile = deps.writeFile ?? defaultWriteFile\n\n const outDir = resolve(cwd, '.theokit/static')\n await ensureDir(outDir)\n\n for (const path of paths) {\n let html: string\n try {\n html = await renderHtml(path.url, cwd)\n } catch (err) {\n throw new StaticRenderError(path.url, err)\n }\n const outPath = resolve(outDir, path.filename)\n await writeFile(outPath, html)\n }\n}\n\nexport const staticAdapter: DeployAdapter = {\n name: 'static',\n build(config, cwd, ctx) {\n return buildStatic(config, cwd, {}, ctx)\n },\n}\n","import type { RouteNode } from '../router/types.js'\n\nexport interface ResolvedPath {\n /** URL path to render, e.g. '/blog/123' */\n url: string\n /** Output file path relative to .theokit/static/, e.g. 'blog/123.html' */\n filename: string\n}\n\nexport type StaticPathParams = Record<string, string | string[]>\n\nexport type LoadStaticPaths = (paramsFilePath: string) => Promise<StaticPathParams[] | null>\n\nexport class StaticPathsRequiredError extends Error {\n constructor(routePath: string, paramsFile: string) {\n super(\n `Route ${routePath} has dynamic segments and requires ${paramsFile}. ` +\n `Export default function returning Array<{ <param>: string | string[] }>.`,\n )\n this.name = 'StaticPathsRequiredError'\n }\n}\n\nexport interface CollectOptions {\n appDir: string\n loadStaticPaths: LoadStaticPaths\n}\n\ntype ParsedSegment =\n | { kind: 'static' }\n | { kind: 'param'; name: string }\n | { kind: 'catch-all'; name: string }\n\nconst CATCH_ALL = /^\\[\\.\\.\\.(.+)\\]$/\nconst PARAM = /^\\[(.+)\\]$/\n\nexport function parseSegment(segment: string): ParsedSegment {\n const catchAll = CATCH_ALL.exec(segment)\n if (catchAll) return { kind: 'catch-all', name: catchAll[1] }\n const param = PARAM.exec(segment)\n if (param) return { kind: 'param', name: param[1] }\n return { kind: 'static' }\n}\n\nexport async function collectStaticPaths(\n tree: RouteNode,\n options: CollectOptions,\n): Promise<ResolvedPath[]> {\n const out: ResolvedPath[] = []\n await walk(tree, [], out, options)\n return out\n}\n\nasync function walk(\n node: RouteNode,\n parentSegments: string[],\n out: ResolvedPath[],\n options: CollectOptions,\n): Promise<void> {\n const segments = node.segment === '' ? parentSegments : [...parentSegments, node.segment]\n\n if (node.page) {\n const resolved = await resolveNodePaths(segments, options)\n out.push(...resolved)\n }\n\n for (const child of node.children) {\n await walk(child, segments, out, options)\n }\n}\n\nasync function resolveNodePaths(\n segments: string[],\n options: CollectOptions,\n): Promise<ResolvedPath[]> {\n if (segments.length === 0) {\n return [{ url: '/', filename: 'index.html' }]\n }\n\n const parsed = segments.map(parseSegment)\n const hasDynamic = parsed.some((p) => p.kind !== 'static')\n\n if (!hasDynamic) {\n const joined = segments.join('/')\n return [{ url: '/' + joined, filename: joined + '.html' }]\n }\n\n let lastDynamicIdx = 0\n for (let i = 0; i < parsed.length; i++) {\n if (parsed[i].kind !== 'static') lastDynamicIdx = i\n }\n\n const dirSegments = segments.slice(0, lastDynamicIdx + 1)\n const paramsFile = `${options.appDir}/${dirSegments.join('/')}/static-paths.ts`\n const params = await options.loadStaticPaths(paramsFile)\n\n if (!params) {\n const routePath = '/' + segments.join('/')\n throw new StaticPathsRequiredError(routePath, paramsFile)\n }\n\n return params.map((paramSet) => {\n const filled: string[] = []\n for (let i = 0; i < segments.length; i++) {\n const p = parsed[i]\n if (p.kind === 'static') {\n filled.push(segments[i])\n } else {\n const value = paramSet[p.name]\n if (Array.isArray(value)) {\n filled.push(...value)\n } else {\n filled.push(value)\n }\n }\n }\n const joined = filled.join('/')\n return { url: '/' + joined, filename: joined + '.html' }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAYA,SAAS,YAAY,WAAW,aAAa,cAAc,UAAU,qBAAqB;AAC1F,SAAS,SAAS,SAAS,gBAAgB;AAC3C,SAAS,qBAAqB;;;ACDvB,IAAM,2BAAN,cAAuC,MAAM;AAAA,EA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ACxB,UAAM,IAAI,6BAA6B,SAAS;AAAA,EAClD;AAEA,QAAM,eAAe,KAAK,gBAAgB,YAAY,MAAM,KAAK,WAAW;AAC5E,QAAM,aAAa,QAAQ,KAAK,GAAG;AAEnC,QAAM,OAAO,KAAK,iBAAiB;AAGnC,QAAM,SAAS,QAAQ,KAAK,OAAO,MAAM;AACzC,QAAM,OAAO,KAAK,MAAM;AAExB,QAAM,kBAAkB,KAAK,mBAAmB;AAChD,QAAM,UAAU,KAAK,gBAAgB;AACrC,QAAM,QAAQ,MAAM,QAAQ,MAAM,EAAE,QAAQ,gBAAgB,CAAC;AAE7D,MAAI,MAAM,WAAW,EAAG;AAExB,QAAM,aAAa,KAAK,cAAc,wBAAwB,GAAG;AACjE,QAAM,YAAY,KAAK,aAAa;AACpC,QAAM,YAAY,KAAK,aAAa;AAEpC,QAAM,SAAS,QAAQ,KAAK,iBAAiB;AAC7C,QAAM,UAAU,MAAM;AAEtB,aAAW,QAAQ,OAAO;AACxB,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,WAAW,KAAK,KAAK,GAAG;AAAA,IACvC,SAAS,KAAK;AACZ,YAAM,IAAI,kBAAkB,KAAK,KAAK,GAAG;AAAA,IAC3C;AACA,UAAM,UAAU,QAAQ,QAAQ,KAAK,QAAQ;AAC7C,UAAM,UAAU,SAAS,IAAI;AAAA,EAC/B;AACF;AAEO,IAAM,gBAA+B;AAAA,EAC1C,MAAM;AAAA,EACN,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,YAAY,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EACzC;AACF;","names":[]}
@@ -3,7 +3,7 @@ import "tsx/esm";
3
3
  import {
4
4
  prepareTheoCloudArtifacts,
5
5
  readManifest
6
- } from "./chunk-45C3WUQ7.js";
6
+ } from "./chunk-QPVXGC7O.js";
7
7
 
8
8
  // src/adapters/theo-cloud.ts
9
9
  var theoCloudAdapter = {
@@ -21,4 +21,4 @@ var theoCloudAdapter = {
21
21
  export {
22
22
  theoCloudAdapter
23
23
  };
24
- //# sourceMappingURL=theo-cloud-DQRP6S6M.js.map
24
+ //# sourceMappingURL=theo-cloud-JL2KXHIS.js.map
@@ -250,4 +250,4 @@ export {
250
250
  scanUpgradeReadiness,
251
251
  upgradeReadinessCommand
252
252
  };
253
- //# sourceMappingURL=upgrade-readiness-ACGW44JC.js.map
253
+ //# sourceMappingURL=upgrade-readiness-77P6VNB4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/upgrade-readiness.ts"],"sourcesContent":["import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { resolve, relative, sep } from 'node:path'\n\n/**\n * T2.3 — Upgrade-readiness scanner for the 0.2 → 0.3 cutover.\n *\n * LINT-only. Reads user source, reports anticipated 0.3.0 violations with\n * file:line + suggested fix. NEVER writes user files (ADR D1).\n *\n * Three rules:\n * 1. csrf-missing-header — raw fetch POST/PUT/PATCH/DELETE missing the\n * X-Theo-Action: '1' header → 403 under strict CSRF.\n * 2. inline-script — <script>...</script> in .html files without\n * `src=` attribute → blocked under enforce CSP without unsafe-inline.\n * 3. dangerously-set-inline-script — React `dangerouslySetInnerHTML`\n * payload that contains <script>.\n *\n * EC-7: occurrences inside line comments (// ...) or wrapped in quoted\n * strings are best-effort skipped. The scanner is not a parser — it\n * filters obvious false-positive lines before running the violation\n * regex.\n * EC-8: scanning a directory with no `app/` and no `server/` returns a\n * 'no-project-detected' report with exitCode 0 (no crash).\n */\n\ntype ViolationRule =\n | 'csrf-missing-header'\n | 'inline-script'\n | 'dangerously-set-inline-script'\n | 'zero-config-tailwind-suggest'\n | 'handrolled-dotenv-suggest'\n\nexport interface Violation {\n file: string\n line: number\n rule: ViolationRule\n message: string\n fix: string\n}\n\nexport type ReadinessStatus =\n | 'ready'\n | 'has-violations'\n | 'no-project-detected'\n | 'not-a-theokit-project'\n\nexport interface UpgradeReadinessReport {\n status: ReadinessStatus\n exitCode: 0 | 1\n violations: Violation[]\n}\n\ninterface ScanOptions {\n cwd: string\n /** When true, exitCode is forced to 0 even when violations exist. */\n allowWarnings?: boolean\n}\n\nconst SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next', '.theokit', '.cache'])\nconst SOURCE_EXTS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'])\nconst HTML_EXTS = new Set(['.html', '.htm'])\n\nfunction walkFiles(dir: string, root: string, out: string[]): void {\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n return\n }\n for (const name of entries) {\n if (SKIP_DIRS.has(name)) continue\n const full = resolve(dir, name)\n let s\n try {\n s = statSync(full)\n } catch {\n continue\n }\n if (s.isDirectory()) {\n walkFiles(full, root, out)\n } else if (s.isFile()) {\n const dot = name.lastIndexOf('.')\n if (dot < 0) continue\n const ext = name.slice(dot)\n if (SOURCE_EXTS.has(ext) || HTML_EXTS.has(ext)) out.push(full)\n }\n }\n}\n\nfunction isLikelyCommentOrString(rawLine: string, matchIndex: number): boolean {\n // Comment: line-comment marker (//) appears before the match position.\n const lineCommentIdx = rawLine.indexOf('//')\n if (lineCommentIdx !== -1 && lineCommentIdx < matchIndex) {\n // Make sure // is not inside a string (best-effort: count unescaped\n // quote chars before the //)\n const before = rawLine.slice(0, lineCommentIdx)\n const quoteCount = (before.match(/(?<!\\\\)[\"']/g) ?? []).length\n if (quoteCount % 2 === 0) return true\n }\n // String literal: scan quote characters around match. If the match is\n // surrounded by an odd number of unescaped quotes on either side, it\n // sits inside a string. Best-effort — does not parse template literals\n // or multiline strings.\n const before = rawLine.slice(0, matchIndex)\n const doubleQuotes = (before.match(/(?<!\\\\)\"/g) ?? []).length\n const singleQuotes = (before.match(/(?<!\\\\)'/g) ?? []).length\n return doubleQuotes % 2 === 1 || singleQuotes % 2 === 1\n}\n\n// `fetch(` followed (within ~200 chars, same call site) by a method:\n// 'POST' | 'PUT' | 'PATCH' | 'DELETE'. We scan per-line to keep regex\n// state simple; multi-line fetch calls match on the line that carries\n// the `method:` literal.\nconst METHOD_PATTERN = /method\\s*:\\s*['\"`](POST|PUT|PATCH|DELETE)['\"`]/gi\n\nfunction scanSourceFile(file: string, rel: string, content: string, out: Violation[]): void {\n const lines = content.split('\\n')\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n METHOD_PATTERN.lastIndex = 0\n const match = METHOD_PATTERN.exec(line)\n if (!match) continue\n if (isLikelyCommentOrString(line, match.index)) continue\n\n // Look 8 lines back AND forward for the enclosing `fetch(` and for an\n // X-Theo-Action header in the same call-site block.\n const blockStart = Math.max(0, i - 8)\n const blockEnd = Math.min(lines.length - 1, i + 8)\n const block = lines.slice(blockStart, blockEnd + 1).join('\\n')\n if (!/\\bfetch\\s*\\(/.test(block)) continue\n if (/\\btheoFetch\\s*\\(/.test(block)) continue\n if (/['\"`]X-Theo-Action['\"`]\\s*:/i.test(block)) continue\n\n out.push({\n file: rel,\n line: i + 1,\n rule: 'csrf-missing-header',\n message:\n 'fetch(' +\n match[1] +\n ') without X-Theo-Action header — will return 403 under 0.3.0 strict CSRF',\n fix: \"Use theoFetch(path, { method, body }) OR add headers: { 'X-Theo-Action': '1' }\",\n })\n }\n\n // dangerouslySetInnerHTML with <script> in the payload.\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (!/dangerouslySetInnerHTML/i.test(line)) continue\n // The script may live on the same line or in __html on a following\n // line; check a small window.\n const window = lines.slice(i, Math.min(lines.length, i + 6)).join('\\n')\n if (!/__html\\s*:\\s*['\"`][^'\"`]*<script\\b/i.test(window)) continue\n out.push({\n file: rel,\n line: i + 1,\n rule: 'dangerously-set-inline-script',\n message:\n 'dangerouslySetInnerHTML payload contains <script> — blocked under 0.3.0 enforce CSP',\n fix: 'Move the script into a real module loaded via <script src=\"...\">, or thread ctx.nonce',\n })\n }\n}\n\nconst INLINE_SCRIPT_PATTERN = /<script\\b(?![^>]*\\bsrc\\s*=)[^>]*>[\\s\\S]*?<\\/script>/gi\n\nfunction scanHtmlFile(file: string, rel: string, content: string, out: Violation[]): void {\n INLINE_SCRIPT_PATTERN.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = INLINE_SCRIPT_PATTERN.exec(content)) !== null) {\n // Compute 1-based line number from match index.\n const before = content.slice(0, match.index)\n const line = (before.match(/\\n/g) ?? []).length + 1\n out.push({\n file: rel,\n line,\n rule: 'inline-script',\n message:\n 'Inline <script> without src — blocked under 0.3.0 enforce CSP without unsafe-inline',\n fix: \"Move into a real script file (e.g. /main.js) and load with <script src='/main.js'>, or thread ctx.nonce\",\n })\n }\n}\n\n/**\n * T4.1 — Zero-config hint: consumer has @theokit/ui in deps AND a manual\n * tailwind.config.* that does NOT import the @theokit/ui preset. Suggest\n * extending via `import preset from '@theokit/ui/preset'`.\n */\nfunction scanZeroConfigTailwindHint(cwd: string, out: Violation[]): void {\n const pkgPath = resolve(cwd, 'package.json')\n if (!existsSync(pkgPath)) return\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> }\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as typeof pkg\n } catch {\n return\n }\n const hasUi =\n Boolean(pkg.dependencies?.['@theokit/ui']) || Boolean(pkg.devDependencies?.['@theokit/ui'])\n if (!hasUi) return\n\n for (const ext of ['.ts', '.js', '.mjs', '.cjs']) {\n const cfgPath = resolve(cwd, `tailwind.config${ext}`)\n if (!existsSync(cfgPath)) continue\n let content: string\n try {\n content = readFileSync(cfgPath, 'utf8')\n } catch {\n continue\n }\n if (content.includes('@theokit/ui/preset')) return // already using preset\n out.push({\n file: `tailwind.config${ext}`,\n line: 1,\n rule: 'zero-config-tailwind-suggest',\n message:\n '@theokit/ui detected with a manual tailwind.config — extend with the UI preset to keep theme tokens in sync.',\n fix: \"import preset from '@theokit/ui/preset'; export default { presets: [preset], content: [...] }\",\n })\n return\n }\n}\n\n/**\n * T4.1 — Zero-config hint: consumer has hand-rolled dotenv loading in\n * server/ (import 'dotenv/config', dotenv.config(), readFile('.env'), etc.).\n * Suggest the framework's loadEnv (auto-invoked by CLI commands; importable\n * from theokit/server for standalone scripts).\n */\nfunction scanHandRolledDotenvHint(\n file: string,\n rel: string,\n content: string,\n out: Violation[],\n): void {\n // Only flag server/ files\n if (!rel.startsWith('server/')) return\n const lines = content.split('\\n')\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? ''\n // import 'dotenv/config' or import * as dotenv from 'dotenv'\n if (/from\\s+['\"]dotenv['\"]/.test(line) || /import\\s+['\"]dotenv\\/config['\"]/.test(line)) {\n out.push({\n file: rel,\n line: i + 1,\n rule: 'handrolled-dotenv-suggest',\n message:\n 'Manual dotenv import detected — TheoKit auto-loads .env in CLI commands. For standalone scripts, import { loadEnv } from \"theokit/server\".',\n fix: \"Remove this import. CLI commands (dev/build/start) auto-load .env. For standalone scripts: import { loadEnv } from 'theokit/server'; loadEnv()\",\n })\n return // one hint per file\n }\n }\n}\n\n/**\n * EC-3: a directory may have an `app/` directory (Next.js, Remix, etc.) but\n * not actually be a TheoKit project. Run our 3 rules against such a project\n * would generate many false positives. The strict guard checks for `theokit`\n * in dependencies OR devDependencies of the cwd's package.json. Returns\n * `null` when the project IS a TheoKit project, or a non-TheoKit report\n * otherwise.\n */\nfunction detectNonTheokitProject(cwd: string): UpgradeReadinessReport | null {\n const pkgPath = resolve(cwd, 'package.json')\n if (!existsSync(pkgPath)) {\n // No package.json — let the existing app/server detection handle it.\n return null\n }\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> }\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as typeof pkg\n } catch {\n // Malformed package.json — treat as \"not a TheoKit project we can verify\".\n return { status: 'not-a-theokit-project', exitCode: 1, violations: [] }\n }\n const deps = pkg.dependencies ?? {}\n const devDeps = pkg.devDependencies ?? {}\n if (!Object.hasOwn(deps, 'theokit') && !Object.hasOwn(devDeps, 'theokit')) {\n return { status: 'not-a-theokit-project', exitCode: 1, violations: [] }\n }\n return null\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async surface for future fs.promises migration\nexport async function scanUpgradeReadiness(options: ScanOptions): Promise<UpgradeReadinessReport> {\n const cwd = options.cwd\n const allowWarnings = options.allowWarnings === true\n\n const appDir = resolve(cwd, 'app')\n const serverDir = resolve(cwd, 'server')\n const publicDir = resolve(cwd, 'public')\n\n const hasApp = existsSync(appDir)\n const hasServer = existsSync(serverDir)\n\n if (!hasApp && !hasServer) {\n return { status: 'no-project-detected', exitCode: 0, violations: [] }\n }\n\n // EC-3: refuse to scan non-TheoKit projects (avoid FP avalanche).\n const nonTheokit = detectNonTheokitProject(cwd)\n if (nonTheokit) return nonTheokit\n\n const files: string[] = []\n if (hasApp) walkFiles(appDir, cwd, files)\n if (hasServer) walkFiles(serverDir, cwd, files)\n if (existsSync(publicDir)) walkFiles(publicDir, cwd, files)\n\n const violations: Violation[] = []\n for (const file of files) {\n let content: string\n try {\n content = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n const rel = relative(cwd, file).split(sep).join('/')\n const dot = file.lastIndexOf('.')\n const ext = dot >= 0 ? file.slice(dot) : ''\n if (HTML_EXTS.has(ext)) {\n scanHtmlFile(file, rel, content, violations)\n } else if (SOURCE_EXTS.has(ext)) {\n scanSourceFile(file, rel, content, violations)\n scanHandRolledDotenvHint(file, rel, content, violations)\n }\n }\n\n // T4.1 — Project-level hint (not per-file): does the consumer have a\n // manual tailwind.config without the UI preset?\n scanZeroConfigTailwindHint(cwd, violations)\n\n const hasHigh = violations.length > 0\n const status: ReadinessStatus = hasHigh ? 'has-violations' : 'ready'\n const exitCode: 0 | 1 = hasHigh && !allowWarnings ? 1 : 0\n return { status, exitCode, violations }\n}\n\n/**\n * CLI wrapper. Prints a human-readable or JSON report and exits with the\n * computed exit code. Imported lazily from `cli/index.ts`.\n */\nexport async function upgradeReadinessCommand(opts: {\n json?: boolean\n allowWarnings?: boolean\n}): Promise<void> {\n const report = await scanUpgradeReadiness({\n cwd: process.cwd(),\n allowWarnings: opts.allowWarnings,\n })\n\n if (opts.json) {\n console.log(JSON.stringify(report, null, 2))\n process.exit(report.exitCode)\n }\n\n console.log('')\n if (report.status === 'no-project-detected') {\n console.log(\" · No theokit project detected here (no 'app/' or 'server/' dir).\")\n console.log('')\n process.exit(report.exitCode)\n }\n if (report.status === 'not-a-theokit-project') {\n console.log(' ✗ Not a TheoKit project (theokit not in package.json).')\n console.log(' Run this command from a TheoKit project root.')\n console.log('')\n process.exit(report.exitCode)\n }\n if (report.violations.length === 0) {\n console.log(' ✓ Upgrade-readiness 0.3: no violations detected.')\n console.log('')\n // T1.3 — friendly post-success URL (blueprint R4; Next.js next-codemod precedent).\n // Anchor canon: #rollback (existing in docs/migration/0.2-to-0.3.md per T1.1).\n console.log(' Migration guide: https://theokit.dev/migration/0.2-to-0.3')\n console.log(' Need to roll back temporarily? See #rollback')\n console.log('')\n process.exit(report.exitCode)\n }\n console.log(` ✗ Upgrade-readiness 0.3: ${report.violations.length} violation(s)`)\n console.log('')\n for (const v of report.violations) {\n console.log(` ${v.file}:${v.line} [${v.rule}]`)\n console.log(` ${v.message}`)\n console.log(` fix: ${v.fix}`)\n console.log('')\n }\n // T1.3 — print migration-guide URL on violations branch too (one canonical link\n // regardless of verdict, per blueprint Q5 Astro CHANGELOG URL pattern).\n console.log(' Migration guide: https://theokit.dev/migration/0.2-to-0.3#rollback')\n console.log('')\n process.exit(report.exitCode)\n}\n"],"mappings":";;;;AAAA,SAAS,YAAY,cAAc,aAAa,gBAAgB;AAChE,SAAS,SAAS,UAAU,WAAW;AAyDvC,IAAM,YAAY,oBAAI,IAAI,CAAC,gBAAgB,QAAQ,QAAQ,SAAS,SAAS,YAAY,QAAQ,CAAC;AAClG,IAAM,cAAc,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,QAAQ,QAAQ,MAAM,CAAC;AAC1E,IAAM,YAAY,oBAAI,IAAI,CAAC,SAAS,MAAM,CAAC;AAE3C,SAAS,UAAU,KAAa,MAAc,KAAqB;AACjE,MAAI;AACJ,MAAI;AACF,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AO,QAAQ;AAAA,EAC9B;AACA,MAAI,OAAO,WAAW,WAAW,GAAG;AAClC,YAAQ,IAAI,yDAAoD;AAChE,YAAQ,IAAI,EAAE;AAGd,YAAQ,IAAI,6DAA6D;AACzE,YAAQ,IAAI,gDAAgD;AAC5D,YAAQ,IAAI,EAAE;AACd,YAAQ,KAAK,OAAO,QAAQ;AAAA,EAC9B;AACA,UAAQ,IAAI,mCAA8B,OAAO,WAAW,MAAM,eAAe;AACjF,UAAQ,IAAI,EAAE;AACd,aAAW,KAAK,OAAO,YAAY;AACjC,YAAQ,IAAI,KAAK,EAAE,IAAI,IAAI,EAAE,IAAI,MAAM,EAAE,IAAI,GAAG;AAChD,YAAQ,IAAI,OAAO,EAAE,OAAO,EAAE;AAC9B,YAAQ,IAAI,YAAY,EAAE,GAAG,EAAE;AAC/B,YAAQ,IAAI,EAAE;AAAA,EAChB;AAGA,UAAQ,IAAI,sEAAsE;AAClF,UAAQ,IAAI,EAAE;AACd,UAAQ,KAAK,OAAO,QAAQ;AAC9B;","names":["before"]}
@@ -2,11 +2,11 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  nodeAdapter
5
- } from "./chunk-FOZIR3TG.js";
5
+ } from "./chunk-SMP2T335.js";
6
6
  import {
7
7
  assertServicesUnsupported,
8
8
  readManifest
9
- } from "./chunk-45C3WUQ7.js";
9
+ } from "./chunk-QPVXGC7O.js";
10
10
 
11
11
  // src/adapters/vercel.ts
12
12
  import { existsSync, mkdirSync, writeFileSync, cpSync } from "fs";
@@ -130,4 +130,4 @@ export {
130
130
  renderVercelVcConfigJson,
131
131
  vercelAdapter
132
132
  };
133
- //# sourceMappingURL=vercel-J6G7ZHYQ.js.map
133
+ //# sourceMappingURL=vercel-FP3C6LN6.js.map
@@ -5,19 +5,19 @@ import {
5
5
  defineTheoIntegration,
6
6
  theoPlugin,
7
7
  theoPluginAsync
8
- } from "../chunk-2ZX4J4SX.js";
9
- import "../chunk-D7ZH7DTG.js";
8
+ } from "../chunk-DQVBL2G4.js";
9
+ import "../chunk-4B2ZMX45.js";
10
10
  import "../chunk-7BIM27LV.js";
11
- import "../chunk-AXVFVMLM.js";
12
- import "../chunk-GW5H4KB4.js";
13
- import "../chunk-QWBXUZAX.js";
14
- import "../chunk-GY5Q27BJ.js";
11
+ import "../chunk-DJFMAWH5.js";
12
+ import "../chunk-FX72VHAE.js";
13
+ import "../chunk-JIL74SFK.js";
14
+ import "../chunk-6FK7FKY6.js";
15
15
  import "../chunk-5QW7IQQU.js";
16
- import "../chunk-WFNLNIJX.js";
16
+ import "../chunk-VPISAMXU.js";
17
17
  import "../chunk-IAJ2JVEH.js";
18
18
  import "../chunk-VMEWD57H.js";
19
19
  import "../chunk-JQSKBMXP.js";
20
- import "../chunk-IHJZPQEF.js";
20
+ import "../chunk-4HAU7AJM.js";
21
21
  import "../chunk-WSJKACWB.js";
22
22
  import "../chunk-ZEGYW52B.js";
23
23
  import "../chunk-JBCHWRKF.js";
@@ -28,7 +28,7 @@ import "../chunk-UVXB2ER7.js";
28
28
  import "../chunk-HZ6USUHC.js";
29
29
  import "../chunk-C3ZZ56YZ.js";
30
30
  import "../chunk-7MQOHNHE.js";
31
- import "../chunk-X2VVCJ4V.js";
31
+ import "../chunk-65EFIUDD.js";
32
32
  import "../chunk-DGUM43GV.js";
33
33
  export {
34
34
  IntegrationRouteCollisionError,
@@ -7,22 +7,22 @@ import {
7
7
  defineTheoIntegration,
8
8
  theoPlugin,
9
9
  theoPluginAsync
10
- } from "./chunk-IPC5UREF.js";
11
- import "./chunk-UO7WS32S.js";
10
+ } from "./chunk-575PAX5L.js";
11
+ import "./chunk-OI6DK6ZJ.js";
12
12
  import "./chunk-2CVV6CNN.js";
13
13
  import "./chunk-IEES3CHD.js";
14
- import "./chunk-AFVTEAES.js";
14
+ import "./chunk-CJNMJUHE.js";
15
15
  import "./chunk-GDN3PXFH.js";
16
- import "./chunk-GSO77FSM.js";
17
- import "./chunk-45C3WUQ7.js";
16
+ import "./chunk-6OXCZMW3.js";
17
+ import "./chunk-QPVXGC7O.js";
18
18
  import "./chunk-5ODOE6EF.js";
19
- import "./chunk-SPJNVWOK.js";
20
- import "./chunk-UNLG36Z5.js";
21
- import "./chunk-M6NMS5LR.js";
22
- import "./chunk-NQRNDPZJ.js";
23
- import "./chunk-L4GCEMNW.js";
24
- import "./chunk-FRUEDJFX.js";
25
- import "./chunk-P37RZRFV.js";
19
+ import "./chunk-N2D5AVRR.js";
20
+ import "./chunk-IE6C4KZX.js";
21
+ import "./chunk-TDNNBLGW.js";
22
+ import "./chunk-OXCALO3W.js";
23
+ import "./chunk-LNVMHQ2Z.js";
24
+ import "./chunk-226KMIGZ.js";
25
+ import "./chunk-A7JBF5FO.js";
26
26
  import "./chunk-HGZL5EOI.js";
27
27
  export {
28
28
  IntegrationRouteCollisionError,
@@ -32,4 +32,4 @@ export {
32
32
  theoPlugin,
33
33
  theoPluginAsync
34
34
  };
35
- //# sourceMappingURL=vite-plugin-6VVU6PPC.js.map
35
+ //# sourceMappingURL=vite-plugin-D2NTPZNC.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "theokit",
3
- "version": "0.43.7",
3
+ "version": "0.43.12",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "license": "Apache-2.0",
@@ -123,8 +123,8 @@
123
123
  "tsx": "^4.22.4",
124
124
  "typescript": "^5.9.3",
125
125
  "vite": "^6.4.3",
126
- "@theokit/http": "^0.7.0",
127
- "@theokit/agents": "^0.44.6"
126
+ "@theokit/http": "^1.0.0",
127
+ "@theokit/agents": "^4.23.1"
128
128
  },
129
129
  "peerDependencies": {
130
130
  "@theokit/sdk": "^4.0.1",
@@ -161,17 +161,14 @@
161
161
  "devDependencies": {
162
162
  "@theokit/sdk": "^4.1.0",
163
163
  "@types/busboy": "^1.5.4",
164
- "@types/pg": "^8.20.0",
165
164
  "@types/picomatch": "^4.0.3",
166
165
  "ai": "^7.0.14",
167
166
  "better-sqlite3": "^12.11.1",
168
167
  "db0": "^0.3.4",
169
- "pg": "^8.22.0",
170
- "pg-mem": "^3.0.14",
171
168
  "unstorage": "^1.17.5"
172
169
  },
173
170
  "publishConfig": {
174
- "provenance": true,
171
+ "provenance": false,
175
172
  "access": "public"
176
173
  },
177
174
  "engines": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/vite-plugin/actions-virtual-module.ts"],"sourcesContent":["/**\n * Vite plugin: resolves `@theo/actions` virtual module and emits a typed\n * Proxy facade that calls `theoFetch('/_actions/<name>', body)` against the\n * server-side action handlers.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 3 / T3.1 + ADR D4.\n * Astro `vite-plugin-actions.ts` modular pattern. Single focused plugin\n * (not monolithic), virtual module + `configureServer` watcher.\n *\n * Module shape emitted on client environment: thin proxy that forwards\n * `actions.<name>(input)` to `POST /_actions/<name>` with JSON or\n * FormData body. On server environment: re-export of the manifest for\n * SSR / module-loader access (T1.3 sub-C consumer).\n *\n * EC-15 (DOCUMENT): HMR uses Vite default invalidation — coarse but\n * correct. Optimization (fine-grained invalidation of only consumers of\n * `@theo/actions`) deferred to G3.1 if dev-server p95 reload > 500ms.\n */\nimport { existsSync, mkdirSync, renameSync, watch as fsWatch, writeFileSync } from 'node:fs'\nimport { dirname, join, posix, resolve } from 'node:path'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\nimport { scanServerActionsEnriched, type ActionManifestEntry } from '../server/internal-api.js'\n\nconst VIRTUAL_ID = '@theo/actions'\nconst RESOLVED_ID = `\\0${VIRTUAL_ID}`\n\nexport interface ActionsVirtualModuleOptions {\n /** Path to server directory (where `actions/` lives). */\n serverDir: string\n /**\n * Optional `.theokit/` output dir for emitting `actions.d.ts`. When provided,\n * the plugin writes an ambient `declare module '@theo/actions'` so TS in\n * consumer apps can resolve the virtual module import. Mirrors the G1\n * `app-typed-client` emit pattern.\n */\n distDir?: string\n}\n\nexport function actionsVirtualModule(opts: ActionsVirtualModuleOptions): Plugin {\n const { serverDir, distDir } = opts\n\n function emitActionsDts(): void {\n if (distDir === undefined) return\n const entries = safeScan(serverDir)\n const dtsPath = posix.join(resolve(distDir).replace(/\\\\/g, '/'), 'actions.d.ts')\n const content = generateActionsDts(entries)\n try {\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n mkdirSync(dirname(dtsPath), { recursive: true })\n const tmp = `${dtsPath}.${process.pid}.tmp`\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n writeFileSync(tmp, content)\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n renameSync(tmp, dtsPath)\n } catch (err) {\n console.error('[theokit:actions-virtual-module] dts emit error:', err)\n }\n }\n\n return {\n name: 'theo:actions-virtual-module',\n enforce: 'pre',\n configResolved() {\n emitActionsDts()\n },\n buildEnd() {\n emitActionsDts()\n },\n resolveId(id: string) {\n if (id === VIRTUAL_ID) return RESOLVED_ID\n return undefined\n },\n load(id: string) {\n if (id !== RESOLVED_ID) return undefined\n const entries = safeScan(serverDir)\n const ctx = this as unknown as { environment?: { name?: string } } | undefined\n const envName = ctx?.environment?.name\n const isClient = envName === 'client' || envName === undefined\n return isClient ? generateClientFacade(entries) : generateServerManifest(entries)\n },\n configureServer(server: ViteDevServer) {\n const actionsDir = join(serverDir, 'actions')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n if (!existsSync(actionsDir)) return\n // EC-15: coarse invalidation — invalidate ALL modules on actions file change.\n // Optimization deferred per plan ADR D4 note.\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time path\n const watcher = fsWatch(actionsDir, { recursive: true }, () => {\n emitActionsDts()\n const mod = server.moduleGraph.getModuleById(RESOLVED_ID)\n if (mod) {\n server.moduleGraph.invalidateModule(mod)\n }\n server.ws.send({ type: 'full-reload' })\n })\n server.httpServer?.once('close', () => {\n watcher.close()\n })\n },\n }\n}\n\n/**\n * Emit `.theokit/actions.d.ts` — ambient declaration of `@theo/actions` so\n * consumer TS apps can `import { actions } from '@theo/actions'` and get\n * typed completions for each scanned action name. Each entry maps name to\n * a generic `(input: unknown) => Promise<{data, error}>` invoker — the full\n * input/output inference from defineAction would require either monomorphic\n * dts-bundle or virtual type emit (deferred to a future plan).\n */\nfunction generateActionsDts(entries: readonly ActionManifestEntry[]): string {\n const lines = entries\n .map((entry) => {\n const invokerType = `(input: unknown) => Promise<{ data: unknown; error: undefined } | { data: undefined; error: { code: string; message: string; fields?: Record<string, string[]>; type?: string } }>`\n // P#4 plugin-forms typed __zodSchema (per plan p4-plugin-forms v1.1 EC-3).\n // When schemaFilePath present, emit intersection type so consumers see both\n // the callable invoker AND the __zodSchema field with the exact schema type.\n if (entry.schemaFilePath !== undefined) {\n const schemaImportPath = entry.schemaFilePath\n .replace(/\\\\/g, '/')\n .replace(/\\.(ts|tsx|js|jsx)$/, '.js')\n return ` ${JSON.stringify(entry.name)}: (${invokerType}) & { readonly __zodSchema: typeof import(${JSON.stringify(schemaImportPath)}).schema }`\n }\n return ` ${JSON.stringify(entry.name)}: ${invokerType}`\n })\n .join('\\n')\n return `// AUTO-GENERATED by @theo/actions virtual module. DO NOT EDIT MANUALLY.\ndeclare module '@theo/actions' {\n export const actions: {\n${lines}\n }\n}\n`\n}\n\nfunction safeScan(serverDir: string): ActionManifestEntry[] {\n try {\n return scanServerActionsEnriched(serverDir)\n } catch {\n // ActionScanError surfaces at build time; for HMR keep an empty manifest\n // so the dev server doesn't crash mid-edit.\n return []\n }\n}\n\n/**\n * Client-side module: emits a Proxy facade. For each action `name` in\n * manifest, `actions.<name>(input)` POSTs to `/_actions/<name>` with JSON\n * body (or FormData when input is a FormData instance) and parses the\n * `application/json+devalue` response via the runtime helper.\n */\nfunction generateClientFacade(entries: ActionManifestEntry[]): string {\n const entryLines = entries\n .map((entry) => ` ${JSON.stringify(entry.name)}: ${JSON.stringify(entry.urlPath)},`)\n .join('\\n')\n\n // P#4 plugin-forms shared-schema convention (per plan p4-plugin-forms v1.1 T1.1).\n // Emit ESM imports + ACTION_SCHEMA_MAP so the Proxy can attach __zodSchema.\n // Vite resolves absolute filesystem paths via its module graph; schema files\n // are isomorphic (zod-only, no server APIs) so they bundle into the client.\n const schemaEntries = entries.filter((e) => e.schemaFilePath !== undefined)\n const schemaImports = schemaEntries\n .map((entry, idx) => {\n // schemaEntries was filtered by `e.schemaFilePath !== undefined` above,\n // so the assertion is provably safe in this scope.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const importPath = entry.schemaFilePath!.replace(/\\\\/g, '/')\n return `import { schema as __theoSchema${idx} } from ${JSON.stringify(importPath)}`\n })\n .join('\\n')\n const schemaMapLines = schemaEntries\n .map((entry, idx) => ` ${JSON.stringify(entry.name)}: __theoSchema${idx},`)\n .join('\\n')\n\n return `// AUTO-GENERATED by @theo/actions virtual module\n/* eslint-disable */\n${schemaImports}\n\nconst ACTION_URL_MAP = {\n${entryLines}\n}\n\nconst ACTION_SCHEMA_MAP = {\n${schemaMapLines}\n}\n\n// Devtools telemetry — fires in the SAME realm as the Overlay React tree\n// (browser), so the Actions tab updates immediately on each call.\n// The Overlay component installs \\`window.__theoDevtoolsDispatcher\\` on\n// mount (dev only; prod tree-shakes the Overlay entirely). Reading the\n// global avoids a cross-package dynamic import that Vite's virtual-module\n// resolver cannot trace. Same pattern as React DevTools'\n// \\`__REACT_DEVTOOLS_GLOBAL_HOOK__\\`.\nfunction emitTelemetry(name, startedAt, input, outcome) {\n if (typeof window === 'undefined') return\n const dispatcher = window.__theoDevtoolsDispatcher\n if (!dispatcher || typeof dispatcher.onActionCall !== 'function') return\n try {\n dispatcher.onActionCall({\n id: 'act-' + String(Date.now()) + '-' + Math.random().toString(36).slice(2, 8),\n timestamp: startedAt,\n name,\n input,\n output: outcome.status === 'success' ? outcome.data : undefined,\n error: outcome.status === 'error' ? outcome.error : undefined,\n durationMs: Date.now() - startedAt,\n status: outcome.status,\n })\n } catch (_) {\n // dispatcher threw — devtools UI bug; never bubble to consumer code\n }\n}\n\nasync function callAction(name, url, input) {\n const startedAt = Date.now()\n const isForm = typeof FormData !== 'undefined' && input instanceof FormData\n const headers = { 'x-theo-action': '1' }\n const body = isForm ? input : JSON.stringify(input ?? {})\n if (!isForm) headers['content-type'] = 'application/json'\n let response\n try {\n response = await fetch(url, { method: 'POST', headers, body, credentials: 'same-origin' })\n } catch (e) {\n const err = { code: 'NETWORK_ERROR', message: e && e.message ? e.message : 'fetch failed' }\n emitTelemetry(name, startedAt, input, { status: 'error', error: err })\n return { data: undefined, error: err }\n }\n const contentType = response.headers.get('content-type') ?? ''\n let result\n if (response.status === 204) {\n result = { data: undefined, error: undefined }\n } else if (contentType.startsWith('application/json+devalue')) {\n const text = await response.text()\n const { parse } = await import('devalue')\n result = { data: parse(text, { URL: (h) => new URL(h) }), error: undefined }\n } else if (contentType.startsWith('application/json')) {\n const json = await response.json()\n result = response.ok ? { data: json, error: undefined } : { data: undefined, error: json }\n } else {\n result = { data: undefined, error: { code: 'INTERNAL_SERVER_ERROR', message: await response.text() } }\n }\n emitTelemetry(name, startedAt, input, result.error\n ? { status: 'error', error: result.error }\n : { status: 'success', data: result.data })\n return result\n}\n\n// P#4 plugin-forms cache: callable proxies must be stable per action so that\n// repeated property access does not allocate + reset the __zodSchema attach.\nconst ACTION_CALLABLE_CACHE = {}\n\nexport const actions = new Proxy({}, {\n get(target, prop) {\n if (typeof prop !== 'string') return undefined\n const url = ACTION_URL_MAP[prop]\n if (!url) return undefined\n if (!ACTION_CALLABLE_CACHE[prop]) {\n const callable = (input) => callAction(prop, url, input)\n const schema = ACTION_SCHEMA_MAP[prop]\n if (schema !== undefined) {\n Object.defineProperty(callable, '__zodSchema', {\n value: schema,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n }\n ACTION_CALLABLE_CACHE[prop] = callable\n }\n return ACTION_CALLABLE_CACHE[prop]\n },\n})\n`\n}\n\n/**\n * Server-side module: re-exports the manifest entries for SSR / module-\n * loader consumption (T1.3 sub-C in action-execute.ts will route requests\n * via this manifest).\n */\nfunction generateServerManifest(entries: ActionManifestEntry[]): string {\n return `// AUTO-GENERATED by @theo/actions virtual module (server env)\n/* eslint-disable */\nexport const manifest = ${JSON.stringify(entries, null, 2)}\nexport const actions = manifest\n`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAS,YAAY,WAAW,YAAY,SAAS,SAAS,qBAAqB;AACnF,SAAS,SAAS,MAAM,OAAO,eAAe;AAM9C,IAAM,aAAa;AACnB,IAAM,cAAc,KAAK,UAAU;AAc5B,SAAS,qBAAqB,MAA2C;AAC9E,QAAM,EAAE,WAAW,QAAQ,IAAI;AAE/B,WAAS,iBAAuB;AAC9B,QAAI,YAAY,OAAW;AAC3B,UAAM,UAAU,SAAS,SAAS;AAClC,UAAM,UAAU,MAAM,KAAK,QAAQ,OAAO,EAAE,QAAQ,OAAO,GAAG,GAAG,cAAc;AAC/E,UAAM,UAAU,mBAAmB,OAAO;AAC1C,QAAI;AAEF,gBAAU,QAAQ,OAAO,GAAG,EAAE,WAAW,KAAK,CAAC;AAC/C,YAAM,MAAM,GAAG,OAAO,IAAI,QAAQ,GAAG;AAErC,oBAAc,KAAK,OAAO;AAE1B,iBAAW,KAAK,OAAO;AAAA,IACzB,SAAS,KAAK;AACZ,cAAQ,MAAM,oDAAoD,GAAG;AAAA,IACvE;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,iBAAiB;AACf,qBAAe;AAAA,IACjB;AAAA,IACA,WAAW;AACT,qBAAe;AAAA,IACjB;AAAA,IACA,UAAU,IAAY;AACpB,UAAI,OAAO,WAAY,QAAO;AAC9B,aAAO;AAAA,IACT;AAAA,IACA,KAAK,IAAY;AACf,UAAI,OAAO,YAAa,QAAO;AAC/B,YAAM,UAAU,SAAS,SAAS;AAClC,YAAM,MAAM;AACZ,YAAM,UAAU,KAAK,aAAa;AAClC,YAAM,WAAW,YAAY,YAAY,YAAY;AACrD,aAAO,WAAW,qBAAqB,O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cesContent":["/**\n * Vite plugin: resolves `@theo/actions` virtual module and emits a typed\n * Proxy facade that calls `theoFetch('/_actions/<name>', body)` against the\n * server-side action handlers.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 3 / T3.1 + ADR D4.\n * Astro `vite-plugin-actions.ts` modular pattern. Single focused plugin\n * (not monolithic), virtual module + `configureServer` watcher.\n *\n * Module shape emitted on client environment: thin proxy that forwards\n * `actions.<name>(input)` to `POST /_actions/<name>` with JSON or\n * FormData body. On server environment: re-export of the manifest for\n * SSR / module-loader access (T1.3 sub-C consumer).\n *\n * EC-15 (DOCUMENT): HMR uses Vite default invalidation — coarse but\n * correct. Optimization (fine-grained invalidation of only consumers of\n * `@theo/actions`) deferred to G3.1 if dev-server p95 reload > 500ms.\n */\nimport { existsSync, mkdirSync, renameSync, watch as fsWatch, writeFileSync } from 'node:fs'\nimport { dirname, join, posix, resolve } from 'node:path'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\nimport { scanServerActionsEnriched, type ActionManifestEntry } from '../server/internal-api.js'\n\nconst VIRTUAL_ID = '@theo/actions'\nconst RESOLVED_ID = `\\0${VIRTUAL_ID}`\n\nexport interface ActionsVirtualModuleOptions {\n /** Path to server directory (where `actions/` lives). */\n serverDir: string\n /**\n * Optional `.theokit/` output dir for emitting `actions.d.ts`. When provided,\n * the plugin writes an ambient `declare module '@theo/actions'` so TS in\n * consumer apps can resolve the virtual module import. Mirrors the G1\n * `app-typed-client` emit pattern.\n */\n distDir?: string\n}\n\nexport function actionsVirtualModule(opts: ActionsVirtualModuleOptions): Plugin {\n const { serverDir, distDir } = opts\n\n function emitActionsDts(): void {\n if (distDir === undefined) return\n const entries = safeScan(serverDir)\n const dtsPath = posix.join(resolve(distDir).replace(/\\\\/g, '/'), 'actions.d.ts')\n const content = generateActionsDts(entries)\n try {\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n mkdirSync(dirname(dtsPath), { recursive: true })\n const tmp = `${dtsPath}.${process.pid}.tmp`\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n writeFileSync(tmp, content)\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n renameSync(tmp, dtsPath)\n } catch (err) {\n console.error('[theokit:actions-virtual-module] dts emit error:', err)\n }\n }\n\n return {\n name: 'theo:actions-virtual-module',\n enforce: 'pre',\n configResolved() {\n emitActionsDts()\n },\n buildEnd() {\n emitActionsDts()\n },\n resolveId(id: string) {\n if (id === VIRTUAL_ID) return RESOLVED_ID\n return undefined\n },\n load(id: string) {\n if (id !== RESOLVED_ID) return undefined\n const entries = safeScan(serverDir)\n const ctx = this as unknown as { environment?: { name?: string } } | undefined\n const envName = ctx?.environment?.name\n const isClient = envName === 'client' || envName === undefined\n return isClient ? generateClientFacade(entries) : generateServerManifest(entries)\n },\n configureServer(server: ViteDevServer) {\n const actionsDir = join(serverDir, 'actions')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n if (!existsSync(actionsDir)) return\n // EC-15: coarse invalidation — invalidate ALL modules on actions file change.\n // Optimization deferred per plan ADR D4 note.\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time path\n const watcher = fsWatch(actionsDir, { recursive: true }, () => {\n emitActionsDts()\n const mod = server.moduleGraph.getModuleById(RESOLVED_ID)\n if (mod) {\n server.moduleGraph.invalidateModule(mod)\n }\n server.ws.send({ type: 'full-reload' })\n })\n server.httpServer?.once('close', () => {\n watcher.close()\n })\n },\n }\n}\n\n/**\n * Emit `.theokit/actions.d.ts` — ambient declaration of `@theo/actions` so\n * consumer TS apps can `import { actions } from '@theo/actions'` and get\n * typed completions for each scanned action name. Each entry maps name to\n * a generic `(input: unknown) => Promise<{data, error}>` invoker — the full\n * input/output inference from defineAction would require either monomorphic\n * dts-bundle or virtual type emit (deferred to a future plan).\n */\nfunction generateActionsDts(entries: readonly ActionManifestEntry[]): string {\n const lines = entries\n .map((entry) => {\n const invokerType = `(input: unknown) => Promise<{ data: unknown; error: undefined } | { data: undefined; error: { code: string; message: string; fields?: Record<string, string[]>; type?: string } }>`\n // P#4 plugin-forms typed __zodSchema (per plan p4-plugin-forms v1.1 EC-3).\n // When schemaFilePath present, emit intersection type so consumers see both\n // the callable invoker AND the __zodSchema field with the exact schema type.\n if (entry.schemaFilePath !== undefined) {\n const schemaImportPath = entry.schemaFilePath\n .replace(/\\\\/g, '/')\n .replace(/\\.(ts|tsx|js|jsx)$/, '.js')\n return ` ${JSON.stringify(entry.name)}: (${invokerType}) & { readonly __zodSchema: typeof import(${JSON.stringify(schemaImportPath)}).schema }`\n }\n return ` ${JSON.stringify(entry.name)}: ${invokerType}`\n })\n .join('\\n')\n return `// AUTO-GENERATED by @theo/actions virtual module. DO NOT EDIT MANUALLY.\ndeclare module '@theo/actions' {\n export const actions: {\n${lines}\n }\n}\n`\n}\n\nfunction safeScan(serverDir: string): ActionManifestEntry[] {\n try {\n return scanServerActionsEnriched(serverDir)\n } catch {\n // ActionScanError surfaces at build time; for HMR keep an empty manifest\n // so the dev server doesn't crash mid-edit.\n return []\n }\n}\n\n/**\n * Client-side module: emits a Proxy facade. For each action `name` in\n * manifest, `actions.<name>(input)` POSTs to `/_actions/<name>` with JSON\n * body (or FormData when input is a FormData instance) and parses the\n * `application/json+devalue` response via the runtime helper.\n */\nfunction generateClientFacade(entries: ActionManifestEntry[]): string {\n const entryLines = entries\n .map((entry) => ` ${JSON.stringify(entry.name)}: ${JSON.stringify(entry.urlPath)},`)\n .join('\\n')\n\n // P#4 plugin-forms shared-schema convention (per plan p4-plugin-forms v1.1 T1.1).\n // Emit ESM imports + ACTION_SCHEMA_MAP so the Proxy can attach __zodSchema.\n // Vite resolves absolute filesystem paths via its module graph; schema files\n // are isomorphic (zod-only, no server APIs) so they bundle into the client.\n const schemaEntries = entries.filter((e) => e.schemaFilePath !== undefined)\n const schemaImports = schemaEntries\n .map((entry, idx) => {\n // schemaEntries was filtered by `e.schemaFilePath !== undefined` above,\n // so the assertion is provably safe in this scope.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const importPath = entry.schemaFilePath!.replace(/\\\\/g, '/')\n return `import { schema as __theoSchema${idx} } from ${JSON.stringify(importPath)}`\n })\n .join('\\n')\n const schemaMapLines = schemaEntries\n .map((entry, idx) => ` ${JSON.stringify(entry.name)}: __theoSchema${idx},`)\n .join('\\n')\n\n return `// AUTO-GENERATED by @theo/actions virtual module\n/* eslint-disable */\n${schemaImports}\n\nconst ACTION_URL_MAP = {\n${entryLines}\n}\n\nconst ACTION_SCHEMA_MAP = {\n${schemaMapLines}\n}\n\n// Devtools telemetry — fires in the SAME realm as the Overlay React tree\n// (browser), so the Actions tab updates immediately on each call.\n// The Overlay component installs \\`window.__theoDevtoolsDispatcher\\` on\n// mount (dev only; prod tree-shakes the Overlay entirely). Reading the\n// global avoids a cross-package dynamic import that Vite's virtual-module\n// resolver cannot trace. Same pattern as React DevTools'\n// \\`__REACT_DEVTOOLS_GLOBAL_HOOK__\\`.\nfunction emitTelemetry(name, startedAt, input, outcome) {\n if (typeof window === 'undefined') return\n const dispatcher = window.__theoDevtoolsDispatcher\n if (!dispatcher || typeof dispatcher.onActionCall !== 'function') return\n try {\n dispatcher.onActionCall({\n id: 'act-' + String(Date.now()) + '-' + Math.random().toString(36).slice(2, 8),\n timestamp: startedAt,\n name,\n input,\n output: outcome.status === 'success' ? outcome.data : undefined,\n error: outcome.status === 'error' ? outcome.error : undefined,\n durationMs: Date.now() - startedAt,\n status: outcome.status,\n })\n } catch (_) {\n // dispatcher threw — devtools UI bug; never bubble to consumer code\n }\n}\n\nasync function callAction(name, url, input) {\n const startedAt = Date.now()\n const isForm = typeof FormData !== 'undefined' && input instanceof FormData\n const headers = { 'x-theo-action': '1' }\n const body = isForm ? input : JSON.stringify(input ?? {})\n if (!isForm) headers['content-type'] = 'application/json'\n let response\n try {\n response = await fetch(url, { method: 'POST', headers, body, credentials: 'same-origin' })\n } catch (e) {\n const err = { code: 'NETWORK_ERROR', message: e && e.message ? e.message : 'fetch failed' }\n emitTelemetry(name, startedAt, input, { status: 'error', error: err })\n return { data: undefined, error: err }\n }\n const contentType = response.headers.get('content-type') ?? ''\n let result\n if (response.status === 204) {\n result = { data: undefined, error: undefined }\n } else if (contentType.startsWith('application/json+devalue')) {\n const text = await response.text()\n const { parse } = await import('devalue')\n result = { data: parse(text, { URL: (h) => new URL(h) }), error: undefined }\n } else if (contentType.startsWith('application/json')) {\n const json = await response.json()\n result = response.ok ? { data: json, error: undefined } : { data: undefined, error: json }\n } else {\n result = { data: undefined, error: { code: 'INTERNAL_SERVER_ERROR', message: await response.text() } }\n }\n emitTelemetry(name, startedAt, input, result.error\n ? { status: 'error', error: result.error }\n : { status: 'success', data: result.data })\n return result\n}\n\n// P#4 plugin-forms cache: callable proxies must be stable per action so that\n// repeated property access does not allocate + reset the __zodSchema attach.\nconst ACTION_CALLABLE_CACHE = {}\n\nexport const actions = new Proxy({}, {\n get(target, prop) {\n if (typeof prop !== 'string') return undefined\n const url = ACTION_URL_MAP[prop]\n if (!url) return undefined\n if (!ACTION_CALLABLE_CACHE[prop]) {\n const callable = (input) => callAction(prop, url, input)\n const schema = ACTION_SCHEMA_MAP[prop]\n if (schema !== undefined) {\n Object.defineProperty(callable, '__zodSchema', {\n value: schema,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n }\n ACTION_CALLABLE_CACHE[prop] = callable\n }\n return ACTION_CALLABLE_CACHE[prop]\n },\n})\n`\n}\n\n/**\n * Server-side module: re-exports the manifest entries for SSR / module-\n * loader consumption (T1.3 sub-C in action-execute.ts will route requests\n * via this manifest).\n */\nfunction generateServerManifest(entries: ActionManifestEntry[]): string {\n return `// AUTO-GENERATED by @theo/actions virtual module (server env)\n/* eslint-disable */\nexport const manifest = ${JSON.stringify(entries, null, 2)}\nexport const actions = manifest\n`\n}\n"],"mappings":";;;;;;;;;;;;;;AAkBA,SAAS,YAAY,WAAW,YAAY,SAAS,SAAS,qBAAqB;AACnF,SAAS,SAAS,MAAM,O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