theokit 0.55.0 → 0.57.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/dist/{actions-virtual-module-PREAJNIS.js → actions-virtual-module-GMRXCAVN.js} +21 -21
- package/dist/{actions-virtual-module-TZFLCIIR.js → actions-virtual-module-XAWZOWSY.js} +4 -4
- package/dist/adapters/agent-mount.d.ts +1 -1
- package/dist/adapters/agent-mount.js +9 -9
- package/dist/{agent-2AELELAC.js → agent-LS7I3ZQB.js} +3 -3
- package/dist/{agents-typed-client-INR2E7B3.js → agents-typed-client-PVUZU65B.js} +3 -3
- package/dist/{app-typed-client-NEKRXPAQ.js → app-typed-client-NMKJ4DR7.js} +4 -4
- package/dist/{app-typed-client-KSFGMOQ6.js → app-typed-client-W74QO5LH.js} +21 -21
- package/dist/boot/index.js +3 -3
- package/dist/{build-ESSQS5F5.js → build-FHE72YXR.js} +5 -5
- package/dist/{bun-L7PP6ID5.js → bun-POLTY2HK.js} +118 -3
- package/dist/bun-POLTY2HK.js.map +1 -0
- package/dist/{chunk-5YPXXSYY.js → chunk-35QIWOHT.js} +9 -8
- package/dist/chunk-35QIWOHT.js.map +1 -0
- package/dist/{chunk-JDN5SAAD.js → chunk-44E7XIZC.js} +6 -6
- package/dist/{chunk-OQCRCXCP.js → chunk-4ERYQBL6.js} +2 -2
- package/dist/{chunk-52PDWL5S.js → chunk-5KRMDP46.js} +2 -2
- package/dist/{chunk-VQPHPQ5L.js → chunk-7NRFZBAL.js} +3 -3
- package/dist/{chunk-3PBAN2YE.js → chunk-CF2DNN5R.js} +9 -8
- package/dist/{chunk-3PBAN2YE.js.map → chunk-CF2DNN5R.js.map} +1 -1
- package/dist/chunk-CLBJTDI6.js +189 -0
- package/dist/chunk-CLBJTDI6.js.map +1 -0
- package/dist/{chunk-3DRALT3J.js → chunk-CMCEGW3B.js} +6 -6
- package/dist/{chunk-3DRALT3J.js.map → chunk-CMCEGW3B.js.map} +1 -1
- package/dist/{chunk-MWWFXYW3.js → chunk-CTRVTBGY.js} +3 -3
- package/dist/chunk-CTRVTBGY.js.map +1 -0
- package/dist/{chunk-HK4AZBKX.js → chunk-D5KBBTVD.js} +7 -7
- package/dist/{chunk-DADMEW4G.js → chunk-G5JYB2LO.js} +3 -3
- package/dist/{chunk-BU6RJPPJ.js → chunk-GO7UWJ47.js} +2 -2
- package/dist/{chunk-BU6RJPPJ.js.map → chunk-GO7UWJ47.js.map} +1 -1
- package/dist/{chunk-VZTYCAO6.js → chunk-IDEZ7FU2.js} +3 -3
- package/dist/{chunk-ITSNTHWN.js → chunk-JW5UFKQ3.js} +17 -17
- package/dist/{chunk-IRASEXOG.js → chunk-KDP2HURW.js} +6 -6
- package/dist/{chunk-VRELW5NF.js → chunk-KEDRCI2L.js} +9 -9
- package/dist/{chunk-GWE4MUKQ.js → chunk-KQ27YDLG.js} +8 -8
- package/dist/{chunk-WX6NHGKS.js → chunk-M357ILK5.js} +10 -10
- package/dist/{chunk-2PSKQWGM.js → chunk-NC2OPE22.js} +3 -3
- package/dist/{chunk-QZUIF64G.js → chunk-OKDCBENR.js} +4 -4
- package/dist/{chunk-ZQO37YQJ.js → chunk-PELXWPDF.js} +5 -5
- package/dist/{chunk-2OEN3YTE.js → chunk-PVNMLZ5G.js} +2 -2
- package/dist/{chunk-F6P6S5YS.js → chunk-Q6HS3NFG.js} +63 -63
- package/dist/{chunk-5K4TDLRG.js → chunk-SOYOYGWY.js} +3 -3
- package/dist/{chunk-4X6H2BXP.js → chunk-U3SPBLJF.js} +3 -3
- package/dist/{chunk-BX6EUYHU.js → chunk-V6Y2SMRG.js} +3 -3
- package/dist/{chunk-I2UN46ZX.js → chunk-XJOU425Y.js} +17 -17
- package/dist/{chunk-BND4YZTQ.js → chunk-ZDCCILMP.js} +2 -2
- package/dist/cli/index.js +6 -6
- package/dist/client/index.js +8 -5
- package/dist/client/index.js.map +1 -1
- package/dist/{controller-swc-transform-T7ZTD55V.js → controller-swc-transform-7EZKG2IS.js} +2 -2
- package/dist/cost-types-BALTuBpG.d.ts +79 -0
- package/dist/{dev-MWGPBGQP.js → dev-WDKROZBS.js} +6 -6
- package/dist/{dev-emit-W27J3DLU.js → dev-emit-FIQASO3D.js} +7 -7
- package/dist/index.js +23 -23
- package/dist/{internal-api-XSUP3NDI.js → internal-api-732K3H75.js} +4 -4
- package/dist/{internal-api-J3BYA3VU.js → internal-api-EVJSGGO3.js} +26 -26
- package/dist/{mcp-6IPY275L.js → mcp-PBUCHHAS.js} +3 -3
- package/dist/{preview-KPAKWBRW.js → preview-VFIFKVP4.js} +3 -3
- package/dist/{provider-resolver-Dx6QuWrw.d.ts → provider-resolver-VS61zqsw.d.ts} +0 -11
- package/dist/{registry-KBZDCFVQ.js → registry-3LUHO4IB.js} +2 -2
- package/dist/server/agent/index.d.ts +1 -1
- package/dist/server/agent/index.js +3 -3
- package/dist/server/cost/index.d.ts +3 -80
- package/dist/server/cost/sqlite/index.d.ts +21 -0
- package/dist/server/cost/sqlite/index.js +102 -0
- package/dist/server/cost/sqlite/index.js.map +1 -0
- package/dist/server/cron/index.js +4 -4
- package/dist/server/http/index.js +7 -7
- package/dist/server/index.d.ts +5 -4
- package/dist/server/index.js +79 -79
- package/dist/server/jobs/index.d.ts +2 -2
- package/dist/server/jobs/index.js +4 -4
- package/dist/server/observability/index.js +2 -2
- package/dist/server/scan/index.js +6 -6
- package/dist/server/storage/index.d.ts +2 -2
- package/dist/server/webhook/index.js +1 -1
- package/dist/{server-boundary-PGPFBJBH.js → server-boundary-B6U4DRRH.js} +4 -4
- package/dist/{server-boundary-7ZO4FZIV.js → server-boundary-QRVK3OIJ.js} +23 -23
- package/dist/{server-routes-hmr-BWN3WIGR.js → server-routes-hmr-TNI3FNGM.js} +2 -2
- package/dist/{services-typed-client-IXNOPVZA.js → services-typed-client-ACTJHAEP.js} +2 -2
- package/dist/{start-F3T2ZPPI.js → start-UAMJ5TSC.js} +6 -6
- package/dist/{storage-manager-C6hmsaer.d.ts → storage-manager-BtG38jYl.d.ts} +1 -1
- package/dist/{storage-types-DsDTCPbp.d.ts → storage-types-CFGPFIdB.d.ts} +1 -1
- package/dist/vite-plugin/index.js +21 -21
- package/dist/{vite-plugin-5O3D472R.js → vite-plugin-ABJIDKE6.js} +6 -6
- package/package.json +7 -3
- package/dist/bun-L7PP6ID5.js.map +0 -1
- package/dist/chunk-5YPXXSYY.js.map +0 -1
- package/dist/chunk-MWWFXYW3.js.map +0 -1
- package/dist/chunk-VSLY4KB3.js +0 -46
- package/dist/chunk-VSLY4KB3.js.map +0 -1
- /package/dist/{actions-virtual-module-PREAJNIS.js.map → actions-virtual-module-GMRXCAVN.js.map} +0 -0
- /package/dist/{actions-virtual-module-TZFLCIIR.js.map → actions-virtual-module-XAWZOWSY.js.map} +0 -0
- /package/dist/{agent-2AELELAC.js.map → agent-LS7I3ZQB.js.map} +0 -0
- /package/dist/{agents-typed-client-INR2E7B3.js.map → agents-typed-client-PVUZU65B.js.map} +0 -0
- /package/dist/{app-typed-client-NEKRXPAQ.js.map → app-typed-client-NMKJ4DR7.js.map} +0 -0
- /package/dist/{app-typed-client-KSFGMOQ6.js.map → app-typed-client-W74QO5LH.js.map} +0 -0
- /package/dist/{build-ESSQS5F5.js.map → build-FHE72YXR.js.map} +0 -0
- /package/dist/{chunk-JDN5SAAD.js.map → chunk-44E7XIZC.js.map} +0 -0
- /package/dist/{chunk-OQCRCXCP.js.map → chunk-4ERYQBL6.js.map} +0 -0
- /package/dist/{chunk-52PDWL5S.js.map → chunk-5KRMDP46.js.map} +0 -0
- /package/dist/{chunk-VQPHPQ5L.js.map → chunk-7NRFZBAL.js.map} +0 -0
- /package/dist/{chunk-HK4AZBKX.js.map → chunk-D5KBBTVD.js.map} +0 -0
- /package/dist/{chunk-DADMEW4G.js.map → chunk-G5JYB2LO.js.map} +0 -0
- /package/dist/{chunk-VZTYCAO6.js.map → chunk-IDEZ7FU2.js.map} +0 -0
- /package/dist/{chunk-ITSNTHWN.js.map → chunk-JW5UFKQ3.js.map} +0 -0
- /package/dist/{chunk-IRASEXOG.js.map → chunk-KDP2HURW.js.map} +0 -0
- /package/dist/{chunk-VRELW5NF.js.map → chunk-KEDRCI2L.js.map} +0 -0
- /package/dist/{chunk-GWE4MUKQ.js.map → chunk-KQ27YDLG.js.map} +0 -0
- /package/dist/{chunk-WX6NHGKS.js.map → chunk-M357ILK5.js.map} +0 -0
- /package/dist/{chunk-2PSKQWGM.js.map → chunk-NC2OPE22.js.map} +0 -0
- /package/dist/{chunk-QZUIF64G.js.map → chunk-OKDCBENR.js.map} +0 -0
- /package/dist/{chunk-ZQO37YQJ.js.map → chunk-PELXWPDF.js.map} +0 -0
- /package/dist/{chunk-2OEN3YTE.js.map → chunk-PVNMLZ5G.js.map} +0 -0
- /package/dist/{chunk-F6P6S5YS.js.map → chunk-Q6HS3NFG.js.map} +0 -0
- /package/dist/{chunk-5K4TDLRG.js.map → chunk-SOYOYGWY.js.map} +0 -0
- /package/dist/{chunk-4X6H2BXP.js.map → chunk-U3SPBLJF.js.map} +0 -0
- /package/dist/{chunk-BX6EUYHU.js.map → chunk-V6Y2SMRG.js.map} +0 -0
- /package/dist/{chunk-I2UN46ZX.js.map → chunk-XJOU425Y.js.map} +0 -0
- /package/dist/{chunk-BND4YZTQ.js.map → chunk-ZDCCILMP.js.map} +0 -0
- /package/dist/{controller-swc-transform-T7ZTD55V.js.map → controller-swc-transform-7EZKG2IS.js.map} +0 -0
- /package/dist/{dev-MWGPBGQP.js.map → dev-WDKROZBS.js.map} +0 -0
- /package/dist/{dev-emit-W27J3DLU.js.map → dev-emit-FIQASO3D.js.map} +0 -0
- /package/dist/{internal-api-XSUP3NDI.js.map → internal-api-732K3H75.js.map} +0 -0
- /package/dist/{internal-api-J3BYA3VU.js.map → internal-api-EVJSGGO3.js.map} +0 -0
- /package/dist/{mcp-6IPY275L.js.map → mcp-PBUCHHAS.js.map} +0 -0
- /package/dist/{preview-KPAKWBRW.js.map → preview-VFIFKVP4.js.map} +0 -0
- /package/dist/{registry-KBZDCFVQ.js.map → registry-3LUHO4IB.js.map} +0 -0
- /package/dist/{server-boundary-PGPFBJBH.js.map → server-boundary-B6U4DRRH.js.map} +0 -0
- /package/dist/{server-boundary-7ZO4FZIV.js.map → server-boundary-QRVK3OIJ.js.map} +0 -0
- /package/dist/{server-routes-hmr-BWN3WIGR.js.map → server-routes-hmr-TNI3FNGM.js.map} +0 -0
- /package/dist/{services-typed-client-IXNOPVZA.js.map → services-typed-client-ACTJHAEP.js.map} +0 -0
- /package/dist/{start-F3T2ZPPI.js.map → start-UAMJ5TSC.js.map} +0 -0
- /package/dist/{vite-plugin-5O3D472R.js.map → vite-plugin-ABJIDKE6.js.map} +0 -0
|
@@ -5,44 +5,44 @@ import {
|
|
|
5
5
|
defineTheoIntegration,
|
|
6
6
|
theoPlugin,
|
|
7
7
|
theoPluginAsync
|
|
8
|
-
} from "../chunk-
|
|
9
|
-
import "../chunk-
|
|
8
|
+
} from "../chunk-Q6HS3NFG.js";
|
|
9
|
+
import "../chunk-7NRFZBAL.js";
|
|
10
10
|
import "../chunk-SSYDEKWF.js";
|
|
11
|
-
import "../chunk-
|
|
11
|
+
import "../chunk-CMCEGW3B.js";
|
|
12
|
+
import "../chunk-M357ILK5.js";
|
|
12
13
|
import "../chunk-OIGJOYX6.js";
|
|
13
|
-
import "../chunk-
|
|
14
|
-
import "../chunk-
|
|
14
|
+
import "../chunk-U3SPBLJF.js";
|
|
15
|
+
import "../chunk-BPYMC7SU.js";
|
|
16
|
+
import "../chunk-IRQGAC4L.js";
|
|
15
17
|
import "../chunk-OGLS76RN.js";
|
|
16
|
-
import "../chunk-
|
|
18
|
+
import "../chunk-JW5UFKQ3.js";
|
|
19
|
+
import "../chunk-P6OS7652.js";
|
|
17
20
|
import "../chunk-ZDUO4IYN.js";
|
|
21
|
+
import "../chunk-D4VP2QPR.js";
|
|
22
|
+
import "../chunk-YN4W7LCX.js";
|
|
18
23
|
import "../chunk-47FFT43U.js";
|
|
19
24
|
import "../chunk-NTDN54XO.js";
|
|
20
|
-
import "../chunk-
|
|
21
|
-
import "../chunk-
|
|
25
|
+
import "../chunk-PVNMLZ5G.js";
|
|
26
|
+
import "../chunk-ZDCCILMP.js";
|
|
22
27
|
import "../chunk-CHTAWXC2.js";
|
|
28
|
+
import "../chunk-AVQU5CQF.js";
|
|
23
29
|
import "../chunk-VSLTKX5L.js";
|
|
24
30
|
import "../chunk-TNI4MARH.js";
|
|
25
|
-
import "../chunk-
|
|
26
|
-
import "../chunk-
|
|
31
|
+
import "../chunk-4ERYQBL6.js";
|
|
32
|
+
import "../chunk-XJOU425Y.js";
|
|
33
|
+
import "../chunk-KDP2HURW.js";
|
|
27
34
|
import "../chunk-DV34VG3N.js";
|
|
28
|
-
import "../chunk-
|
|
29
|
-
import "../chunk-BX6EUYHU.js";
|
|
30
|
-
import "../chunk-BPYMC7SU.js";
|
|
31
|
-
import "../chunk-IRQGAC4L.js";
|
|
32
|
-
import "../chunk-P6OS7652.js";
|
|
33
|
-
import "../chunk-AVQU5CQF.js";
|
|
35
|
+
import "../chunk-V6Y2SMRG.js";
|
|
34
36
|
import "../chunk-ACKBVBUI.js";
|
|
35
37
|
import "../chunk-IZ3TIL6K.js";
|
|
36
38
|
import "../chunk-YOIVCCZT.js";
|
|
37
|
-
import "../chunk-
|
|
39
|
+
import "../chunk-CF2DNN5R.js";
|
|
38
40
|
import "../chunk-YSJOZEI6.js";
|
|
39
41
|
import "../chunk-Z4PJMZLM.js";
|
|
40
42
|
import "../chunk-UMNXCU3K.js";
|
|
41
|
-
import "../chunk-
|
|
42
|
-
import "../chunk-
|
|
43
|
+
import "../chunk-5KRMDP46.js";
|
|
44
|
+
import "../chunk-SOYOYGWY.js";
|
|
43
45
|
import "../chunk-ZWN3AODA.js";
|
|
44
|
-
import "../chunk-D4VP2QPR.js";
|
|
45
|
-
import "../chunk-YN4W7LCX.js";
|
|
46
46
|
import "../chunk-XTHN6JBX.js";
|
|
47
47
|
export {
|
|
48
48
|
IntegrationRouteCollisionError,
|
|
@@ -7,15 +7,15 @@ import {
|
|
|
7
7
|
defineTheoIntegration,
|
|
8
8
|
theoPlugin,
|
|
9
9
|
theoPluginAsync
|
|
10
|
-
} from "./chunk-
|
|
11
|
-
import "./chunk-
|
|
10
|
+
} from "./chunk-KEDRCI2L.js";
|
|
11
|
+
import "./chunk-OKDCBENR.js";
|
|
12
12
|
import "./chunk-2CVV6CNN.js";
|
|
13
13
|
import "./chunk-3PWQQWT6.js";
|
|
14
14
|
import "./chunk-FDOOBTXJ.js";
|
|
15
15
|
import "./chunk-47MM2JUK.js";
|
|
16
|
-
import "./chunk-
|
|
17
|
-
import "./chunk-
|
|
18
|
-
import "./chunk-
|
|
16
|
+
import "./chunk-G5JYB2LO.js";
|
|
17
|
+
import "./chunk-35QIWOHT.js";
|
|
18
|
+
import "./chunk-CTRVTBGY.js";
|
|
19
19
|
import "./chunk-RPET332G.js";
|
|
20
20
|
import "./chunk-5VLP3GQ2.js";
|
|
21
21
|
import "./chunk-C27VRUVN.js";
|
|
@@ -40,4 +40,4 @@ export {
|
|
|
40
40
|
theoPlugin,
|
|
41
41
|
theoPluginAsync
|
|
42
42
|
};
|
|
43
|
-
//# sourceMappingURL=vite-plugin-
|
|
43
|
+
//# sourceMappingURL=vite-plugin-ABJIDKE6.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "theokit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.57.0",
|
|
4
4
|
"description": "The TheoKit web framework — file-based routing, typed server surfaces, the Vite plugin, the CLI and the deploy adapters, around agents served from agents/*.ts.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -42,6 +42,10 @@
|
|
|
42
42
|
"types": "./dist/server/cost/index.d.ts",
|
|
43
43
|
"import": "./dist/server/cost/index.js"
|
|
44
44
|
},
|
|
45
|
+
"./server/cost/sqlite": {
|
|
46
|
+
"types": "./dist/server/cost/sqlite/index.d.ts",
|
|
47
|
+
"import": "./dist/server/cost/sqlite/index.js"
|
|
48
|
+
},
|
|
45
49
|
"./server/cron": {
|
|
46
50
|
"types": "./dist/server/cron/index.d.ts",
|
|
47
51
|
"import": "./dist/server/cron/index.js"
|
|
@@ -145,13 +149,13 @@
|
|
|
145
149
|
"tsx": "^4.22.4",
|
|
146
150
|
"typescript": "^5.9.3",
|
|
147
151
|
"vite": "^7.0.0",
|
|
148
|
-
"@theokit/agents": "^
|
|
152
|
+
"@theokit/agents": "^12.1.0",
|
|
149
153
|
"@theokit/http": "^1.1.1",
|
|
150
154
|
"@theokit/presenter": "^0.8.0"
|
|
151
155
|
},
|
|
152
156
|
"peerDependencies": {
|
|
153
157
|
"@theokit/sdk": "^4.52.1",
|
|
154
|
-
"@theokit/studio": "
|
|
158
|
+
"@theokit/studio": ">=0.2.0 <1",
|
|
155
159
|
"@theokit/ui": "^1.1.0",
|
|
156
160
|
"db0": "^0.3.0",
|
|
157
161
|
"react": "^19.0.0",
|
package/dist/bun-L7PP6ID5.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;AA4BjB,SAAS,eACd,MACA,OAKwB,CAAC,GACjB;AACR,QAAM,mBAAmB,KAAK,eAC1B,mFACA;AACJ,QAAM,gBAAgB,8BAA8B,IAAI;AACxD,QAAM,iBAAiB;AAAA,IACrB,EAAE,MAAM,QAAQ,aAAa,OAAO,YAAY,aAAa;AAAA,IAC7D,EAAE,UAAU,WAAW;AAAA,EACzB;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA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AA;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":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/_internal/process-singleton.ts","../src/server/agent/provider-resolver.ts","../src/server/agent/approval-registry.ts"],"sourcesContent":["/**\n * One object per PROCESS, whatever the bundler did to the module holding it.\n *\n * ## The defect this exists to remove\n *\n * A module-level `let x` gives one instance per **module instance**, and a bundler is free to place\n * the same source in more than one chunk. When it does, each chunk gets its own `x` and any state\n * written through one is invisible through the other.\n *\n * Measured in this repository's own `dist` (usetheokit/theokit#401) by grepping the built chunks for\n * each module's marker: `provider-resolver` lands in two chunks, and `approval-registry` in two.\n * Neither copy is redundant — one of the provider chunks is tree-shaken to `resolveProvider` and\n * does not carry `resetProviderRegistry` at all, which is precisely how the halves diverge: an\n * application calling `registerProvider` — public API, with a documented self-hosting example —\n * mutated the array in one chunk while `theokit start` resolved against the array in the other.\n *\n * The second is worse in kind, because `approval-registry.ts` states the requirement in its own\n * source: *\"the approval a request awaits and the approval the route resolves MUST be the same\n * object, so a single instance per process is not a convenience but a correctness requirement.\"* A\n * chunk boundary can break that silently, and the symptom would be a HITL pause that never resumes.\n *\n * ## Why `globalThis` and not better chunking\n *\n * Chunking is a bundler heuristic that changes between versions and with the shape of the import\n * graph. A fix that depends on tsup continuing to place this module in exactly one chunk is a fix\n * that holds until someone adds an import. `Symbol.for` gives a key that is equal across every\n * module instance in the realm, so identity stops depending on the build at all.\n *\n * @internal\n */\n\n/** Namespaced so a key cannot collide with an unrelated global. */\nconst NAMESPACE = 'theokit.singleton.'\n\n/**\n * The object registered under `key`, creating it with `factory` the first time.\n *\n * `factory` runs at most once per process. A later call with the same key returns what the first\n * call built and never replaces it — replacing it is the same defect wearing a different hat, since\n * two callers would again hold different objects.\n */\nexport function processSingleton<T extends object>(key: string, factory: () => T): T {\n const slot = Symbol.for(NAMESPACE + key)\n const host = globalThis as unknown as Record<symbol, T | undefined>\n\n const existing = host[slot]\n if (existing !== undefined) return existing\n\n const created = factory()\n host[slot] = created\n return created\n}\n","import { processSingleton } from '../_internal/process-singleton.js'\n\n/**\n * Provider Resolver — Strategy + Registry pattern (FAANG-grade).\n *\n * Inspiration: Dapr Conversation Registry (`dapr/pkg/components/conversation/registry.go`)\n * + Encore Manager provider array (`encore/runtimes/go/pubsub/manager_internal.go`).\n *\n * Principle: provider routing is the FRAMEWORK's responsibility, not the consumer's — but the\n * consumer still gets to SAY which provider it wants, and it says so in the model id.\n *\n * `provider/model` is the convention every agent in this ecosystem already writes\n * (`anthropic/claude-sonnet-4-6`, `openrouter/anthropic/claude-haiku-4.5`), and it is the one the\n * SDK routes on. Until theokit#326 this resolver ignored it entirely and picked by env-var\n * priority, so an agent that declared `anthropic/...` was handed an OpenRouter key whenever one\n * happened to be present — and every turn failed with `auth_failed (HTTP 401)` against a provider\n * nobody asked for. The declared provider now wins; priority is the fallback for a bare model id.\n *\n * Wire protocol: OpenAI Chat Completions (universal — implemented by every\n * os providers: OpenRouter, Groq, Mistral, Together, Anthropic via proxy, etc).\n *\n * Resolution by priority (FIRST match wins):\n * 1. OPENROUTER_API_KEY → baseUrl=openrouter.ai (multi-model gateway)\n * 2. OPENAI_API_KEY → baseUrl=api.openai.com\n * 3. ANTHROPIC_API_KEY → direct Anthropic (Messages API, not OpenAI-compat)\n *\n * Escape hatch: an explicit `options.apiKey` OVERRIDES auto-resolution\n * (the consumer can force a specific provider if it wants to).\n */\n\n/**\n * Provider configuration descriptor — Registry entry shape.\n *\n * @public\n */\nexport interface ProviderDescriptor {\n /** Stable name used internally — not exposed on the wire. */\n name: string\n /**\n * Environment variable that holds the API key for this provider.\n *\n * **Absent means the provider needs no credential** — a model running on the developer's own\n * machine has nothing to authenticate against. Such a provider is reachable ONLY when a model id\n * names it (`ollama/llama3.2`); it never participates in the priority walk, because the walk\n * reads \"this variable is set\" as \"a human configured this provider\", and a keyless entry offers\n * no equivalent signal. Including it would route every bare model id to localhost the moment no\n * cloud key was set (usetheokit/theokit#407).\n */\n envKey?: string\n /** Base URL for the provider's OpenAI-compatible (or native) API. */\n baseUrl: string\n /**\n * Environment variable that OVERRIDES {@link baseUrl} when set.\n *\n * Scoped honestly: every caller inside this framework takes `.apiKey` from the resolved provider\n * and discards `.baseUrl` (`cli/commands/start/handlers.ts`, `vite-plugin/api-middleware.ts`,\n * `cli/commands/agent.ts`), so the endpoint a request actually reaches is chosen by the SDK, from\n * its own profile — which reads `OLLAMA_HOST` itself. This field therefore does not redirect\n * traffic today.\n *\n * It exists so that the `baseUrl` this function REPORTS agrees with where the request goes, for\n * the consumers that read it — `resolveProvider` is public API, and a reported endpoint that\n * contradicts the real one is a debugging trap rather than a harmless inaccuracy.\n */\n baseUrlEnv?: string\n /** Resolution priority (lower = higher priority). FIRST match wins. */\n priority: number\n}\n\n/**\n * Resolved provider configuration — output of `resolveProvider()`.\n *\n * @public\n */\nexport interface ResolvedProvider {\n name: string\n apiKey: string\n baseUrl: string\n}\n\n/**\n * Default provider registry. Order = priority (first = highest).\n *\n * Adding a new provider:\n * 1. Append entry below (or register via `registerProvider()`).\n * 2. Set `envKey` matching the user's env var convention.\n * 3. Set `baseUrl` to the OpenAI-compat endpoint (or native if not compat).\n * 4. Provider name used in telemetry/logs only — never wire-exposed.\n */\nconst DEFAULT_REGISTRY: ProviderDescriptor[] = [\n {\n name: 'openrouter',\n envKey: 'OPENROUTER_API_KEY',\n baseUrl: 'https://openrouter.ai/api/v1',\n priority: 1,\n },\n {\n name: 'openai',\n envKey: 'OPENAI_API_KEY',\n baseUrl: 'https://api.openai.com/v1',\n priority: 2,\n },\n {\n name: 'anthropic',\n envKey: 'ANTHROPIC_API_KEY',\n baseUrl: 'https://api.anthropic.com',\n priority: 3,\n },\n {\n // Mirrors the profile `@theokit/sdk` already ships for this provider — same default host, same\n // override variable — so the two cannot disagree about where ollama is listening. The SDK is\n // what dials it (see `baseUrlEnv`); this entry's job is to stop the resolver from rejecting the\n // model before the SDK is ever reached. No `envKey`: see that field's doc comment for why the\n // absence also keeps this entry out of the priority walk.\n name: 'ollama',\n baseUrl: 'http://localhost:11434',\n baseUrlEnv: 'OLLAMA_HOST',\n priority: 100,\n },\n]\n\n/**\n * Runtime registry — copy of DEFAULT_REGISTRY mutable via registerProvider().\n * Sorted by priority on every resolve (stable, O(n log n) — n <= ~10 providers).\n *\n * Held per PROCESS rather than per module instance (usetheokit/theokit#401). As a module-level\n * `const` it was one array per chunk, and the bundler emits this module into two of them: an\n * application calling `registerProvider` mutated one array while `theokit start` resolved against\n * another, so the call had no effect and the resulting error listed the defaults while the\n * registered provider sat in an object nobody read.\n */\nfunction registryOf(): ProviderDescriptor[] {\n return processSingleton('provider-registry', () => [...DEFAULT_REGISTRY])\n}\n\n/**\n * Providers already announced, so a boot line does not become a per-request line.\n *\n * theokit#326 — resolution was silent on success. `resolveProvider` returns `{ name, apiKey,\n * baseUrl }` and every call site consumes only the key, so an operator could only learn which\n * provider was selected from an error message: exactly when it has already failed, and never in\n * the case that hurts most — a stale key that resolves cleanly and 401s at the provider.\n */\nconst announced = new Set<string>()\n\n/** Test-only reset, so announcement state does not leak between cases. @public */\nexport function resetProviderAnnouncements(): void {\n announced.clear()\n}\n\n/** Where the announcement goes, and what it may contain. @public */\nexport interface ResolveOptions {\n /** Receives one line per provider, at most once. NEVER receives the key. */\n announce?: (line: string) => void\n}\n\n/**\n * Register a new provider (Registry pattern — runtime extension point).\n * Useful for self-hosted endpoints or custom providers without touching theokit src.\n *\n * @example\n * registerProvider({\n * name: 'self-hosted',\n * envKey: 'SELF_HOSTED_API_KEY',\n * baseUrl: 'https://llm.internal.acme.com/v1',\n * priority: 0, // highest priority\n * })\n *\n * @public\n */\nexport function registerProvider(descriptor: ProviderDescriptor): void {\n // Idempotent — replace existing by name.\n const registry = registryOf()\n const idx = registry.findIndex((p) => p.name === descriptor.name)\n if (idx >= 0) registry[idx] = descriptor\n else registry.push(descriptor)\n}\n\n/**\n * Reset registry to DEFAULT_REGISTRY (test-only / dev escape hatch).\n *\n * @public\n */\nexport function resetProviderRegistry(): void {\n const registry = registryOf()\n registry.length = 0\n registry.push(...DEFAULT_REGISTRY)\n}\n\n/**\n * Get current registry snapshot (read-only — inspection).\n *\n * @public\n */\nexport function listProviders(): readonly ProviderDescriptor[] {\n return [...registryOf()].sort((a, b) => a.priority - b.priority)\n}\n\n/**\n * Says which provider was selected, once.\n *\n * Carries the provider, HOW it was chosen, and the variable the credential came from — never the\n * credential. Which env var holds it is what an operator needs to fix a mis-selection; the value\n * is what a log must never hold.\n */\nfunction announce(\n desc: ProviderDescriptor,\n how: 'declared by the model' | 'by env priority',\n options: ResolveOptions | undefined,\n): void {\n if (announced.has(desc.name)) return\n announced.add(desc.name)\n const source = desc.envKey ?? 'none (this provider takes no credential)'\n const line = `[theokit] provider=${desc.name} (${how}) source=${source} baseUrl=${baseUrlOf(desc)}`\n if (options?.announce) options.announce(line)\n // `warn` rather than `info` because the repo's lint rule allows only `warn`/`error` — and this\n // line is closer to a warning in spirit anyway: it is the one chance an operator gets to notice\n // that the provider serving their agents is not the one they expected.\n else console.warn(line)\n}\n\n/**\n * Where this provider is listening, after any environment override.\n *\n * One function so the announcement line and the resolved config can never name different hosts —\n * an operator reading a log to find out where requests went must be reading the truth.\n */\nfunction baseUrlOf(desc: ProviderDescriptor): string {\n if (desc.baseUrlEnv === undefined) return desc.baseUrl\n const override = process.env[desc.baseUrlEnv]\n return override !== undefined && override.length > 0 ? override : desc.baseUrl\n}\n\n/**\n * The provider a model id declares, or `undefined` when it declares none.\n *\n * `provider/model` and `gateway/provider/model` both resolve on the FIRST segment: a gateway is a\n * provider from the framework's point of view (it holds the credential), and everything after it\n * is the upstream namespace the gateway itself routes on.\n *\n * A bare id (`gpt-4o-mini`, `qwen2.5:3b`) declares nothing, and an unregistered prefix is treated\n * the same way rather than as an error — a project may legitimately point a custom id at a\n * registered provider's endpoint, and refusing it here would break that before it reached the SDK.\n */\nfunction providerOf(\n modelId: string | undefined,\n registered: readonly ProviderDescriptor[],\n): ProviderDescriptor | undefined {\n const prefix = declaredPrefixOf(modelId)\n if (prefix === undefined) return undefined\n return registered.find((p) => p.name === prefix)\n}\n\n/**\n * The provider name a model id declares, registered or not.\n *\n * Split out of {@link providerOf} because the two questions differ exactly where the error message\n * used to go wrong: \"which registered provider is this?\" answers `undefined` both for a bare id and\n * for `groq/…`, and the resolver needs to tell those apart to say something true about the second.\n */\nfunction declaredPrefixOf(modelId: string | undefined): string | undefined {\n if (modelId === undefined) return undefined\n const slash = modelId.indexOf('/')\n if (slash <= 0) return undefined\n return modelId.slice(0, slash)\n}\n\n/** A provider that authenticates — the only kind the priority walk may select. */\ntype CredentialedProvider = ProviderDescriptor & { envKey: string }\n\nfunction takesCredential(desc: ProviderDescriptor): desc is CredentialedProvider {\n return desc.envKey !== undefined\n}\n\n/**\n * Resolve the provider for a model.\n *\n * When `modelId` declares a registered provider (`anthropic/…`), THAT provider's key is\n * required — no substitution. Otherwise the registry is walked by priority, first match wins.\n *\n * @returns ResolvedProvider with apiKey + baseUrl + name\n * @throws Error if NO provider env var is set (actionable message)\n *\n * @public\n */\nexport function resolveProvider(modelId?: string, options?: ResolveOptions): ResolvedProvider {\n const sorted = [...registryOf()].sort((a, b) => a.priority - b.priority)\n\n const declared = modelId === undefined ? undefined : providerOf(modelId, sorted)\n if (declared !== undefined && modelId !== undefined) {\n if (declared.envKey === undefined) {\n // Keyless — a model on the developer's own machine. The empty string is the honest value and\n // not a placeholder: the SDK's client sets an `authorization` header only when the key is\n // non-empty, so anything else would put a meaningless credential on every local request.\n announce(declared, 'declared by the model', options)\n return { name: declared.name, apiKey: '', baseUrl: baseUrlOf(declared) }\n }\n const apiKey = process.env[declared.envKey]\n if (apiKey && apiKey.length > 0) {\n announce(declared, 'declared by the model', options)\n return { name: declared.name, apiKey, baseUrl: baseUrlOf(declared) }\n }\n // Deliberately NOT falling back to another provider's key. Silently substituting one is how\n // theokit#326 produced a 401 nobody could attribute: the request went somewhere the agent\n // never named. Say which variable is missing and stop.\n throw new Error(\n `Model \"${modelId}\" declares provider \"${declared.name}\", but ${declared.envKey} is not set. ` +\n `Set ${declared.envKey}, or change the model's provider prefix.`,\n )\n }\n\n // Only providers that take a credential. A keyless entry is reachable exclusively through the\n // declared branch above; see `ProviderDescriptor.envKey` for why the walk cannot include it.\n const credentialed = sorted.filter(takesCredential)\n\n for (const desc of credentialed) {\n const apiKey = process.env[desc.envKey]\n if (apiKey && apiKey.length > 0) {\n announce(desc, 'by env priority', options)\n return {\n name: desc.name,\n apiKey,\n baseUrl: baseUrlOf(desc),\n }\n }\n }\n\n // Nothing resolved. When the model id named a provider this registry does not know, say THAT —\n // the generic message below sent a reader whose id read `groq/…` off to buy an OpenRouter key,\n // which would not have helped and could not have been the fix (usetheokit/theokit#407).\n const prefix = declaredPrefixOf(modelId)\n if (prefix !== undefined) {\n throw new Error(\n `Model \"${modelId}\" declares provider \"${prefix}\", which is not registered. ` +\n `Registered providers: ${sorted.map((p) => p.name).join(', ')}. ` +\n `Register it with registerProvider({ name: '${prefix}', … }), or use a registered prefix.`,\n )\n }\n\n const envKeys = credentialed.map((p) => p.envKey).join(' OR ')\n throw new Error(\n `No LLM provider API key found in environment. Set one of: ${envKeys}. ` +\n `Get a free OpenRouter key at https://openrouter.ai/keys (recommended — one key, many models).`,\n )\n}\n\n/**\n * Try to resolve — does NOT throw. Returns null if no provider available.\n * Useful for graceful degradation (e.g., mock mode).\n *\n * @public\n */\nexport function tryResolveProvider(modelId?: string): ResolvedProvider | null {\n try {\n return resolveProvider(modelId)\n } catch {\n return null\n }\n}\n","/**\n * M4 (theokit-ai-first) — the in-process HITL approval registry.\n *\n * The HITL plugin's `awaitApproval` calls `register(approvalId)` and awaits the returned Promise\n * (this is what genuinely PAUSES the SDK run — the SDK `pre_tool_call` hook is awaited). The\n * approve route calls `resolve(approvalId, approved)` to settle it. A per-approval timeout settles\n * the Promise deterministically per the `@HumanInTheLoop` `onTimeout` policy so a hung approval\n * never leaks the paused stream.\n *\n * Single-process contract (ADR 0038 / plan Drawback 2): a multi-instance deploy needs a shared\n * registry — the interface is injectable so a durable impl (Redis, etc.) slots in without touching\n * the harness. We do NOT build a durable store now (YAGNI).\n */\n// The timeout policy vocabulary is owned by the `@HumanInTheLoop` decorator (DRY / G12) — reuse it\n// rather than re-declaring the union, so the two can never drift.\nimport type { TimeoutAction } from '@theokit/agents'\n\nimport { processSingleton } from '../_internal/process-singleton.js'\n\nexport interface RegisterOptions {\n /** Milliseconds before the approval auto-settles per `onTimeout`. */\n timeoutMs: number\n /**\n * What a timeout means. Only `'proceed'` auto-approves; `'abort'` and `'retry'` both deny — the\n * registry does NOT implement retry semantics (a timed-out `'retry'` is a deny, not a re-prompt).\n */\n onTimeout: TimeoutAction\n /** M14 — the gated tool name, surfaced by `list()` (optional; absent for legacy callers). */\n toolName?: string\n /** M14 — the approval question, surfaced by `list()` (optional). */\n question?: string\n /**\n * Who the run belongs to — the `RouteSubject.id` admitted for it (B-016).\n *\n * Absent when the run had no identity to record, which is the `'public'` agent path:\n * `admitAgentRequest` deliberately does not resolve a subject when the policy is absent or\n * `'public'`, so there is nothing to attribute the approval to. Absent therefore means \"no owner\n * was established\", never \"anyone\", and the caller must branch on the difference — a rule that\n * refused when it is absent would start turning public agents away.\n *\n * Deliberately NOT surfaced by `list()`: that listing feeds a UI, and owner ids are identity.\n */\n owner?: string\n /**\n * M20 — an optional JSON-schema descriptor of the custom payload the approver may attach. Carried\n * verbatim into `list()` + the `approval_required` event so the UI knows what to collect. Kept as\n * a plain JSON object (not a live Zod schema) so the registry stays serializable and SDK-free.\n */\n payloadSchema?: Record<string, unknown>\n}\n\n/**\n * M20 — a settled HITL decision. `approved` is the allow/deny bit (backward-compatible with the\n * legacy boolean); `reason` + `payload` are the optional approver-attached extras that surface to\n * the model (on denial, via the veto message) and to the app/UI.\n */\nexport interface ApprovalDecision {\n approved: boolean\n reason?: string\n payload?: unknown\n /**\n * What settled this, when it was not a person (usetheokit/theokit#393).\n *\n * Absent means the decision arrived through `resolve()` — a human, or whatever the application\n * wired to that route. `'timeout'` means the window closed with nobody deciding and `onTimeout`\n * was applied.\n *\n * The distinction is the whole point of a HITL gate: without it an expired approval and an\n * explicit deny are byte-identical on the wire, and the sentence the caller gets — \"denied by\n * human approver\" — asserts a fact that did not happen. It is marked on the ALLOW side too:\n * `onTimeout: 'proceed'` permits the tool BECAUSE nobody answered, and recording that as a plain\n * approval is the same fabrication with the opposite sign.\n *\n * One member rather than `timedOut: boolean`, because the question is what settled it; a second\n * cause (a cancel, a shutdown) joins the union instead of adding another boolean.\n */\n settledBy?: 'timeout'\n}\n\n/** M14 — a pending approval as surfaced by {@link ApprovalRegistry.list}. */\nexport interface PendingApproval {\n approvalId: string\n toolName?: string\n question?: string\n /** Epoch millis when the pending approval auto-settles (registeredAt + timeoutMs). */\n expiresAt: number\n /** M20 — the declared custom-payload schema, if the gated tool declares one. */\n payloadSchema?: Record<string, unknown>\n}\n\nexport interface ApprovalRegistry {\n /**\n * Register a pending approval; the returned Promise settles with the full {@link ApprovalDecision}\n * on `resolve` or timeout (M20 — was a bare boolean pre-M20).\n */\n register(approvalId: string, opts: RegisterOptions): Promise<ApprovalDecision>\n /**\n * Settle a pending approval. Accepts a full {@link ApprovalDecision} OR a bare boolean (coerced to\n * `{ approved }` — backward-compatible). Returns false if the id is unknown or already settled.\n */\n resolve(approvalId: string, decision: boolean | ApprovalDecision): boolean\n /** M14 — list the currently-pending approvals (process-wide; single-process contract). */\n list(): PendingApproval[]\n /**\n * Who owns the pending approval `approvalId`, or `undefined` (B-016).\n *\n * `undefined` covers three cases the caller treats identically — never registered, already\n * settled, and registered without an owner — because in all three there is nothing to compare a\n * caller against.\n */\n ownerOf(approvalId: string): string | undefined\n}\n\ninterface Pending {\n settle: (decision: ApprovalDecision) => void\n timer: ReturnType<typeof setTimeout>\n info: PendingApproval\n /** Held beside `info` rather than inside it, so `list()` cannot leak it (B-016). */\n owner?: string\n}\n\n/**\n * The one process-wide registry the stream mount (`mountAgent`) and the approve route share.\n *\n * The in-process impl holds LIVE Promise resolvers in memory — the approval a request awaits and\n * the approval the route resolves MUST be the same object, so a single instance per process is not\n * a convenience but a correctness requirement. Lazily created; a durable/multi-instance deploy\n * swaps this accessor for a shared-store impl (ADR 0038 / plan Drawback 2) without touching callers.\n * Tests use {@link createInProcessApprovalRegistry} directly — never this singleton.\n */\nexport function getApprovalRegistry(): ApprovalRegistry {\n // Per PROCESS, not per module instance (usetheokit/theokit#401). The paragraph above calls a\n // single instance \"not a convenience but a correctness requirement\", and a module-level `let`\n // does not deliver that: it gives one instance per MODULE INSTANCE, and this module is emitted\n // into two chunks of the published bundle. A run awaiting an approval and the route resolving it\n // could hold different objects, and the symptom would be a HITL pause that never resumes.\n return processSingleton('approval-registry', () => createInProcessApprovalRegistry())\n}\n\nexport function createInProcessApprovalRegistry(): ApprovalRegistry {\n const pending = new Map<string, Pending>()\n\n return {\n register(approvalId, opts) {\n return new Promise<ApprovalDecision>((resolve) => {\n const settle = (decision: ApprovalDecision): void => {\n const entry = pending.get(approvalId)\n if (!entry) return\n clearTimeout(entry.timer)\n pending.delete(approvalId)\n resolve(decision)\n }\n // 'proceed' → allow on timeout; 'abort'/'retry' → deny on timeout.\n const timer = setTimeout(() => {\n settle({\n approved: opts.onTimeout === 'proceed',\n settledBy: 'timeout',\n // Every value in this sentence was already here and none of it used to survive the\n // settle. `onTimeout` is named because all three of its values reach this line and two\n // of them deny — an operator who wrote `'retry'` and got a denial had nothing to read\n // that mentioned retry.\n reason: `no decision within ${String(opts.timeoutMs)} ms; onTimeout: '${opts.onTimeout}' was applied`,\n })\n }, opts.timeoutMs)\n const info: PendingApproval = {\n approvalId,\n toolName: opts.toolName,\n question: opts.question,\n expiresAt: Date.now() + opts.timeoutMs,\n ...(opts.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n }\n pending.set(approvalId, {\n settle,\n timer,\n info,\n ...(opts.owner !== undefined ? { owner: opts.owner } : {}),\n })\n })\n },\n resolve(approvalId, decision) {\n const entry = pending.get(approvalId)\n if (!entry) return false\n // M20 — coerce the legacy bare-boolean form to a decision object.\n entry.settle(typeof decision === 'boolean' ? { approved: decision } : decision)\n return true\n },\n list() {\n return [...pending.values()].map((p) => p.info)\n },\n ownerOf(approvalId) {\n // `settle` deletes the entry, so an approval that has been answered or timed out reports no\n // owner — which is what stops a later registration of the same id from inheriting one.\n return pending.get(approvalId)?.owner\n },\n }\n}\n"],"mappings":";;;;AAgCA,IAAM,YAAY;AASX,SAAS,iBAAmC,KAAa,SAAqB;AACnF,QAAM,OAAO,uBAAO,IAAI,YAAY,GAAG;AACvC,QAAM,OAAO;AAEb,QAAM,WAAW,KAAK,IAAI;AAC1B,MAAI,aAAa,OAAW,QAAO;AAEnC,QAAM,UAAU,QAAQ;AACxB,OAAK,IAAI,IAAI;AACb,SAAO;AACT;;;ACsCA,IAAM,mBAAyC;AAAA,EAC7C;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,UAAU;AAAA,EACZ;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;A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;AAAA,IAChD;AAAA,IACA,QAAQ,YAAY;AAGlB,aAAO,QAAQ,IAAI,UAAU,GAAG;AAAA,IAClC;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/contracts/client-safe-error.ts","../src/server/http/send-response.ts","../src/server/http/node-request.ts","../src/server/http/controller-dispatch.ts","../src/server/security/csrf-warn-dispatch.ts","../src/server/observability/audit-log.ts","../src/server/security/csrf.ts"],"sourcesContent":["import type { TheoErrorEnvelope } from './error-envelope.js'\n\n/**\n * What an error is allowed to tell the caller.\n *\n * Most error codes describe something the caller did and can fix, so their message is the useful\n * part of the response. An *internal* failure is the opposite: its message describes the server —\n * a connection string, an upstream host, a stack of internal names — and the caller can act on\n * none of it. In production it is redacted; in development it is exactly what makes the framework\n * debuggable, so it stays.\n *\n * This lives in one place because it was previously stated in two and missing from a third. The\n * Node runner redacted, the Web error builder redacted, and an exception escaping a Web handler\n * took a hand-built path that did neither — same route, same failure, more disclosure depending\n * on which transport served it. That is the \"one contract, three transports\" rule in\n * `rules/three-target-parity.md` being broken by duplication rather than by design.\n */\n\n/** Both spellings the codebase uses for \"this is our fault, and the detail is ours too\". */\nconst INTERNAL_CODES: ReadonlySet<string> = new Set(['INTERNAL_ERROR', 'INTERNAL_SERVER_ERROR'])\n\nconst GENERIC_INTERNAL_MESSAGE = 'Internal server error'\n\nfunction redacts(code: string): boolean {\n return INTERNAL_CODES.has(code) && process.env.NODE_ENV === 'production'\n}\n\n/** The message this code may carry to the caller. */\nexport function clientSafeErrorMessage(code: string, message: string): string {\n return redacts(code) ? GENERIC_INTERNAL_MESSAGE : message\n}\n\n/**\n * The envelope this code may carry to the caller.\n *\n * When it redacts, `cause`, `meta` and `ext` go with the message rather than being filtered\n * field by field: they exist to describe the failure, and the whole point is that this failure is\n * not describable to the caller. Keeping the code is what lets a client branch on it.\n */\nexport function clientSafeErrorEnvelope(envelope: TheoErrorEnvelope): TheoErrorEnvelope {\n if (!redacts(envelope.code)) return envelope\n return { code: envelope.code, message: GENERIC_INTERNAL_MESSAGE }\n}\n","import type { ServerResponse } from 'node:http'\n\nimport { clientSafeErrorMessage } from '../../core/contracts/client-safe-error.js'\nimport type { TheoTransformer } from '../transformer.js'\n\n/**\n * Canonical HTTP response helpers (T5.1 extraction).\n *\n * Moved out of execute.ts so request-pipeline stages (execute-stages.ts,\n * handle-request-error.ts, etc.) can depend on these helpers without\n * creating a cycle through execute.ts.\n *\n * Public surface re-exported from execute.ts for backward compat — every\n * existing caller of `sendError` / `sendJson` continues to work via the\n * `theokit/server` barrel.\n */\n\nexport function sendJson(\n res: ServerResponse,\n data: unknown,\n status = 200,\n transformer?: TheoTransformer,\n): void {\n // T1.2 — transformer-aware serialization. Default (no transformer) uses\n // JSON.stringify direct for backward compat.\n const body = transformer ? transformer.serialize(data) : JSON.stringify(data)\n res.writeHead(status, {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(body),\n })\n res.end(body)\n}\n\n/** Render anything that would end the log line as a visible escape, so one call logs one line. */\nfunction oneLine(value: string): string {\n return value.replace(/[\\r\\n]/g, '\\\\n')\n}\n\nexport interface SendErrorOptions {\n custom404Html?: string\n custom500Html?: string\n}\n\n/**\n * Canonical error response.\n *\n * T6.3 (PV-17): the positional 7-param signature is preserved for backward\n * compat. New call sites should use the options-bag form:\n *\n * sendError(res, { code, message, status, issues?, requestId?, options? })\n *\n * Both shapes resolve to the same implementation.\n */\nexport interface SendErrorInput {\n code: string\n message: string\n status: number\n issues?: unknown[]\n requestId?: string\n options?: SendErrorOptions\n}\n\nexport function sendError(res: ServerResponse, input: SendErrorInput): void\n/* eslint-disable-next-line max-params -- T6.3: positional overload preserved\n for backward compat (callers across cli/server still use positional). The\n options-bag overload above is the recommended path. */\nexport function sendError(\n res: ServerResponse,\n code: string,\n message: string,\n status: number,\n issues?: unknown[],\n requestId?: string,\n options?: SendErrorOptions,\n): void\n/* eslint-disable-next-line max-params -- delegates to two surface overloads above; the parameter\n count mirrors the back-compat contract, not internal complexity. The `complexity` half of this\n suppression went away when the redaction rule stopped being restated inline. */\nexport function sendError(\n res: ServerResponse,\n codeOrInput: string | SendErrorInput,\n message?: string,\n status?: number,\n issues?: unknown[],\n requestId?: string,\n options?: SendErrorOptions,\n): void {\n let code: string\n if (typeof codeOrInput === 'string') {\n code = codeOrInput\n message = message ?? ''\n status = status ?? 500\n } else {\n code = codeOrInput.code\n message = codeOrInput.message\n status = codeOrInput.status\n issues = codeOrInput.issues\n requestId = codeOrInput.requestId\n options = codeOrInput.options\n }\n const errorMessage = clientSafeErrorMessage(code, message)\n\n if (code === 'INTERNAL_ERROR') {\n // One log entry per call, whatever the message contains. An exception message can be built\n // from request data and can therefore carry a newline; unescaped, that lets a caller append\n // whatever lines it likes to the log — including a plausible entry attributed to something\n // else (CodeQL `js/log-injection`).\n console.error(`[${oneLine(requestId ?? 'no-id')}] ${oneLine(message)}`)\n }\n\n if (status === 404 && options?.custom404Html) {\n const body = options.custom404Html\n res.writeHead(404, {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Length': Buffer.byteLength(body),\n })\n res.end(body)\n return\n }\n if (status === 500 && options?.custom500Html) {\n const body = options.custom500Html\n res.writeHead(500, {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Length': Buffer.byteLength(body),\n })\n res.end(body)\n return\n }\n\n sendJson(\n res,\n {\n error: {\n code,\n message: errorMessage,\n ...(requestId ? { requestId } : {}),\n ...(issues ? { issues } : {}),\n },\n },\n status,\n )\n}\n\n/**\n * T5a.2 Phase G slice 4/N — Web-Standards response helpers.\n *\n * Mirror of `sendJson` + `sendError` for the Web `Request`/`Response`\n * shape. Returns a native `Response` directly instead of mutating a\n * `ServerResponse`.\n *\n * v1.0 § Phase G.\n *\n * **Difference vs IncomingMessage path:**\n * - No `Content-Length` set explicitly — the runtime computes it from\n * the body when needed. CF Workers / Bun / Deno all do this; setting\n * it manually risks conflict if the body is a stream rather than a\n * fixed string.\n * - Custom 404/500 HTML options preserved (same opts shape).\n * - `requestId` flows into the response body's error envelope AND\n * surfaces as `x-request-id` header (parity with handleWebRequestError\n * Phase G slice 3/N).\n */\nexport function buildJsonResponse(\n data: unknown,\n status = 200,\n transformer?: TheoTransformer,\n): Response {\n const body = transformer ? transformer.serialize(data) : JSON.stringify(data)\n return new Response(body, {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\nexport function buildErrorResponse(input: SendErrorInput): Response {\n const { code, message, status, issues, requestId, options } = input\n const errorMessage = clientSafeErrorMessage(code, message)\n\n if (code === 'INTERNAL_ERROR') {\n // One log entry per call, whatever the message contains. An exception message can be built\n // from request data and can therefore carry a newline; unescaped, that lets a caller append\n // whatever lines it likes to the log — including a plausible entry attributed to something\n // else (CodeQL `js/log-injection`).\n console.error(`[${oneLine(requestId ?? 'no-id')}] ${oneLine(message)}`)\n }\n\n const headers: Record<string, string> = {}\n if (requestId !== undefined) headers['x-request-id'] = requestId\n\n if (status === 404 && options?.custom404Html !== undefined) {\n headers['content-type'] = 'text/html; charset=utf-8'\n return new Response(options.custom404Html, { status: 404, headers })\n }\n if (status === 500 && options?.custom500Html !== undefined) {\n headers['content-type'] = 'text/html; charset=utf-8'\n return new Response(options.custom500Html, { status: 500, headers })\n }\n\n headers['content-type'] = 'application/json'\n const body = JSON.stringify({\n error: {\n code,\n message: errorMessage,\n ...(requestId ? { requestId } : {}),\n ...(issues ? { issues } : {}),\n },\n })\n return new Response(body, { status, headers })\n}\n","/**\n * Pure Node `IncomingMessage` → Web `Request` converters.\n *\n * Kept free of any dependency on `web-handler.js` / `execute*.js` so the\n * executor (`execute.ts`) can build the handler-facing Web `Request` without\n * pulling the Web dispatch pipeline into its import graph (ADR-0028 R3a — the\n * Node adapter is the ONLY place IncomingMessage ↔ Request conversion lives;\n * these are the primitive converters it and the executor share).\n */\nimport type { IncomingMessage } from 'node:http'\nimport { Readable } from 'node:stream'\n\n/** Pick the first usable string from Node's `string | string[] | undefined` headers. */\nfunction pickHeaderString(value: string | string[] | undefined): string | undefined {\n if (typeof value === 'string') return value\n if (Array.isArray(value)) {\n for (const v of value) if (typeof v === 'string' && v.length > 0) return v\n }\n return undefined\n}\n\n/** Web Request requires an absolute URL; synthesize one from the Host header. */\nfunction synthesizeAbsoluteUrl(req: IncomingMessage): string {\n const host = pickHeaderString(req.headers.host) ?? 'localhost'\n return `http://${host}${req.url ?? '/'}`\n}\n\n/**\n * Collapse Node's `string | string[]` headers into a Web `Headers`. Repeated\n * headers are comma-joined (not `.append`ed) because `Headers.append` creates\n * multi-value entries that behave differently on `.get()` (EC-1).\n */\nfunction nodeHeadersToWeb(req: IncomingMessage): Headers {\n const headers = new Headers()\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue\n if (Array.isArray(value)) {\n headers.set(key, value.join(', '))\n } else {\n headers.set(key, value)\n }\n }\n return headers\n}\n\n/**\n * Build a Web `Request` from a Node `IncomingMessage`, body included. The Web\n * Request spec requires an absolute URL; we synthesize one from the Host header\n * (fallback `localhost` for test doubles).\n *\n * For methods with a body (POST/PUT/PATCH/DELETE), the Node Readable stream is\n * wrapped as a Web ReadableStream via `Readable.toWeb()` so downstream consumers\n * can call `request.json()` / `request.formData()` / `request.text()` natively.\n */\nexport function incomingMessageToWebRequest(req: IncomingMessage): Request {\n const url = synthesizeAbsoluteUrl(req)\n const headers = nodeHeadersToWeb(req)\n\n const method = (req.method ?? 'GET').toUpperCase()\n const hasBody = method !== 'GET' && method !== 'HEAD'\n\n if (!hasBody) {\n return new Request(url, { method, headers })\n }\n\n // Drain Node's Readable into a Web ReadableStream. `Readable.toWeb` is\n // available in Node 18+ (theokit's engines.node floor is 22+, so safe).\n const webStream = Readable.toWeb(req) as ReadableStream\n return new Request(url, {\n method,\n headers,\n body: webStream,\n // EC-2: Node 18+ requires `duplex: 'half'` when body is a stream.\n // The `RequestInit` type omits it (Web spec gap); cast accordingly.\n ...({ duplex: 'half' } as { duplex: 'half' }),\n })\n}\n\n/**\n * A Node request that has NOT been converted yet — method now, body only if someone claims it.\n *\n * theokit#400. `incomingMessageToWebRequest` drains the Node stream, and a stream drains once. A\n * dispatcher that converts in order to decide whether it owns a path has already spent the body on\n * every path it does not own: the next branch attaches to a readable that has already ended, waits\n * for an `'end'` that cannot fire twice, and the request hangs with no status at all.\n *\n * The fix is an ordering one, so the type encodes the ordering: a router reads `method` (free) and\n * calls `toRequest()` only after it has decided the request is its own. Passing the source instead\n * of a `Request` is what makes \"did you convert before deciding?\" answerable by reading a signature.\n *\n * `toRequest()` memoizes, because a second conversion of the same `IncomingMessage` yields a\n * Request whose body is an empty closed stream — a silent truncation, which is worse than the hang\n * it would replace.\n */\nexport interface WebRequestSource {\n /** Uppercase HTTP method. Available without touching the body. */\n readonly method: string\n /** Convert on demand. Idempotent: repeated calls return the same `Request`. */\n toRequest: () => Request\n}\n\n/** Wrap `req` as a {@link WebRequestSource} — the conversion is deferred and memoized. */\nexport function createWebRequestSource(req: IncomingMessage): WebRequestSource {\n let converted: Request | undefined\n return {\n method: (req.method ?? 'GET').toUpperCase(),\n toRequest: () => (converted ??= incomingMessageToWebRequest(req)),\n }\n}\n\n/**\n * Build the Web `Request` handed to a route handler as `ctx.request` in the\n * Node server path (dev + `theokit start`). Method + absolute URL + headers\n * only — NO body.\n *\n * Why no body: the Node executor parses the request body BEFORE the handler\n * runs and exposes the parsed value as `ctx.body` (the typed, documented body\n * API). By the time the handler is called the Node stream is already drained,\n * so re-wrapping it would yield an empty/closed stream. Handlers read the body\n * via `ctx.body`; `ctx.request` is for the Web-standard header/cookie/URL/method\n * surface (e.g. `createSessionManagerWeb.getSession(ctx.request)`).\n *\n * Per ADR-0028 R3a, handlers see a Web `Request` in every runtime — this closes\n * the gap where the Node path leaked the raw `IncomingMessage` (whose `.headers`\n * is a plain object, so `.headers.get(...)` threw for Web-standard consumers).\n */\nexport function incomingMessageToHandlerRequest(req: IncomingMessage): Request {\n return new Request(synthesizeAbsoluteUrl(req), {\n method: (req.method ?? 'GET').toUpperCase(),\n headers: nodeHeadersToWeb(req),\n })\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Controller files are walked from the developer's `serverDir/controllers`\n * (a build-time config path), never from HTTP input. No injection vector.\n */\nimport { readdirSync, type Dirent } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { join } from 'node:path'\n\nimport { createDecoratorHandler, isControllerClass, type ServeAgent } from '@theokit/http'\n\nimport { dispatchCsrfWarn } from '../security/csrf-warn-dispatch.js'\nimport { enforceCsrf, type DisallowedConfig } from '../security/csrf.js'\n\nimport { incomingMessageToWebRequest } from './node-request.js'\nimport { sendError } from './send-response.js'\n\n/** A decorator controller constructor (`@Controller` class). */\ntype ControllerClass = new (...args: never[]) => object\n\n/** Loads a controller module by absolute path. In dev this is Vite's `ssrLoadModule`\n * (the Task 1.1 swc transform has already compiled the parameter decorators); tests\n * inject `@theokit/http`'s `loadControllerWithSwc`. */\nexport type ControllerModuleLoader = (absPath: string) => Promise<Record<string, unknown>>\n\n/** A built controller route table exposed as a pure Web-Standard handler. */\ninterface ControllerDispatcher {\n /** `null` = no controller route matched — the host owns the miss (404 / fall-through). */\n dispatch(request: Request): Promise<Response | null>\n /** Non-executing route probe — true when a controller route owns `method` + `pathname`. */\n matches(method: string, pathname: string): boolean\n}\n\n// State-mutating methods get CSRF, mirroring the file-route pipeline (execute.ts).\nconst CSRF_PROTECTED_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/** Recursively collect `*.controller.ts` files under `dir` (absolute paths). */\n/**\n * Every `*.controller.ts` under `dir`, recursively. Exported for theokit#123: the build emitter\n * must find exactly the same set the dev dispatcher does, and two independent walks would be two\n * definitions of \"a controller\" that drift.\n */\nexport function findControllerFiles(dir: string): string[] {\n const found: string[] = []\n const walk = (current: string): void => {\n let entries: Dirent[]\n try {\n entries = readdirSync(current, { withFileTypes: true })\n } catch {\n return // dir doesn't exist — no controllers\n }\n for (const entry of entries) {\n const full = join(current, entry.name)\n if (entry.isDirectory()) walk(full)\n // theokit#123 — `.mjs` alongside `.ts`. Dev walks the SOURCE tree; production walks the\n // COMPILED tree under `dist/controllers`, where the same files exist as `*.controller.mjs`.\n // One walk for both keeps a single definition of \"a controller file\"; two would drift, and a\n // file that counts in dev and not in production is exactly the dev/prod split this fixes.\n else if (entry.name.endsWith('.controller.ts') || entry.name.endsWith('.controller.mjs'))\n found.push(full)\n }\n }\n walk(dir)\n return found\n}\n\n/** A discovered controller: its source file + the loaded `@Controller` class. */\ninterface ControllerModule {\n filePath: string\n cls: ControllerClass\n /**\n * The module's full export namespace — theokit#124.\n *\n * Kept alongside the class because it is the ONLY place a `@Body(schema)` regains a name. The\n * schema on `WalkResult.bodySchema` is a runtime `z.ZodType` with no source identifier, but it is\n * the very object this module exported, so matching it back by reference identity recovers the\n * exported name the typed-client codegen needs to write `z.infer<typeof ...>`.\n *\n * Unused by the dispatch path, which needs only the class.\n */\n exports: Readonly<Record<string, unknown>>\n}\n\n/**\n * Load every `@Controller` class under `controllersDir` via the injected loader,\n * keeping each class paired with its source file (needed by the typed-client\n * codegen to emit `import type { X } from '<file>'`). Non-controller exports are\n * ignored (`isControllerClass` — reused from @theokit/http).\n */\nexport async function scanControllerModules(\n controllersDir: string,\n loadModule: ControllerModuleLoader,\n): Promise<ControllerModule[]> {\n const files = findControllerFiles(controllersDir)\n const modules: ControllerModule[] = []\n for (const filePath of files) {\n const mod = await loadModule(filePath)\n for (const exported of Object.values(mod)) {\n if (typeof exported === 'function' && isControllerClass(exported)) {\n modules.push({ filePath, cls: exported as ControllerClass, exports: mod })\n }\n }\n }\n return modules\n}\n\n/** Load every `@Controller` class under `controllersDir` (classes only). */\nasync function scanControllers(\n controllersDir: string,\n loadModule: ControllerModuleLoader,\n): Promise<ControllerClass[]> {\n const modules = await scanControllerModules(controllersDir, loadModule)\n return modules.map((m) => m.cls)\n}\n\n/**\n * Scan `controllersDir` and build a Web-Standard dispatcher over the decorator\n * controllers found. Returns `null` when the directory has no controllers, so\n * the host can skip the controller path entirely (zero cost for routes-only apps).\n *\n * Dispatch REUSES @theokit/http's `createDecoratorHandler` (match + `@Param`\n * binding + `@Body` validation + Response building) — never re-implemented (ADR-1).\n */\nexport async function createControllerDispatcher(opts: {\n controllersDir: string\n loadModule: ControllerModuleLoader\n /** M47 — serves `@Expose`-bound agent routes (theo supplies a `mountAgent`-backed impl). */\n serveAgent?: ServeAgent\n}): Promise<ControllerDispatcher | null> {\n const classes = await scanControllers(opts.controllersDir, opts.loadModule)\n if (classes.length === 0) return null\n const handle = createDecoratorHandler({ controllers: classes, serveAgent: opts.serveAgent })\n return {\n dispatch: (request) => handle(request),\n matches: (method, pathname) => handle.matches(method, pathname),\n }\n}\n\n/** Write a buffered Web `Response` (controllers never stream) to a Node response. */\nasync function writeControllerResponse(res: ServerResponse, response: Response): Promise<void> {\n const headersBag: Record<string, string> = {}\n for (const [k, v] of response.headers) {\n if (k.toLowerCase() !== 'set-cookie') headersBag[k] = v\n }\n const setCookies = response.headers.getSetCookie()\n if (setCookies.length > 0) res.setHeader('Set-Cookie', setCookies)\n res.writeHead(response.status, headersBag)\n const body = response.body ? await response.text() : ''\n res.end(body || undefined)\n}\n\n/**\n * The `api-middleware` fall-through in one call: scan `controllersDir`, build the\n * dispatcher, and serve the request. Builds a body-ful Web `Request` (`@Body`\n * needs the body; the raw stream is undrained at a route miss) and enforces CSRF\n * with the SAME gate file routes use (parity). Returns `true` when a controller\n * handled it (or CSRF blocked it), `false` when there are no controllers OR none\n * matched (the host continues to its own 404). Built per-miss so controller edits\n * reflect via HMR.\n */\nexport async function dispatchControllerRequest(args: {\n controllersDir: string\n loadModule: ControllerModuleLoader\n req: IncomingMessage\n res: ServerResponse\n csrfMode: 'off' | 'warn' | 'strict'\n disallowed?: DisallowedConfig\n requestId: string\n /** M47 — serves `@Expose`-bound agent routes (mountAgent-backed); omit for routes-only apps. */\n serveAgent?: ServeAgent\n}): Promise<boolean> {\n const { req, res, csrfMode, disallowed, requestId } = args\n const dispatcher = await createControllerDispatcher({\n controllersDir: args.controllersDir,\n loadModule: args.loadModule,\n serveAgent: args.serveAgent,\n })\n if (!dispatcher) return false\n\n const method = (req.method ?? 'GET').toUpperCase()\n const webRequest = incomingMessageToWebRequest(req)\n const pathname = new URL(webRequest.url).pathname\n\n // CSRF parity: enforce ONLY when a protected-method controller route actually\n // owns this path (probe with the non-executing matcher — never double-dispatch,\n // which would run the handler + its side effects). An unrouted path falls\n // through to the host's own 404, not a 403.\n if (CSRF_PROTECTED_METHODS.has(method) && dispatcher.matches(method, pathname)) {\n const decision = enforceCsrf(\n req,\n csrfMode,\n { warn: dispatchCsrfWarn, path: req.url },\n disallowed,\n )\n if (!decision.allow) {\n sendError(\n res,\n 'CSRF_INVALID',\n decision.reason ?? 'CSRF check failed',\n 403,\n undefined,\n requestId,\n )\n return true\n }\n }\n\n const response = await dispatcher.dispatch(webRequest)\n if (response === null) return false\n await writeControllerResponse(res, response)\n return true\n}\n","/**\n * Canonical CSRF warn dispatcher (T3.3 of architecture-review-remediation-plan).\n *\n * Consolidates the duplicated `warn: (payload) => { warnOnce(...) }` closure\n * that previously appeared in both `http/execute.ts` and\n * `http/action-execute.ts`. Resolves PV-10 (DRY).\n *\n * `warnOnce` dedupes by `event:method:path` so a request loop with 1000 POSTs\n * doesn't flood logs with identical warnings. Apps grep for `event\":\"csrf.warn\"`\n * (stable event shape — see [[enforcement-cutover.md]]).\n */\nimport { warnOnce } from '../observability/logger.js'\n\ninterface CsrfWarnPayload {\n event: string\n method: string\n path?: string\n reason: string\n code?: string\n docsUrl?: string\n warnOnce?: boolean\n}\n\n/**\n * Build the warn callback that `enforceCsrf` invokes for soft-mode warnings.\n * Returned function is suitable for the `warn` field of `enforceCsrf`'s options.\n */\nexport function dispatchCsrfWarn(payload: CsrfWarnPayload): void {\n const key = `${payload.event}:${payload.method}:${payload.path ?? ''}`\n warnOnce(key, payload as unknown as Record<string, unknown>)\n}\n","/**\n * T4.1 — Audit logging interface + default JSON stdout sink.\n *\n * Per ADR D4: define the interface; ship a zero-dep default; reserve\n * adapter shapes for Postgres, File, OpenTelemetry, Sentry as follow-up\n * packages. Persistence has heavy deps (`pg`, `better-sqlite3`); we\n * keep core dep-free and let users opt in.\n *\n * Compatibility:\n * - Node / Bun / Deno / Vercel — console.log is sync, captured.\n * - Edge runtimes (CF Workers, Vercel Edge) — console.log is captured\n * but may be rate-limited by the platform. For high-volume edge audit,\n * implement a custom sink writing to a queue / HTTP endpoint.\n */\n\nexport interface AuditEvent {\n /** Domain-qualified verb. Convention: `<domain>.<verb>` (e.g. csrf.warn, session.rotated). */\n action: string\n /** Who triggered the event. Anonymous = no auth at time of event. */\n actor?: { type: 'user' | 'system' | 'anonymous'; id?: string }\n /** What was operated on (optional). */\n resource?: { type: string; id?: string }\n /** Arbitrary event-specific metadata. JSON-serializable. */\n metadata?: Record<string, unknown>\n /** ISO 8601 timestamp. If absent, sink fills in `new Date().toISOString()`. */\n timestamp?: string\n /** Optional trace id (populated by middleware from `x-trace-id`). */\n traceId?: string\n}\n\nexport interface AuditLogger {\n log(event: AuditEvent): void | Promise<void>\n}\n\n/**\n * Default sink: one JSON line per event to stdout. Sync. Never throws.\n *\n * EC: circular refs / BigInt values fall back to a placeholder line so\n * the event is still observable (action + traceId) without crashing the\n * request lifecycle.\n */\nexport class JsonStdoutSink implements AuditLogger {\n log(event: AuditEvent): void {\n const enriched = {\n level: 'audit' as const,\n ...event,\n timestamp: event.timestamp ?? new Date().toISOString(),\n }\n try {\n // eslint-disable-next-line no-console -- JsonStdoutSink IS the audit output\n console.log(JSON.stringify(enriched, jsonReplacer))\n } catch {\n // eslint-disable-next-line no-console -- fallback when payload won't serialize\n console.log(\n `{\"level\":\"audit\",\"action\":${JSON.stringify(event.action)},\"timestamp\":${JSON.stringify(enriched.timestamp)},\"note\":\"payload could not be serialized\"}`,\n )\n }\n }\n}\n\n/**\n * Replacer that walks BigInt → string. Circular ref handling is via the\n * outer try/catch (JSON.stringify throws TypeError on cycles; we drop to\n * the fallback line). We don't implement custom cycle-breaking walker\n * because the audit payload is meant to be JSON — if user metadata has\n * a cycle, the right answer is to fix the caller, not silently lose\n * the structure.\n */\nfunction jsonReplacer(_key: string, value: unknown): unknown {\n if (typeof value === 'bigint') return value.toString()\n return value\n}\n\n/**\n * No-op logger. Returned when `config.audit` is unset. Zero overhead;\n * framework wiring sites null-check before calling.\n */\nexport function createNoOpLogger(): AuditLogger {\n return {\n log() {\n // intentionally empty\n },\n }\n}\n\n/**\n * T4.2 — Safe-emit wrapper. Used by framework wiring sites (csrf.ts,\n * rate-limit.ts, session.ts) so a logger throw NEVER propagates into\n * the request handler.\n */\nexport function safeAudit(logger: AuditLogger | undefined, event: AuditEvent): void {\n if (!logger) return\n try {\n const r = logger.log(event)\n // Discard the Promise — async sinks are fire-and-forget by design.\n if (r && typeof r.then === 'function') {\n r.catch(() => {\n // swallow async sink failures — audit must never crash the request\n })\n }\n } catch {\n // swallow sync sink failures — audit must never crash the request\n }\n}\n","import type { IncomingMessage } from 'node:http'\n\nimport type { AuditLogger } from '../observability/audit-log.js'\nimport { safeAudit } from '../observability/audit-log.js'\n\n/**\n * CSRF enforcement mode.\n *\n * - `off` — skip CSRF entirely. Use only when you have another defense\n * (e.g. you don't ship session cookies, all auth is bearer).\n * - `warn` — log a structured warning when the check would fail, but\n * still serve the request. Default for 0.2.0. Migration mode.\n * - `strict` — reject failing requests with 403 + code `CSRF_INVALID`.\n * Will become the default in 0.3.0.\n */\nexport type CsrfMode = 'off' | 'warn' | 'strict'\n\n/**\n * Per-request structured logger surface. Only `warn` is used by enforceCsrf;\n * we don't require a full Logger here so callers can pass a mock or the\n * console directly.\n */\nexport interface CsrfLogger {\n warn: (payload: CsrfWarnPayload) => void\n /** Optional path the request was destined for — used for log correlation. */\n path?: string\n}\n\n/**\n * T5.1 — Rails-inspired per-route escalation.\n *\n * `routes` accepts string (exact match) or RegExp entries. When a request\n * path matches AND the request would otherwise emit a warning, the\n * `behavior` field decides what happens:\n *\n * - `'warn'` → normal warn dispatch (no-op vs default)\n * - `'raise'` → escalate to 403 regardless of global `csrf` mode\n *\n * `'raise'` never downgrades: when global mode is `'off'`, validation is\n * skipped entirely and disallowed dispatch never runs.\n */\nexport interface DisallowedConfig {\n routes: (string | RegExp)[]\n behavior: 'warn' | 'raise'\n}\n\n/**\n * Test whether `path` matches any of the supplied patterns. String\n * patterns are EXACT (trailing slash matters — use RegExp for tolerance).\n *\n * EC-5: when a RegExp carries the `/g` flag, `.test()` mutates\n * `lastIndex` and the next invocation may miss. We reset `lastIndex`\n * before each test so the matcher is a pure function.\n */\nexport function matchDisallowed(path: string, patterns: readonly (string | RegExp)[]): boolean {\n for (const p of patterns) {\n if (typeof p === 'string') {\n if (path === p) return true\n } else if (p instanceof RegExp) {\n p.lastIndex = 0\n if (p.test(path)) return true\n }\n // Neither string nor RegExp: ignore silently (defensive — the public\n // type forbids it but runtime data may slip past).\n }\n return false\n}\n\n/**\n * T2.2 — Stable cutover identifier shipped with every csrf.warn payload.\n *\n * Convention borrowed from Vite's `deprecations.ts:74` — a `code` plus a\n * `docsUrl` lets users (a) grep their logs for a single stable identifier\n * to find every csrf.warn line, and (b) click through directly to the\n * migration guide. Strings are exported constants so the analyzer (T2.3)\n * and migration guide can reference the same source of truth.\n */\nexport const CSRF_WARN_CODE = 'CSRF_STRICT_CUTOVER' as const\nexport const CSRF_WARN_DOCS_URL = 'https://theokit.dev/upgrade/csrf-strict-cutover' as const\n\n/**\n * Pick a header value, choosing the first entry when an array (Node sets\n * arrays for headers that legitimately appear multiple times). Returns\n * `''` when the header is absent or empty — callers treat `''` as \"skip\".\n */\nfunction pickHeader(value: string | string[] | undefined): string {\n if (typeof value === 'string') return value\n if (Array.isArray(value) && value.length > 0) return value[0]\n return ''\n}\n\nexport interface CsrfWarnPayload {\n event: 'csrf.warn'\n method: string\n path: string | undefined\n reason: string\n /**\n * Stable identifier for the 0.2 → 0.3 CSRF strict cutover. Always\n * `'CSRF_STRICT_CUTOVER'`. Grep-able from prod logs.\n */\n code: string\n /**\n * Link to the section of the migration guide explaining how to clear\n * this specific warning class.\n */\n docsUrl: string\n}\n\n/**\n * T5a.2 Phase B (slice 1/6): pure header-only CSRF check extracted from\n * `validateCsrf(req: IncomingMessage)` so it can be re-used by the Web-\n * Standards `validateCsrfRequest(request: Request)` sibling. Per the T5a.2\n * plan v1.0 § Phase B, header-only leaves are first to migrate. This is\n * the dual-signature pattern (anti-pattern #2 avoidance): IncomingMessage\n * consumers unchanged; new Request consumers go through the same logic\n * via the shared helper.\n *\n * Pure logic — accepts pre-extracted header values as strings or null.\n */\nfunction isCsrfValidFromHeaders(opts: {\n csrfActionHeader: string | null\n origin: string | null\n host: string | null\n}): { valid: true } | { valid: false; reason: string } {\n // 1. Custom header must be present (primary defense — simple form posts\n // cannot set custom headers, browsers gate via CORS preflight)\n if (opts.csrfActionHeader !== '1') {\n return { valid: false, reason: 'Missing X-Theo-Action header' }\n }\n\n // 2. Origin matching (secondary defense)\n if (opts.origin === null || opts.origin === '') {\n // Browsers omit Origin for same-origin requests — treat as valid\n return { valid: true }\n }\n\n if (opts.host === null || opts.host === '') {\n return { valid: true }\n }\n\n try {\n const originHost = new URL(opts.origin).host\n if (originHost !== opts.host) {\n return { valid: false, reason: `Origin ${opts.origin} does not match host ${opts.host}` }\n }\n } catch {\n return { valid: false, reason: `Invalid origin: ${opts.origin}` }\n }\n\n return { valid: true }\n}\n\nexport function validateCsrf(\n req: IncomingMessage,\n): { valid: true } | { valid: false; reason: string } {\n // IncomingMessage adapter — normalize Node header shape to the pure\n // helper's input shape (string|null).\n const action = req.headers['x-theo-action']\n const origin = req.headers.origin\n const host = req.headers.host\n\n // RFC 6454: Origin is single-valued. A caller that synthesizes an\n // IncomingMessage — an adapter, a shim, a proxy library — can hand us an\n // array, and choosing one of two conflicting origins is a decision the\n // request never authorized. The disagreement IS the rejection.\n //\n // `node:http` itself joins a repeated Origin with `, ` rather than\n // producing an array, and that string already fails to parse as a URL\n // below. This branch covers the shape the type allows and `pickHeader`\n // used to resolve silently.\n if (Array.isArray(origin)) {\n return { valid: false, reason: 'Multiple Origin headers (RFC 6454 violation)' }\n }\n\n return isCsrfValidFromHeaders({\n csrfActionHeader: typeof action === 'string' ? action : null,\n origin: origin !== undefined ? origin || null : null,\n host: host !== undefined ? pickHeader(host) || null : null,\n })\n}\n\n/**\n * T5a.2 Phase B (slice 1/6) — Web-Standards-shaped CSRF validator.\n *\n * Mirror of `validateCsrf(req: IncomingMessage)` for the Web `Request`\n * shape. Consumes `request.headers.get(name)` (native Web `Headers` API)\n * instead of `req.headers[name]` (Node `IncomingMessage` indexer). Same\n * CSRF policy + same return shape — the difference is only the input\n * extraction.\n *\n * Used by `executeWebRequest` (T5a.2 Phase A) to enforce CSRF on the\n * Web-Standards request handler entry-point.\n */\nexport function validateCsrfRequest(\n request: Request,\n): { valid: true } | { valid: false; reason: string } {\n return isCsrfValidFromHeaders({\n csrfActionHeader: request.headers.get('x-theo-action'),\n origin: request.headers.get('origin'),\n host: request.headers.get('host'),\n })\n}\n\n/**\n * Enforce CSRF policy with mode-aware behavior. Wrapper over `validateCsrf`\n * that turns the boolean valid/invalid into a request-level allow decision,\n * gated by mode + structured warning in warn mode.\n *\n * Phase 5 — CSRF warn-first (EC-1).\n */\n/**\n * Dispatch the csrf.warn payload to both the structured logger and the\n * audit sink (when configured). Extracted from `enforceCsrf` to keep that\n * function's complexity within ceiling.\n */\nfunction dispatchCsrfWarn(\n req: IncomingMessage,\n reason: string,\n logger: CsrfLogger | undefined,\n auditLogger: AuditLogger | undefined,\n pathFallback = '',\n): void {\n const payload: CsrfWarnPayload = {\n event: 'csrf.warn',\n method: req.method ?? 'UNKNOWN',\n path: logger?.path ?? pathFallback,\n reason,\n code: CSRF_WARN_CODE,\n docsUrl: CSRF_WARN_DOCS_URL,\n }\n logger?.warn(payload)\n // `metadata` is typed as Record<string, unknown>; CsrfWarnPayload is a\n // structurally-equivalent shape but lacks the index signature.\n safeAudit(auditLogger, {\n action: 'csrf.warn',\n actor: { type: 'anonymous' },\n metadata: { ...payload },\n })\n}\n\nexport function enforceCsrf(\n req: IncomingMessage,\n mode: CsrfMode,\n logger?: CsrfLogger,\n disallowed?: DisallowedConfig,\n auditLogger?: AuditLogger,\n): { allow: boolean; reason?: string } {\n if (mode === 'off') {\n // `off` short-circuits before disallowed dispatch — users who set\n // csrf: 'off' globally have explicitly turned validation off, and\n // disallowed must never re-introduce it. The escape hatch is to\n // set csrf: 'warn' and use disallowed for surgical strict pockets.\n return { allow: true }\n }\n\n const check = validateCsrf(req)\n if (check.valid) {\n return { allow: true }\n }\n\n // T5.1 — disallowed dispatch: when the failing request matches a\n // disallowed pattern AND behavior is 'raise', escalate to 403 even if\n // global mode is 'warn'. Strict mode would 403 anyway, so the branch\n // is a no-op there.\n if (disallowed?.behavior === 'raise') {\n const path = logger?.path ?? req.url ?? ''\n if (matchDisallowed(path, disallowed.routes)) {\n return { allow: false, reason: check.reason }\n }\n }\n\n if (mode === 'warn') {\n // T2.1: emit via warnOnce by default — callers can override via the\n // injected logger.warn (tests, custom log routers).\n // T2.2: include the stable cutover code + docsUrl so logs are\n // grep-able and click-through-able.\n dispatchCsrfWarn(req, check.reason, logger, auditLogger)\n return { allow: true, reason: check.reason }\n }\n\n // strict — 403 the request, AND emit a warn payload so the dev (and\n // devtools UI) sees WHY it was blocked + the docsUrl to fix it.\n // Without this, strict-mode users get a silent 403 with no context.\n dispatchCsrfWarn(req, check.reason, logger, auditLogger)\n return { allow: false, reason: check.reason }\n}\n"],"mappings":";;;;;;;AAmBA,IAAM,iBAAsC,oBAAI,IAAI,CAAC,kBAAkB,uBAAuB,CAAC;AAE/F,IAAM,2BAA2B;AAEjC,SAAS,QAAQ,MAAuB;AACtC,SAAO,eAAe,IAAI,IAAI,KAAK,QAAQ,IAAI,aAAa;AAC9D;AAGO,SAAS,uBAAuB,MAAc,SAAyB;AAC5E,SAAO,QAAQ,IAAI,IAAI,2BAA2B;AACpD;;;ACb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SLY4KB3.js
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import "tsx/esm";
|
|
3
|
-
import {
|
|
4
|
-
findControllerFiles
|
|
5
|
-
} from "./chunk-MWWFXYW3.js";
|
|
6
|
-
|
|
7
|
-
// src/cli/commands/build/emit-controllers.ts
|
|
8
|
-
import { mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
9
|
-
import { basename, dirname, join, relative, resolve } from "path";
|
|
10
|
-
import { transformControllerSource } from "@theokit/http";
|
|
11
|
-
var CONTROLLER_MANIFEST_FILE = "controllers.json";
|
|
12
|
-
var CONTROLLER_OUT_DIR = "controllers";
|
|
13
|
-
async function emitControllerArtifacts(opts) {
|
|
14
|
-
const controllersDir = resolve(opts.serverDir, CONTROLLER_OUT_DIR);
|
|
15
|
-
const files = findControllerFiles(controllersDir);
|
|
16
|
-
if (files.length === 0) return null;
|
|
17
|
-
const outDir = resolve(opts.distDir, CONTROLLER_OUT_DIR);
|
|
18
|
-
mkdirSync(outDir, { recursive: true });
|
|
19
|
-
const modules = [];
|
|
20
|
-
for (const file of files) {
|
|
21
|
-
const code = await transformControllerSource(readFileSync(file, "utf-8"), file);
|
|
22
|
-
const rel = relative(controllersDir, file).replace(/\.controller\.ts$/, ".controller.mjs");
|
|
23
|
-
const outPath = join(outDir, rel);
|
|
24
|
-
mkdirSync(dirname(outPath), { recursive: true });
|
|
25
|
-
writeFileSync(outPath, code);
|
|
26
|
-
modules.push(`${CONTROLLER_OUT_DIR}/${rel.split("\\").join("/")}`);
|
|
27
|
-
}
|
|
28
|
-
const manifest = { version: 1, modules };
|
|
29
|
-
writeFileSync(
|
|
30
|
-
resolve(opts.distDir, CONTROLLER_MANIFEST_FILE),
|
|
31
|
-
JSON.stringify(manifest, null, 2) + "\n"
|
|
32
|
-
);
|
|
33
|
-
return manifest;
|
|
34
|
-
}
|
|
35
|
-
function describeControllerArtifacts(manifest) {
|
|
36
|
-
if (manifest === null) return "controllers: none";
|
|
37
|
-
const names = manifest.modules.map((m) => basename(m, ".mjs")).join(", ");
|
|
38
|
-
return `controllers: ${manifest.modules.length} compiled (${names})`;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export {
|
|
42
|
-
CONTROLLER_MANIFEST_FILE,
|
|
43
|
-
emitControllerArtifacts,
|
|
44
|
-
describeControllerArtifacts
|
|
45
|
-
};
|
|
46
|
-
//# sourceMappingURL=chunk-VSLY4KB3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/commands/build/emit-controllers.ts"],"sourcesContent":["import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\n\nimport { transformControllerSource } from '@theokit/http'\n\nimport { findControllerFiles } from '../../../server/http/controller-dispatch.js'\n\n/**\n * theokit#123 — compile `server/controllers/**` into `dist` so production can serve them.\n *\n * ## Why production needed anything at all\n *\n * #122 made decorator controllers first-class in `theokit dev`, where a Vite `enforce:'pre'` swc\n * transform compiles them on the fly — parameter decorators (`@Body`/`@Param`/`@Query`) emit\n * metadata esbuild cannot produce. `theokit start` has no Vite and no transform, so an uncompiled\n * `.controller.ts` simply cannot load, and controller routes 404'd in production while working in\n * dev. That split is the whole issue.\n *\n * ## Why compile at BUILD time rather than load with swc at runtime\n *\n * `loadControllerWithSwc` would work in production and was the smaller diff. It is refused on\n * purpose: `@swc/core` is a peer dependency and a native binary, so that path makes every deployed\n * app carry a compiler it only needs once, and turns a missing optional peer into a runtime 404\n * instead of a build failure. Compilation belongs where the rest of the build already is — and it\n * is what the issue's root-cause note asks for.\n *\n * ## Why NOT in `generateManifest`\n *\n * ADR-5 keeps controllers out of the manifest, and that is preserved here: the manifest is the\n * deploy-adapter contract, and adding a parallel route source to it would ripple through every\n * adapter. This emits a SEPARATE artifact (`dist/controllers.json` + `dist/controllers/*.mjs`) that\n * only the Node start path reads. An adapter that knows nothing about controllers keeps working\n * exactly as before.\n */\n\n/** The build artifact `theokit start` reads to find compiled controllers. */\ninterface ControllerBuildManifest {\n version: 1\n /** Emitted module paths, relative to `distDir`, in scan order. */\n modules: string[]\n}\n\nexport const CONTROLLER_MANIFEST_FILE = 'controllers.json'\nconst CONTROLLER_OUT_DIR = 'controllers'\n\n/**\n * Compile every controller under `<serverDir>/controllers` into `<distDir>/controllers`.\n *\n * No controllers ⇒ **no artifact at all** (not an empty one). `theokit start` treats a missing\n * manifest as \"this app has no controllers\" and skips the whole branch, so a routes-only app pays\n * nothing and its `dist` is byte-identical to before — the ADR-5 posture, kept.\n */\nexport async function emitControllerArtifacts(opts: {\n serverDir: string\n distDir: string\n}): Promise<ControllerBuildManifest | null> {\n const controllersDir = resolve(opts.serverDir, CONTROLLER_OUT_DIR)\n const files = findControllerFiles(controllersDir)\n if (files.length === 0) return null\n\n const outDir = resolve(opts.distDir, CONTROLLER_OUT_DIR)\n mkdirSync(outDir, { recursive: true })\n\n const modules: string[] = []\n for (const file of files) {\n // Errors are NOT caught. A controller that fails to compile must fail the BUILD — swallowing it\n // here would ship an app whose routes 404 at runtime with nothing pointing back at the cause,\n // which is the exact failure mode this issue reports (error-handling.md § 2).\n const code = await transformControllerSource(readFileSync(file, 'utf-8'), file)\n\n // Mirror the source tree under `dist/controllers` so two files with the same basename in\n // different folders cannot overwrite each other.\n const rel = relative(controllersDir, file).replace(/\\.controller\\.ts$/, '.controller.mjs')\n const outPath = join(outDir, rel)\n mkdirSync(dirname(outPath), { recursive: true })\n writeFileSync(outPath, code)\n modules.push(`${CONTROLLER_OUT_DIR}/${rel.split('\\\\').join('/')}`)\n }\n\n const manifest: ControllerBuildManifest = { version: 1, modules }\n writeFileSync(\n resolve(opts.distDir, CONTROLLER_MANIFEST_FILE),\n JSON.stringify(manifest, null, 2) + '\\n',\n )\n return manifest\n}\n\n/** Human-facing summary for the build log (mirrors the cron/job emitters). */\nexport function describeControllerArtifacts(manifest: ControllerBuildManifest | null): string {\n if (manifest === null) return 'controllers: none'\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AAM,cAAc,KAAK;AACnE;","names":[]}
|
/package/dist/{actions-virtual-module-PREAJNIS.js.map → actions-virtual-module-GMRXCAVN.js.map}
RENAMED
|
File without changes
|
/package/dist/{actions-virtual-module-TZFLCIIR.js.map → actions-virtual-module-XAWZOWSY.js.map}
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
/package/dist/{controller-swc-transform-T7ZTD55V.js.map → controller-swc-transform-7EZKG2IS.js.map}
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
/package/dist/{services-typed-client-IXNOPVZA.js.map → services-typed-client-ACTJHAEP.js.map}
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|