theokit 0.48.13 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/README.md +1 -0
  2. package/dist/{actions-virtual-module-YQXRSSMW.js → actions-virtual-module-5WBVSDOM.js} +22 -12
  3. package/dist/actions-virtual-module-5WBVSDOM.js.map +1 -0
  4. package/dist/{actions-virtual-module-LB4NGONI.js → actions-virtual-module-ZYLMNW6K.js} +13 -8
  5. package/dist/{actions-virtual-module-LB4NGONI.js.map → actions-virtual-module-ZYLMNW6K.js.map} +1 -1
  6. package/dist/adapters/agent-mount.d.ts +127 -0
  7. package/dist/adapters/agent-mount.js +24 -0
  8. package/dist/adapters/security-headers.d.ts +132 -0
  9. package/dist/adapters/security-headers.js +64 -0
  10. package/dist/adapters/security-headers.js.map +1 -0
  11. package/dist/adapters/web-shim.d.ts +100 -13
  12. package/dist/adapters/web-shim.js +158 -54
  13. package/dist/adapters/web-shim.js.map +1 -1
  14. package/dist/agent-GKUEL6OH.js +15 -0
  15. package/dist/agent-scan-BZa-pagG.d.ts +16 -0
  16. package/dist/{app-typed-client-GHO3EWZK.js → app-typed-client-4LAIEGFX.js} +23 -13
  17. package/dist/app-typed-client-4LAIEGFX.js.map +1 -0
  18. package/dist/{app-typed-client-G3J5G7E5.js → app-typed-client-DQM3Y6YY.js} +14 -9
  19. package/dist/app-typed-client-DQM3Y6YY.js.map +1 -0
  20. package/dist/aws-lambda-VKMYUMP2.js +261 -0
  21. package/dist/aws-lambda-VKMYUMP2.js.map +1 -0
  22. package/dist/{build-WU6AKKIB.js → build-FLX6VF7Q.js} +71 -26
  23. package/dist/build-FLX6VF7Q.js.map +1 -0
  24. package/dist/{bun-33RD6K7O.js → bun-L7PP6ID5.js} +105 -13
  25. package/dist/bun-L7PP6ID5.js.map +1 -0
  26. package/dist/{check-45NKUVSQ.js → check-GIPZBFTX.js} +2 -2
  27. package/dist/{chunk-KD5G3YXI.js → chunk-2AMLGJJA.js} +35 -9
  28. package/dist/chunk-2AMLGJJA.js.map +1 -0
  29. package/dist/chunk-3PBAN2YE.js +146 -0
  30. package/dist/chunk-3PBAN2YE.js.map +1 -0
  31. package/dist/{chunk-HBU2GIMZ.js → chunk-3QPVEJ7D.js} +15 -9
  32. package/dist/chunk-3QPVEJ7D.js.map +1 -0
  33. package/dist/{chunk-47CINLWF.js → chunk-44J2ANQC.js} +2 -2
  34. package/dist/{chunk-IEES3CHD.js → chunk-47MM2JUK.js} +8 -2
  35. package/dist/chunk-47MM2JUK.js.map +1 -0
  36. package/dist/chunk-4X6H2BXP.js +108 -0
  37. package/dist/chunk-4X6H2BXP.js.map +1 -0
  38. package/dist/{chunk-A7JBF5FO.js → chunk-5K4TDLRG.js} +8 -5
  39. package/dist/chunk-5K4TDLRG.js.map +1 -0
  40. package/dist/chunk-5YPXXSYY.js +181 -0
  41. package/dist/chunk-5YPXXSYY.js.map +1 -0
  42. package/dist/{chunk-YGAXV5HR.js → chunk-6J4JWHDJ.js} +191 -112
  43. package/dist/chunk-6J4JWHDJ.js.map +1 -0
  44. package/dist/chunk-72DMJBXI.js +424 -0
  45. package/dist/chunk-72DMJBXI.js.map +1 -0
  46. package/dist/chunk-7PM6K5EV.js +513 -0
  47. package/dist/chunk-7PM6K5EV.js.map +1 -0
  48. package/dist/{chunk-MTEWLGVY.js → chunk-BPYMC7SU.js} +4 -48
  49. package/dist/chunk-BPYMC7SU.js.map +1 -0
  50. package/dist/chunk-BU6RJPPJ.js +421 -0
  51. package/dist/chunk-BU6RJPPJ.js.map +1 -0
  52. package/dist/{chunk-FB2HBNIC.js → chunk-BX6EUYHU.js} +6 -2
  53. package/dist/chunk-BX6EUYHU.js.map +1 -0
  54. package/dist/{chunk-BIVCP6X5.js → chunk-C62IZEJI.js} +465 -202
  55. package/dist/chunk-C62IZEJI.js.map +1 -0
  56. package/dist/chunk-D4VP2QPR.js +16 -0
  57. package/dist/chunk-D4VP2QPR.js.map +1 -0
  58. package/dist/{chunk-J5MXCGKA.js → chunk-DHAD2O3S.js} +6 -6
  59. package/dist/chunk-DHAD2O3S.js.map +1 -0
  60. package/dist/chunk-E43VJ3E5.js +188 -0
  61. package/dist/chunk-E43VJ3E5.js.map +1 -0
  62. package/dist/chunk-EVZKNA2W.js +110 -0
  63. package/dist/chunk-EVZKNA2W.js.map +1 -0
  64. package/dist/chunk-FD4ZDTQ6.js +181 -0
  65. package/dist/chunk-FD4ZDTQ6.js.map +1 -0
  66. package/dist/chunk-FDOOBTXJ.js +17 -0
  67. package/dist/chunk-FDOOBTXJ.js.map +1 -0
  68. package/dist/chunk-FH3SQR6P.js +275 -0
  69. package/dist/chunk-FH3SQR6P.js.map +1 -0
  70. package/dist/chunk-HJHGTFEJ.js +23 -0
  71. package/dist/chunk-HJHGTFEJ.js.map +1 -0
  72. package/dist/{chunk-LXAESF4Y.js → chunk-HK4AZBKX.js} +7 -4
  73. package/dist/chunk-HK4AZBKX.js.map +1 -0
  74. package/dist/{chunk-T5C46IIU.js → chunk-HWBRS4DZ.js} +28 -269
  75. package/dist/chunk-HWBRS4DZ.js.map +1 -0
  76. package/dist/chunk-IRQGAC4L.js +52 -0
  77. package/dist/chunk-IRQGAC4L.js.map +1 -0
  78. package/dist/{chunk-FNTLKHZ7.js → chunk-JDN5SAAD.js} +7 -4
  79. package/dist/chunk-JDN5SAAD.js.map +1 -0
  80. package/dist/{chunk-GXEX4CBH.js → chunk-JIKNR5LX.js} +673 -484
  81. package/dist/chunk-JIKNR5LX.js.map +1 -0
  82. package/dist/{chunk-GRI4XHBJ.js → chunk-JWRCZIA4.js} +266 -108
  83. package/dist/chunk-JWRCZIA4.js.map +1 -0
  84. package/dist/{chunk-E576KYYT.js → chunk-KI4DOTN4.js} +25 -2
  85. package/dist/chunk-KI4DOTN4.js.map +1 -0
  86. package/dist/{chunk-ZB7D62OA.js → chunk-KUZVRJ7M.js} +3 -3
  87. package/dist/chunk-L4VFNFDL.js +248 -0
  88. package/dist/chunk-L4VFNFDL.js.map +1 -0
  89. package/dist/chunk-M2WC5MF7.js +127 -0
  90. package/dist/chunk-M2WC5MF7.js.map +1 -0
  91. package/dist/{chunk-O3JIAU3V.js → chunk-MCTC6HSE.js} +157 -103
  92. package/dist/chunk-MCTC6HSE.js.map +1 -0
  93. package/dist/{chunk-PXFXSFJL.js → chunk-NZ5JU6D3.js} +9 -9
  94. package/dist/{chunk-YRBR424R.js → chunk-OAUI273L.js} +338 -165
  95. package/dist/chunk-OAUI273L.js.map +1 -0
  96. package/dist/chunk-OGLS76RN.js +43 -0
  97. package/dist/chunk-OGLS76RN.js.map +1 -0
  98. package/dist/{chunk-7LVM22VG.js → chunk-OQCRCXCP.js} +6 -6
  99. package/dist/chunk-OQCRCXCP.js.map +1 -0
  100. package/dist/{chunk-OLGPYOLO.js → chunk-P6OS7652.js} +5 -2
  101. package/dist/chunk-P6OS7652.js.map +1 -0
  102. package/dist/chunk-Q5L5EGWZ.js +26 -0
  103. package/dist/chunk-Q5L5EGWZ.js.map +1 -0
  104. package/dist/{chunk-S433N3CT.js → chunk-QTHVHNJJ.js} +6 -36
  105. package/dist/chunk-QTHVHNJJ.js.map +1 -0
  106. package/dist/chunk-RPET332G.js +84 -0
  107. package/dist/chunk-RPET332G.js.map +1 -0
  108. package/dist/{chunk-646CA6RV.js → chunk-RQW5YMH7.js} +12 -4
  109. package/dist/chunk-RQW5YMH7.js.map +1 -0
  110. package/dist/{chunk-XALU5LCU.js → chunk-RWNYIU6A.js} +550 -146
  111. package/dist/chunk-RWNYIU6A.js.map +1 -0
  112. package/dist/chunk-SL7YUHPV.js +111 -0
  113. package/dist/chunk-SL7YUHPV.js.map +1 -0
  114. package/dist/chunk-U5PWXS3J.js +39 -0
  115. package/dist/chunk-U5PWXS3J.js.map +1 -0
  116. package/dist/chunk-ULDCFL2O.js +273 -0
  117. package/dist/chunk-ULDCFL2O.js.map +1 -0
  118. package/dist/{chunk-RWNSW4FM.js → chunk-UMNXCU3K.js} +12 -6
  119. package/dist/{chunk-RWNSW4FM.js.map → chunk-UMNXCU3K.js.map} +1 -1
  120. package/dist/chunk-VI7ZANB3.js +193 -0
  121. package/dist/chunk-VI7ZANB3.js.map +1 -0
  122. package/dist/chunk-VQPHPQ5L.js +14 -0
  123. package/dist/chunk-VQPHPQ5L.js.map +1 -0
  124. package/dist/chunk-WNJTJRM6.js +147 -0
  125. package/dist/chunk-WNJTJRM6.js.map +1 -0
  126. package/dist/chunk-WOBSEO75.js +790 -0
  127. package/dist/chunk-WOBSEO75.js.map +1 -0
  128. package/dist/{chunk-BMHS4WAN.js → chunk-XS7EX55U.js} +156 -42
  129. package/dist/chunk-XS7EX55U.js.map +1 -0
  130. package/dist/chunk-YN4W7LCX.js +31 -0
  131. package/dist/chunk-YN4W7LCX.js.map +1 -0
  132. package/dist/chunk-YSJOZEI6.js +1 -0
  133. package/dist/{chunk-JA2ZAT5Q.js → chunk-Z4PJMZLM.js} +2 -2
  134. package/dist/chunk-Z4PJMZLM.js.map +1 -0
  135. package/dist/{chunk-7VPQHEAJ.js → chunk-ZNZISJDZ.js} +6 -2
  136. package/dist/chunk-ZNZISJDZ.js.map +1 -0
  137. package/dist/chunk-ZWN3AODA.js +11 -0
  138. package/dist/chunk-ZWN3AODA.js.map +1 -0
  139. package/dist/cli/index.js +25 -10
  140. package/dist/cli/index.js.map +1 -1
  141. package/dist/client/core.d.ts +1 -1
  142. package/dist/client/core.js +2 -0
  143. package/dist/client/core.js.map +1 -1
  144. package/dist/client/index.d.ts +44 -10
  145. package/dist/client/index.js +35 -0
  146. package/dist/client/index.js.map +1 -1
  147. package/dist/cloudflare-SIG42OIW.js +335 -0
  148. package/dist/cloudflare-SIG42OIW.js.map +1 -0
  149. package/dist/config-support-WQHQIJTA.js +104 -0
  150. package/dist/config-support-WQHQIJTA.js.map +1 -0
  151. package/dist/{csrf-BBrEZSBW.d.ts → csrf-Dgot9qSM.d.ts} +1 -1
  152. package/dist/deno-deploy-LQAYOOPW.js +196 -0
  153. package/dist/deno-deploy-LQAYOOPW.js.map +1 -0
  154. package/dist/{dev-MUWJAZRD.js → dev-ANDSEVLB.js} +28 -18
  155. package/dist/dev-ANDSEVLB.js.map +1 -0
  156. package/dist/{dev-emit-GWD6IXV7.js → dev-emit-BFNMDCPB.js} +5 -5
  157. package/dist/{dev-emit-NBT6JD7R.js → dev-emit-MVAJAFGX.js} +5 -3
  158. package/dist/dev-emit-MVAJAFGX.js.map +1 -0
  159. package/dist/engine-singleton-X4R7AZBJ.js +315 -0
  160. package/dist/engine-singleton-X4R7AZBJ.js.map +1 -0
  161. package/dist/{generate-Y3GWM57K.js → generate-EN6EDITF.js} +43 -4
  162. package/dist/generate-EN6EDITF.js.map +1 -0
  163. package/dist/index-CzxtQcnp.d.ts +1058 -0
  164. package/dist/index.d.ts +4 -0
  165. package/dist/index.js +24 -13
  166. package/dist/index.js.map +1 -1
  167. package/dist/{info-XW7HGUPH.js → info-Y55RWS42.js} +8 -6
  168. package/dist/{info-XW7HGUPH.js.map → info-Y55RWS42.js.map} +1 -1
  169. package/dist/{internal-api-V5L65YSJ.js → internal-api-IP35YU3G.js} +22 -12
  170. package/dist/{internal-api-WEOSTMSN.js → internal-api-OPU456AT.js} +30 -16
  171. package/dist/internal-api-OPU456AT.js.map +1 -0
  172. package/dist/load-config-4ATXQUN3.js +16 -0
  173. package/dist/match-DmGgxjIU.d.ts +44 -0
  174. package/dist/{mcp-ULUFJNSZ.js → mcp-5LLNAGKA.js} +7 -7
  175. package/dist/netlify-C2IRCZKI.js +245 -0
  176. package/dist/netlify-C2IRCZKI.js.map +1 -0
  177. package/dist/node-OSVPYQ3D.js +10 -0
  178. package/dist/nonce-BXt7Qu_C.d.ts +31 -0
  179. package/dist/observability-bootstrap-MZMSOE66.js +15 -0
  180. package/dist/{openapi-HZXR335W.js → openapi-VFPEZSRI.js} +13 -11
  181. package/dist/{openapi-HZXR335W.js.map → openapi-VFPEZSRI.js.map} +1 -1
  182. package/dist/{plugin-runner-BFEcgtmJ.d.ts → plugin-runner-BVMOSxvb.d.ts} +1 -1
  183. package/dist/{plugin-types-D69-lJZ9.d.ts → plugin-types-BUVfUQ0V.d.ts} +13 -1
  184. package/dist/preview-GHPT2EQ5.js +23 -0
  185. package/dist/preview-GHPT2EQ5.js.map +1 -0
  186. package/dist/provider-resolver-Dx6QuWrw.d.ts +128 -0
  187. package/dist/registry-KBZDCFVQ.js +23 -0
  188. package/dist/route-config-Cm_ZMA1C.d.ts +72 -0
  189. package/dist/route-policy-BxOycCDq.d.ts +65 -0
  190. package/dist/router/element-scroll-restoration.d.ts +28 -0
  191. package/dist/router/element-scroll-restoration.js +96 -0
  192. package/dist/router/element-scroll-restoration.js.map +1 -0
  193. package/dist/{routes-OLNQX7CT.js → routes-BPLU3ISV.js} +11 -9
  194. package/dist/{routes-OLNQX7CT.js.map → routes-BPLU3ISV.js.map} +1 -1
  195. package/dist/{scan-7MJC6PYU.js → scan-YJEE4KQK.js} +2 -2
  196. package/dist/{schema-ZO3OSWVG.js → schema-SOAD43RQ.js} +7 -5
  197. package/dist/schemas-4AXHQMV3.js +25 -0
  198. package/dist/schemas-4AXHQMV3.js.map +1 -0
  199. package/dist/security-headers-Ccj7ncNx.d.ts +129 -0
  200. package/dist/server/agent/index.d.ts +2 -90
  201. package/dist/server/agent/index.js +1 -1
  202. package/dist/server/auth/index.d.ts +2 -21
  203. package/dist/server/auth/index.js +3 -2
  204. package/dist/server/cron/index.js +4 -3
  205. package/dist/server/define/index.d.ts +51 -57
  206. package/dist/server/define/index.js +10 -1
  207. package/dist/server/http/index.d.ts +7 -5
  208. package/dist/server/http/index.js +56 -12
  209. package/dist/server/index.d.ts +47 -439
  210. package/dist/server/index.js +119 -201
  211. package/dist/server/index.js.map +1 -1
  212. package/dist/server/jobs/index.js +4 -3
  213. package/dist/server/observability/index.d.ts +109 -35
  214. package/dist/server/observability/index.js +10 -7
  215. package/dist/server/plugins/index.d.ts +3 -3
  216. package/dist/server/scan/index.d.ts +47 -12
  217. package/dist/server/scan/index.js +13 -4
  218. package/dist/server/security/index.d.ts +61 -103
  219. package/dist/server/security/index.js +15 -6
  220. package/dist/server/webhook/index.d.ts +90 -3
  221. package/dist/server/webhook/index.js +12 -2
  222. package/dist/server-boundary-6B4ZQUY7.js +148 -0
  223. package/dist/server-boundary-6B4ZQUY7.js.map +1 -0
  224. package/dist/server-boundary-7VZQRPPX.js +133 -0
  225. package/dist/server-boundary-7VZQRPPX.js.map +1 -0
  226. package/dist/{services-typed-client-PSAGRPFF.js → services-typed-client-XGT5SUUN.js} +2 -2
  227. package/dist/{start-KR2JJR7K.js → start-UZDMOT7I.js} +342 -111
  228. package/dist/start-UZDMOT7I.js.map +1 -0
  229. package/dist/{static-M2W4HUWS.js → static-SVDWIOXJ.js} +24 -13
  230. package/dist/static-SVDWIOXJ.js.map +1 -0
  231. package/dist/{theo-cloud-XAHWOUFK.js → theo-cloud-3ET4G5T6.js} +9 -2
  232. package/dist/theo-cloud-3ET4G5T6.js.map +1 -0
  233. package/dist/vercel-BMCQKCWE.js +277 -0
  234. package/dist/vercel-BMCQKCWE.js.map +1 -0
  235. package/dist/vite-plugin/index.js +24 -13
  236. package/dist/vite-plugin-VKCT2LF2.js +42 -0
  237. package/dist/vite-plugin-VKCT2LF2.js.map +1 -0
  238. package/package.json +19 -6
  239. package/dist/actions-virtual-module-YQXRSSMW.js.map +0 -1
  240. package/dist/agent-7JJW3TPB.js +0 -15
  241. package/dist/app-typed-client-G3J5G7E5.js.map +0 -1
  242. package/dist/app-typed-client-GHO3EWZK.js.map +0 -1
  243. package/dist/aws-lambda-CYNDGU5O.js +0 -172
  244. package/dist/aws-lambda-CYNDGU5O.js.map +0 -1
  245. package/dist/build-WU6AKKIB.js.map +0 -1
  246. package/dist/bun-33RD6K7O.js.map +0 -1
  247. package/dist/chunk-646CA6RV.js.map +0 -1
  248. package/dist/chunk-6E5WKMDS.js +0 -67
  249. package/dist/chunk-6E5WKMDS.js.map +0 -1
  250. package/dist/chunk-6GGWS7J3.js +0 -91
  251. package/dist/chunk-6GGWS7J3.js.map +0 -1
  252. package/dist/chunk-7LVM22VG.js.map +0 -1
  253. package/dist/chunk-7VPQHEAJ.js.map +0 -1
  254. package/dist/chunk-A7JBF5FO.js.map +0 -1
  255. package/dist/chunk-AM3QABW5.js +0 -161
  256. package/dist/chunk-AM3QABW5.js.map +0 -1
  257. package/dist/chunk-BIVCP6X5.js.map +0 -1
  258. package/dist/chunk-BMHS4WAN.js.map +0 -1
  259. package/dist/chunk-E576KYYT.js.map +0 -1
  260. package/dist/chunk-FB2HBNIC.js.map +0 -1
  261. package/dist/chunk-FNTLKHZ7.js.map +0 -1
  262. package/dist/chunk-GRI4XHBJ.js.map +0 -1
  263. package/dist/chunk-GVW5EKEU.js +0 -422
  264. package/dist/chunk-GVW5EKEU.js.map +0 -1
  265. package/dist/chunk-GXEX4CBH.js.map +0 -1
  266. package/dist/chunk-HBU2GIMZ.js.map +0 -1
  267. package/dist/chunk-IEES3CHD.js.map +0 -1
  268. package/dist/chunk-J5MXCGKA.js.map +0 -1
  269. package/dist/chunk-JA2ZAT5Q.js.map +0 -1
  270. package/dist/chunk-KD5G3YXI.js.map +0 -1
  271. package/dist/chunk-LNVMHQ2Z.js +0 -54
  272. package/dist/chunk-LNVMHQ2Z.js.map +0 -1
  273. package/dist/chunk-LXAESF4Y.js.map +0 -1
  274. package/dist/chunk-MTEWLGVY.js.map +0 -1
  275. package/dist/chunk-O3JIAU3V.js.map +0 -1
  276. package/dist/chunk-OJLL4YD6.js +0 -403
  277. package/dist/chunk-OJLL4YD6.js.map +0 -1
  278. package/dist/chunk-OLGPYOLO.js.map +0 -1
  279. package/dist/chunk-S433N3CT.js.map +0 -1
  280. package/dist/chunk-T5C46IIU.js.map +0 -1
  281. package/dist/chunk-U267AOWS.js +0 -28
  282. package/dist/chunk-U267AOWS.js.map +0 -1
  283. package/dist/chunk-UW2TEAGR.js +0 -77
  284. package/dist/chunk-UW2TEAGR.js.map +0 -1
  285. package/dist/chunk-WPJOTQA5.js +0 -1
  286. package/dist/chunk-XALU5LCU.js.map +0 -1
  287. package/dist/chunk-XR74JD4M.js +0 -457
  288. package/dist/chunk-XR74JD4M.js.map +0 -1
  289. package/dist/chunk-YGAXV5HR.js.map +0 -1
  290. package/dist/chunk-YRBR424R.js.map +0 -1
  291. package/dist/cloudflare-KYUWCEPL.js +0 -122
  292. package/dist/cloudflare-KYUWCEPL.js.map +0 -1
  293. package/dist/deno-deploy-CCTB7HGS.js +0 -107
  294. package/dist/deno-deploy-CCTB7HGS.js.map +0 -1
  295. package/dist/dev-MUWJAZRD.js.map +0 -1
  296. package/dist/dev-emit-NBT6JD7R.js.map +0 -1
  297. package/dist/generate-Y3GWM57K.js.map +0 -1
  298. package/dist/index-BEtEv6ZH.d.ts +0 -575
  299. package/dist/load-config-VKD6LKWU.js +0 -14
  300. package/dist/match-CfbEFRG4.d.ts +0 -26
  301. package/dist/netlify-AFMDNKT4.js +0 -150
  302. package/dist/netlify-AFMDNKT4.js.map +0 -1
  303. package/dist/node-ZJQEJSP3.js +0 -10
  304. package/dist/registry-GKR3EWRW.js +0 -23
  305. package/dist/start-KR2JJR7K.js.map +0 -1
  306. package/dist/static-M2W4HUWS.js.map +0 -1
  307. package/dist/theo-cloud-XAHWOUFK.js.map +0 -1
  308. package/dist/vercel-SRS2DH6O.js +0 -133
  309. package/dist/vercel-SRS2DH6O.js.map +0 -1
  310. package/dist/vite-plugin-VPJFD4HK.js +0 -36
  311. /package/dist/{chunk-WPJOTQA5.js.map → adapters/agent-mount.js.map} +0 -0
  312. /package/dist/{agent-7JJW3TPB.js.map → agent-GKUEL6OH.js.map} +0 -0
  313. /package/dist/{check-45NKUVSQ.js.map → check-GIPZBFTX.js.map} +0 -0
  314. /package/dist/{chunk-47CINLWF.js.map → chunk-44J2ANQC.js.map} +0 -0
  315. /package/dist/{chunk-ZB7D62OA.js.map → chunk-KUZVRJ7M.js.map} +0 -0
  316. /package/dist/{chunk-PXFXSFJL.js.map → chunk-NZ5JU6D3.js.map} +0 -0
  317. /package/dist/{internal-api-WEOSTMSN.js.map → chunk-YSJOZEI6.js.map} +0 -0
  318. /package/dist/{dev-emit-GWD6IXV7.js.map → dev-emit-BFNMDCPB.js.map} +0 -0
  319. /package/dist/{internal-api-V5L65YSJ.js.map → internal-api-IP35YU3G.js.map} +0 -0
  320. /package/dist/{load-config-VKD6LKWU.js.map → load-config-4ATXQUN3.js.map} +0 -0
  321. /package/dist/{mcp-ULUFJNSZ.js.map → mcp-5LLNAGKA.js.map} +0 -0
  322. /package/dist/{node-ZJQEJSP3.js.map → node-OSVPYQ3D.js.map} +0 -0
  323. /package/dist/{scan-7MJC6PYU.js.map → observability-bootstrap-MZMSOE66.js.map} +0 -0
  324. /package/dist/{registry-GKR3EWRW.js.map → registry-KBZDCFVQ.js.map} +0 -0
  325. /package/dist/{schema-ZO3OSWVG.js.map → scan-YJEE4KQK.js.map} +0 -0
  326. /package/dist/{vite-plugin-VPJFD4HK.js.map → schema-SOAD43RQ.js.map} +0 -0
  327. /package/dist/{services-typed-client-PSAGRPFF.js.map → services-typed-client-XGT5SUUN.js.map} +0 -0
