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.
- package/README.md +1 -0
- package/dist/{actions-virtual-module-YQXRSSMW.js → actions-virtual-module-5WBVSDOM.js} +22 -12
- package/dist/actions-virtual-module-5WBVSDOM.js.map +1 -0
- package/dist/{actions-virtual-module-LB4NGONI.js → actions-virtual-module-ZYLMNW6K.js} +13 -8
- package/dist/{actions-virtual-module-LB4NGONI.js.map → actions-virtual-module-ZYLMNW6K.js.map} +1 -1
- package/dist/adapters/agent-mount.d.ts +127 -0
- package/dist/adapters/agent-mount.js +24 -0
- package/dist/adapters/security-headers.d.ts +132 -0
- package/dist/adapters/security-headers.js +64 -0
- package/dist/adapters/security-headers.js.map +1 -0
- package/dist/adapters/web-shim.d.ts +100 -13
- package/dist/adapters/web-shim.js +158 -54
- package/dist/adapters/web-shim.js.map +1 -1
- package/dist/agent-GKUEL6OH.js +15 -0
- package/dist/agent-scan-BZa-pagG.d.ts +16 -0
- package/dist/{app-typed-client-GHO3EWZK.js → app-typed-client-4LAIEGFX.js} +23 -13
- package/dist/app-typed-client-4LAIEGFX.js.map +1 -0
- package/dist/{app-typed-client-G3J5G7E5.js → app-typed-client-DQM3Y6YY.js} +14 -9
- package/dist/app-typed-client-DQM3Y6YY.js.map +1 -0
- package/dist/aws-lambda-VKMYUMP2.js +261 -0
- package/dist/aws-lambda-VKMYUMP2.js.map +1 -0
- package/dist/{build-WU6AKKIB.js → build-FLX6VF7Q.js} +71 -26
- package/dist/build-FLX6VF7Q.js.map +1 -0
- package/dist/{bun-33RD6K7O.js → bun-L7PP6ID5.js} +105 -13
- package/dist/bun-L7PP6ID5.js.map +1 -0
- package/dist/{check-45NKUVSQ.js → check-GIPZBFTX.js} +2 -2
- package/dist/{chunk-KD5G3YXI.js → chunk-2AMLGJJA.js} +35 -9
- package/dist/chunk-2AMLGJJA.js.map +1 -0
- package/dist/chunk-3PBAN2YE.js +146 -0
- package/dist/chunk-3PBAN2YE.js.map +1 -0
- package/dist/{chunk-HBU2GIMZ.js → chunk-3QPVEJ7D.js} +15 -9
- package/dist/chunk-3QPVEJ7D.js.map +1 -0
- package/dist/{chunk-47CINLWF.js → chunk-44J2ANQC.js} +2 -2
- package/dist/{chunk-IEES3CHD.js → chunk-47MM2JUK.js} +8 -2
- package/dist/chunk-47MM2JUK.js.map +1 -0
- package/dist/chunk-4X6H2BXP.js +108 -0
- package/dist/chunk-4X6H2BXP.js.map +1 -0
- package/dist/{chunk-A7JBF5FO.js → chunk-5K4TDLRG.js} +8 -5
- package/dist/chunk-5K4TDLRG.js.map +1 -0
- package/dist/chunk-5YPXXSYY.js +181 -0
- package/dist/chunk-5YPXXSYY.js.map +1 -0
- package/dist/{chunk-YGAXV5HR.js → chunk-6J4JWHDJ.js} +191 -112
- package/dist/chunk-6J4JWHDJ.js.map +1 -0
- package/dist/chunk-72DMJBXI.js +424 -0
- package/dist/chunk-72DMJBXI.js.map +1 -0
- package/dist/chunk-7PM6K5EV.js +513 -0
- package/dist/chunk-7PM6K5EV.js.map +1 -0
- package/dist/{chunk-MTEWLGVY.js → chunk-BPYMC7SU.js} +4 -48
- package/dist/chunk-BPYMC7SU.js.map +1 -0
- package/dist/chunk-BU6RJPPJ.js +421 -0
- package/dist/chunk-BU6RJPPJ.js.map +1 -0
- package/dist/{chunk-FB2HBNIC.js → chunk-BX6EUYHU.js} +6 -2
- package/dist/chunk-BX6EUYHU.js.map +1 -0
- package/dist/{chunk-BIVCP6X5.js → chunk-C62IZEJI.js} +465 -202
- package/dist/chunk-C62IZEJI.js.map +1 -0
- package/dist/chunk-D4VP2QPR.js +16 -0
- package/dist/chunk-D4VP2QPR.js.map +1 -0
- package/dist/{chunk-J5MXCGKA.js → chunk-DHAD2O3S.js} +6 -6
- package/dist/chunk-DHAD2O3S.js.map +1 -0
- package/dist/chunk-E43VJ3E5.js +188 -0
- package/dist/chunk-E43VJ3E5.js.map +1 -0
- package/dist/chunk-EVZKNA2W.js +110 -0
- package/dist/chunk-EVZKNA2W.js.map +1 -0
- package/dist/chunk-FD4ZDTQ6.js +181 -0
- package/dist/chunk-FD4ZDTQ6.js.map +1 -0
- package/dist/chunk-FDOOBTXJ.js +17 -0
- package/dist/chunk-FDOOBTXJ.js.map +1 -0
- package/dist/chunk-FH3SQR6P.js +275 -0
- package/dist/chunk-FH3SQR6P.js.map +1 -0
- package/dist/chunk-HJHGTFEJ.js +23 -0
- package/dist/chunk-HJHGTFEJ.js.map +1 -0
- package/dist/{chunk-LXAESF4Y.js → chunk-HK4AZBKX.js} +7 -4
- package/dist/chunk-HK4AZBKX.js.map +1 -0
- package/dist/{chunk-T5C46IIU.js → chunk-HWBRS4DZ.js} +28 -269
- package/dist/chunk-HWBRS4DZ.js.map +1 -0
- package/dist/chunk-IRQGAC4L.js +52 -0
- package/dist/chunk-IRQGAC4L.js.map +1 -0
- package/dist/{chunk-FNTLKHZ7.js → chunk-JDN5SAAD.js} +7 -4
- package/dist/chunk-JDN5SAAD.js.map +1 -0
- package/dist/{chunk-GXEX4CBH.js → chunk-JIKNR5LX.js} +673 -484
- package/dist/chunk-JIKNR5LX.js.map +1 -0
- package/dist/{chunk-GRI4XHBJ.js → chunk-JWRCZIA4.js} +266 -108
- package/dist/chunk-JWRCZIA4.js.map +1 -0
- package/dist/{chunk-E576KYYT.js → chunk-KI4DOTN4.js} +25 -2
- package/dist/chunk-KI4DOTN4.js.map +1 -0
- package/dist/{chunk-ZB7D62OA.js → chunk-KUZVRJ7M.js} +3 -3
- package/dist/chunk-L4VFNFDL.js +248 -0
- package/dist/chunk-L4VFNFDL.js.map +1 -0
- package/dist/chunk-M2WC5MF7.js +127 -0
- package/dist/chunk-M2WC5MF7.js.map +1 -0
- package/dist/{chunk-O3JIAU3V.js → chunk-MCTC6HSE.js} +157 -103
- package/dist/chunk-MCTC6HSE.js.map +1 -0
- package/dist/{chunk-PXFXSFJL.js → chunk-NZ5JU6D3.js} +9 -9
- package/dist/{chunk-YRBR424R.js → chunk-OAUI273L.js} +338 -165
- package/dist/chunk-OAUI273L.js.map +1 -0
- package/dist/chunk-OGLS76RN.js +43 -0
- package/dist/chunk-OGLS76RN.js.map +1 -0
- package/dist/{chunk-7LVM22VG.js → chunk-OQCRCXCP.js} +6 -6
- package/dist/chunk-OQCRCXCP.js.map +1 -0
- package/dist/{chunk-OLGPYOLO.js → chunk-P6OS7652.js} +5 -2
- package/dist/chunk-P6OS7652.js.map +1 -0
- package/dist/chunk-Q5L5EGWZ.js +26 -0
- package/dist/chunk-Q5L5EGWZ.js.map +1 -0
- package/dist/{chunk-S433N3CT.js → chunk-QTHVHNJJ.js} +6 -36
- package/dist/chunk-QTHVHNJJ.js.map +1 -0
- package/dist/chunk-RPET332G.js +84 -0
- package/dist/chunk-RPET332G.js.map +1 -0
- package/dist/{chunk-646CA6RV.js → chunk-RQW5YMH7.js} +12 -4
- package/dist/chunk-RQW5YMH7.js.map +1 -0
- package/dist/{chunk-XALU5LCU.js → chunk-RWNYIU6A.js} +550 -146
- package/dist/chunk-RWNYIU6A.js.map +1 -0
- package/dist/chunk-SL7YUHPV.js +111 -0
- package/dist/chunk-SL7YUHPV.js.map +1 -0
- package/dist/chunk-U5PWXS3J.js +39 -0
- package/dist/chunk-U5PWXS3J.js.map +1 -0
- package/dist/chunk-ULDCFL2O.js +273 -0
- package/dist/chunk-ULDCFL2O.js.map +1 -0
- package/dist/{chunk-RWNSW4FM.js → chunk-UMNXCU3K.js} +12 -6
- package/dist/{chunk-RWNSW4FM.js.map → chunk-UMNXCU3K.js.map} +1 -1
- package/dist/chunk-VI7ZANB3.js +193 -0
- package/dist/chunk-VI7ZANB3.js.map +1 -0
- package/dist/chunk-VQPHPQ5L.js +14 -0
- package/dist/chunk-VQPHPQ5L.js.map +1 -0
- package/dist/chunk-WNJTJRM6.js +147 -0
- package/dist/chunk-WNJTJRM6.js.map +1 -0
- package/dist/chunk-WOBSEO75.js +790 -0
- package/dist/chunk-WOBSEO75.js.map +1 -0
- package/dist/{chunk-BMHS4WAN.js → chunk-XS7EX55U.js} +156 -42
- package/dist/chunk-XS7EX55U.js.map +1 -0
- package/dist/chunk-YN4W7LCX.js +31 -0
- package/dist/chunk-YN4W7LCX.js.map +1 -0
- package/dist/chunk-YSJOZEI6.js +1 -0
- package/dist/{chunk-JA2ZAT5Q.js → chunk-Z4PJMZLM.js} +2 -2
- package/dist/chunk-Z4PJMZLM.js.map +1 -0
- package/dist/{chunk-7VPQHEAJ.js → chunk-ZNZISJDZ.js} +6 -2
- package/dist/chunk-ZNZISJDZ.js.map +1 -0
- package/dist/chunk-ZWN3AODA.js +11 -0
- package/dist/chunk-ZWN3AODA.js.map +1 -0
- package/dist/cli/index.js +25 -10
- package/dist/cli/index.js.map +1 -1
- package/dist/client/core.d.ts +1 -1
- package/dist/client/core.js +2 -0
- package/dist/client/core.js.map +1 -1
- package/dist/client/index.d.ts +44 -10
- package/dist/client/index.js +35 -0
- package/dist/client/index.js.map +1 -1
- package/dist/cloudflare-SIG42OIW.js +335 -0
- package/dist/cloudflare-SIG42OIW.js.map +1 -0
- package/dist/config-support-WQHQIJTA.js +104 -0
- package/dist/config-support-WQHQIJTA.js.map +1 -0
- package/dist/{csrf-BBrEZSBW.d.ts → csrf-Dgot9qSM.d.ts} +1 -1
- package/dist/deno-deploy-LQAYOOPW.js +196 -0
- package/dist/deno-deploy-LQAYOOPW.js.map +1 -0
- package/dist/{dev-MUWJAZRD.js → dev-ANDSEVLB.js} +28 -18
- package/dist/dev-ANDSEVLB.js.map +1 -0
- package/dist/{dev-emit-GWD6IXV7.js → dev-emit-BFNMDCPB.js} +5 -5
- package/dist/{dev-emit-NBT6JD7R.js → dev-emit-MVAJAFGX.js} +5 -3
- package/dist/dev-emit-MVAJAFGX.js.map +1 -0
- package/dist/engine-singleton-X4R7AZBJ.js +315 -0
- package/dist/engine-singleton-X4R7AZBJ.js.map +1 -0
- package/dist/{generate-Y3GWM57K.js → generate-EN6EDITF.js} +43 -4
- package/dist/generate-EN6EDITF.js.map +1 -0
- package/dist/index-CzxtQcnp.d.ts +1058 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +24 -13
- package/dist/index.js.map +1 -1
- package/dist/{info-XW7HGUPH.js → info-Y55RWS42.js} +8 -6
- package/dist/{info-XW7HGUPH.js.map → info-Y55RWS42.js.map} +1 -1
- package/dist/{internal-api-V5L65YSJ.js → internal-api-IP35YU3G.js} +22 -12
- package/dist/{internal-api-WEOSTMSN.js → internal-api-OPU456AT.js} +30 -16
- package/dist/internal-api-OPU456AT.js.map +1 -0
- package/dist/load-config-4ATXQUN3.js +16 -0
- package/dist/match-DmGgxjIU.d.ts +44 -0
- package/dist/{mcp-ULUFJNSZ.js → mcp-5LLNAGKA.js} +7 -7
- package/dist/netlify-C2IRCZKI.js +245 -0
- package/dist/netlify-C2IRCZKI.js.map +1 -0
- package/dist/node-OSVPYQ3D.js +10 -0
- package/dist/nonce-BXt7Qu_C.d.ts +31 -0
- package/dist/observability-bootstrap-MZMSOE66.js +15 -0
- package/dist/{openapi-HZXR335W.js → openapi-VFPEZSRI.js} +13 -11
- package/dist/{openapi-HZXR335W.js.map → openapi-VFPEZSRI.js.map} +1 -1
- package/dist/{plugin-runner-BFEcgtmJ.d.ts → plugin-runner-BVMOSxvb.d.ts} +1 -1
- package/dist/{plugin-types-D69-lJZ9.d.ts → plugin-types-BUVfUQ0V.d.ts} +13 -1
- package/dist/preview-GHPT2EQ5.js +23 -0
- package/dist/preview-GHPT2EQ5.js.map +1 -0
- package/dist/provider-resolver-Dx6QuWrw.d.ts +128 -0
- package/dist/registry-KBZDCFVQ.js +23 -0
- package/dist/route-config-Cm_ZMA1C.d.ts +72 -0
- package/dist/route-policy-BxOycCDq.d.ts +65 -0
- package/dist/router/element-scroll-restoration.d.ts +28 -0
- package/dist/router/element-scroll-restoration.js +96 -0
- package/dist/router/element-scroll-restoration.js.map +1 -0
- package/dist/{routes-OLNQX7CT.js → routes-BPLU3ISV.js} +11 -9
- package/dist/{routes-OLNQX7CT.js.map → routes-BPLU3ISV.js.map} +1 -1
- package/dist/{scan-7MJC6PYU.js → scan-YJEE4KQK.js} +2 -2
- package/dist/{schema-ZO3OSWVG.js → schema-SOAD43RQ.js} +7 -5
- package/dist/schemas-4AXHQMV3.js +25 -0
- package/dist/schemas-4AXHQMV3.js.map +1 -0
- package/dist/security-headers-Ccj7ncNx.d.ts +129 -0
- package/dist/server/agent/index.d.ts +2 -90
- package/dist/server/agent/index.js +1 -1
- package/dist/server/auth/index.d.ts +2 -21
- package/dist/server/auth/index.js +3 -2
- package/dist/server/cron/index.js +4 -3
- package/dist/server/define/index.d.ts +51 -57
- package/dist/server/define/index.js +10 -1
- package/dist/server/http/index.d.ts +7 -5
- package/dist/server/http/index.js +56 -12
- package/dist/server/index.d.ts +47 -439
- package/dist/server/index.js +119 -201
- package/dist/server/index.js.map +1 -1
- package/dist/server/jobs/index.js +4 -3
- package/dist/server/observability/index.d.ts +109 -35
- package/dist/server/observability/index.js +10 -7
- package/dist/server/plugins/index.d.ts +3 -3
- package/dist/server/scan/index.d.ts +47 -12
- package/dist/server/scan/index.js +13 -4
- package/dist/server/security/index.d.ts +61 -103
- package/dist/server/security/index.js +15 -6
- package/dist/server/webhook/index.d.ts +90 -3
- package/dist/server/webhook/index.js +12 -2
- package/dist/server-boundary-6B4ZQUY7.js +148 -0
- package/dist/server-boundary-6B4ZQUY7.js.map +1 -0
- package/dist/server-boundary-7VZQRPPX.js +133 -0
- package/dist/server-boundary-7VZQRPPX.js.map +1 -0
- package/dist/{services-typed-client-PSAGRPFF.js → services-typed-client-XGT5SUUN.js} +2 -2
- package/dist/{start-KR2JJR7K.js → start-UZDMOT7I.js} +342 -111
- package/dist/start-UZDMOT7I.js.map +1 -0
- package/dist/{static-M2W4HUWS.js → static-SVDWIOXJ.js} +24 -13
- package/dist/static-SVDWIOXJ.js.map +1 -0
- package/dist/{theo-cloud-XAHWOUFK.js → theo-cloud-3ET4G5T6.js} +9 -2
- package/dist/theo-cloud-3ET4G5T6.js.map +1 -0
- package/dist/vercel-BMCQKCWE.js +277 -0
- package/dist/vercel-BMCQKCWE.js.map +1 -0
- package/dist/vite-plugin/index.js +24 -13
- package/dist/vite-plugin-VKCT2LF2.js +42 -0
- package/dist/vite-plugin-VKCT2LF2.js.map +1 -0
- package/package.json +19 -6
- package/dist/actions-virtual-module-YQXRSSMW.js.map +0 -1
- package/dist/agent-7JJW3TPB.js +0 -15
- package/dist/app-typed-client-G3J5G7E5.js.map +0 -1
- package/dist/app-typed-client-GHO3EWZK.js.map +0 -1
- package/dist/aws-lambda-CYNDGU5O.js +0 -172
- package/dist/aws-lambda-CYNDGU5O.js.map +0 -1
- package/dist/build-WU6AKKIB.js.map +0 -1
- package/dist/bun-33RD6K7O.js.map +0 -1
- package/dist/chunk-646CA6RV.js.map +0 -1
- package/dist/chunk-6E5WKMDS.js +0 -67
- package/dist/chunk-6E5WKMDS.js.map +0 -1
- package/dist/chunk-6GGWS7J3.js +0 -91
- package/dist/chunk-6GGWS7J3.js.map +0 -1
- package/dist/chunk-7LVM22VG.js.map +0 -1
- package/dist/chunk-7VPQHEAJ.js.map +0 -1
- package/dist/chunk-A7JBF5FO.js.map +0 -1
- package/dist/chunk-AM3QABW5.js +0 -161
- package/dist/chunk-AM3QABW5.js.map +0 -1
- package/dist/chunk-BIVCP6X5.js.map +0 -1
- package/dist/chunk-BMHS4WAN.js.map +0 -1
- package/dist/chunk-E576KYYT.js.map +0 -1
- package/dist/chunk-FB2HBNIC.js.map +0 -1
- package/dist/chunk-FNTLKHZ7.js.map +0 -1
- package/dist/chunk-GRI4XHBJ.js.map +0 -1
- package/dist/chunk-GVW5EKEU.js +0 -422
- package/dist/chunk-GVW5EKEU.js.map +0 -1
- package/dist/chunk-GXEX4CBH.js.map +0 -1
- package/dist/chunk-HBU2GIMZ.js.map +0 -1
- package/dist/chunk-IEES3CHD.js.map +0 -1
- package/dist/chunk-J5MXCGKA.js.map +0 -1
- package/dist/chunk-JA2ZAT5Q.js.map +0 -1
- package/dist/chunk-KD5G3YXI.js.map +0 -1
- package/dist/chunk-LNVMHQ2Z.js +0 -54
- package/dist/chunk-LNVMHQ2Z.js.map +0 -1
- package/dist/chunk-LXAESF4Y.js.map +0 -1
- package/dist/chunk-MTEWLGVY.js.map +0 -1
- package/dist/chunk-O3JIAU3V.js.map +0 -1
- package/dist/chunk-OJLL4YD6.js +0 -403
- package/dist/chunk-OJLL4YD6.js.map +0 -1
- package/dist/chunk-OLGPYOLO.js.map +0 -1
- package/dist/chunk-S433N3CT.js.map +0 -1
- package/dist/chunk-T5C46IIU.js.map +0 -1
- package/dist/chunk-U267AOWS.js +0 -28
- package/dist/chunk-U267AOWS.js.map +0 -1
- package/dist/chunk-UW2TEAGR.js +0 -77
- package/dist/chunk-UW2TEAGR.js.map +0 -1
- package/dist/chunk-WPJOTQA5.js +0 -1
- package/dist/chunk-XALU5LCU.js.map +0 -1
- package/dist/chunk-XR74JD4M.js +0 -457
- package/dist/chunk-XR74JD4M.js.map +0 -1
- package/dist/chunk-YGAXV5HR.js.map +0 -1
- package/dist/chunk-YRBR424R.js.map +0 -1
- package/dist/cloudflare-KYUWCEPL.js +0 -122
- package/dist/cloudflare-KYUWCEPL.js.map +0 -1
- package/dist/deno-deploy-CCTB7HGS.js +0 -107
- package/dist/deno-deploy-CCTB7HGS.js.map +0 -1
- package/dist/dev-MUWJAZRD.js.map +0 -1
- package/dist/dev-emit-NBT6JD7R.js.map +0 -1
- package/dist/generate-Y3GWM57K.js.map +0 -1
- package/dist/index-BEtEv6ZH.d.ts +0 -575
- package/dist/load-config-VKD6LKWU.js +0 -14
- package/dist/match-CfbEFRG4.d.ts +0 -26
- package/dist/netlify-AFMDNKT4.js +0 -150
- package/dist/netlify-AFMDNKT4.js.map +0 -1
- package/dist/node-ZJQEJSP3.js +0 -10
- package/dist/registry-GKR3EWRW.js +0 -23
- package/dist/start-KR2JJR7K.js.map +0 -1
- package/dist/static-M2W4HUWS.js.map +0 -1
- package/dist/theo-cloud-XAHWOUFK.js.map +0 -1
- package/dist/vercel-SRS2DH6O.js +0 -133
- package/dist/vercel-SRS2DH6O.js.map +0 -1
- package/dist/vite-plugin-VPJFD4HK.js +0 -36
- /package/dist/{chunk-WPJOTQA5.js.map → adapters/agent-mount.js.map} +0 -0
- /package/dist/{agent-7JJW3TPB.js.map → agent-GKUEL6OH.js.map} +0 -0
- /package/dist/{check-45NKUVSQ.js.map → check-GIPZBFTX.js.map} +0 -0
- /package/dist/{chunk-47CINLWF.js.map → chunk-44J2ANQC.js.map} +0 -0
- /package/dist/{chunk-ZB7D62OA.js.map → chunk-KUZVRJ7M.js.map} +0 -0
- /package/dist/{chunk-PXFXSFJL.js.map → chunk-NZ5JU6D3.js.map} +0 -0
- /package/dist/{internal-api-WEOSTMSN.js.map → chunk-YSJOZEI6.js.map} +0 -0
- /package/dist/{dev-emit-GWD6IXV7.js.map → dev-emit-BFNMDCPB.js.map} +0 -0
- /package/dist/{internal-api-V5L65YSJ.js.map → internal-api-IP35YU3G.js.map} +0 -0
- /package/dist/{load-config-VKD6LKWU.js.map → load-config-4ATXQUN3.js.map} +0 -0
- /package/dist/{mcp-ULUFJNSZ.js.map → mcp-5LLNAGKA.js.map} +0 -0
- /package/dist/{node-ZJQEJSP3.js.map → node-OSVPYQ3D.js.map} +0 -0
- /package/dist/{scan-7MJC6PYU.js.map → observability-bootstrap-MZMSOE66.js.map} +0 -0
- /package/dist/{registry-GKR3EWRW.js.map → registry-KBZDCFVQ.js.map} +0 -0
- /package/dist/{schema-ZO3OSWVG.js.map → scan-YJEE4KQK.js.map} +0 -0
- /package/dist/{vite-plugin-VPJFD4HK.js.map → schema-SOAD43RQ.js.map} +0 -0
- /package/dist/{services-typed-client-PSAGRPFF.js.map → services-typed-client-XGT5SUUN.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/commands/build.ts","../src/adapters/types.ts","../src/server/cron/adapter-translators.ts","../src/server/_internal/atomic-write.ts","../src/server/cron/cron-manifest.ts","../src/server/cron/cron-scan.ts","../src/server/jobs/job-manifest.ts","../src/server/jobs/job-scan.ts","../src/cli/cleanup/cleanup.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { dirname, relative, resolve, sep } from 'node:path'\n\n// T1.1 (architecture-medium-deferrals) — nodeAdapter no longer static-imported.\n// All adapters dispatch via `adapterRegistry` (lazy-imported within runAdapterBuild).\nimport { VALID_TARGETS, type BuildTarget, type AdapterBuildContext } from '../../adapters/types.js'\nimport { loadConfig } from '../../config/load-config.js'\nimport { loadEnv } from '../../config/load-env.js'\nimport { validateProjectStructure } from '../../config/validate-structure.js'\nimport {\n ExistingConfigUnparseableError,\n translateCronToAws,\n translateCronToCloudflare,\n translateCronToDeno,\n translateCronToVercel,\n} from '../../server/cron/adapter-translators.js'\nimport { writeCronManifest } from '../../server/cron/cron-manifest.js'\nimport { scanCronDirs } from '../../server/cron/cron-scan.js'\nimport { writeJobManifest } from '../../server/jobs/job-manifest.js'\nimport { scanJobs } from '../../server/jobs/job-scan.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\nimport { generateManifest, writeManifest } from '../../server/scan/manifest.js'\nimport { scanServerRoutes } from '../../server/scan/scan.js'\nimport { scanWebSocketRoutes } from '../../server/scan/ws-scan.js'\nimport {\n buildManifest as buildServicesManifest,\n writeManifest as writeServicesManifest,\n} from '../../services/index.js'\n// G2 T2.2 — OpenAPI emit. Opt-in via `config.openapi`. Dual output:\n// 1. <distDir>/openapi.json (pre-Vite, dev surface + manifests sibling)\n// 2. dist/openapi.json (post-Vite, build artifact)\n// The dist emit awaits runAdapterBuild — if Vite fails, the second emit\n// never runs (EC-2 absorbed: no stale dist artifact).\nimport { emitOpenApi } from '../../vite-plugin/openapi-emit/emit.js'\nimport { loadRoutesForOpenApi } from '../../vite-plugin/openapi-emit/load-routes.js'\nimport { cleanOutDir } from '../cleanup/cleanup.js'\nimport { preflightNodeAndBindings } from '../preflight-node-version.js'\n\nimport { describeControllerArtifacts, emitControllerArtifacts } from './build/emit-controllers.js'\n\n// Adapters that do NOT support cron triggers natively. Build still\n// succeeds with crons declared, but emits a warning + skip note.\nconst CRON_NA_TARGETS = new Set<BuildTarget>(['bun', 'netlify', 'static'])\n\n// DERIVED, never restated. A hand-written list here went stale and told users\n// that three working targets were unsupported: it named node/vercel/cloudflare\n// while aws-lambda, deno-deploy and theo-cloud also translate crons. Deriving\n// from the two constants means adding a target cannot desynchronise the message.\nconst CRON_SUPPORTED_TARGETS = VALID_TARGETS.filter((t) => !CRON_NA_TARGETS.has(t))\n\nexport async function buildCommand(options?: { target?: string }): Promise<void> {\n const cwd = process.cwd()\n // Preflight (FIRST — BEFORE anything that touches native bindings).\n preflightNodeAndBindings(cwd)\n // Phase 1 (T1.2) — Load .env BEFORE config load.\n loadEnv({ cwd, mode: 'production' })\n\n const config = await loadConfig(cwd)\n // #95 — honor config.appDir so a custom frontend dir (e.g. apps/web) passes the structure gate.\n validateProjectStructure(cwd, config.appDir)\n\n // T2.2 — Clean .theokit/ at build start (Astro pattern). Skip .git*.\n const distDirAbs = resolve(cwd, config.distDir)\n await cleanOutDir({ dir: distDirAbs })\n\n const target = (options?.target ?? 'node') as BuildTarget\n\n if (!VALID_TARGETS.includes(target)) {\n throw new Error(\n `Invalid build target \"${target}\". Available targets: ${VALID_TARGETS.join(', ')}`,\n )\n }\n\n // EC-201 — cross-reference note when config.adapters[] diverges from\n // the --target flag. --target is authoritative per ADR D2.\n const configAdapters = (config as { adapters?: readonly string[] }).adapters\n if (configAdapters && configAdapters.length > 0) {\n const otherAdapters = configAdapters.filter((a) => a !== target)\n if (otherAdapters.length > 0) {\n console.log(\n `\\n Note: theo.config.ts.adapters lists [${otherAdapters.join(', ')}]; ` +\n `this build translates for ${target} only. ` +\n `Run \\`theokit build --target=<adapter>\\` separately for each (cross-reference).`,\n )\n }\n }\n\n console.log(`\\n Building for ${target}...\\n`)\n\n // Manifests emit BEFORE adapter bundling (Vite). Why: manifests are\n // fast + deterministic + don't depend on Vite. If Vite fails (missing\n // dep, malformed entry), the user still gets manifests for diagnostics.\n const serverDir = resolve(cwd, config.serverDir)\n const distDir = distDirAbs\n // #95 follow-up — pass projectRoot (cwd) + config.agentsDir so agents scan honors a custom dir.\n const manifest = generateManifest(serverDir, cwd, config.agentsDir)\n writeManifest(manifest, distDir)\n\n const totalEndpoints =\n manifest.routes.length + manifest.actions.length + manifest.websockets.length\n console.log(\n ` ✓ Manifest: ${manifest.routes.length} routes, ${manifest.actions.length} actions, ${manifest.websockets.length} ws (${totalEndpoints} total)`,\n )\n\n // T1.1 — cron scan + manifest + per-target adapter translation\n await emitCronArtifacts({ cwd, serverDir, agentsDir: config.agentsDir, distDir, target })\n\n // T1.2 — job scan + manifest (no per-target translation needed)\n await emitJobArtifacts({ cwd, serverDir, distDir })\n\n // theokit#123 — compile `server/controllers/**` so `theokit start` can serve them.\n //\n // #122 made controllers first-class in dev, where Vite's swc transform compiles them on the fly.\n // Production has neither, so an uncompiled `.controller.ts` cannot load and its routes 404'd —\n // working in dev and failing in prod, which is the worst place for a gap to live.\n //\n // Deliberately NOT folded into `generateManifest` (ADR-5): the manifest is the deploy-adapter\n // contract, and a parallel route source in it would ripple through every adapter. This writes a\n // separate artifact only the Node start path reads. No controllers ⇒ no artifact at all.\n const controllerManifest = await emitControllerArtifacts({ serverDir, distDir })\n if (controllerManifest !== null) {\n console.log(` ${describeControllerArtifacts(controllerManifest)}`)\n }\n\n // Wave 2 (T1.2) — services manifest at <cwd>/.theokit/services.json. Always\n // emit (empty array when services: {} is empty) so adapters can rely on\n // the file existing. Topological order preserved by buildServicesManifest.\n //\n // Plan v1.2 T2.1 — when theo.config.ts declares `name`, emit services.json\n // v2 with that project identifier. Falling back to v1 (no project field)\n // keeps TheoCloud's deprecation warning path intact (services-bundle).\n const projectName = config.name\n const servicesManifest = buildServicesManifest(config.services, projectName)\n writeServicesManifest(cwd, servicesManifest)\n if (servicesManifest.services.length > 0) {\n const versionLabel = `v${String(servicesManifest.version)}`\n const projectLabel =\n servicesManifest.version === 2 ? ` project=\"${servicesManifest.project}\"` : ''\n console.log(\n ` ✓ Services manifest (${versionLabel}${projectLabel}): ${String(servicesManifest.services.length)} service(s) ` +\n `(${servicesManifest.services.map((s) => s.name).join(', ')})`,\n )\n } else if (servicesManifest.version === 1) {\n console.log(\n ' ⚠ services.json emitted as v1 (no `name` in theo.config.ts). ' +\n 'TheoCloud will accept this with a deprecation warning; sunset in theokit 0.6.0. ' +\n 'Run `theokit migrate services-json-v1-to-v2` to upgrade.',\n )\n }\n\n // G2 T2.2 — OpenAPI dev-surface emit (pre-Vite, sibling of manifests).\n // Opt-in: only when config.openapi is defined. Best-effort: a route load\n // failure produces a warning, not a build abort.\n if (config.openapi !== undefined) {\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const devResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distDir },\n })\n console.log(` ✓ OpenAPI: ${String(hydrated.length)} ops → ${devResult.path}`)\n }\n\n // Now run the adapter-specific bundling (Vite + adapter-specific work).\n await runAdapterBuild(target, config, cwd)\n\n // G2 T2.2 — OpenAPI build-artifact emit (post-Vite, EC-2 gated on success).\n // If runAdapterBuild threw, execution never reaches this point — no stale\n // dist/openapi.json is written.\n if (config.openapi !== undefined) {\n const distOut = resolve(cwd, 'dist')\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const distResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distOut },\n })\n console.log(` ✓ OpenAPI (dist): ${distResult.path}`)\n }\n\n const ssrNote = config.ssr ? ' (SSR)' : ''\n console.log(`\\n ✓ Build complete → ${target}${ssrNote}\\n`)\n}\n\nasync function runAdapterBuild(\n target: BuildTarget,\n config: Awaited<ReturnType<typeof loadConfig>>,\n cwd: string,\n): Promise<void> {\n // T1.1 (architecture-cleanup) — CLI composes the Vite Plugin[] and INJECTS it into\n // the adapter via ctx.makeVitePlugins. This inverts the previous `adapters → vite-plugin`\n // edge — adapters no longer import from vite-plugin/ directly.\n //\n // theoPlugin AND `@vitejs/plugin-react` are dynamically imported so the deps are\n // materialized only when needed (adapter is `node`). This keeps the CLI's startup\n // path independent of optional build-time deps (so e.g. `theokit build --target=static`\n // does not need react installed). dep-cruiser's per-module rule allows `cli → vite-plugin`.\n //\n // 0.2.2 regression fix: switched sync `theoPlugin()` → `theoPluginAsync()` so the\n // returned Plugin[] includes the @theo/actions virtual module + typed-client +\n // services + @theokit/ui auto-chain. Without async, build-time Rollup couldn't\n // resolve `@theo/actions` even though dev-time Vite (which already used async)\n // could. See https://github.com/usetheo/theokit/commits — 0.2.2 changelog.\n const { theoPluginAsync } = await import('../../vite-plugin/index.js')\n const { default: react } = await import('@vitejs/plugin-react')\n const ctx: AdapterBuildContext = {\n // `react()` may return Plugin or Plugin[] depending on version; spread the\n // async chain so the contract returns a flat Plugin[] (AdapterBuildContext\n // type updated to `Plugin[] | Promise<Plugin[]>`).\n // #95 — inject the config dirs so the client build's router/entry + typed-client codegen honor\n // custom appDir/serverDir/agentsDir (e.g. \"apps/web\" / \"core\" / \"core/agents\").\n makeVitePlugins: async (opts) =>\n [\n react(),\n ...(await theoPluginAsync({\n ...opts,\n appDir: config.appDir,\n serverDir: config.serverDir,\n agentsDir: config.agentsDir,\n })),\n ].flat(),\n\n // #369 — the same inversion, for the same reason. A Worker has no filesystem, so the Cloudflare\n // entry bakes its routes at build time; importing the scanner from `adapters/` would add the\n // `adapters → server` edge that `adapters-may-only-depend-on-core-router-services` refuses. The\n // CLI already imports both sides, so it composes the scan and hands over the result.\n //\n // Paths are made relative to the project root here, where `cwd` is known: that string is both\n // the emitted import specifier and the key the executor looks a module up by, and the scanners\n // return absolute paths.\n scanRoutes: (serverDir) => {\n const abs = resolve(cwd, serverDir)\n const toProjectRelative = (p: string): string => relative(cwd, p).split(sep).join('/')\n return {\n routes: scanServerRoutes(abs).map((route) => ({\n filePath: toProjectRelative(route.filePath),\n routePath: route.routePath,\n methods: route.methods ?? [],\n })),\n wsRoutes: scanWebSocketRoutes(abs).map((ws) =>\n toProjectRelative(typeof ws === 'string' ? ws : ws.filePath),\n ),\n // #367 — agents are a DIFFERENT scan served by a DIFFERENT function, which is why no\n // adapter had ever heard of them: the entries route `/api/` through `scanServerRoutes` +\n // `executeRoute` alone, so `/api/agents/<name>` matched nothing and 404'd on every target.\n // Scanned here, beside the routes, because the same inversion argument applies verbatim.\n agents: scanAgents(dirname(abs), config.agentsDir).map((agent) => ({\n filePath: toProjectRelative(agent.filePath),\n agentPath: agent.agentPath,\n name: agent.name,\n })),\n }\n },\n }\n\n // T1.1 (architecture-medium-deferrals, ADR D1) — Adapter Registry replaces\n // the previous 9-case switch. New adapters add 1 line in `adapters/registry.ts`;\n // CLI is closed for modification (OCP).\n const { resolveAdapter } = await import('../../adapters/registry.js')\n const adapter = await resolveAdapter(target)\n\n // #409 / #410 — a config key that validates and is then never read makes the\n // deployed app behave as if the operator had not written it, with nothing\n // anywhere saying so. Name it before the build output scrolls past.\n const { warnUnappliedConfig } = await import('../../adapters/config-support.js')\n warnUnappliedConfig(config, adapter, target, (message) => {\n console.log(message)\n })\n\n await adapter.build(config, cwd, ctx)\n}\n\nasync function emitCronArtifacts(opts: {\n cwd: string\n serverDir: string\n agentsDir: string\n distDir: string\n target: BuildTarget\n}): Promise<void> {\n // Crons live in two conventional homes: `server/crons/` (a backend trigger) and\n // `agents/schedules/` (a scheduled agent run, kept in the agent domain). Both feed one manifest.\n const cronsDir = resolve(opts.serverDir, 'crons')\n const agentsSchedulesDir = resolve(opts.cwd, opts.agentsDir, 'schedules')\n\n const cronNodes = await scanCronDirs([cronsDir, agentsSchedulesDir])\n const manifestPath = resolve(opts.distDir, 'crons.json')\n writeCronManifest(manifestPath, cronNodes, opts.cwd)\n\n console.log(` ✓ Crons: ${cronNodes.length} declared`)\n\n if (cronNodes.length === 0) return\n\n // EC-201: target-specific translation. N/A targets emit a warning + skip.\n if (CRON_NA_TARGETS.has(opts.target)) {\n console.log(\n ` ⚠ Cron not supported by target \"${opts.target}\" — declared crons skipped. ` +\n `Supported targets: ${CRON_SUPPORTED_TARGETS.join(', ')}.`,\n )\n return\n }\n\n const manifestEntries = cronNodes.map((n) => ({\n name: n.name,\n filePath: relativize(n.filePath, opts.cwd),\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n\n try {\n switch (opts.target) {\n case 'vercel':\n translateCronToVercel(resolve(opts.cwd, 'vercel.json'), manifestEntries)\n console.log(` ✓ Cron → vercel.json crons[] (${cronNodes.length} entries)`)\n break\n case 'cloudflare':\n translateCronToCloudflare(resolve(opts.cwd, 'wrangler.toml'), manifestEntries)\n console.log(` ✓ Cron → wrangler.toml [triggers] (${cronNodes.length})`)\n break\n case 'aws-lambda':\n translateCronToAws(resolve(opts.cwd, 'serverless.yml'), manifestEntries)\n console.log(` ✓ Cron → serverless.yml functions (${cronNodes.length})`)\n break\n case 'deno-deploy':\n translateCronToDeno(resolve(opts.distDir, 'crons-entry.ts'), manifestEntries)\n console.log(` ✓ Cron → ${opts.distDir}/crons-entry.ts (Deno.cron)`)\n break\n case 'node':\n console.log(` ✓ Cron → in-process scheduler (theokit start)`)\n break\n }\n } catch (err) {\n if (err instanceof ExistingConfigUnparseableError) throw err\n throw err\n }\n}\n\nasync function emitJobArtifacts(opts: {\n cwd: string\n serverDir: string\n distDir: string\n}): Promise<void> {\n const jobsDir = resolve(opts.serverDir, 'jobs')\n\n const jobNodes = existsSync(jobsDir) ? await scanJobs(jobsDir) : []\n const manifestPath = resolve(opts.distDir, 'jobs.json')\n writeJobManifest(manifestPath, jobNodes, opts.cwd)\n console.log(` ✓ Jobs: ${jobNodes.length} declared`)\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","import type { Plugin } from 'vite'\n\nimport type { TheoConfig } from '../config/schema.js'\n\nimport type { DeployedAgent } from './deployed-agents.js'\n\n/**\n * Build context injected by the CLI into adapter.build.\n *\n * - `makeVitePlugins` — optional factory provided by CLI for adapters\n * that drive `viteBuild()` directly (currently: `nodeAdapter`).\n * When omitted, adapters that need Vite must fail with an actionable\n * error. This inverts the previous direct edge `adapters → vite-plugin`\n * per ADR-0001 v3 (T1.1 of the architecture-cleanup plan).\n *\n * The factory MAY return a Promise — `theokit build` uses\n * `theoPluginAsync` to wire the full Plugin[] chain (actions virtual\n * module + typed client + services + @theokit/ui auto-chain) so adapters\n * MUST `await` the result. See `cli/commands/build.ts` for the canonical\n * invocation.\n */\n/** One server route, flattened to what an adapter can bake into an emitted entry (#369). */\nexport interface AdapterRoute {\n /** Path relative to the project root — both the import specifier and the executor's lookup key. */\n filePath: string\n routePath: string\n methods: readonly string[]\n}\n\nexport interface AdapterBuildContext {\n makeVitePlugins?: (opts: { root: string; ssr?: boolean }) => Plugin[] | Promise<Plugin[]>\n /**\n * Scan the project's routes, INJECTED for the same reason `makeVitePlugins` is (#369).\n *\n * A Worker has no filesystem, so the Cloudflare entry has to bake its routes at build time\n * instead of scanning for them at request time. Importing the scanner here would put an\n * `adapters → server` edge in the graph — the layering inversion ADR-0001 v3 removed for\n * `vite-plugin`, and the one `adapters-may-only-depend-on-core-router-services` refuses. The CLI\n * already imports both sides, so it composes this and passes it in.\n */\n scanRoutes?: (serverDir: string) => {\n routes: AdapterRoute[]\n wsRoutes: string[]\n /**\n * The app's agents (#367). A different scan from the routes, served by a different function —\n * which is precisely why no adapter had ever heard of them and every deployed\n * `/api/agents/<name>` was a 404.\n */\n agents?: DeployedAgent[]\n }\n}\n\n/**\n * A configuration key that a request handler applies at runtime. Build-time\n * keys are deliberately absent: a runtime cannot silently drop them.\n */\nexport type ConfigConcern =\n | 'rateLimit'\n | 'cors'\n | 'csrf'\n | 'disallowed'\n | 'serialization'\n | 'plugins'\n | 'securityHeaders'\n\nexport interface DeployAdapter {\n name: string\n /**\n * #382 — does the handler this adapter emits hand its runtime a response\n * whose body is still being written?\n *\n * The claim is deliberately narrow, and it is the only part we can verify\n * without a real deployment: `true` means the emitted contract carries a\n * live body (a `Response` over a `ReadableStream`, or a chunk-by-chunk drain\n * into the runtime's own writable) rather than a fully materialized string\n * or buffer. It does NOT claim the platform was observed flushing early —\n * that needs a deploy, and none of these targets has one in CI.\n *\n * Omitted means no, on purpose: a new adapter should have to state that it\n * streams, because the failure mode of the opposite default is a target\n * silently listed for something nobody exercised.\n *\n * `aws-lambda` is the one target that answers no by construction — its v2\n * result object carries `body` as a string, so the response cannot exist\n * before the run ends. Making it stream means `awslambda.streamifyResponse`\n * plus a Function URL in `RESPONSE_STREAM` invoke mode, which this adapter\n * does not emit and which would break every API Gateway deployment of it.\n */\n streamsResponses?: boolean\n /**\n * Which configuration keys the handler this adapter emits actually applies.\n *\n * Same contract as `streamsResponses`, for the same reason: omitted means\n * **none**, on purpose. A new adapter should have to state what it honours,\n * because the failure mode of the opposite default is a target that parses a\n * rate limit, validates it, and refuses nothing — with no line anywhere\n * saying so.\n *\n * `'runtime-not-emitted-here'` is a third answer, not a synonym for none: it\n * belongs to an adapter that emits no request handler at all, so this build\n * genuinely cannot say what the runtime applies. Reporting such a target as\n * dropping configuration would be asserting rather than measuring.\n *\n * The declaration is a claim, and nothing here can verify it — a wrong claim\n * reads exactly like a right one. What it buys is that dropping a concern\n * becomes a visible edit instead of an omission.\n */\n /**\n * #367 — can the handler this adapter emits serve an AGENT?\n *\n * Same contract as `streamsResponses` and `appliesConfig`, for the same reason: omitted means\n * **no**, on purpose. The gap this answers went unnoticed because nothing in this layer had ever\n * heard of agents — `grep -rc \"agent\"` over the 14 adapter files returned nothing — so an agent\n * was served by no pipeline at all outside a machine running `theokit start`, in a framework\n * whose stated reason to exist is that the agent ships through the same pipeline as the page.\n *\n * `true` claims the emitted entry routes `/api/agents/<name>` to `mountAgent`. It is a claim\n * nothing here can verify, exactly like the other two; what it buys is that a target which drops\n * agents has to say so rather than be silently assumed to serve them.\n */\n servesAgents?: boolean\n appliesConfig?: readonly ConfigConcern[] | 'runtime-not-emitted-here'\n build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void>\n}\n\nexport type BuildTarget =\n | 'node'\n | 'vercel'\n | 'cloudflare'\n | 'static'\n | 'bun'\n | 'deno-deploy'\n | 'netlify'\n | 'aws-lambda'\n | 'theo-cloud'\n\nexport const VALID_TARGETS: BuildTarget[] = [\n 'node',\n 'vercel',\n 'cloudflare',\n 'static',\n 'bun',\n 'deno-deploy',\n 'netlify',\n 'aws-lambda',\n 'theo-cloud',\n]\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time adapter translators: caller-controlled paths only.\n */\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronManifestEntry } from './cron-manifest.js'\n\n/**\n * Thrown when an existing platform-config file (vercel.json, wrangler.toml,\n * serverless.yml) cannot be parsed. Caller must fix the file before\n * re-running `theokit build`. We NEVER silently overwrite a user's config.\n */\nexport class ExistingConfigUnparseableError extends Error {\n readonly code = 'EXISTING_CONFIG_UNPARSEABLE'\n constructor(\n public readonly filePath: string,\n public readonly parseError: string,\n ) {\n super(\n `Existing config \"${filePath}\" could not be parsed: ${parseError}. ` +\n 'Fix or remove the file before re-running build — TheoKit never silently overwrites user configuration.',\n )\n this.name = 'ExistingConfigUnparseableError'\n }\n}\n\n// ──────────────────────────────────────────────────────────\n// Vercel — vercel.json crons[]\n// ──────────────────────────────────────────────────────────\n\ninterface VercelJson {\n crons?: { path: string; schedule: string }[]\n [key: string]: unknown\n}\n\n/**\n * Translate a TheoKit cron manifest into `vercel.json crons[]`.\n *\n * EC-105: existing fields (functions, headers, redirects, rewrites, env,\n * etc.) are preserved verbatim — ONLY the `crons[]` slice is replaced.\n */\nexport function translateCronToVercel(\n vercelJsonPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n let existing: VercelJson = {}\n if (existsSync(vercelJsonPath)) {\n const raw = readFileSync(vercelJsonPath, 'utf8')\n try {\n existing = JSON.parse(raw) as VercelJson\n } catch (err) {\n throw new ExistingConfigUnparseableError(\n vercelJsonPath,\n err instanceof Error ? err.message : String(err),\n )\n }\n }\n const merged: VercelJson = {\n ...existing,\n crons: crons.map((c) => ({\n path: `/api/__crons/${c.name}`,\n schedule: c.schedule,\n })),\n }\n writeAtomic(vercelJsonPath, JSON.stringify(merged, null, 2))\n}\n\n// ──────────────────────────────────────────────────────────\n// Cloudflare — wrangler.toml [triggers] crons\n// ──────────────────────────────────────────────────────────\n\n/**\n * Translate a TheoKit cron manifest into `wrangler.toml [triggers] crons`.\n *\n * EC-105: regex-based mutation that preserves comments + other sections\n * verbatim. Replaces only the `[triggers]` block (or appends if absent).\n */\nexport function translateCronToCloudflare(\n wranglerTomlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const schedules = crons.map((c) => `\"${c.schedule}\"`).join(', ')\n const triggersBlock = `[triggers]\\ncrons = [${schedules}]\\n`\n\n if (!existsSync(wranglerTomlPath)) {\n writeAtomic(wranglerTomlPath, triggersBlock)\n return\n }\n\n const existing = readFileSync(wranglerTomlPath, 'utf8')\n\n // Replace existing [triggers] section if present. Strategy: split into\n // line array, find the [triggers] header line, drop subsequent lines\n // until the next section header (line starting with `[`) or EOF.\n const lines = existing.split('\\n')\n const triggersIdx = lines.findIndex((l) => l.trim() === '[triggers]')\n\n let next: string\n if (triggersIdx !== -1) {\n let endIdx = lines.length\n for (let i = triggersIdx + 1; i < lines.length; i++) {\n if (lines[i].trim().startsWith('[')) {\n endIdx = i\n break\n }\n }\n const before = lines.slice(0, triggersIdx).join('\\n')\n const after = lines.slice(endIdx).join('\\n')\n next = `${before}\\n${triggersBlock.trimEnd()}\\n${after}`.replace(/\\n{3,}/g, '\\n\\n')\n } else {\n next = existing.endsWith('\\n')\n ? `${existing}\\n${triggersBlock}`\n : `${existing}\\n\\n${triggersBlock}`\n }\n writeAtomic(wranglerTomlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// AWS Lambda — serverless.yml functions.<fn>.events: schedule\n// ──────────────────────────────────────────────────────────\n\n/**\n * Convert TheoKit's 5-field UTC cron to AWS EventBridge's 6-field format.\n * EventBridge requires `?` in EITHER day-of-month OR day-of-week (not both `*`).\n *\n * Algorithm:\n * - If DOM is \"*\" and DOW is \"*\" → insert ? in DOW (default)\n * - If DOM is \"*\" and DOW is specific → insert ? in DOM\n * - If DOM is specific and DOW is \"*\" → insert ? in DOW\n * - Append \"*\" year field at end.\n */\nexport function convertToAwsCron(schedule: string): string {\n const parts = schedule.trim().split(/\\s+/)\n if (parts.length !== 5) {\n throw new Error(`Invalid 5-field schedule for AWS conversion: \"${schedule}\"`)\n }\n const [minute, hour, dom, month, dow] = parts\n let awsDom = dom\n let awsDow = dow\n if (dom === '*' && dow === '*') {\n awsDow = '?'\n } else if (dom === '*') {\n awsDom = '?'\n } else if (dow === '*') {\n awsDow = '?'\n }\n return `cron(${minute} ${hour} ${awsDom} ${month} ${awsDow} *)`\n}\n\n/**\n * Translate a TheoKit cron manifest into a `serverless.yml` functions\n * map with `events: - schedule: cron(...)` entries.\n *\n * EC-105: appends to `functions:` block, preserving all existing\n * functions/sections. Cron functions are named `cron_<name>` to avoid\n * collision with user-declared functions.\n */\nexport function translateCronToAws(\n serverlessYmlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const cronFunctionsYaml = crons\n .map(\n (c) => ` cron_${c.name}:\n handler: .theokit/server/crons/${c.name}.handler\n events:\n - schedule: ${convertToAwsCron(c.schedule)}`,\n )\n .join('\\n')\n\n const block = `\\nfunctions:\\n${cronFunctionsYaml}\\n`\n\n if (!existsSync(serverlessYmlPath)) {\n // Minimal serverless.yml scaffold\n writeAtomic(\n serverlessYmlPath,\n `service: theokit-app\\nprovider:\\n name: aws\\n runtime: nodejs22.x\\n${block}`,\n )\n return\n }\n\n const existing = readFileSync(serverlessYmlPath, 'utf8')\n\n // Look for an existing top-level `functions:` block; if present, append our\n // cron entries under it (don't replace user-declared functions).\n const functionsRe = /^functions:\\s*\\n/m\n let next: string\n if (functionsRe.test(existing)) {\n next = existing.replace(functionsRe, (match) => `${match}${cronFunctionsYaml}\\n`)\n } else {\n next = existing.endsWith('\\n') ? `${existing}${block}` : `${existing}\\n${block}`\n }\n writeAtomic(serverlessYmlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// Deno Deploy — Deno.cron registrations\n// ──────────────────────────────────────────────────────────\n\n/**\n * Emit a Deno entry file that registers each cron via `Deno.cron`.\n *\n * Unlike Vercel/CF/AWS, Deno.cron is an in-process runtime API — the\n * entry file is a managed artifact (overwritten each build), not a user\n * config (so EC-105 doesn't apply here).\n */\nexport function translateCronToDeno(entryPath: string, crons: readonly CronManifestEntry[]): void {\n const lines = crons.map(\n (c) =>\n `Deno.cron(\"${c.name}\", \"${c.schedule}\", async () => {\n const mod = await import(\"../${c.filePath}\");\n const def = mod.default;\n await def.handler({\n traceId: crypto.randomUUID().replace(/-/g, \"\"),\n scheduledAt: new Date(),\n signal: AbortSignal.timeout(60_000),\n });\n});`,\n )\n const content = `// AUTOGENERATED by TheoKit cron build — DO NOT EDIT.\n// Source: server/crons/*.ts → .theokit/crons.json → this file.\n${lines.join('\\n\\n')}\n`\n writeAtomic(entryPath, content)\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time atomic write: caller-controlled paths only. No HTTP input\n * reaches these fs calls.\n */\n// T5a.1b — Web Crypto migration. Build-time only; node:fs + node:path stay\n// because this is a manifest-write leaf (e.g. .theokit/jobs.json) and per\n// ADR-0028 the runtime-portable boundary is the request handler, not the\n// scanner. Only node:crypto is swapped out — Web Crypto's\n// getRandomValues works in every supported runtime.\nimport { mkdirSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\n/**\n * Write `content` to `path` atomically via the tmp + rename pattern.\n *\n * Two concurrent calls to `writeAtomic(path, ...)` are guaranteed to\n * leave `path` containing valid content from ONE of the calls (never\n * truncated, never interleaved). POSIX rename is atomic on the same\n * filesystem.\n *\n * EC-106 (jobs-crons-webhooks-cost-tracking-plan) — shared helper for\n * `.theokit/crons.json` and `.theokit/jobs.json` manifest writes so a\n * concurrent dev-server scan + build manifest emit never produces\n * partial JSON.\n *\n * @param path destination path\n * @param content bytes (UTF-8 string) to write\n */\nexport function writeAtomic(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n // Include a random suffix so two concurrent writes don't trample each\n // other's tmp file. Web Crypto getRandomValues is non-blocking +\n // collision-safe for the tiny entropy we need (8 hex chars = 32 bits).\n // Hex-encoded manually to avoid Buffer (runtime-agnostic per ADR-0028).\n const randBuf = new Uint8Array(4)\n globalThis.crypto.getRandomValues(randBuf)\n let suffix = ''\n for (const b of randBuf) suffix += b.toString(16).padStart(2, '0')\n const tmp = `${path}.tmp-${process.pid}-${suffix}`\n writeFileSync(tmp, content, 'utf8')\n renameSync(tmp, path)\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronNode } from './cron-scan.js'\n\nexport const CRON_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface CronManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: 'forbid' | 'allow'\n}\n\nexport interface CronManifest {\n readonly schemaVersion: typeof CRON_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly crons: readonly CronManifestEntry[]\n}\n\n/**\n * Build a `CronManifest` from scanned `CronNode[]`. Filepaths are kept\n * relative to the caller's project root for portability.\n */\nexport function buildCronManifest(nodes: readonly CronNode[], projectRoot?: string): CronManifest {\n const crons: CronManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n return {\n schemaVersion: CRON_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n crons,\n }\n}\n\n/**\n * Write the cron manifest to `path` atomically (EC-106).\n *\n * Accepts either a pre-built `CronManifest` OR an array of `CronNode[]`\n * (which gets converted via `buildCronManifest`). The atomic-write\n * helper guarantees `path` always contains valid JSON, even under\n * concurrent writes (e.g., dev-server rescan + build).\n */\nexport function writeCronManifest(\n path: string,\n input: readonly CronNode[] | CronManifest,\n projectRoot?: string,\n): void {\n const manifest: CronManifest = isManifest(input) ? input : buildCronManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is CronManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'crons' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only. No HTTP\n * input ever reaches these fs calls.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport { importUserModule } from '../../config/import-user-module.js'\nimport { compareByCodeUnit } from '../_internal/compare-by-code-unit.js'\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { CronConcurrencyPolicy, CronDefinition } from './cron-types.js'\n\n/**\n * One discovered cron from build-time scan. The handler is intentionally\n * NOT included — manifest is platform-neutral and consumed by adapters\n * that emit static config. Runtime dispatch loads the handler at fire time.\n */\nexport interface CronNode {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: CronConcurrencyPolicy\n}\n\nexport class DuplicateCronNameError extends Error {\n readonly code = 'DUPLICATE_CRON_NAME'\n constructor(\n public readonly cronName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate cron name \"${cronName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Cron names must be unique across server/crons/ and agents/schedules/.',\n )\n this.name = 'DuplicateCronNameError'\n }\n}\n\nconst CRON_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface CronModule {\n default?: unknown\n}\n\nfunction isCronDefinition(value: unknown): value is CronDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.schedule === 'string' &&\n typeof def.handler === 'function' &&\n (def.concurrency === 'forbid' || def.concurrency === 'allow')\n )\n}\n\n/**\n * Scan a directory for cron definition files and return the discovered\n * `CronNode[]` sorted by name. Throws `DuplicateCronNameError` on name\n * collision and `Error` on missing default export.\n *\n * Sequential by design — module imports are awaited one-by-one to keep\n * error messages anchored to the file that failed.\n */\nexport async function scanCrons(cronsDir: string): Promise<CronNode[]> {\n return scanCronDirs([cronsDir])\n}\n\n/**\n * Scan MULTIPLE cron directories and merge the results with a UNIFIED\n * duplicate-name guard across all of them. The framework discovers crons in\n * two conventional homes: `server/crons/` (a backend trigger) and\n * `agents/schedules/` (a scheduled agent run — kept in the agent domain). Both\n * feed the same manifest + deploy translation; a name may not collide across\n * the two dirs. Missing dirs are skipped (no error). Nodes are returned sorted\n * by name for a stable manifest.\n */\nexport async function scanCronDirs(dirs: readonly string[]): Promise<CronNode[]> {\n const filePaths: string[] = []\n for (const dir of dirs) {\n if (!existsSync(dir)) continue\n walkSourceFiles(dir, { extensions: CRON_EXTENSIONS }, (p) => {\n const base = basename(p)\n // Skip private helpers (`_helper.ts`) and OS junk (`.DS_Store`).\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n }\n\n const nodes: CronNode[] = []\n for (const filePath of filePaths) {\n let mod: CronModule\n try {\n mod = await importUserModule(filePath)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import cron file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isCronDefinition(exported)) {\n throw new Error(\n `Cron file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineCron(name, { schedule, handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n schedule: exported.schedule,\n concurrency: exported.concurrency,\n })\n }\n\n // Dup-name detection (unified across every scanned dir).\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateCronNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => compareByCodeUnit(a.name, b.name))\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { JobNode } from './job-scan.js'\n\nexport const JOB_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface JobManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport interface JobManifest {\n readonly schemaVersion: typeof JOB_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly jobs: readonly JobManifestEntry[]\n}\n\nexport function buildJobManifest(nodes: readonly JobNode[], projectRoot?: string): JobManifest {\n const jobs: JobManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n maxAttempts: n.maxAttempts,\n hasInputSchema: n.hasInputSchema,\n }))\n return {\n schemaVersion: JOB_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n jobs,\n }\n}\n\nexport function writeJobManifest(\n path: string,\n input: readonly JobNode[] | JobManifest,\n projectRoot?: string,\n): void {\n const manifest: JobManifest = isManifest(input) ? input : buildJobManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is JobManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'jobs' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport { importUserModule } from '../../config/import-user-module.js'\nimport { compareByCodeUnit } from '../_internal/compare-by-code-unit.js'\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { JobDefinition } from './job-types.js'\n\nexport interface JobNode {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport class DuplicateJobNameError extends Error {\n readonly code = 'DUPLICATE_JOB_NAME'\n constructor(\n public readonly jobName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate job name \"${jobName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Job names must be unique across server/jobs/.',\n )\n this.name = 'DuplicateJobNameError'\n }\n}\n\nconst JOB_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface JobModule {\n default?: unknown\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.handler === 'function' &&\n typeof def.maxAttempts === 'number' &&\n typeof def.hasInputSchema === 'boolean'\n )\n}\n\nexport async function scanJobs(jobsDir: string): Promise<JobNode[]> {\n if (!existsSync(jobsDir)) return []\n\n const filePaths: string[] = []\n walkSourceFiles(jobsDir, { extensions: JOB_EXTENSIONS }, (p) => {\n const base = basename(p)\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n\n const nodes: JobNode[] = []\n for (const filePath of filePaths) {\n let mod: JobModule\n try {\n mod = await importUserModule(filePath)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import job file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isJobDefinition(exported)) {\n throw new Error(\n `Job file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineJob(name, { handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n maxAttempts: exported.maxAttempts,\n hasInputSchema: exported.hasInputSchema,\n })\n }\n\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateJobNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => compareByCodeUnit(a.name, b.name))\n}\n","/**\n * State cleanup utilities (Phase 2 of\n *\n * - `cleanOutDir` — Astro pattern: empty a directory except a skip list,\n * used at `theokit build` start.\n * - `gcAgentRegistry` — Nuxt LRU pattern: delete oldest agent dirs when\n * count exceeds cap, used at `theokit dev` startup.\n *\n * EC-3 (MUST FIX, CRITICAL): cleanOutDir refuses to wipe anything outside\n * the current cwd. Prevents catastrophic `distDir: '/'` data loss.\n * EC-9 (SHOULD TEST): gcAgentRegistry handles dirs with mtime=0 (Docker overlay).\n * EC-11 (SHOULD TEST): cleanOutDir normalizes trailing-slash in skip basenames.\n * EC-12 (SHOULD TEST): cleanOutDir catches EROFS and continues.\n */\n\nimport { promises as fs } from 'node:fs'\nimport { basename, resolve as resolvePath, sep } from 'node:path'\n\nimport type {\n CleanOutDirOptions,\n CleanOutDirResult,\n GcAgentRegistryOptions,\n GcAgentRegistryResult,\n} from './cleanup-types.js'\n\nconst DEFAULT_SKIP = ['.git', '.gitkeep', '.gitignore']\n// DEFAULT_MAX_AGENTS removed in Phase 7 — gcAgentRegistry is a tombstone.\n\nfunction normalizeSkipName(name: string): string {\n // EC-11 — strip trailing slash + leading `./`\n return basename(name.replace(/\\/$/, ''))\n}\n\n/**\n * Empty a directory, preserving entries in the skip list.\n *\n * Throws if `opts.dir` is not inside `process.cwd()` (EC-3 path safety).\n * Returns `{deleted:0, kept:0}` when the directory does not exist.\n */\nexport async function cleanOutDir(opts: CleanOutDirOptions): Promise<CleanOutDirResult> {\n const resolvedDir = resolvePath(opts.dir)\n const resolvedCwd = resolvePath(process.cwd())\n\n // EC-3 — path safety guard. CRITICAL.\n if (resolvedDir === resolvedCwd) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be a child of cwd, not cwd itself`,\n )\n }\n if (!resolvedDir.startsWith(resolvedCwd + sep)) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be inside cwd (${resolvedCwd})`,\n )\n }\n\n const skip = new Set((opts.skip ?? DEFAULT_SKIP).map(normalizeSkipName))\n\n let entries: { name: string }[]\n try {\n entries = await fs.readdir(resolvedDir, { withFileTypes: true })\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return { deleted: 0, kept: 0 }\n throw err\n }\n\n let deleted = 0\n let kept = 0\n for (const entry of entries) {\n const name = entry.name\n if (skip.has(name)) {\n kept++\n continue\n }\n const fullPath = resolvePath(resolvedDir, name)\n try {\n await fs.rm(fullPath, { recursive: true, force: true, maxRetries: 3 })\n deleted++\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n deleted++ // already gone\n continue\n }\n // EC-12 — EROFS or other rm failure: warn + continue, don't crash.\n console.warn(\n `[theokit] cleanOutDir could not remove ${fullPath} (${code ?? 'unknown'}); skipping`,\n )\n kept++\n }\n }\n\n return { deleted, kept }\n}\n\n/**\n * Phase 7 — TOMBSTONE for backward-compat. The SDK v1.1.0's `Agent.registry`\n * handles GC natively; this function is a no-op + emits a deprecation warning\n * ONCE per process (EC-10).\n *\n * Will be deleted entirely in TheoKit 0.4.0. Marked deprecated via runtime\n * warning rather than `@deprecated` JSDoc tag to avoid the eslint\n * sonarjs/deprecation flagging our own internal symbols.\n */\nlet warnedOnce = false\nexport async function gcAgentRegistry(\n _opts: GcAgentRegistryOptions,\n): Promise<GcAgentRegistryResult> {\n if (!warnedOnce) {\n warnedOnce = true\n console.warn(\n '[theokit] gcAgentRegistry is deprecated; SDK Agent.registry handles GC natively (configure via theo.config.ts > agents.registry)',\n )\n }\n return Promise.resolve({ deleted: 0, kept: 0 })\n}\n\n/**\n * @internal — testing helper. Resets the module-scoped warnedOnce flag.\n */\nexport function __resetGcDeprecationWarnedForTests(): void {\n warnedOnce = false\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,WAAAC,UAAS,UAAU,SAAS,OAAAC,YAAW;;;ACuIzC,IAAM,gBAA+B;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;AC/IA,SAAS,YAAY,oBAAoB;;;ACMzC,SAAS,WAAW,YAAY,qBAAqB;AACrD,SAAS,eAAe;AAkBjB,SAAS,YAAY,MAAc,SAAuB;AAC/D,YAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAK5C,QAAM,UAAU,IAAI,WAAW,CAAC;AAChC,aAAW,OAAO,gBAAgB,OAAO;AACzC,MAAI,SAAS;AACb,aAAW,KAAK,QAAS,WAAU,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AACjE,QAAM,MAAM,GAAG,IAAI,QAAQ,QAAQ,GAAG,IAAI,MAAM;AAChD,gBAAc,KAAK,SAAS,MAAM;AAClC,aAAW,KAAK,IAAI;AACtB;;;AD3BO,IAAM,iCAAN,cAA6C,MAAM;AAAA,EAExD,YACkB,UACA,YAChB;AACA;AAAA,MACE,oBAAoB,QAAQ,0BAA0B,UAAU;AAAA,IAElE;AANgB;AACA;AAMhB,SAAK,OAAO;AAAA,EACd;AAAA,EARkB;AAAA,EACA;AAAA,EAHT,OAAO;AAWlB;AAiBO,SAAS,sBACd,gBACA,OACM;AACN,MAAI,WAAuB,CAAC;AAC5B,MAAI,WAAW,cAAc,GAAG;AAC9B,UAAM,MAAM,aAAa,gBAAgB,MAAM;AAC/C,QAAI;AACF,iBAAW,KAAK,MAAM,GAAG;AAAA,IA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AG;AACvE;AAAA,MACF,KAAK;AACH,4BAAoB,QAAQ,KAAK,SAAS,gBAAgB,GAAG,eAAe;AAC5E,gBAAQ,IAAI,wBAAc,KAAK,OAAO,6BAA6B;AACnE;AAAA,MACF,KAAK;AACH,gBAAQ,IAAI,2DAAiD;AAC7D;AAAA,IACJ;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,eAAe,+BAAgC,OAAM;AACzD,UAAM;AAAA,EACR;AACF;AAEA,eAAe,iBAAiB,MAId;AAChB,QAAM,UAAU,QAAQ,KAAK,WAAW,MAAM;AAE9C,QAAM,WAAWC,YAAW,OAAO,IAAI,MAAM,SAAS,OAAO,IAAI,CAAC;AAClE,QAAM,eAAe,QAAQ,KAAK,SAAS,WAAW;AACtD,mBAAiB,cAAc,UAAU,KAAK,GAAG;AACjD,UAAQ,IAAI,kBAAa,SAAS,MAAM,WAAW;AACrD;AAEA,SAASD,YAAW,SAAiB,MAAsB;AACzD,MAAI,QAAQ,WAAW,IAAI,GAAG;AAC5B,UAAM,UAAU,QAAQ,MAAM,KAAK,MAAM;AACzC,WAAO,QAAQ,WAAW,GAAG,IAAI,QAAQ,MAAM,CAAC,IAAI;AAAA,EACtD;AACA,SAAO;AACT;","names":["existsSync","dirname","sep","existsSync","existsSync","relativize","isManifest","existsSync","basename","existsSync","basename","basename","writeManifest","sep","dirname","relativize","existsSync"]}
|
|
@@ -1,18 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "tsx/esm";
|
|
3
|
+
import {
|
|
4
|
+
deployedAgentsFragment,
|
|
5
|
+
planDeployedPlugins
|
|
6
|
+
} from "./chunk-M2WC5MF7.js";
|
|
7
|
+
import {
|
|
8
|
+
deployedCorsFragment,
|
|
9
|
+
deployedCsrfFragment,
|
|
10
|
+
deployedRuntimeConfigFragment,
|
|
11
|
+
deployedTraceFragment,
|
|
12
|
+
describeDeployedSecurityHeaders,
|
|
13
|
+
renderSecurityHeadersConfigLiteral
|
|
14
|
+
} from "./chunk-E43VJ3E5.js";
|
|
3
15
|
import {
|
|
4
16
|
nodeAdapter
|
|
5
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-KI4DOTN4.js";
|
|
18
|
+
import "./chunk-RPET332G.js";
|
|
6
19
|
import {
|
|
7
20
|
assertServicesUnsupported,
|
|
8
21
|
readManifest
|
|
9
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-ZNZISJDZ.js";
|
|
10
23
|
|
|
11
24
|
// src/adapters/bun.ts
|
|
12
25
|
import { mkdirSync, writeFileSync } from "fs";
|
|
13
26
|
import { resolve } from "path";
|
|
14
27
|
function renderBunEntry(port, opts = {}) {
|
|
15
28
|
const streamingComment = opts.ssrStreaming ? `// T2.3 \u2014 ssrStreaming on; renderStreamingWeb may be consumed by app code` : `// (ssrStreaming off)`;
|
|
29
|
+
const runtimeConfig = deployedRuntimeConfigFragment(opts);
|
|
30
|
+
const agentsFragment = deployedAgentsFragment(
|
|
31
|
+
{ kind: "scan", projectRoot: "cwd", loadModule: "loadModule" },
|
|
32
|
+
{ pathname: "pathname" }
|
|
33
|
+
);
|
|
16
34
|
return [
|
|
17
35
|
`// Generated by Theo \u2014 Bun Adapter`,
|
|
18
36
|
`// Run: bun run .theokit/bun/server.mjs`,
|
|
@@ -40,9 +58,9 @@ function renderBunEntry(port, opts = {}) {
|
|
|
40
58
|
``,
|
|
41
59
|
`import { resolve, join } from 'node:path'`,
|
|
42
60
|
`import { existsSync } from 'node:fs'`,
|
|
43
|
-
`import {
|
|
44
|
-
`import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader } from 'theokit/server'`,
|
|
61
|
+
`import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,
|
|
45
62
|
`import { createWebShim } from 'theokit/adapters/web-shim'`,
|
|
63
|
+
`import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,
|
|
46
64
|
`// T3.2 \u2014 WS bridge for Bun runtime`,
|
|
47
65
|
`import { createBunWsBridge } from 'theokit/adapters/ws-shim'`,
|
|
48
66
|
`import { scanWebSocketRoutes } from 'theokit/server'`,
|
|
@@ -52,6 +70,23 @@ function renderBunEntry(port, opts = {}) {
|
|
|
52
70
|
`const serverDir = resolve(cwd, 'server')`,
|
|
53
71
|
`const port = process.env.PORT ? Number(process.env.PORT) : ${port}`,
|
|
54
72
|
``,
|
|
73
|
+
`// #410 \u2014 the security baseline \`theokit start\` puts on every response,`,
|
|
74
|
+
`// carried here as a literal because the deployed process has no`,
|
|
75
|
+
`// theo.config.ts to read. Bun is the one Web target whose own handler serves`,
|
|
76
|
+
`// the HTML document (static file + SPA fallback below), so the document gets`,
|
|
77
|
+
`// these headers too -- with a nonce-less CSP, because that HTML was written`,
|
|
78
|
+
`// at build time and carries no nonce on its script tags (EC-4).`,
|
|
79
|
+
`const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,
|
|
80
|
+
`const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,
|
|
81
|
+
``,
|
|
82
|
+
...runtimeConfig.imports,
|
|
83
|
+
...agentsFragment.imports,
|
|
84
|
+
...runtimeConfig.declarations,
|
|
85
|
+
...agentsFragment.declarations,
|
|
86
|
+
...deployedCsrfFragment(opts),
|
|
87
|
+
``,
|
|
88
|
+
...deployedCorsFragment(opts.cors, "bun"),
|
|
89
|
+
``,
|
|
55
90
|
`const routes = existsSync(serverDir) ? scanServerRoutes(serverDir) : []`,
|
|
56
91
|
`const wsRoutes = existsSync(serverDir) ? scanWebSocketRoutes(serverDir) : []`,
|
|
57
92
|
`const loadModule = createProductionLoader()`,
|
|
@@ -78,6 +113,20 @@ function renderBunEntry(port, opts = {}) {
|
|
|
78
113
|
` port,`,
|
|
79
114
|
` websocket: wsBridge,`,
|
|
80
115
|
` async fetch(request, server) {`,
|
|
116
|
+
` // #409 \u2014 the preflight is answered BEFORE anything routes: an OPTIONS the router`,
|
|
117
|
+
` // handles is an OPTIONS the browser never gets a CORS answer to.`,
|
|
118
|
+
` const preflight = corsPreflight(request)`,
|
|
119
|
+
` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,
|
|
120
|
+
` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,
|
|
121
|
+
` },`,
|
|
122
|
+
`})`,
|
|
123
|
+
``,
|
|
124
|
+
...bunHandleRequestFragment(runtimeConfig.executeRouteSpread, agentsFragment.branch)
|
|
125
|
+
].join("\n");
|
|
126
|
+
}
|
|
127
|
+
function bunHandleRequestFragment(runtimeSpread, agentBranch) {
|
|
128
|
+
return [
|
|
129
|
+
`async function handleRequest(request) {`,
|
|
81
130
|
` const url = new URL(request.url)`,
|
|
82
131
|
` const pathname = url.pathname`,
|
|
83
132
|
``,
|
|
@@ -91,13 +140,16 @@ function renderBunEntry(port, opts = {}) {
|
|
|
91
140
|
``,
|
|
92
141
|
` // 2) API routes through the full executeRoute pipeline via the shim`,
|
|
93
142
|
` if (pathname.startsWith('/api/')) {`,
|
|
143
|
+
...agentBranch,
|
|
144
|
+
``,
|
|
94
145
|
` const match = matchRoute(pathname, routes)`,
|
|
95
146
|
` if (!match) return notFoundResponse()`,
|
|
96
147
|
` const { req, res, toResponse } = createWebShim(request)`,
|
|
97
|
-
|
|
148
|
+
...deployedTraceFragment("request", " "),
|
|
98
149
|
` const method = request.method.toUpperCase()`,
|
|
99
|
-
`
|
|
100
|
-
`
|
|
150
|
+
` // #382 \u2014 not awaited: toResponse() settles at the headers and carries`,
|
|
151
|
+
` // a live body, so Bun.serve streams while the handler writes.`,
|
|
152
|
+
` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,
|
|
101
153
|
` }`,
|
|
102
154
|
``,
|
|
103
155
|
` // 3) SPA fallback`,
|
|
@@ -105,11 +157,10 @@ function renderBunEntry(port, opts = {}) {
|
|
|
105
157
|
` if (existsSync(indexPath)) return new Response(Bun.file(indexPath))`,
|
|
106
158
|
``,
|
|
107
159
|
` return notFoundResponse()`,
|
|
108
|
-
`
|
|
109
|
-
`})`,
|
|
160
|
+
`}`,
|
|
110
161
|
``,
|
|
111
162
|
`console.log('Theo (Bun) listening on http://localhost:' + port)`
|
|
112
|
-
]
|
|
163
|
+
];
|
|
113
164
|
}
|
|
114
165
|
async function buildBun(config, cwd, deps = {}, ctx) {
|
|
115
166
|
assertServicesUnsupported("bun", readManifest(cwd));
|
|
@@ -118,15 +169,56 @@ async function buildBun(config, cwd, deps = {}, ctx) {
|
|
|
118
169
|
const outputDir = resolve(cwd, ".theokit/bun");
|
|
119
170
|
const ensureDir = deps.ensureDir ?? ((p) => mkdirSync(p, { recursive: true }));
|
|
120
171
|
ensureDir(outputDir);
|
|
121
|
-
const
|
|
172
|
+
const pluginsPlan = planDeployedPlugins(config.plugins, "bun");
|
|
173
|
+
const entry = renderBunEntry(config.port, {
|
|
174
|
+
ssrStreaming: config.ssrStreaming,
|
|
175
|
+
securityHeaders: config.security?.headers,
|
|
176
|
+
csrf: config.security?.csrf,
|
|
177
|
+
disallowed: config.security?.disallowed,
|
|
178
|
+
cors: config.security?.cors,
|
|
179
|
+
// #425 — a selector, not a transformer, so it rides as a literal like the values above.
|
|
180
|
+
serialization: config.serialization,
|
|
181
|
+
// #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin
|
|
182
|
+
// declared by module specifier is imported by the emitted module instead; a constructed one
|
|
183
|
+
// is refused by name at build time rather than dropped in silence.
|
|
184
|
+
runtimeConfigModule: pluginsPlan?.moduleSpecifier
|
|
185
|
+
});
|
|
122
186
|
const write = deps.writeEntry ?? ((p, c) => {
|
|
123
187
|
writeFileSync(p, c);
|
|
124
188
|
});
|
|
189
|
+
if (pluginsPlan !== void 0) {
|
|
190
|
+
write(resolve(outputDir, "theo.plugins.mjs"), pluginsPlan.source);
|
|
191
|
+
}
|
|
125
192
|
write(resolve(outputDir, "server.mjs"), entry);
|
|
126
|
-
console.log("\n \u2713 Bun output \u2192 .theokit/bun/server.mjs
|
|
193
|
+
console.log("\n \u2713 Bun output \u2192 .theokit/bun/server.mjs");
|
|
194
|
+
console.log(
|
|
195
|
+
`${describeDeployedSecurityHeaders({
|
|
196
|
+
target: "bun",
|
|
197
|
+
securityHeaders: config.security?.headers,
|
|
198
|
+
// No deploy target other than the streamed Cloudflare worker renders HTML
|
|
199
|
+
// at request time, so none of the rest can mint a nonce.
|
|
200
|
+
mintsNonce: false,
|
|
201
|
+
// Bun serves `.theokit/client` itself, so the document DOES pass through
|
|
202
|
+
// the handler these headers are attached to.
|
|
203
|
+
documentHeaders: "handler"
|
|
204
|
+
})}
|
|
205
|
+
`
|
|
206
|
+
);
|
|
127
207
|
}
|
|
128
208
|
var bunAdapter = {
|
|
129
209
|
name: "bun",
|
|
210
|
+
streamsResponses: true,
|
|
211
|
+
// #409 / #410 — the generated entry calls `executeRoute` with routes, loader
|
|
212
|
+
// and serverDir only. CSRF, route policy, file middleware and Zod validation
|
|
213
|
+
// still run because they live inside `executeRoute`; none of the remaining
|
|
214
|
+
// configurable concerns reach it. Declared explicitly rather than omitted so
|
|
215
|
+
// the gap is a statement in the source and not an absence.
|
|
216
|
+
//
|
|
217
|
+
// `securityHeaders` IS applied: the entry carries `security.headers` as a
|
|
218
|
+
// literal and puts the built baseline on every response, the served document
|
|
219
|
+
// included.
|
|
220
|
+
servesAgents: true,
|
|
221
|
+
appliesConfig: ["securityHeaders", "csrf", "disallowed", "cors", "serialization", "plugins"],
|
|
130
222
|
build(config, cwd, ctx) {
|
|
131
223
|
return buildBun(config, cwd, {}, ctx);
|
|
132
224
|
}
|
|
@@ -136,4 +228,4 @@ export {
|
|
|
136
228
|
bunAdapter,
|
|
137
229
|
renderBunEntry
|
|
138
230
|
};
|
|
139
|
-
//# sourceMappingURL=bun-
|
|
231
|
+
//# sourceMappingURL=bun-L7PP6ID5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapters/bun.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Bun deploy adapter. Writes to `cwd/.theokit/bun/`. Build-time.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment } from './deployed-agents.js'\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport {\n deployedRuntimeConfigFragment,\n type DeployedRuntimeConfigOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport {\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport interface BunBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\nexport function renderBunEntry(\n port: number,\n opts: {\n ssrStreaming?: boolean\n securityHeaders?: SecurityHeadersConfig\n } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedCorsOptions = {},\n): string {\n const streamingComment = opts.ssrStreaming\n ? `// T2.3 — ssrStreaming on; renderStreamingWeb may be consumed by app code`\n : `// (ssrStreaming off)`\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(\n { kind: 'scan', projectRoot: 'cwd', loadModule: 'loadModule' },\n { pathname: 'pathname' },\n )\n return [\n `// Generated by Theo — Bun Adapter`,\n `// Run: bun run .theokit/bun/server.mjs`,\n `// Requires Bun >= 1.1`,\n streamingComment,\n ``,\n `// EC-1: dev-mode guard`,\n `if (process.env.NODE_ENV !== 'production') {`,\n ` console.error('TheoBunAdapter is production-only. Use \\\\'theokit dev\\\\' (Node) for development.')`,\n ` process.exit(1)`,\n `}`,\n ``,\n `// Version check: Bun >= 1.1`,\n `if (typeof Bun === 'undefined') {`,\n ` console.error('TheoBunAdapter must run inside Bun. Got Node.js or unknown runtime.')`,\n ` process.exit(1)`,\n `}`,\n `{`,\n ` const [maj, min] = (Bun.version ?? '0.0').split('.').map(Number)`,\n ` if (maj < 1 || (maj === 1 && min < 1)) {`,\n ` console.error('TheoBunAdapter requires Bun >= 1.1; got ' + Bun.version)`,\n ` process.exit(1)`,\n ` }`,\n `}`,\n ``,\n `import { resolve, join } from 'node:path'`,\n `import { existsSync } from 'node:fs'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n `// T3.2 — WS bridge for Bun runtime`,\n `import { createBunWsBridge } from 'theokit/adapters/ws-shim'`,\n `import { scanWebSocketRoutes } from 'theokit/server'`,\n ``,\n `const cwd = process.cwd()`,\n `const clientDir = resolve(cwd, '.theokit/client')`,\n `const serverDir = resolve(cwd, 'server')`,\n `const port = process.env.PORT ? Number(process.env.PORT) : ${port}`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed process has no`,\n `// theo.config.ts to read. Bun is the one Web target whose own handler serves`,\n `// the HTML document (static file + SPA fallback below), so the document gets`,\n `// these headers too -- with a nonce-less CSP, because that HTML was written`,\n `// at build time and carries no nonce on its script tags (EC-4).`,\n `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ``,\n ...runtimeConfig.imports,\n ...agentsFragment.imports,\n ...runtimeConfig.declarations,\n ...agentsFragment.declarations,\n ...deployedCsrfFragment(opts),\n ``,\n ...deployedCorsFragment(opts.cors, 'bun'),\n ``,\n `const routes = existsSync(serverDir) ? scanServerRoutes(serverDir) : []`,\n `const wsRoutes = existsSync(serverDir) ? scanWebSocketRoutes(serverDir) : []`,\n `const loadModule = createProductionLoader()`,\n ``,\n `// Bun WebSocket config — single handler dispatches to first ws route,`,\n `// or a default no-op when none declared. Per-route routing happens above`,\n `// (the upgrade decision is made in fetch handler before Bun.serve hands off).`,\n `const wsBridge = wsRoutes.length > 0`,\n ` ? createBunWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` })`,\n ` : { open: () => {}, message: () => {}, close: () => {} }`,\n ``,\n `function notFoundResponse() {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Route not found' } }), {`,\n ` status: 404,`,\n ` headers: { 'Content-Type': 'application/json' },`,\n ` })`,\n `}`,\n ``,\n `Bun.serve({`,\n ` port,`,\n ` websocket: wsBridge,`,\n ` async fetch(request, server) {`,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n ` },`,\n `})`,\n ``,\n ...bunHandleRequestFragment(runtimeConfig.executeRouteSpread, agentsFragment.branch),\n ].join('\\n')\n}\n\n/**\n * The request handler, as generated source.\n *\n * Extracted for the reason `vercel.ts` extracts its own fragments: the emitter is one array\n * literal, so every line the entry gains counts against `max-lines-per-function`, and #410 added\n * the CSRF literal to an emitter that was already sitting exactly at the ceiling.\n */\nfunction bunHandleRequestFragment(runtimeSpread: string, agentBranch: readonly string[]): string[] {\n return [\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ` const pathname = url.pathname`,\n ``,\n ` // 1) Static assets`,\n ` const staticPath = pathname === '/' ? '/index.html' : pathname`,\n ` const fullStatic = join(clientDir, staticPath)`,\n ` if (existsSync(fullStatic)) {`,\n ` const file = Bun.file(fullStatic)`,\n ` if (await file.exists()) return new Response(file)`,\n ` }`,\n ``,\n ` // 2) API routes through the full executeRoute pipeline via the shim`,\n ` if (pathname.startsWith('/api/')) {`,\n ...agentBranch,\n ``,\n ` const match = matchRoute(pathname, routes)`,\n ` if (!match) return notFoundResponse()`,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — not awaited: toResponse() settles at the headers and carries`,\n ` // a live body, so Bun.serve streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,\n ` }`,\n ``,\n ` // 3) SPA fallback`,\n ` const indexPath = join(clientDir, 'index.html')`,\n ` if (existsSync(indexPath)) return new Response(Bun.file(indexPath))`,\n ``,\n ` return notFoundResponse()`,\n `}`,\n ``,\n `console.log('Theo (Bun) listening on http://localhost:' + port)`,\n ]\n}\n\nexport async function buildBun(\n config: TheoConfig,\n cwd: string,\n deps: BunBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('bun', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/bun')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const pluginsPlan = planDeployedPlugins(config.plugins, 'bun')\n const entry = renderBunEntry(config.port, {\n ssrStreaming: config.ssrStreaming,\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n })\n const write =\n deps.writeEntry ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n if (pluginsPlan !== undefined) {\n // Beside the entry, so the emitted import is a sibling. Written through the same seam as\n // the entry so a test that captures one captures both (#425).\n write(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n write(resolve(outputDir, 'server.mjs'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Bun output → .theokit/bun/server.mjs')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'bun',\n securityHeaders: config.security?.headers,\n // No deploy target other than the streamed Cloudflare worker renders HTML\n // at request time, so none of the rest can mint a nonce.\n mintsNonce: false,\n // Bun serves `.theokit/client` itself, so the document DOES pass through\n // the handler these headers are attached to.\n documentHeaders: 'handler',\n })}\\n`,\n )\n}\n\nexport const bunAdapter: DeployAdapter = {\n name: 'bun',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied: the entry carries `security.headers` as a\n // literal and puts the built baseline on every response, the served document\n // included.\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n build(config, cwd, ctx) {\n return buildBun(config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C,cAAc,OAAO;AAAA,IACrB,iBAAiB,OAAO,UAAU;AAAA,IAClC,MAAM,OAAO,UAAU;AAAA,IACvB,YAAY,OAAO,UAAU;AAAA,IAC7B,MAAM,OAAO,UAAU;AAAA;AAAA,IAEvB,eAAe,OAAO;AAAA;AAAA;AAAA;AAAA,IAItB,qBAAqB,aAAa;AAAA,EACpC,CAAC;AACD,QAAM,QACJ,KAAK,eACJ,CAAC,GAAG,MAAM;AACT,kBAAc,GAAG,CAAC;AAAA,EACpB;AACF,MAAI,gBAAgB,QAAW;AAG7B,UAAM,QAAQ,WAAW,kBAAkB,GAAG,YAAY,MAAM;AAAA,EAClE;AACA,QAAM,QAAQ,WAAW,YAAY,GAAG,KAAK;AAG7C,UAAQ,IAAI,sDAA4C;AAExD,UAAQ;AAAA,IACN,GAAG,gCAAgC;AAAA,MACjC,QAAQ;AAAA,MACR,iBAAiB,OAAO,UAAU;AAAA;AAAA;AAAA,MAGlC,YAAY;AAAA;AAAA;AAAA,MAGZ,iBAAiB;AAAA,IACnB,CAAC,CAAC;AAAA;AAAA,EACJ;AACF;AAEO,IAAM,aAA4B;AAAA,EACvC,MAAM;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,cAAc;AAAA,EACd,eAAe,CAAC,mBAAmB,QAAQ,cAAc,QAAQ,iBAAiB,SAAS;AAAA,EAC3F,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,SAAS,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EACtC;AACF;","names":[]}
|
|
@@ -53,7 +53,7 @@ async function defaultScanProject(cwd) {
|
|
|
53
53
|
for (const child of n.children) walk2(child);
|
|
54
54
|
};
|
|
55
55
|
var walk = walk2;
|
|
56
|
-
const { scanRoutes } = await import("./scan-
|
|
56
|
+
const { scanRoutes } = await import("./scan-YJEE4KQK.js");
|
|
57
57
|
const appDir = resolve(cwd, "app");
|
|
58
58
|
if (!existsSync(appDir)) return { ok: true, routesCount: 0 };
|
|
59
59
|
const tree = scanRoutes(appDir);
|
|
@@ -122,4 +122,4 @@ export {
|
|
|
122
122
|
checkCommand,
|
|
123
123
|
runCheck
|
|
124
124
|
};
|
|
125
|
-
//# sourceMappingURL=check-
|
|
125
|
+
//# sourceMappingURL=check-GIPZBFTX.js.map
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import "tsx/esm";
|
|
3
|
+
|
|
1
4
|
// src/server/body-parser.ts
|
|
2
5
|
import { basename } from "path";
|
|
3
6
|
import Busboy from "busboy";
|
|
@@ -5,6 +8,22 @@ var METHODS_WITH_BODY = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
|
|
|
5
8
|
var DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
|
|
6
9
|
var DEFAULT_MAX_FILES = 10;
|
|
7
10
|
var DEFAULT_MAX_FIELD_SIZE = 1 * 1024 * 1024;
|
|
11
|
+
var RequestBodyConsumedError = class extends Error {
|
|
12
|
+
code = "REQUEST_BODY_CONSUMED";
|
|
13
|
+
status = 500;
|
|
14
|
+
constructor(method, url) {
|
|
15
|
+
super(
|
|
16
|
+
`Request body for ${method} ${url ?? "(unknown url)"} was already consumed before the body parser ran, so it can never arrive. Something upstream read the request stream \u2014 a route dispatcher, a middleware, or an adapter that converted the request \u2014 without passing the parsed body on.`
|
|
17
|
+
);
|
|
18
|
+
this.name = "RequestBodyConsumedError";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
function declaresEmptyBody(req) {
|
|
22
|
+
return (req.headers["content-length"] ?? "") === "0";
|
|
23
|
+
}
|
|
24
|
+
function bodyAlreadyConsumed(req) {
|
|
25
|
+
return req.readableEnded && !declaresEmptyBody(req);
|
|
26
|
+
}
|
|
8
27
|
var FileTooLargeError = class extends Error {
|
|
9
28
|
constructor(message, truncatedFilenames, maxFileSize) {
|
|
10
29
|
super(message);
|
|
@@ -26,6 +45,14 @@ function stashBodyPreview(req, body) {
|
|
|
26
45
|
}
|
|
27
46
|
function parseJsonBody(req) {
|
|
28
47
|
return new Promise((resolve, reject) => {
|
|
48
|
+
if (req.readableEnded) {
|
|
49
|
+
if (declaresEmptyBody(req)) {
|
|
50
|
+
resolve(void 0);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
reject(new RequestBodyConsumedError(req.method ?? "POST", req.url));
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
29
56
|
const chunks = [];
|
|
30
57
|
req.on("data", (chunk) => chunks.push(chunk));
|
|
31
58
|
req.on("end", () => {
|
|
@@ -47,6 +74,9 @@ function parseMultipartBody(req, contentType, options) {
|
|
|
47
74
|
if (!contentType.includes("boundary=")) {
|
|
48
75
|
return Promise.reject(new Error("Missing multipart boundary"));
|
|
49
76
|
}
|
|
77
|
+
if (bodyAlreadyConsumed(req)) {
|
|
78
|
+
return Promise.reject(new RequestBodyConsumedError(req.method ?? "POST", req.url));
|
|
79
|
+
}
|
|
50
80
|
return new Promise((resolve, reject) => {
|
|
51
81
|
const fields = {};
|
|
52
82
|
const files = [];
|
|
@@ -178,8 +208,8 @@ function randomRequestId() {
|
|
|
178
208
|
}
|
|
179
209
|
function broadcastToDevtoolsCore(info, headers, stashedBody) {
|
|
180
210
|
void Promise.all([
|
|
181
|
-
import("./broadcast-
|
|
182
|
-
import("./build-request-body-preview-
|
|
211
|
+
import("./broadcast-LUMOJIJT.js"),
|
|
212
|
+
import("./build-request-body-preview-XPZ2GYMG.js")
|
|
183
213
|
]).then(([{ broadcastRequest }, { buildRequestBodyPreview }]) => {
|
|
184
214
|
const bodyInfo = buildRequestBodyPreview(stashedBody);
|
|
185
215
|
broadcastRequest({
|
|
@@ -267,9 +297,6 @@ function createLogger(options) {
|
|
|
267
297
|
}
|
|
268
298
|
var _warnOnceSeen = /* @__PURE__ */ new Set();
|
|
269
299
|
var MAX_SEEN = 1024;
|
|
270
|
-
function _resetWarnOnceForTests() {
|
|
271
|
-
_warnOnceSeen.clear();
|
|
272
|
-
}
|
|
273
300
|
function warnOnce(key, payload) {
|
|
274
301
|
if (_warnOnceSeen.has(key)) return;
|
|
275
302
|
if (_warnOnceSeen.size >= MAX_SEEN) {
|
|
@@ -296,7 +323,7 @@ function randomDevtoolsId() {
|
|
|
296
323
|
return `warn-${String(Date.now())}-${Math.random().toString(36).slice(2, 8)}`;
|
|
297
324
|
}
|
|
298
325
|
function broadcastWarnOnceToDevtools(key, payload) {
|
|
299
|
-
void import("./broadcast-
|
|
326
|
+
void import("./broadcast-LUMOJIJT.js").then(({ broadcastCsrfWarn, broadcastError }) => {
|
|
300
327
|
if (payload.event === "csrf.warn" && typeof payload.code === "string" && typeof payload.docsUrl === "string") {
|
|
301
328
|
broadcastCsrfWarn({
|
|
302
329
|
event: "csrf.warn",
|
|
@@ -319,11 +346,10 @@ function broadcastWarnOnceToDevtools(key, payload) {
|
|
|
319
346
|
}
|
|
320
347
|
|
|
321
348
|
export {
|
|
322
|
-
|
|
349
|
+
RequestBodyConsumedError,
|
|
323
350
|
parseRequestBody,
|
|
324
351
|
logRequest,
|
|
325
352
|
createLogger,
|
|
326
|
-
_resetWarnOnceForTests,
|
|
327
353
|
warnOnce
|
|
328
354
|
};
|
|
329
|
-
//# sourceMappingURL=chunk-
|
|
355
|
+
//# sourceMappingURL=chunk-2AMLGJJA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/body-parser.ts","../src/server/observability/request-log.ts","../src/server/observability/logger.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http'\nimport { basename } from 'node:path'\n\nimport Busboy from 'busboy'\n\n// --- Types ---\n\nexport interface UploadedFile {\n fieldname: string\n filename: string\n encoding: string\n mimeType: string\n buffer: Buffer\n size: number\n}\n\nexport interface ParsedBody {\n fields: Record<string, string>\n files: UploadedFile[]\n json?: unknown\n}\n\nexport interface BodyParserOptions {\n maxFileSize?: number // bytes, default 10MB\n maxFiles?: number // default 10\n maxFieldSize?: number // bytes, default 1MB\n}\n\nconst METHODS_WITH_BODY = new Set(['POST', 'PUT', 'PATCH'])\n\nconst DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024 // 10MB\nconst DEFAULT_MAX_FILES = 10\nconst DEFAULT_MAX_FIELD_SIZE = 1 * 1024 * 1024 // 1MB\n\n/**\n * theokit#400 — the request body was consumed before the parser could read it.\n *\n * A Node `IncomingMessage` is a single-use stream. Once something drains it, `'end'` has fired and\n * cannot fire again, so a parser that attaches its listeners afterwards waits for an event that\n * will never come: the request hangs with no status, no error, and no timeout — the failure family\n * of `docs/adr/0002`, in its least readable form, since nothing terminates at all.\n *\n * That is a framework bug wherever it happens (a dispatcher converting the request before deciding\n * it owns the path, a middleware reading the stream and not passing the value on), so this reports\n * it by name instead of waiting. A 500 that says which request lost its body is recoverable\n * information; silence is not.\n */\nexport class RequestBodyConsumedError extends Error {\n readonly code = 'REQUEST_BODY_CONSUMED'\n readonly status = 500\n constructor(method: string, url: string | undefined) {\n super(\n `Request body for ${method} ${url ?? '(unknown url)'} was already consumed before the body ` +\n `parser ran, so it can never arrive. Something upstream read the request stream — a route ` +\n `dispatcher, a middleware, or an adapter that converted the request — without passing the ` +\n `parsed body on.`,\n )\n this.name = 'RequestBodyConsumedError'\n }\n}\n\n/**\n * Was the request declared to carry no bytes at all? `content-length: 0` is the one case where an\n * already-ended stream is honestly empty rather than eaten, and it must stay an `undefined` body\n * instead of an error — an empty POST is legal.\n */\nfunction declaresEmptyBody(req: IncomingMessage): boolean {\n return (req.headers['content-length'] ?? '') === '0'\n}\n\n/**\n * True once the stream has emitted `'end'` — which, at the moment the parser is about to attach,\n * means somebody else drained it. A stream nobody has read yet reports `false` here even when Node\n * has already buffered every byte, because `'end'` only fires on consumption.\n *\n * Read as a plain truthiness check on purpose: the type says `boolean`, but the suite's request\n * doubles are plain emitters carrying `headers` and no `readableEnded` at all, and `undefined` must\n * take the untouched-stream path exactly as `false` does.\n */\nfunction bodyAlreadyConsumed(req: IncomingMessage): boolean {\n return req.readableEnded && !declaresEmptyBody(req)\n}\n\nexport class FileTooLargeError extends Error {\n readonly code = 'FILE_TOO_LARGE'\n readonly status = 413\n constructor(\n message: string,\n readonly truncatedFilenames: string[],\n readonly maxFileSize: number,\n ) {\n super(message)\n this.name = 'FileTooLargeError'\n }\n}\n\n// --- JSON parsing ---\n\n/**\n * Stash the parsed body on the IncomingMessage for the devtools forwarder\n * to read at log time. Symbol-keyed so it never leaks into user-visible\n * surfaces. Best-effort — failures (e.g. frozen req) are swallowed.\n */\nfunction stashBodyPreview(req: IncomingMessage, body: unknown): void {\n try {\n ;(req as unknown as Record<symbol, unknown>)[DEVTOOLS_BODY_PREVIEW] = body\n } catch {\n // best-effort; never break the request\n }\n}\n\nfunction parseJsonBody(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n // theokit#400 — an ended stream re-emits nothing, so attaching here would wait forever. A\n // declared-empty body resolves as the absent body it is; anything else was eaten upstream and\n // is reported rather than awaited.\n if (req.readableEnded) {\n if (declaresEmptyBody(req)) {\n resolve(undefined)\n return\n }\n reject(new RequestBodyConsumedError(req.method ?? 'POST', req.url))\n return\n }\n const chunks: Buffer[] = []\n req.on('data', (chunk: Buffer) => chunks.push(chunk))\n req.on('end', () => {\n const raw = Buffer.concat(chunks).toString()\n if (!raw) {\n resolve(undefined)\n return\n }\n try {\n resolve(JSON.parse(raw))\n } catch {\n reject(new Error('Invalid JSON body'))\n }\n })\n req.on('error', reject)\n })\n}\n\n// --- Multipart parsing ---\n\nfunction parseMultipartBody(\n req: IncomingMessage,\n contentType: string,\n options: Required<Pick<BodyParserOptions, 'maxFileSize' | 'maxFiles' | 'maxFieldSize'>>,\n): Promise<{ fields: Record<string, string>; files: UploadedFile[] }> {\n // EC-3: Validate boundary exists.\n if (!contentType.includes('boundary=')) {\n return Promise.reject(new Error('Missing multipart boundary'))\n }\n\n // theokit#400 — the multipart arm fails differently and no better. Piping an already-drained\n // stream into busboy rejects with `Unexpected end of form` (measured), which\n // `parseQueryAndBody` maps to a 400 VALIDATION_ERROR: the caller is told to fix a request that\n // was correct, and the framework's own mistake reads as theirs. Same cause, so the same name.\n if (bodyAlreadyConsumed(req)) {\n return Promise.reject(new RequestBodyConsumedError(req.method ?? 'POST', req.url))\n }\n\n return new Promise((resolve, reject) => {\n const fields: Record<string, string> = {}\n const files: UploadedFile[] = []\n // CR-010: track filenames that were truncated mid-stream. The previous\n // implementation skipped truncated files from `files` and relied on\n // `files.some(f => f.size > maxFileSize)` to detect — but since the\n // file was never added, the guard never fired. Silent data loss.\n const truncatedFilenames: string[] = []\n let fileCount = 0\n\n const bb = Busboy({\n headers: req.headers,\n limits: {\n fileSize: options.maxFileSize,\n files: options.maxFiles,\n fieldSize: options.maxFieldSize,\n },\n })\n\n bb.on('field', (name: string, value: string) => {\n fields[name] = value\n })\n\n bb.on(\n 'file',\n (\n fieldname: string,\n stream: NodeJS.ReadableStream,\n info: { filename: string; encoding: string; mimeType: string },\n ) => {\n fileCount++\n if (fileCount > options.maxFiles) {\n stream.resume() // drain\n return\n }\n\n // EC-6: Sanitize filename — basename only, no path traversal.\n const safeName = basename(info.filename || 'unnamed')\n const chunks: Buffer[] = []\n let size = 0\n let truncated = false\n\n stream.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > options.maxFileSize) {\n truncated = true\n stream.resume() // drain the rest\n return\n }\n chunks.push(chunk)\n })\n\n stream.on('end', () => {\n if (truncated) {\n truncatedFilenames.push(safeName)\n return\n }\n\n const buffer = Buffer.concat(chunks)\n files.push({\n fieldname,\n filename: safeName,\n encoding: info.encoding,\n mimeType: info.mimeType,\n buffer,\n size: buffer.length,\n })\n })\n },\n )\n\n bb.on('filesLimit', () => {\n reject(new Error(`Too many files. Maximum: ${options.maxFiles}`))\n })\n\n bb.on('error', (err: Error) => {\n reject(err)\n })\n\n bb.on('close', () => {\n if (truncatedFilenames.length > 0) {\n reject(\n new FileTooLargeError(\n `File too large (max ${options.maxFileSize} bytes): ${truncatedFilenames.join(', ')}`,\n truncatedFilenames,\n options.maxFileSize,\n ),\n )\n return\n }\n resolve({ fields, files })\n })\n\n req.pipe(bb)\n })\n}\n\n// --- Main parser ---\n\n/**\n * Symbol-keyed slot on IncomingMessage that the devtools request log\n * forwarder reads to enrich the broadcast payload with a body preview.\n * Symbol-keyed so it can't collide with user-land props and is invisible\n * to JSON.stringify / iteration. Always optional — readers must guard.\n */\nexport const DEVTOOLS_BODY_PREVIEW = Symbol('theo:devtools:bodyPreview')\n\nexport async function parseRequestBody(\n req: IncomingMessage,\n options?: BodyParserOptions,\n): Promise<ParsedBody> {\n const method = req.method?.toUpperCase() ?? 'GET'\n if (!METHODS_WITH_BODY.has(method)) {\n return { fields: {}, files: [], json: undefined }\n }\n\n const contentType = req.headers['content-type'] ?? ''\n\n // JSON\n if (contentType.includes('application/json')) {\n const json = await parseJsonBody(req)\n stashBodyPreview(req, json)\n return { fields: {}, files: [], json }\n }\n\n // Multipart\n if (contentType.includes('multipart/form-data')) {\n const limits = {\n maxFileSize: options?.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,\n maxFiles: options?.maxFiles ?? DEFAULT_MAX_FILES,\n maxFieldSize: options?.maxFieldSize ?? DEFAULT_MAX_FIELD_SIZE,\n }\n const { fields, files } = await parseMultipartBody(req, contentType, limits)\n stashBodyPreview(req, {\n fields,\n files: files.map((f) => ({\n fieldname: f.fieldname,\n filename: f.filename,\n mimeType: f.mimeType,\n size: f.size,\n })),\n })\n return { fields, files }\n }\n\n // No body or empty\n if (!contentType) {\n return { fields: {}, files: [] }\n }\n\n // Unsupported content type\n throw new Error(`Unsupported Content-Type: ${contentType}`)\n}\n","/**\n * Request log primitive (T6.2 of architecture-review-remediation-plan).\n *\n * Split out from `logger.ts` per PV-12 (SRP) — the file previously mixed\n * 3 concerns (factory, warnOnce, request log). This module owns ONLY the\n * `logRequest` flow + the devtools broadcast best-effort forwarder.\n *\n * Public API surface is unchanged — `logger.ts` re-exports `logRequest`\n * + `RequestLog` + `LoggerFn` for backward compat.\n */\nimport type { IncomingMessage } from 'node:http'\n\nimport { DEVTOOLS_BODY_PREVIEW } from '../body-parser.js'\n\nexport interface RequestLog {\n level: string\n method: string\n url: string\n status: number\n duration: number\n requestId: string\n timestamp: string\n}\n\nexport type LoggerFn = (log: RequestLog) => void\n\nconst defaultLoggerFn: LoggerFn = (log) => {\n // eslint-disable-next-line no-console -- request-log default output IS the contract\n console.log(JSON.stringify(log))\n}\n\nexport function logRequest(\n info: Omit<RequestLog, 'level' | 'timestamp'>,\n customLogger?: LoggerFn,\n req?: IncomingMessage,\n): void {\n const log: RequestLog = {\n level: 'info',\n ...info,\n timestamp: new Date().toISOString(),\n }\n const logger = customLogger ?? defaultLoggerFn\n logger(log)\n // T2.1 — also broadcast to devtools (no-op in prod / when no dev server).\n // Pass `req` so the devtools forwarder can extract headers + body preview\n // stashed by body-parser (Symbol-keyed). Without `req`, only metadata\n // (method/path/status/duration) reaches the devtools UI — the expanded\n // row view then shows nothing useful.\n broadcastRequestToDevtools(info, req)\n}\n\n/**\n * T2.1 — Forward a request record to the devtools UI. Lazy import keeps\n * this module dep-free for prod; broadcast.ts internally guards on\n * `globalThis.__theoViteHotServer`.\n */\nfunction randomRequestId(): string {\n // eslint-disable-next-line sonarjs/pseudo-random -- non-secret correlation id for devtools UI\n return `req-${String(Date.now())}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * T5a.2 Phase C slice 2/2 — pure devtools broadcast that takes a\n * pre-extracted headers object + optional stashed body, so both\n * IncomingMessage and Web Request paths share the same dispatch logic.\n *\n * Errors here must not propagate — devtools forwarding is best-effort\n * and silenced.\n */\nfunction broadcastToDevtoolsCore(\n info: Omit<RequestLog, 'level' | 'timestamp'>,\n headers: Record<string, string> | undefined,\n stashedBody: unknown,\n): void {\n void Promise.all([\n import('../../devtools/server-side/broadcast.js'),\n import('../../devtools/server-side/build-request-body-preview.js'),\n ])\n .then(([{ broadcastRequest }, { buildRequestBodyPreview }]) => {\n const bodyInfo = buildRequestBodyPreview(stashedBody)\n broadcastRequest({\n id: randomRequestId(),\n traceId: info.requestId,\n method: info.method,\n path: info.url,\n status: info.status,\n durationMs: info.duration,\n startedAt: Date.now() - info.duration,\n ...(headers ? { headers } : {}),\n ...(bodyInfo\n ? {\n bodyPreview: bodyInfo.preview,\n bodyLength: bodyInfo.length,\n bodyTruncated: bodyInfo.truncated,\n }\n : {}),\n })\n })\n .catch(() => {\n // No-op: devtools forwarding is best-effort.\n })\n}\n\nfunction broadcastRequestToDevtools(\n info: Omit<RequestLog, 'level' | 'timestamp'>,\n req?: IncomingMessage,\n): void {\n // T2.1 forwarder. Errors here must not propagate.\n const headers = req?.headers\n ? Object.fromEntries(\n Object.entries(req.headers).map(([k, v]) => [\n k,\n Array.isArray(v) ? v.join(', ') : (v ?? ''),\n ]),\n )\n : undefined\n const stashedBody = req\n ? (req as unknown as Record<symbol, unknown>)[DEVTOOLS_BODY_PREVIEW]\n : undefined\n broadcastToDevtoolsCore(info, headers, stashedBody)\n}\n\n/**\n * T5a.2 Phase C slice 2/2 — Web-Standards request log + devtools\n * forward. Mirror of `logRequest(info, logger?, req?: IncomingMessage)`\n * accepting `request?: Request`.\n *\n * Extracts headers via `request.headers.entries()` (Web `Headers`\n * iterator). Body preview stash is NOT yet supported on the Web path —\n * `body-parser-web.ts` doesn't yet stash like `body-parser.ts` does for\n * the IncomingMessage path. That hookup is Phase E scope (body parsing\n * migration). Until then, the devtools UI shows headers but no body\n * preview for Web-handled requests — same surface as the IncomingMessage\n * path before the stash convention shipped.\n */\nexport function logRequestFromRequest(\n info: Omit<RequestLog, 'level' | 'timestamp'>,\n customLogger?: LoggerFn,\n request?: Request,\n): void {\n const log: RequestLog = {\n level: 'info',\n ...info,\n timestamp: new Date().toISOString(),\n }\n const logger = customLogger ?? defaultLoggerFn\n logger(log)\n\n let headers: Record<string, string> | undefined\n if (request) {\n headers = {}\n for (const [k, v] of request.headers.entries()) {\n headers[k] = v\n }\n }\n // Phase E will add body-preview stash on Web Request; for now no stash.\n broadcastToDevtoolsCore(info, headers, undefined)\n}\n","// --- Types ---\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'\n\nexport interface StructuredLog {\n level: string\n msg: string\n timestamp: string\n [key: string]: unknown\n}\n\nexport interface TheoLogger {\n debug(msg: string, context?: Record<string, unknown>): void\n info(msg: string, context?: Record<string, unknown>): void\n warn(msg: string, context?: Record<string, unknown>): void\n error(msg: string, context?: Record<string, unknown>): void\n child(context: Record<string, unknown>): TheoLogger\n}\n\n// --- Level filtering ---\n\nconst LEVEL_ORDER: Record<string, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n silent: 4,\n}\n\nfunction shouldLog(msgLevel: string, configLevel: string): boolean {\n return LEVEL_ORDER[msgLevel] >= LEVEL_ORDER[configLevel]\n}\n\n// --- Default output ---\n\nfunction defaultOutput(log: StructuredLog): void {\n // eslint-disable-next-line no-console -- structured logger output IS the contract here\n console.log(JSON.stringify(log))\n}\n\n// --- Factory ---\n\nexport function createLogger(options?: {\n level?: LogLevel\n output?: (log: StructuredLog) => void\n context?: Record<string, unknown>\n}): TheoLogger {\n const level = options?.level ?? 'info'\n const output = options?.output ?? defaultOutput\n const baseContext = options?.context ?? {}\n\n function log(msgLevel: string, msg: string, context?: Record<string, unknown>): void {\n if (!shouldLog(msgLevel, level)) return\n\n const entry: StructuredLog = {\n level: msgLevel,\n msg,\n timestamp: new Date().toISOString(),\n ...baseContext,\n ...context,\n }\n\n // Serialize Error objects to stack string\n if (entry.error instanceof Error) {\n entry.error = entry.error.stack ?? entry.error.message\n }\n\n output(entry)\n }\n\n return {\n debug: (msg, ctx) => {\n log('debug', msg, ctx)\n },\n info: (msg, ctx) => {\n log('info', msg, ctx)\n },\n warn: (msg, ctx) => {\n log('warn', msg, ctx)\n },\n error: (msg, ctx) => {\n log('error', msg, ctx)\n },\n child(ctx) {\n return createLogger({\n level,\n output,\n context: { ...baseContext, ...ctx },\n })\n },\n }\n}\n\n// --- warnOnce (T2.1) ---\n\n/**\n * Per-key dedup state. Module-scoped — reset per-process at boot.\n *\n * CR-011 fix: previous implementation used an unbounded `Set` which grew\n * forever in long-running prod processes with high-cardinality keys\n * (e.g. dynamic path segments). The bound below uses LRU-by-insertion:\n * when the Set hits `MAX_SEEN`, the OLDEST key is evicted. Subsequent\n * occurrences of that key will warn ONCE more — acceptable in exchange\n * for bounded memory.\n */\nconst _warnOnceSeen = new Set<string>()\nconst MAX_SEEN = 1024\n\n/**\n * Reset internal state. Test-only export — do not call from production.\n */\nexport function _resetWarnOnceForTests(): void {\n _warnOnceSeen.clear()\n}\n\n/**\n * Emit a structured warning ONCE per key. Subsequent calls with the same\n * key are suppressed. Used for cutover-style warnings (e.g. CSRF warn)\n * that would otherwise flood logs under load.\n *\n * Convention: key is `<event>:<method>:<path>` — see callers in csrf.ts.\n *\n * EC-2: payload may contain circular references. Wrap `JSON.stringify`\n * in try/catch so a malformed payload doesn't crash the request handler.\n */\nexport function warnOnce(key: string, payload: Record<string, unknown>): void {\n if (_warnOnceSeen.has(key)) return\n // CR-011: bounded LRU. Evict oldest insertion when at capacity.\n if (_warnOnceSeen.size >= MAX_SEEN) {\n const oldest = _warnOnceSeen.values().next().value\n if (oldest !== undefined) _warnOnceSeen.delete(oldest)\n }\n _warnOnceSeen.add(key)\n\n let line: string\n try {\n line = JSON.stringify({ ...payload, warnOnce: true })\n } catch {\n // EC-2 fallback — preserve the key for grep-ability even when payload\n // can't serialize (e.g., circular references, BigInt, etc.).\n line = `[warnOnce] ${key} — (payload could not be serialized)`\n }\n console.warn(line)\n\n // T2.1 — also broadcast to devtools (no-op in prod / when no dev server).\n // Imported lazily to keep logger.ts dependency-free for non-dev contexts;\n // broadcastToDevtools internally guards on globalThis.__theoViteHotServer.\n broadcastWarnOnceToDevtools(key, payload)\n}\n\n/**\n * T2.1 — Forward a warnOnce payload to the devtools UI. Recognizes the\n * canonical CSRF warn shape and dispatches as 'csrf.warn'; otherwise\n * falls back to a generic 'error' broadcast.\n *\n * No-op when:\n * - globalThis.__theoViteHotServer is undefined (prod / no dev server)\n * - any error occurs (default-deny via broadcastToDevtools' try/catch)\n */\nfunction payloadField(payload: Record<string, unknown>, key: string, fallback = ''): string {\n const value = payload[key]\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n return fallback\n}\n\nfunction randomDevtoolsId(): string {\n // eslint-disable-next-line sonarjs/pseudo-random -- non-secret correlation id for devtools UI\n return `warn-${String(Date.now())}-${Math.random().toString(36).slice(2, 8)}`\n}\n\nfunction broadcastWarnOnceToDevtools(key: string, payload: Record<string, unknown>): void {\n // CR-021: removed dead `void key` statement.\n // T2.1 forwarder. Errors here must not propagate (default-deny).\n void import('../../devtools/server-side/broadcast.js')\n .then(({ broadcastCsrfWarn, broadcastError }) => {\n if (\n payload.event === 'csrf.warn' &&\n typeof payload.code === 'string' &&\n typeof payload.docsUrl === 'string'\n ) {\n broadcastCsrfWarn({\n event: 'csrf.warn',\n code: payload.code,\n docsUrl: payload.docsUrl,\n method: payloadField(payload, 'method'),\n path: payloadField(payload, 'path'),\n reason: payloadField(payload, 'reason'),\n })\n } else {\n broadcastError({\n id: randomDevtoolsId(),\n type: 'console',\n message: payloadField(payload, 'event', key),\n timestamp: Date.now(),\n })\n }\n })\n .catch(() => {\n // No-op: devtools forwarding is best-effort.\n })\n}\n\n// --- Backward compat re-exports ---\n//\n// T6.2 (PV-12 SRP): `logRequest` + `RequestLog` + `LoggerFn` moved to a\n// dedicated `request-log.ts`. Re-exported here so consumers importing\n// from `theokit/server` see no change.\n\nexport { logRequest } from './request-log.js'\nexport type { RequestLog, LoggerFn } from './request-log.js'\n"],"mappings":";;;;AACA,SAAS,gBAAgB;AAEzB,OAAO,YAAY;AAyBnB,IAAM,oBAAoB,oBAAI,IAAI,CAAC,QAAQ,OAAO,OAAO,CAAC;AAE1D,IAAM,wBAAwB,KAAK,OAAO;AAC1C,IAAM,oB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