@@ -1,150 +0,0 @@
1
- #!/usr/bin/env node
2
- import "tsx/esm";
3
- import {
4
- nodeAdapter
5
- } from "./chunk-E576KYYT.js";
6
- import {
7
- assertServicesUnsupported,
8
- readManifest
9
- } from "./chunk-7VPQHEAJ.js";
10
-
11
- // src/adapters/netlify.ts
12
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
- import { resolve } from "path";
14
- var NetlifyConflictError = class extends Error {
15
- constructor(path, currentTo) {
16
- super(
17
- `netlify.toml has a conflicting redirect: "${path}" \u2192 "${currentTo}". Remove it manually or edit it to point to "/.netlify/functions/theo" before running the Netlify adapter again.`
18
- );
19
- this.name = "NetlifyConflictError";
20
- }
21
- };
22
- function renderNetlifyFunction() {
23
- return [
24
- `// Generated by Theo \u2014 Netlify Functions adapter`,
25
- `import { resolve } from 'node:path'`,
26
- `import { randomUUID } from 'node:crypto'`,
27
- `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader } from 'theokit/server'`,
28
- `import { createWebShim } from 'theokit/adapters/web-shim'`,
29
- ``,
30
- `const cwd = process.cwd()`,
31
- `const serverDir = resolve(cwd, 'server')`,
32
- `let routesCache = null`,
33
- `let loaderCache = null`,
34
- ``,
35
- `export default async (request, context) => {`,
36
- ` const url = new URL(request.url)`,
37
- ` if (!url.pathname.startsWith('/api/')) {`,
38
- ` return new Response('Not Found', { status: 404 })`,
39
- ` }`,
40
- ``,
41
- ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,
42
- ` if (!loaderCache) loaderCache = createProductionLoader()`,
43
- ``,
44
- ` const match = matchRoute(url.pathname, routesCache)`,
45
- ` if (!match) {`,
46
- ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,
47
- ` status: 404,`,
48
- ` headers: { 'content-type': 'application/json' },`,
49
- ` })`,
50
- ` }`,
51
- ``,
52
- ` const { req, res, toResponse } = createWebShim(request)`,
53
- ` const requestId = randomUUID()`,
54
- ` const method = request.method.toUpperCase()`,
55
- ` await executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId })`,
56
- ` return toResponse()`,
57
- `}`
58
- ].join("\n");
59
- }
60
- var THEO_REDIRECT_FROM = "/api/*";
61
- var THEO_REDIRECT_TO = "/.netlify/functions/theo";
62
- function parseRedirectBlocks(lines) {
63
- const blocks = [];
64
- let current = null;
65
- for (let i = 0; i < lines.length; i++) {
66
- const trimmed = lines[i].trim();
67
- if (trimmed === "[[redirects]]") {
68
- if (current) {
69
- current.endLine = i - 1;
70
- blocks.push(current);
71
- }
72
- current = { startLine: i, endLine: i };
73
- continue;
74
- }
75
- if (current && /^\[(\[|[^[])/.test(trimmed)) {
76
- current.endLine = i - 1;
77
- blocks.push(current);
78
- current = null;
79
- }
80
- if (current) {
81
- const fromMatch = /^from\s*=\s*"([^"]+)"/.exec(trimmed);
82
- if (fromMatch) current.from = fromMatch[1];
83
- const toMatch = /^to\s*=\s*"([^"]+)"/.exec(trimmed);
84
- if (toMatch) current.to = toMatch[1];
85
- current.endLine = i;
86
- }
87
- }
88
- if (current) blocks.push(current);
89
- return blocks;
90
- }
91
- var THEO_REDIRECT_TARGET = [
92
- "[[redirects]]",
93
- ' from = "/api/*"',
94
- ' to = "/.netlify/functions/theo"',
95
- " status = 200",
96
- " force = true"
97
- ].join("\n");
98
- function mergeNetlifyToml(existing) {
99
- if (existing === null || existing.trim().length === 0) {
100
- return `${THEO_REDIRECT_TARGET}
101
- `;
102
- }
103
- const blocks = parseRedirectBlocks(existing.split(/\r?\n/));
104
- for (const b of blocks) {
105
- if (b.from !== THEO_REDIRECT_FROM) continue;
106
- if (b.to === THEO_REDIRECT_TO) {
107
- return existing.endsWith("\n") ? existing : `${existing}
108
- `;
109
- }
110
- throw new NetlifyConflictError(b.from, b.to ?? "(unknown)");
111
- }
112
- const sep = existing.endsWith("\n") ? "" : "\n";
113
- return `${existing}${sep}
114
- ${THEO_REDIRECT_TARGET}
115
- `;
116
- }
117
- async function buildNetlify(config, cwd, deps = {}, ctx) {
118
- assertServicesUnsupported("netlify", readManifest(cwd));
119
- const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter);
120
- await runNodeBuild(config, cwd, ctx);
121
- const ensureDir = deps.ensureDir ?? ((p) => mkdirSync(p, { recursive: true }));
122
- const writeFile = deps.writeFile ?? ((p, c) => {
123
- writeFileSync(p, c);
124
- });
125
- const readTomlIfExists = deps.readTomlIfExists ?? (() => {
126
- const p = resolve(cwd, "netlify.toml");
127
- return existsSync(p) ? readFileSync(p, "utf-8") : null;
128
- });
129
- const fnDir = resolve(cwd, ".netlify/functions");
130
- ensureDir(fnDir);
131
- writeFile(resolve(fnDir, "theo.mjs"), renderNetlifyFunction());
132
- const existingToml = readTomlIfExists();
133
- const merged = mergeNetlifyToml(existingToml);
134
- writeFile(resolve(cwd, "netlify.toml"), merged);
135
- console.log("\n \u2713 Netlify output \u2192 .netlify/functions/theo.mjs + netlify.toml\n");
136
- }
137
- var netlifyAdapter = {
138
- name: "netlify",
139
- build(config, cwd, ctx) {
140
- return buildNetlify(config, cwd, {}, ctx);
141
- }
142
- };
143
- export {
144
- NetlifyConflictError,
145
- buildNetlify,
146
- mergeNetlifyToml,
147
- netlifyAdapter,
148
- renderNetlifyFunction
149
- };
150
- //# sourceMappingURL=netlify-AFMDNKT4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/netlify.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Netlify deploy adapter. All paths derived from `cwd` and a fixed\n * `.theokit/netlify/` output layout. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { nodeAdapter } from './node.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport class NetlifyConflictError extends Error {\n constructor(path: string, currentTo: string) {\n super(\n `netlify.toml has a conflicting redirect: \"${path}\" → \"${currentTo}\". ` +\n `Remove it manually or edit it to point to \"/.netlify/functions/theo\" ` +\n `before running the Netlify adapter again.`,\n )\n this.name = 'NetlifyConflictError'\n }\n}\n\nexport interface NetlifyBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeFile?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n readTomlIfExists?: () => string | null\n}\n\nexport function renderNetlifyFunction(): string {\n return [\n `// Generated by Theo — Netlify Functions adapter`,\n `import { resolve } from 'node:path'`,\n `import { randomUUID } from 'node:crypto'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n ``,\n `const cwd = process.cwd()`,\n `const serverDir = resolve(cwd, 'server')`,\n `let routesCache = null`,\n `let loaderCache = null`,\n ``,\n `export default async (request, context) => {`,\n ` const url = new URL(request.url)`,\n ` if (!url.pathname.startsWith('/api/')) {`,\n ` return new Response('Not Found', { status: 404 })`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'application/json' },`,\n ` })`,\n ` }`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ` const requestId = randomUUID()`,\n ` const method = request.method.toUpperCase()`,\n ` await executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId })`,\n ` return toResponse()`,\n `}`,\n ].join('\\n')\n}\n\nconst THEO_REDIRECT_FROM = '/api/*'\nconst THEO_REDIRECT_TO = '/.netlify/functions/theo'\n\n/**\n * TOML merge (EC-2) — non-destructive.\n *\n * We avoid adding a TOML parser dependency by working at the line level. The\n * supported subset is sufficient for the Netlify use case:\n * - detect existing `[[redirects]]` blocks\n * - find a block whose `from = \"...\"` matches our target\n * - error if such a block points elsewhere\n * - otherwise append our block\n *\n * Unknown sections (e.g. `[build]`, `[[headers]]`, `[context.production.environment]`)\n * are preserved as-is.\n */\ninterface NetlifyRedirectBlock {\n startLine: number\n endLine: number\n from?: string\n to?: string\n}\n\nfunction parseRedirectBlocks(lines: readonly string[]): NetlifyRedirectBlock[] {\n const blocks: NetlifyRedirectBlock[] = []\n let current: NetlifyRedirectBlock | null = null\n\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i].trim()\n if (trimmed === '[[redirects]]') {\n if (current) {\n current.endLine = i - 1\n blocks.push(current)\n }\n current = { startLine: i, endLine: i }\n continue\n }\n if (current && /^\\[(\\[|[^[])/.test(trimmed)) {\n // Entering another section — close current.\n current.endLine = i - 1\n blocks.push(current)\n current = null\n }\n if (current) {\n const fromMatch = /^from\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (fromMatch) current.from = fromMatch[1]\n const toMatch = /^to\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (toMatch) current.to = toMatch[1]\n current.endLine = i\n }\n }\n if (current) blocks.push(current)\n return blocks\n}\n\nconst THEO_REDIRECT_TARGET = [\n '[[redirects]]',\n ' from = \"/api/*\"',\n ' to = \"/.netlify/functions/theo\"',\n ' status = 200',\n ' force = true',\n].join('\\n')\n\nexport function mergeNetlifyToml(existing: string | null): string {\n if (existing === null || existing.trim().length === 0) {\n return `${THEO_REDIRECT_TARGET}\\n`\n }\n\n const blocks = parseRedirectBlocks(existing.split(/\\r?\\n/))\n\n // Detect conflict: every `/api/*` block must point at our function.\n for (const b of blocks) {\n if (b.from !== THEO_REDIRECT_FROM) continue\n if (b.to === THEO_REDIRECT_TO) {\n // Already merged — return existing as-is (idempotent).\n return existing.endsWith('\\n') ? existing : `${existing}\\n`\n }\n throw new NetlifyConflictError(b.from, b.to ?? '(unknown)')\n }\n\n // No conflict — append target block.\n const sep = existing.endsWith('\\n') ? '' : '\\n'\n return `${existing}${sep}\\n${THEO_REDIRECT_TARGET}\\n`\n}\n\nexport async function buildNetlify(\n config: TheoConfig,\n cwd: string,\n deps: NetlifyBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('netlify', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n const writeFile =\n deps.writeFile ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n const readTomlIfExists =\n deps.readTomlIfExists ??\n (() => {\n const p = resolve(cwd, 'netlify.toml')\n return existsSync(p) ? readFileSync(p, 'utf-8') : null\n })\n\n const fnDir = resolve(cwd, '.netlify/functions')\n ensureDir(fnDir)\n writeFile(resolve(fnDir, 'theo.mjs'), renderNetlifyFunction())\n\n const existingToml = readTomlIfExists()\n const merged = mergeNetlifyToml(existingToml)\n writeFile(resolve(cwd, 'netlify.toml'), merged)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Netlify output → .netlify/functions/theo.mjs + netlify.toml\\n')\n}\n\nexport const netlifyAdapter: DeployAdapter = {\n name: 'netlify',\n build(config, cwd, ctx) {\n return buildNetlify(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AAQjB,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAAY,MAAc,WAAmB;AAC3C;AAAA,MACE,6CAA6C,IAAI,aAAQ,SAAS;AAAA,IAGpE;AACA,SAAK,OAAO;AAAA,EACd;AACF;AASO,SAAS,wBAAgC;AAC9C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AAsBzB,SAAS,oBAAoB,OAAkD;AAC7E,QAAM,SAAiC,CAAC;AACxC,MAAI,UAAuC;AAE3C,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC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A,eAAsB,aACpB,QACA,KACA,OAAyB,CAAC,GAC1B,KACe;AAEf,4BAA0B,WAAW,aAAa,GAAG,CAAC;AAEtD,QAAM,eAAe,KAAK,gBAAgB,YAAY,MAAM,KAAK,WAAW;AAC5E,QAAM,aAAa,QAAQ,KAAK,GAAG;AAEnC,QAAM,YAAY,KAAK,cAAc,CAAC,MAAc,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;AACpF,QAAM,YACJ,KAAK,cACJ,CAAC,GAAG,MAAM;AACT,kBAAc,GAAG,CAAC;AAAA,EACpB;AACF,QAAM,mBACJ,KAAK,qBACJ,MAAM;AACL,UAAM,IAAI,QAAQ,KAAK,cAAc;AACrC,WAAO,WAAW,CAAC,IAAI,aAAa,GAAG,OAAO,IAAI;AAAA,EACpD;AAEF,QAAM,QAAQ,QAAQ,KAAK,oBAAoB;AAC/C,YAAU,KAAK;AACf,YAAU,QAAQ,OAAO,UAAU,GAAG,sBAAsB,CAAC;AAE7D,QAAM,eAAe,iBAAiB;AACtC,QAAM,SAAS,iBAAiB,YAAY;AAC5C,YAAU,QAAQ,KAAK,cAAc,GAAG,MAAM;AAG9C,UAAQ,IAAI,+EAAqE;AACnF;AAEO,IAAM,iBAAgC;AAAA,EAC3C,MAAM;AAAA,EACN,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,aAAa,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EAC1C;AACF;","names":[]}
@@ -1,10 +0,0 @@
1
- #!/usr/bin/env node
2
- import "tsx/esm";
3
- import {
4
- nodeAdapter
5
- } from "./chunk-E576KYYT.js";
6
- import "./chunk-7VPQHEAJ.js";
7
- export {
8
- nodeAdapter
9
- };
10
- //# sourceMappingURL=node-ZJQEJSP3.js.map
@@ -1,23 +0,0 @@
1
- #!/usr/bin/env node
2
- import "tsx/esm";
3
-
4
- // src/adapters/registry.ts
5
- var adapterRegistry = {
6
- node: async () => (await import("./node-ZJQEJSP3.js")).nodeAdapter,
7
- vercel: async () => (await import("./vercel-SRS2DH6O.js")).vercelAdapter,
8
- cloudflare: async () => (await import("./cloudflare-KYUWCEPL.js")).cloudflareAdapter,
9
- static: async () => (await import("./static-M2W4HUWS.js")).staticAdapter,
10
- bun: async () => (await import("./bun-33RD6K7O.js")).bunAdapter,
11
- "deno-deploy": async () => (await import("./deno-deploy-CCTB7HGS.js")).denoDeployAdapter,
12
- netlify: async () => (await import("./netlify-AFMDNKT4.js")).netlifyAdapter,
13
- "aws-lambda": async () => (await import("./aws-lambda-CYNDGU5O.js")).awsLambdaAdapter,
14
- "theo-cloud": async () => (await import("./theo-cloud-XAHWOUFK.js")).theoCloudAdapter
15
- };
16
- async function resolveAdapter(target) {
17
- const factory = adapterRegistry[target];
18
- return factory();
19
- }
20
- export {
21
- resolveAdapter
22
- };
23
- //# sourceMappingURL=registry-GKR3EWRW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/start/index.ts","../src/server/define/health-route.ts","../src/server/rate-limit/client-ip.ts","../src/server/rate-limit/rate-limit-per-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 { createRouteRateLimiter } from '../../../server/rate-limit/rate-limit-per-route.js'\nimport { createProductionLoader } from '../../../server/scan/module-loader.js'\nimport { resolveTransformer } from '../../../server/transformer.js'\nimport { preflightNodeAndBindings } from '../../preflight-node-version.js'\nimport { CONTROLLER_MANIFEST_FILE } from '../build/emit-controllers.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 // theokit#123 — compiled controllers, when `theokit build` emitted any.\n //\n // Keyed on the MANIFEST rather than on the directory existing: a stale `dist/controllers` left by\n // an earlier build whose sources were since deleted would otherwise keep serving routes the app\n // no longer declares. `theokit build` writes the manifest only when it compiles something, and\n // `cleanOutDir` removes both, so the manifest is the authoritative \"this build has controllers\".\n const controllersDistDir = existsSync(resolve(distDir, CONTROLLER_MANIFEST_FILE))\n ? resolve(distDir, 'controllers')\n : undefined\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 // `createRouteRateLimiter` accepts BOTH config shapes — it detects the legacy flat form and\n // treats it as the default bucket — so one call covers everything the schema allows.\n //\n // The previous code built a limiter only for the flat shape, on the belief that the per-route\n // variant was handled by an api-middleware path. No such path runs under `theokit start`, so a\n // per-route config produced `null` here and `handlers.ts` skipped limiting on every request. The\n // app booted clean, the config validated, and nothing was ever limited — see\n // usetheokit/theokit#321. A config that validates and then does nothing is worse than one that\n // fails loudly, because the operator has no reason to look.\n const rateLimiter = config.rateLimit ? createRouteRateLimiter(config.rateLimit) : 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 controllersDistDir,\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 // \"NEVER swallow exceptions\"). 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","import type { IncomingMessage } from 'node:http'\n\n/**\n * Resolves the address a rate-limit bucket should be keyed on.\n *\n * ## Why this is not just `req.socket.remoteAddress`\n *\n * Behind any reverse proxy — Caddy, nginx, a load balancer, an ingress controller — the socket\n * address is the PROXY's, identical for every visitor on the internet. Keying buckets on it gives\n * the whole world one shared budget, so the first few requests each minute exhaust it and everyone\n * else is refused. That is worse than no limiting: a limit meant to stop one abusive client becomes\n * a denial of service any single client can trigger for everybody.\n *\n * ## Why it is opt-in\n *\n * `x-forwarded-for` is a request header, and a request header is whatever the client typed. Reading\n * it without being told to would let anyone bypass the limiter by rotating a forged value — a\n * one-line `curl -H`. So the default is to trust nothing and use the socket.\n *\n * ## Why the RIGHTMOST entry\n *\n * Each proxy APPENDS the address that connected to it. A client that sends `x-forwarded-for: 1.2.3.4`\n * through one proxy produces `1.2.3.4, <real client>` — the forgery lands on the left, and the entry\n * the trusted proxy wrote is last. Counting from the right therefore skips exactly the hops the\n * operator vouched for, and everything a client can influence stays to the left of where we look.\n *\n * This mirrors the `'trusted-proxy'` policy in `adapters/web-shim.ts`, which documents the same rule\n * for the Web-Request runtimes.\n */\n\n/**\n * How many proxies sit in front of the app.\n *\n * `false` (the default) trusts nothing and uses the socket address. `true` means one trusted proxy.\n * A number names the hop count for a longer chain — a CDN in front of your own proxy is `2`.\n */\nexport type TrustProxy = boolean | number\n\n/** `true` is shorthand for a single proxy; `false` for none. A number passes through. */\nfunction hopCount(trustProxy: TrustProxy): number {\n if (trustProxy === true) return 1\n if (trustProxy === false) return 0\n return trustProxy\n}\n\n/** Reads a header that Node may hand back as an array. */\nfunction headerValue(req: IncomingMessage, name: string): string | undefined {\n const raw = req.headers[name]\n if (Array.isArray(raw)) return raw[raw.length - 1]\n return raw\n}\n\nexport function resolveClientIp(req: IncomingMessage, trustProxy: TrustProxy = false): string {\n // `req.socket` is typed as always-present in Node typings; the optional chain keeps the fallback\n // reachable for test doubles built as plain object literals.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- defensive for test doubles\n const socketAddress = req.socket?.remoteAddress ?? 'unknown'\n\n const hops = hopCount(trustProxy)\n if (hops < 1) return socketAddress\n\n const forwarded = headerValue(req, 'x-forwarded-for')\n if (forwarded) {\n const entries = forwarded\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean)\n\n // Count in from the right by the number of hops the operator vouched for. A chain shorter than\n // configured means a request did NOT come through the expected proxies — a direct hit on the\n // app's port, say — so we fall back to the socket rather than reading an entry the client could\n // have written.\n const index = entries.length - hops\n if (index >= 0 && index < entries.length) return entries[index]\n }\n\n // `x-real-ip` carries a single address and is written by the proxy, not appended to, so there is\n // no hop arithmetic to do. Only consulted when a proxy is trusted at all.\n const realIp = headerValue(req, 'x-real-ip')\n if (realIp) return realIp.trim()\n\n return socketAddress\n}\n","// T5a.1d — Web Crypto migration. The last node:crypto consumer in server/.\n// `createHash('sha256')` is sync but Web Crypto's `subtle.digest('SHA-256', ...)`\n// is async. This propagates through hashFragment → deriveKey → the factory's\n// returned checker, which is why the checker is async. `theokit start` awaits it\n// (usetheokit/theokit#321 — before that fix this factory had no production consumer at all, and a\n// per-route config silently disabled rate limiting outright). IncomingMessage stays as a type-only\n// import (TS-erased; runtime-clean).\nimport type { IncomingMessage } from 'node:http'\n\nimport { parseCookieHeader } from '../http/cookies.js'\n\nimport { resolveClientIp, type TrustProxy } from './client-ip.js'\nimport { InMemoryStore, type RateLimitStore } from './rate-limit-store.js'\nimport type { RateLimitConfig, RateLimitResult } from './rate-limit.js'\n\n/**\n * T2.2 — Per-route + per-user rate limiting.\n *\n * Layered on top of `rate-limit-store.ts`. The route map allows\n * declarative policies (\"strict /api/login, loose everything else\")\n * driven by config, not handler-decorated. `keyBy` selects what\n * identifier the limiter buckets on.\n *\n * ADR D2: per-route via path matching, NOT per-handler decorator.\n * Operators can tune policies without touching route definitions.\n */\n\nexport type KeyByMode = 'ip' | 'session' | 'user' | ((req: IncomingMessage) => string)\n\nexport interface RouteRateLimitConfig {\n /** Fallback config used when no per-route entry matches. */\n default?: RateLimitConfig\n /** Map of path pattern → config. Exact-string keys (RegExp via API). */\n routes?: Record<string, RateLimitConfig>\n /** Same as `routes` but each entry is a [pattern, config] tuple, RegExp allowed. */\n routePatterns?: readonly [string | RegExp, RateLimitConfig][]\n /** Bucket identifier strategy. Default 'ip'. */\n keyBy?: KeyByMode\n /** Cookie name used by keyBy='session'. Defaults to 'theo_session'. */\n cookieName?: string\n /** Optional shared store (for multi-route correlation). Default per-limiter InMemoryStore. */\n store?: RateLimitStore\n /**\n * How many reverse proxies sit in front of the app, for `keyBy: 'ip'`. Default `false` — trust\n * none and key on the socket address.\n *\n * Set this whenever the app is behind Caddy, nginx, a load balancer or an ingress controller:\n * without it every visitor keys on the proxy's address and shares one bucket, so a handful of\n * requests exhausts the budget for the entire internet. With it, the client address is read from\n * `x-forwarded-for` counting in from the right, past exactly the hops declared here.\n *\n * Leaving it off by default is deliberate — `x-forwarded-for` is client-writable, and honouring it\n * uninvited turns the limiter into a one-header bypass. See `client-ip.ts`.\n */\n trustProxy?: TrustProxy\n}\n\n/**\n * Normalize a path for matching: strip query string, drop trailing slash\n * unless root. EC-5: `/api/login` and `/api/login/` collapse to the same\n * canonical form so attackers can't bypass strict limits.\n */\nfunction normalizePath(input: string): string {\n const noQuery = input.split('?')[0]\n if (noQuery.length > 1 && noQuery.endsWith('/')) return noQuery.slice(0, -1)\n return noQuery\n}\n\n/**\n * Test whether `path` matches `pattern`. String patterns are compared\n * after trailing-slash normalization (EC-5). RegExp uses `.test` after\n * resetting `lastIndex` (defensive against `/g` flag).\n */\nexport function matchRoutePattern(path: string, pattern: string | RegExp): boolean {\n const canonical = normalizePath(path)\n if (typeof pattern === 'string') {\n return canonical === normalizePath(pattern)\n }\n pattern.lastIndex = 0\n return pattern.test(canonical)\n}\n\n/**\n * Hash a string with SHA-256 and return the first 16 base64url chars.\n * Used by `keyBy='session'` so the raw cookie value never lands in a\n * rate-limit key (which may flow into audit logs).\n *\n * T5a.1d — async via Web Crypto subtle.digest (no node:crypto). The\n * base64url encoding is done manually because btoa+url-safe transform is\n * available everywhere but `digest('base64url')` is Node-only.\n */\nasync function hashFragment(input: string): Promise<string> {\n const buf = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(input))\n const bytes = new Uint8Array(buf)\n let bin = ''\n for (const b of bytes) bin += String.fromCharCode(b)\n // eslint-disable-next-line sonarjs/slow-regex -- input is fixed-length 44 chars (SHA-256 base64), trailing '=' padding ≤ 2 chars, no ReDoS surface\n const b64url = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n return b64url.slice(0, 16)\n}\n\n// T3.2 DRY consolidation: cookie parsing moved to ../http/cookies.ts.\n// The canonical `parseCookieHeader` returns a Map for O(1) lookup; this\n// wrapper preserves the original `readCookie(req, name)` signature so the\n// rest of the file stays untouched.\nfunction readCookie(req: IncomingMessage, name: string): string | undefined {\n return parseCookieHeader(req.headers.cookie ?? undefined).get(name)\n}\n\n/**\n * Build the rate-limit bucket key for the request based on `keyBy`.\n *\n * EC-6: session mode reads the configured `cookieName`. With the wrong\n * cookie name (e.g., default 'theo_session' but app uses 'app_session'),\n * we fall back to IP so anonymous users still get rate-limited rather\n * than sharing an empty bucket.\n */\nexport async function deriveKey(\n req: IncomingMessage,\n keyBy: KeyByMode,\n cookieName: string,\n trustProxy: TrustProxy = false,\n): Promise<string> {\n if (typeof keyBy === 'function') return keyBy(req)\n // Behind a proxy the socket address is the proxy's, the same for every visitor. `resolveClientIp`\n // returns it unchanged unless the operator declared how many proxies to trust — see its comment\n // for why reading `x-forwarded-for` uninvited would hand out a one-header bypass.\n const ip = resolveClientIp(req, trustProxy)\n switch (keyBy) {\n case 'session': {\n const cookie = readCookie(req, cookieName)\n return cookie ? `session:${await hashFragment(cookie)}` : `ip:${ip}`\n }\n case 'user': {\n const userId = (req as unknown as { user?: { id?: string } }).user?.id\n return userId ? `user:${userId}` : `ip:${ip}`\n }\n case 'ip':\n default:\n return `ip:${ip}`\n }\n}\n\n/**\n * Per-route rate limiter factory. Returns a sync checker compatible with\n * the existing api-middleware shape.\n *\n * Backwards-compatibility (ADR D2): a flat `{ windowMs, max }` config is\n * accepted and treated as `default` (no per-route variants).\n */\nexport function createRouteRateLimiter(config: RouteRateLimitConfig | RateLimitConfig) {\n // Detect legacy flat shape\n const isFlat =\n 'windowMs' in config && 'max' in config && !('default' in config) && !('routes' in config)\n const cfg: RouteRateLimitConfig = isFlat ? { default: config } : config\n\n const store = cfg.store ?? new InMemoryStore()\n // CR-005: validate store shape ONCE at construction. The previous\n // implementation ran `instanceof InMemoryStore` on every request and\n // threw at request-time if a non-InMemoryStore was passed — which\n // turned a clear config error into a runtime 500 on the first request.\n if (!(store instanceof InMemoryStore)) {\n throw new Error(\n 'createRouteRateLimiter: async RateLimitStore implementations require a dedicated async middleware path. ' +\n 'Use the InMemoryStore default for the sync facade.',\n )\n }\n const inMemoryStore = store\n const keyBy = cfg.keyBy ?? 'ip'\n const cookieName = cfg.cookieName ?? 'theo_session'\n const trustProxy = cfg.trustProxy ?? false\n\n // Build a pre-compiled list of (pattern, config) tuples for matching.\n const patternList: [string | RegExp, RateLimitConfig][] = []\n if (cfg.routes) {\n for (const [pattern, c] of Object.entries(cfg.routes)) patternList.push([pattern, c])\n }\n if (cfg.routePatterns) {\n for (const tuple of cfg.routePatterns) patternList.push(tuple)\n }\n\n return async function checkRouteRateLimit(req: IncomingMessage): Promise<RateLimitResult> {\n const url = req.url ?? ''\n let matched: RateLimitConfig | undefined\n for (const [pattern, c] of patternList) {\n if (matchRoutePattern(url, pattern)) {\n matched = c\n break\n }\n }\n const effective = matched ?? cfg.default\n if (!effective) {\n // No route match + no default → not limited.\n return { limited: false, headers: {} }\n }\n\n // Bucket key includes normalized path so /api/login and /api/login/\n // collapse to the same bucket (EC-5).\n const bucketSuffix = typeof matched === 'undefined' ? '*default*' : normalizePath(url)\n const key = `${await deriveKey(req, keyBy, cookieName, trustProxy)}|${bucketSuffix}`\n const state = inMemoryStore.incrSync(key, effective.windowMs)\n\n if (state.count > effective.max) {\n const retryAfter = Math.ceil((state.resetAt - Date.now()) / 1000)\n return {\n limited: true,\n headers: {\n 'X-RateLimit-Limit': String(effective.max),\n 'X-RateLimit-Remaining': '0',\n 'Retry-After': String(retryAfter),\n },\n }\n }\n return {\n limited: false,\n headers: {\n 'X-RateLimit-Limit': String(effective.max),\n 'X-RateLimit-Remaining': String(Math.max(0, effective.max - state.count)),\n },\n }\n }\n}\n\n/**\n * T5a.2 Phase D slice 1/3 — Web-Standards rate-limiter inputs context.\n *\n * Web `Request` has no equivalent of `req.socket.remoteAddress` (Node\n * runtime concept) or `req.user` (set by upstream middleware). The\n * Web-shaped rate-limiter requires the caller to pass these explicitly:\n *\n * - `clientIp` — resolved per-runtime (Node: `socket.remoteAddress`;\n * CF Workers: `request.headers.get('cf-connecting-ip')`; Vercel:\n * `x-forwarded-for` first hop; Bun/Deno: adapter-specific).\n * - `userId` — resolved by auth middleware (Phase D slice 3/3 ships\n * the Web-shaped session helper).\n *\n * Defaults: `clientIp = 'unknown'`, `userId = undefined` (matches the\n * IncomingMessage path's fallback semantics).\n */\nexport interface DeriveKeyRequestContext {\n clientIp?: string\n userId?: string\n}\n\n/**\n * T5a.2 Phase D slice 1/3 — Web-Standards-shaped key derivation.\n *\n * Mirror of `deriveKey(req: IncomingMessage, keyBy, cookieName)` for the\n * Web `Request` shape. Same `'ip' | 'session' | 'user'` enum cases (the\n * `function` callback case is IncomingMessage-only because the existing\n * `KeyByMode` callback type is Node-shaped; Web callers use the enum\n * cases or call a future `KeyByModeWeb` shape — out of T5a.2 Phase D scope).\n *\n * Uses `getCookieFromRequest` (Phase B slice 6/6) for session-mode cookie\n * lookup. Cookie parsing has the same CR-009 percent-encoding safety.\n */\nexport async function deriveKeyFromRequest(\n request: Request,\n keyBy: Exclude<KeyByMode, (req: IncomingMessage) => string>,\n cookieName: string,\n ctx: DeriveKeyRequestContext = {},\n): Promise<string> {\n const ip = ctx.clientIp ?? 'unknown'\n switch (keyBy) {\n case 'session': {\n // Reuse the Web cookie helper extracted in Phase B slice 6/6 so\n // CR-009 percent-encoding sanity stays consistent across paths.\n const { getCookieFromRequest } = await import('../http/cookies.js')\n const cookie = getCookieFromRequest(request, cookieName)\n return cookie ? `session:${await hashFragment(cookie)}` : `ip:${ip}`\n }\n case 'user': {\n return ctx.userId ? `user:${ctx.userId}` : `ip:${ip}`\n }\n case 'ip':\n default:\n return `ip:${ip}`\n }\n}\n\n/**\n * T5a.2 Phase D slice 1/3 — Web-Standards rate-limiter factory.\n *\n * Mirror of `createRouteRateLimiter(config)` returning a checker that\n * accepts `(request: Request, ctx?: DeriveKeyRequestContext)` instead of\n * `(req: IncomingMessage)`. Same `RouteRateLimitConfig` accepted; same\n * `keyBy` enum cases; same `InMemoryStore` constraint (CR-005 guard).\n *\n * Same returned `RateLimitResult` shape (headers + limited boolean).\n *\n * Web `Request` has no `req.url` path-only property — uses\n * `new URL(request.url).pathname + search` to derive the URL the way the\n * IncomingMessage path's `req.url ?? ''` would.\n */\nexport function createRouteRateLimiterWeb(config: RouteRateLimitConfig | RateLimitConfig) {\n const isFlat =\n 'windowMs' in config && 'max' in config && !('default' in config) && !('routes' in config)\n const cfg: RouteRateLimitConfig = isFlat ? { default: config } : config\n\n const store = cfg.store ?? new InMemoryStore()\n if (!(store instanceof InMemoryStore)) {\n throw new Error(\n 'createRouteRateLimiterWeb: async RateLimitStore implementations require a dedicated async middleware path. ' +\n 'Use the InMemoryStore default for the Web facade.',\n )\n }\n const inMemoryStore = store\n const keyBy = (cfg.keyBy ?? 'ip') as Exclude<KeyByMode, (req: IncomingMessage) => string>\n const cookieName = cfg.cookieName ?? 'theo_session'\n\n const patternList: [string | RegExp, RateLimitConfig][] = []\n if (cfg.routes) {\n for (const [pattern, c] of Object.entries(cfg.routes)) patternList.push([pattern, c])\n }\n if (cfg.routePatterns) {\n for (const tuple of cfg.routePatterns) patternList.push(tuple)\n }\n\n return async function checkRouteRateLimitWeb(\n request: Request,\n ctx: DeriveKeyRequestContext = {},\n ): Promise<RateLimitResult> {\n // Web Request guarantees absolute URL — extract path+query for pattern\n // matching (mirror of IncomingMessage's `req.url ?? ''`).\n const parsed = new URL(request.url)\n const url = `${parsed.pathname}${parsed.search}`\n let matched: RateLimitConfig | undefined\n for (const [pattern, c] of patternList) {\n if (matchRoutePattern(url, pattern)) {\n matched = c\n break\n }\n }\n const effective = matched ?? cfg.default\n if (!effective) {\n return { limited: false, headers: {} }\n }\n\n const bucketSuffix = typeof matched === 'undefined' ? '*default*' : normalizePath(url)\n const key = `${await deriveKeyFromRequest(request, keyBy, cookieName, ctx)}|${bucketSuffix}`\n const state = inMemoryStore.incrSync(key, effective.windowMs)\n\n if (state.count > effective.max) {\n const retryAfter = Math.ceil((state.resetAt - Date.now()) / 1000)\n return {\n limited: true,\n headers: {\n 'X-RateLimit-Limit': String(effective.max),\n 'X-RateLimit-Remaining': '0',\n 'Retry-After': String(retryAfter),\n },\n }\n }\n return {\n limited: false,\n headers: {\n 'X-RateLimit-Limit': String(effective.max),\n 'X-RateLimit-Remaining': String(Math.max(0, effective.max - state.count)),\n },\n }\n }\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 * ks.\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'\nimport { extractHeadTags, injectIntoHead } from '../../../vite-plugin/hoist-head-tags.js'\nimport { applyNonceToInlineScripts } from '../../../vite-plugin/ssr-dev-middleware.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\n/**\n * Moves the route's `<title>`/`<meta>`/`<link>` from the rendered body into the head.\n *\n * `ctx.htmlHead` is the template up to and including `<div id=\"root\">`, so it still contains the\n * `</head>` this injects before. Without it, a route's metadata ships inside the body and only\n * reaches the head after hydration — which never happens for a crawler that does not run\n * JavaScript, and those are exactly the ones that render social cards.\n *\n * The dev middleware does the same thing; both paths have to, or previews work in one and not the\n * other, which is worse than neither.\n */\nexport function withHoistedHead(\n htmlHead: string,\n ssrHtml: string,\n nonce: string,\n): { head: string; body: string } {\n const { html, headTags } = extractHeadTags(ssrHtml)\n\n // The nonce is stamped onto the template's own inline scripts here, per request, because the\n // nonce differs per request while `ctx.htmlHead` is computed once at startup. Without it, a CSP\n // with a nonce blocks anything the template inlines — including the theme-init script that\n // applications put in `<head>` specifically to avoid a flash of the wrong theme on load.\n const head = applyNonceToInlineScripts(injectIntoHead(htmlHead, headTags), nonce)\n return { head, body: html }\n}\n\nfunction buildSsrHtml(\n ctx: RequestHandlerContext,\n result: string | SsrRenderResult,\n nonce: string,\n): string {\n if (typeof result === 'string') {\n const { head, body } = withHoistedHead(ctx.htmlHead, result, nonce)\n return head + body + 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 const { head, body } = withHoistedHead(ctx.htmlHead, rendered.html, nonce)\n return head + body + hydrationScript + ctx.htmlTail\n }\n return applyNonceToInlineScripts(ctx.htmlHead, nonce) + 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'\nimport { pathToFileURL } from 'node:url'\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 { dispatchControllerRequest } from '../../../server/http/controller-dispatch.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/**\n * Load a controller module that `theokit build` already compiled — theokit#123.\n *\n * A plain dynamic `import()`, deliberately: production must not need `@swc/core`. That peer is a\n * native binary the app would otherwise carry solely to re-do work the build already did, and a\n * missing optional peer would degrade into a runtime 404 instead of a build failure.\n */\nasync function loadCompiledController(absPath: string): Promise<Record<string, unknown>> {\n return (await import(pathToFileURL(absPath).href)) as Record<string, unknown>\n}\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 /**\n * theokit#123 — absolute path to the COMPILED controllers emitted by `theokit build`\n * (`<distDir>/controllers`), or `undefined` when the build produced none.\n *\n * `undefined` is the routes-only app, and it must stay free: no scan, no import, no cost.\n */\n controllersDistDir: string | undefined\n pluginRunner: PluginRunner | undefined\n transformer: TheoTransformer | undefined\n csrfMode: CsrfMode\n disallowed: DisallowedConfig | undefined\n /**\n * Async because the per-route limiter hashes the session cookie with Web Crypto when\n * `keyBy: 'session'`, and `subtle.digest` is promise-based.\n */\n rateLimiter:\n | ((req: IncomingMessage) => Promise<{ limited: boolean; headers: Record<string, string> }>)\n | null\n}\n\n/** Apply rate limit; return true if request was limited (response sent). */\nasync function applyRateLimit(c: RequestHandlerCtx, method: string): Promise<boolean> {\n if (!c.rateLimiter) return false\n const check = await 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 (await 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 (await 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 (await 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 (await applyRateLimit(c, c.req.method ?? 'GET')) return true\n\n const match = matchRoute(c.url, c.cachedRoutes)\n if (!match) {\n // theokit#123 — controller fall-through, mirroring the dev `api-middleware` arm.\n //\n // Before this, `theokit dev` served a decorator controller and `theokit start` 404'd it: the\n // production path has no Vite/swc transform, so an uncompiled `.controller.ts` could not load.\n // `theokit build` now emits compiled modules and this branch serves them, so the SAME app\n // answers the same routes in both. Reached only after a file-route miss, so file routes keep\n // precedence exactly as in dev.\n if (c.controllersDistDir !== undefined) {\n const handled = await dispatchControllerRequest({\n controllersDir: c.controllersDistDir,\n loadModule: loadCompiledController,\n req: c.req,\n res: c.res,\n csrfMode: c.csrfMode,\n disallowed: c.disallowed,\n requestId: c.requestId,\n })\n if (handled) return true\n }\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 { findRootDiv } from '../../../core/contracts/find-root-div.js'\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 rootDiv = findRootDiv(opts.indexHtml)\n if (rootDiv) {\n htmlHead = opts.indexHtml.slice(0, rootDiv.insertAt)\n htmlTail = opts.indexHtml.slice(rootDiv.insertAt)\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,Q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AAY,uBAAuB,OAAO,SAAS,IAAI;AAElF,QAAM,MAAM,MAAM,SAAS;AAAA,IACzB;AAAA,IACA;AAAA,IACA,kBAAkB,OAAO;AAAA,IACzB,oBAAoB,OAAO;AAAA,EAC7B,CAAC;AAED,QAAM,SAAS;AAAA,IACb,qBAAqB;AAAA,MACnB,UAAU,CAAC,KAAK,KAAK,WAAW,eAAkC;AAAA,QAChE;AAAA,QACA;AAAA,QACA,KAAK,IAAI,OAAO;AAAA,QAChB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,aAAa;AAAA,QACb;AAAA,QACA;AAAA,QACA;AAAA,QACA,UAAU,OAAO,UAAU,QAAQ;AAAA,QACnC,YAAY,OAAO,UAAU;AAAA,QAC7B;AAAA,MACF;AAAA,MACA,uBAAuB,OAAO,UAAU,WAAW,CAAC;AAAA,MACpD,WAAW,IAAI;AAAA,MACf,oBAAoB,IAAI;AAAA,MACxB,qBAAqB,IAAI;AAAA,MACzB,UAAU,IAAI;AAAA,MACd,UAAU,IAAI;AAAA,MACd;AAAA,MACA;AAAA;AAAA;AAAA;AAAA,MAIA,gBAAgB,EAAE,QAAQ,kBAAkB,EAAE;AAAA,IAChD,CAAC;AAAA,EACH;AAEA,QAAM,uBAAuB,QAAQ,gBAAgB,UAAU;AAE/D,SAAO,OAAO,MAAM,MAAM;AACxB,YAAQ,IAAI;AAAA,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"]}
@@ -1 +0,0 @@
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 { findRootDiv } from '../core/contracts/find-root-div.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\n/** Keeps this call site's `RegExpExecArray`-shaped usage while ignoring commented mentions. */\nfunction findRootDivLegacyShape(html: string): [string] | null {\n const found = findRootDiv(html)\n return found ? [found.tag] : null\n}\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 = findRootDivLegacyShape(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,EAClD,YAAY,WAAmB,YAAoB;AACjD;AAAA,MACE,SAAS,SAAS,sCAAsC,UAAU;AAAA,IAEpE;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAYA,IAAM,YAAY;AAClB,IAAM,QAAQ;AAEP,SAAS,aAAa,SAAgC;AAC3D,QAAM,WAAW,UAAU,KAAK,OAAO;AACvC,MAAI,SAAU,QAAO,EAAE,MAAM,aAAa,MAAM,SAAS,CAAC,EAAE;AAC5D,QAAM,QAAQ,MAAM,KAAK,OAAO;AAChC,MAAI,MAAO,QAAO,EAAE,MAAM,SAAS,MAAM,MAAM,CAAC,EAAE;AAClD,SAAO,EAAE,MAAM,SAAS;AAC1B;AAEA,eAAsB,mBACpB,MACA,SACyB;AACzB,QAAM,MAAsB,CAAC;AAC7B,QAAM,KAAK,MAAM,CAAC,GAAG,KAAK,OAAO;AACjC,SAAO;AACT;AAEA,eAAe,KACb,MACA,gBACA,KACA,SACe;AACf,QAAM,WAAW,KAAK,YAAY,KAAK,iBAAiB,CAAC,GAAG,gBAAgB,KAAK,OAAO;AAExF,MAAI,KAAK,MAAM;AACb,UAAM,WAAW,MAAM,iBAAiB,UAAU,OAAO;AACzD,QAAI,KAAK,GAAG,QAAQ;AAAA,EACtB;AAEA,aAAW,SAAS,KAAK,UAAU;AACjC,UAAM,KAA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,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 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/theo-cloud.ts"],"sourcesContent":["/**\n * TheoCloud deploy adapter (Wave 3 v2.0 thin validator).\n *\n * Per ADR-0012 (mission expansion) + 2026-06-05 owner architectural decision,\n * TheoKit OSS does NOT emit K8s manifests. This adapter is intentionally thin:\n * 1. Validates the `.theokit/services.json` manifest shape (existing zod gate)\n * 2. Logs the services that will be deployed (visibility)\n * 3. Returns — bundle is ready for upload\n *\n * K8s manifest emission lives ENTIRELY inside TheoCloud (proprietary Go code)\n * upon receiving the upload. Rationale: OSS framework MUST emit formats\n * consumed by public/open systems OR neutral exchange formats; NOT formats\n * consumed by proprietary closed systems. Exposing K8s shape here would leak\n * TheoCloud-internal infrastructure choices into the OSS surface.\n */\nimport type { TheoConfig } from '../config/schema.js'\nimport { prepareTheoCloudArtifacts, readManifest } from '../services/index.js'\n\nimport type { DeployAdapter } from './types.js'\n\nexport const theoCloudAdapter: DeployAdapter = {\n name: 'theo-cloud',\n\n build(_config: TheoConfig, cwd: string): Promise<void> {\n const manifest = readManifest(cwd)\n const artifacts = prepareTheoCloudArtifacts(manifest)\n const summary =\n artifacts.services.length === 0 ? 'TS-only app (no services)' : artifacts.services.join(', ')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `[theo-cloud] Wave 3 v2.0: manifest schemaVersion=${String(artifacts.manifestVersion)}, ` +\n `services=${summary}. Bundle ready for upload — TheoCloud emits K8s manifests internally upon deploy.`,\n )\n return Promise.resolve()\n },\n}\n"],"mappings":";;;;;;;;AAoBO,IAAM,mBAAkC;AAAA,EAC7C,MAAM;AAAA,EAEN,MAAM,SAAqB,KAA4B;AACrD,UAAM,WAAW,aAAa,GAAG;AACjC,UAAM,YAAY,0BAA0B,QAAQ;AACpD,UAAM,UACJ,UAAU,SAAS,WAAW,IAAI,8BAA8B,UAAU,SAAS,KAAK,IAAI;AAE9F,YAAQ;AAAA,MACN,oDAAoD,OAAO,UAAU,eAAe,CAAC,cACvE,OAAO;AAAA,IACvB;AACA,WAAO,QAAQ,QAAQ;AAAA,EACzB;AACF;","names":[]}