theokit 0.30.0 → 0.30.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +201 -0
  2. package/dist/{actions-virtual-module-PBLLMJY4.js → actions-virtual-module-XHVLBFNN.js} +7 -7
  3. package/dist/actions-virtual-module-Z2IXNF72.js +0 -0
  4. package/dist/add-W6FNTAFS.js +0 -0
  5. package/dist/agent-I5QEOMCN.js +0 -0
  6. package/dist/agents-typed-client-5DCGDWFZ.js +0 -0
  7. package/dist/{app-typed-client-EXHUWPOI.js → app-typed-client-4PAUHTO6.js} +7 -7
  8. package/dist/app-typed-client-YCQC3MZ7.js +0 -0
  9. package/dist/aws-lambda-7GSCNLPY.js +0 -0
  10. package/dist/body-parser-web-FV5HWCY3.js +0 -0
  11. package/dist/boot/index.js +3 -3
  12. package/dist/broadcast-LUMOJIJT.js +0 -0
  13. package/dist/build-V2QEBE7I.js +0 -0
  14. package/dist/build-request-body-preview-QMWD2IXK.js +0 -0
  15. package/dist/bun-KP2KES6S.js +0 -0
  16. package/dist/check-PD2FTKMM.js +0 -0
  17. package/dist/chunk-2CVV6CNN.js +0 -0
  18. package/dist/chunk-45C3WUQ7.js +0 -0
  19. package/dist/{chunk-UYFZ6DDW.js → chunk-4MTCKE5I.js} +1 -189
  20. package/dist/chunk-4MTCKE5I.js.map +1 -0
  21. package/dist/chunk-5ODOE6EF.js +0 -0
  22. package/dist/chunk-63BUBV5L.js +64 -0
  23. package/dist/chunk-63BUBV5L.js.map +1 -0
  24. package/dist/chunk-AFVTEAES.js +0 -0
  25. package/dist/chunk-FOZIR3TG.js +0 -0
  26. package/dist/chunk-FRUEDJFX.js +0 -0
  27. package/dist/chunk-GDN3PXFH.js +0 -0
  28. package/dist/chunk-GEQJAFSV.js +0 -0
  29. package/dist/chunk-GSO77FSM.js +0 -0
  30. package/dist/{chunk-EHUT4FMG.js → chunk-HAOPVC47.js} +29 -27
  31. package/dist/{chunk-EHUT4FMG.js.map → chunk-HAOPVC47.js.map} +1 -1
  32. package/dist/chunk-HGZL5EOI.js +0 -0
  33. package/dist/chunk-HNBWZKIQ.js +0 -0
  34. package/dist/chunk-HZ6USUHC.js +191 -0
  35. package/dist/chunk-HZ6USUHC.js.map +1 -0
  36. package/dist/chunk-IEES3CHD.js +0 -0
  37. package/dist/chunk-JAIKGP3Q.js +0 -0
  38. package/dist/chunk-KXA37ONC.js +0 -0
  39. package/dist/chunk-M6NMS5LR.js +0 -0
  40. package/dist/chunk-P37RZRFV.js +0 -0
  41. package/dist/chunk-S7L6H3KP.js +0 -0
  42. package/dist/chunk-SPFMJAFW.js +326 -0
  43. package/dist/chunk-SPFMJAFW.js.map +1 -0
  44. package/dist/chunk-TERFLG67.js +0 -0
  45. package/dist/{chunk-DMGVH3VG.js → chunk-V3X5FWJA.js} +5 -62
  46. package/dist/chunk-V3X5FWJA.js.map +1 -0
  47. package/dist/chunk-VRVNM3QL.js +0 -0
  48. package/dist/chunk-WR4F4EEZ.js +0 -0
  49. package/dist/chunk-Y4TOVMNC.js +0 -0
  50. package/dist/chunk-YJWEADAW.js +0 -0
  51. package/dist/cloudflare-C6E5SPAE.js +0 -0
  52. package/dist/configure-agent-registry-ZOBVU3MV.js +0 -0
  53. package/dist/db-3UNAMSFK.js +0 -0
  54. package/dist/define-agent-tool-ChaGymol.d.ts +88 -0
  55. package/dist/deno-deploy-RFZN56X4.js +0 -0
  56. package/dist/dev-5ZQMWVFC.js +0 -0
  57. package/dist/dev-emit-EFQRBVYS.js +0 -0
  58. package/dist/dispatcher-EJHL6JMJ.js +0 -0
  59. package/dist/docker-LZZB4D5E.js +0 -0
  60. package/dist/generate-373DALPY.js +0 -0
  61. package/dist/index.js +11 -10
  62. package/dist/index.js.map +1 -1
  63. package/dist/info-2OOXFTJX.js +0 -0
  64. package/dist/{internal-api-JIR3HRKF.js → internal-api-QSP2HCUU.js} +20 -20
  65. package/dist/internal-api-Y5REPVUS.js +0 -0
  66. package/dist/load-config-3EAQTXPH.js +0 -0
  67. package/dist/mcp-VMKWB2BY.js +0 -0
  68. package/dist/netlify-PMLHVPN4.js +0 -0
  69. package/dist/node-BPJ3Z4DT.js +0 -0
  70. package/dist/openapi-ERYWAT3A.js +0 -0
  71. package/dist/registry-3NB7KOUI.js +0 -0
  72. package/dist/router-TLEAOFID.js +0 -0
  73. package/dist/routes-XNS3UM3B.js +0 -0
  74. package/dist/scan-7MJC6PYU.js +0 -0
  75. package/dist/schema-LYOLNHZ7.js +0 -0
  76. package/dist/server/agent/index.d.ts +387 -0
  77. package/dist/server/agent/index.js +43 -0
  78. package/dist/server/agent/index.js.map +1 -0
  79. package/dist/server/auth/index.js +1 -1
  80. package/dist/server/define/index.d.ts +3 -86
  81. package/dist/server/define/index.js +4 -2
  82. package/dist/server/index.d.ts +10 -387
  83. package/dist/server/index.js +112 -398
  84. package/dist/server/index.js.map +1 -1
  85. package/dist/server/jobs/index.js +4 -4
  86. package/dist/server/scan/index.js +1 -1
  87. package/dist/server/webhook/index.d.ts +4 -45
  88. package/dist/server-error-to-envelope-UUXDSLAZ.js +0 -0
  89. package/dist/server-routes-hmr-VZXOP5YT.js +0 -0
  90. package/dist/services-json-Y3XODNB5.js +0 -0
  91. package/dist/services-typed-client-32KMTTXR.js +0 -0
  92. package/dist/start-IFTLTEPZ.js +0 -0
  93. package/dist/static-MB2CD5Y3.js +0 -0
  94. package/dist/storage-manager-ZSQFLEYT.js +0 -0
  95. package/dist/theo-cloud-DQRP6S6M.js +0 -0
  96. package/dist/upgrade-readiness-ACGW44JC.js +0 -0
  97. package/dist/vercel-J6G7ZHYQ.js +0 -0
  98. package/dist/vite-plugin/index.js +11 -10
  99. package/dist/vite-plugin-BNI7YLCD.js +0 -0
  100. package/dist/webhook-types-CNUZY7o1.d.ts +45 -0
  101. package/package.json +14 -10
  102. package/dist/chunk-DMGVH3VG.js.map +0 -1
  103. package/dist/chunk-UYFZ6DDW.js.map +0 -1
  104. /package/dist/{actions-virtual-module-PBLLMJY4.js.map → actions-virtual-module-XHVLBFNN.js.map} +0 -0
  105. /package/dist/{app-typed-client-EXHUWPOI.js.map → app-typed-client-4PAUHTO6.js.map} +0 -0
  106. /package/dist/{internal-api-JIR3HRKF.js.map → internal-api-QSP2HCUU.js.map} +0 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 usetheo.dev
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -1,5 +1,8 @@
1
1
  import "./chunk-RSVN727G.js";
2
+ import "./chunk-TGTNRUH3.js";
3
+ import "./chunk-GY5Q27BJ.js";
2
4
  import "./chunk-5QW7IQQU.js";
5
+ import "./chunk-WFNLNIJX.js";
3
6
  import "./chunk-IAJ2JVEH.js";
4
7
  import "./chunk-VMEWD57H.js";
5
8
  import "./chunk-JQSKBMXP.js";
@@ -7,17 +10,14 @@ import {
7
10
  scanServerActionsEnriched
8
11
  } from "./chunk-RKDH4DWL.js";
9
12
  import "./chunk-WSJKACWB.js";
10
- import "./chunk-JBCHWRKF.js";
11
- import "./chunk-C3ZZ56YZ.js";
12
- import "./chunk-X2VVCJ4V.js";
13
- import "./chunk-TGTNRUH3.js";
14
- import "./chunk-GY5Q27BJ.js";
15
- import "./chunk-WFNLNIJX.js";
16
13
  import "./chunk-ZEGYW52B.js";
14
+ import "./chunk-JBCHWRKF.js";
17
15
  import "./chunk-TSLSIRBR.js";
18
16
  import "./chunk-UD3LFGDL.js";
19
17
  import "./chunk-X32XEJXR.js";
20
18
  import "./chunk-UVXB2ER7.js";
19
+ import "./chunk-C3ZZ56YZ.js";
20
+ import "./chunk-X2VVCJ4V.js";
21
21
  import "./chunk-DGUM43GV.js";
22
22
 
23
23
  // src/vite-plugin/actions-virtual-module.ts
@@ -221,4 +221,4 @@ export const actions = manifest
221
221
  export {
222
222
  actionsVirtualModule
223
223
  };
224
- //# sourceMappingURL=actions-virtual-module-PBLLMJY4.js.map
224
+ //# sourceMappingURL=actions-virtual-module-XHVLBFNN.js.map
File without changes
File without changes
File without changes
File without changes
@@ -1,5 +1,8 @@
1
1
  import "./chunk-RSVN727G.js";
2
+ import "./chunk-TGTNRUH3.js";
3
+ import "./chunk-GY5Q27BJ.js";
2
4
  import "./chunk-5QW7IQQU.js";
5
+ import "./chunk-WFNLNIJX.js";
3
6
  import "./chunk-IAJ2JVEH.js";
4
7
  import "./chunk-VMEWD57H.js";
5
8
  import "./chunk-JQSKBMXP.js";
@@ -9,17 +12,14 @@ import {
9
12
  import {
10
13
  HTTP_METHODS
11
14
  } from "./chunk-WSJKACWB.js";
12
- import "./chunk-JBCHWRKF.js";
13
- import "./chunk-C3ZZ56YZ.js";
14
- import "./chunk-X2VVCJ4V.js";
15
- import "./chunk-TGTNRUH3.js";
16
- import "./chunk-GY5Q27BJ.js";
17
- import "./chunk-WFNLNIJX.js";
18
15
  import "./chunk-ZEGYW52B.js";
16
+ import "./chunk-JBCHWRKF.js";
19
17
  import "./chunk-TSLSIRBR.js";
20
18
  import "./chunk-UD3LFGDL.js";
21
19
  import "./chunk-X32XEJXR.js";
22
20
  import "./chunk-UVXB2ER7.js";
21
+ import "./chunk-C3ZZ56YZ.js";
22
+ import "./chunk-X2VVCJ4V.js";
23
23
  import "./chunk-DGUM43GV.js";
24
24
 
25
25
  // src/vite-plugin/app-typed-client.ts
@@ -296,4 +296,4 @@ export {
296
296
  emitClientDts,
297
297
  generateClientDts
298
298
  };
299
- //# sourceMappingURL=app-typed-client-EXHUWPOI.js.map
299
+ //# sourceMappingURL=app-typed-client-4PAUHTO6.js.map
File without changes
File without changes
File without changes
@@ -1,6 +1,3 @@
1
- import {
2
- serveReservedRoute
3
- } from "../chunk-V3LJN2GS.js";
4
1
  import {
5
2
  envelopeCodeToStatus
6
3
  } from "../chunk-X32XEJXR.js";
@@ -8,6 +5,9 @@ import {
8
5
  NotFoundError,
9
6
  serverErrorToEnvelope
10
7
  } from "../chunk-UVXB2ER7.js";
8
+ import {
9
+ serveReservedRoute
10
+ } from "../chunk-V3LJN2GS.js";
11
11
  import "../chunk-DGUM43GV.js";
12
12
 
13
13
  // src/server/boot.ts
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -146,48 +146,6 @@ function resolveTransformer(selector) {
146
146
  return selector;
147
147
  }
148
148
 
149
- // src/server/agent/mcp-app-resources.ts
150
- function defineAppResource(input) {
151
- if (!input.uri.startsWith("ui://")) {
152
- throw new Error(
153
- `defineAppResource: uri must use the ui:// scheme (an app UI resource). Got: ${JSON.stringify(input.uri)}`
154
- );
155
- }
156
- if (input.html.length === 0) {
157
- throw new Error(`defineAppResource(${JSON.stringify(input.uri)}): html must be non-empty.`);
158
- }
159
- return {
160
- uri: input.uri,
161
- name: input.name,
162
- mimeType: "text/html",
163
- html: input.html,
164
- ...input.description !== void 0 ? { description: input.description } : {}
165
- };
166
- }
167
- function buildResourceDescriptors(resources) {
168
- return resources.map((r) => ({
169
- uri: r.uri,
170
- name: r.name,
171
- mimeType: r.mimeType,
172
- ...r.description !== void 0 ? { description: r.description } : {}
173
- }));
174
- }
175
- function readAppResource(resources, uri) {
176
- const found = resources.find((r) => r.uri === uri);
177
- if (!found) return null;
178
- return { contents: [{ uri: found.uri, mimeType: "text/html", text: found.html }] };
179
- }
180
- function isAppResource(v) {
181
- if (typeof v !== "object" || v === null) return false;
182
- const r = v;
183
- return typeof r.uri === "string" && r.uri.startsWith("ui://") && r.mimeType === "text/html" && typeof r.html === "string";
184
- }
185
- function extractAppResources(mod) {
186
- const raw = mod?.appResources;
187
- if (!Array.isArray(raw)) return [];
188
- return raw.filter(isAppResource);
189
- }
190
-
191
149
  // src/server/http/validate-route-input.ts
192
150
  function validateRouteInput(config, raw) {
193
151
  let query = raw.query;
@@ -487,159 +445,13 @@ async function runErrorHooks(err, hookCtx, onError) {
487
445
  return mergeHookHeaders(errorResponse, hookCtx.responseHeaders);
488
446
  }
489
447
 
490
- // src/server/agent/mcp-handler.ts
491
- import { compileAgentModule } from "@theokit/agents";
492
- var MCP_PATH = /^\/api\/agents\/([^/]+)\/mcp$/;
493
- var MCP_PROTOCOL_VERSION = "2025-06-18";
494
- function toolDescriptors(tools) {
495
- return tools.map((t) => ({
496
- name: t.name,
497
- description: t.description,
498
- // The compiled tool already carries a JSON Schema (via `z.toJSONSchema()` in defineAgentTool).
499
- // Fall back to a permissive object only when a tool genuinely declared no schema.
500
- inputSchema: t.inputSchema && typeof t.inputSchema === "object" ? t.inputSchema : { type: "object", properties: {} }
501
- }));
502
- }
503
- function isMcpPath(urlPath) {
504
- const match = MCP_PATH.exec(urlPath);
505
- return match ? decodeURIComponent(match[1]) : null;
506
- }
507
- function isJsonRpcRequest(body) {
508
- return typeof body === "object" && body !== null && body.jsonrpc === "2.0" && typeof body.method === "string";
509
- }
510
- function jsonResponse(payload) {
511
- return new Response(JSON.stringify(payload), {
512
- status: 200,
513
- headers: { "content-type": "application/json; charset=utf-8" }
514
- });
515
- }
516
- async function callTool(tools, toolName, args, hitl) {
517
- if (typeof toolName !== "string") {
518
- return {
519
- content: [{ type: "text", text: "tools/call requires a string `name`." }],
520
- isError: true
521
- };
522
- }
523
- const tool = tools.find((t) => t.name === toolName);
524
- if (!tool) {
525
- return { content: [{ type: "text", text: `Unknown tool: ${toolName}` }], isError: true };
526
- }
527
- if (hitl?.has(toolName)) {
528
- return {
529
- content: [
530
- {
531
- type: "text",
532
- text: `Tool "${toolName}" requires human approval, which is not available over MCP. Refused.`
533
- }
534
- ],
535
- isError: true
536
- };
537
- }
538
- try {
539
- const result = await tool.handler(args);
540
- const text = typeof result === "string" ? result : JSON.stringify(result);
541
- return { content: [{ type: "text", text }] };
542
- } catch (err) {
543
- return {
544
- content: [
545
- { type: "text", text: err instanceof Error ? err.message : "Tool execution failed" }
546
- ],
547
- isError: true
548
- };
549
- }
550
- }
551
- function handleResourcesRead(id, params, appResources) {
552
- const uri = params?.uri;
553
- if (typeof uri !== "string") {
554
- return jsonResponse({
555
- jsonrpc: "2.0",
556
- id,
557
- error: { code: -32602, message: "resources/read requires a string `uri` param." }
558
- });
559
- }
560
- const contents = readAppResource(appResources, uri);
561
- if (contents === null) {
562
- return jsonResponse({
563
- jsonrpc: "2.0",
564
- id,
565
- error: { code: -32602, message: `Resource not found: ${uri}` }
566
- });
567
- }
568
- return jsonResponse({ jsonrpc: "2.0", id, result: contents });
569
- }
570
- async function handleMcpJsonRpc(mod, name, body, appResources = []) {
571
- if (!isJsonRpcRequest(body)) {
572
- return jsonResponse({
573
- jsonrpc: "2.0",
574
- id: null,
575
- error: { code: -32600, message: "Invalid Request" }
576
- });
577
- }
578
- const { id, method, params } = body;
579
- try {
580
- const compiled = compileAgentModule(mod, `mcp server for "${name}"`);
581
- if (method === "initialize") {
582
- const capabilities = { tools: {} };
583
- if (appResources.length > 0) capabilities.resources = {};
584
- return jsonResponse({
585
- jsonrpc: "2.0",
586
- id,
587
- result: {
588
- protocolVersion: MCP_PROTOCOL_VERSION,
589
- capabilities,
590
- serverInfo: { name, version: "1.0" }
591
- }
592
- });
593
- }
594
- if (method === "tools/list") {
595
- return jsonResponse({
596
- jsonrpc: "2.0",
597
- id,
598
- result: { tools: toolDescriptors(compiled.tools) }
599
- });
600
- }
601
- if (method === "tools/call") {
602
- const p = params;
603
- const result = await callTool(compiled.tools, p?.name, p?.arguments ?? {}, compiled.hitl);
604
- return jsonResponse({ jsonrpc: "2.0", id, result });
605
- }
606
- if (method === "resources/list") {
607
- return jsonResponse({
608
- jsonrpc: "2.0",
609
- id,
610
- result: { resources: buildResourceDescriptors(appResources) }
611
- });
612
- }
613
- if (method === "resources/read") {
614
- return handleResourcesRead(id, params, appResources);
615
- }
616
- return jsonResponse({
617
- jsonrpc: "2.0",
618
- id,
619
- error: { code: -32601, message: `Method not found: ${method}` }
620
- });
621
- } catch (err) {
622
- return jsonResponse({
623
- jsonrpc: "2.0",
624
- id,
625
- error: { code: -32603, message: err instanceof Error ? err.message : "Internal error" }
626
- });
627
- }
628
- }
629
-
630
448
  export {
631
449
  _resetEnvCache,
632
450
  loadEnv,
633
451
  superjsonTransformer,
634
452
  jsonTransformer,
635
453
  resolveTransformer,
636
- defineAppResource,
637
- buildResourceDescriptors,
638
- readAppResource,
639
- extractAppResources,
640
- isMcpPath,
641
- handleMcpJsonRpc,
642
454
  validateRouteInput,
643
455
  executeWebRequest
644
456
  };
645
- //# sourceMappingURL=chunk-UYFZ6DDW.js.map
457
+ //# sourceMappingURL=chunk-4MTCKE5I.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/load-env.ts","../src/server/transformer.ts","../src/server/http/validate-route-input.ts","../src/server/http/web-middleware-runner.ts","../src/server/web-handler.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Reads `.env` files from a CLI-controlled `cwd`. File names are a fixed\n * literal set. Build-time + CLI tool; no HTTP input.\n */\n/**\n * `loadEnv()` — auto-loads `.env` files into `process.env` for server code.\n *\n * Implements the Next.js `loadEnvConfig` algorithm\n * (`referencias/next.js/packages/next-env/index.ts:114-180`) with TheoKit\n * adaptations:\n *\n * - EC-1: 1MB file-size cap (anti-OOM, anti-supply-chain).\n * - EC-2: `_resetEnvCache()` test-only side-door.\n * - EC-8: `dotenv-expand` circular-ref safe (lib-provided).\n * - EC-13: log when `.env` is a symlink (transparency).\n * - D6: real `process.env` wins over `.env`-file values.\n * - NODE_ENV stash: `.env`-set NODE_ENV NEVER overrides the real\n * `process.env.NODE_ENV`. Stashed in `__THEOKIT_USER_NODE_ENV` instead.\n */\n\nimport { lstatSync, readFileSync, realpathSync, statSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport dotenv from 'dotenv'\nimport { expand, type DotenvPopulateInput } from 'dotenv-expand'\n\nimport type { LoadEnvOptions, LoadEnvResult } from './load-env-types.js'\n\n/** EC-1: 1MB cap. Real `.env`s are < 10KB. */\nconst MAX_ENV_FILE_BYTES = 1_048_576\n\nconst cache = new Map<string, LoadEnvResult>()\n\n/** Test-only side-door for EC-2 — clear the module-level cache between vitest test files. */\nexport function _resetEnvCache(): void {\n cache.clear()\n}\n\nfunction envFilesInPriorityOrder(mode: string): string[] {\n // Top of list = highest priority. Will be read in REVERSE so first-in\n // wins via overwrite during merge.\n const files = [`.env.${mode}.local`, `.env.local`, `.env.${mode}`, `.env`]\n // Test mode skips `.env.local` per dotenv convention (avoid leaking dev\n // secrets into the test suite).\n if (mode === 'test') {\n return files.filter((f) => f !== '.env.local')\n }\n return files\n}\n\nfunction readEnvFile(path: string): Record<string, string> | null {\n let stat\n try {\n stat = statSync(path)\n } catch {\n return null // ENOENT / EACCES → skip\n }\n\n // Allow files + FIFOs (1Password/SOPS pipe support).\n if (!stat.isFile() && !stat.isFIFO()) return null\n\n // EC-1 — anti-OOM cap.\n if (stat.size > MAX_ENV_FILE_BYTES) {\n console.warn(\n `[theokit] .env file at ${path} exceeds ${MAX_ENV_FILE_BYTES} bytes — skipping (likely a generated artifact, not a real env file)`,\n )\n return null\n }\n\n // EC-13 — symlink transparency. Don't refuse; just log.\n try {\n const lstat = lstatSync(path)\n if (lstat.isSymbolicLink()) {\n const real = realpathSync(path)\n // eslint-disable-next-line no-console -- intentional transparency log on a build-time tool\n console.info(`[theokit] .env at ${path} is a symlink → ${real}`)\n }\n } catch {\n // lstat failure is non-fatal — fall through to read.\n }\n\n try {\n const content = readFileSync(path, 'utf-8')\n return dotenv.parse(content)\n } catch {\n return null\n }\n}\n\n// eslint-disable-next-line complexity -- canonical env-load algorithm (priority → expand → guards → apply); inlining branches is clearer than extracting micro-helpers\nexport function loadEnv(options: LoadEnvOptions = {}): LoadEnvResult {\n const cwd = options.cwd ?? process.cwd()\n const mode = options.mode ?? process.env.NODE_ENV ?? 'development'\n const cacheKey = `${cwd}:${mode}`\n\n if (!options.forceReload) {\n const cached = cache.get(cacheKey)\n if (cached) return cached\n }\n\n const fileNames = envFilesInPriorityOrder(mode)\n const filePaths = fileNames.map((f) => resolve(cwd, f))\n\n // Read in REVERSE — lower-priority files first, so higher-priority\n // (lower-index) overwrites during merge.\n const merged: Record<string, string> = {}\n const loadedFromFiles: string[] = []\n for (const path of [...filePaths].reverse()) {\n const parsed = readEnvFile(path)\n if (parsed === null) continue\n for (const [k, v] of Object.entries(parsed)) {\n merged[k] = v\n }\n loadedFromFiles.unshift(path) // keep priority order in result\n }\n\n // NODE_ENV stash — `.env`-set NODE_ENV never overrides real process.env.NODE_ENV.\n if (merged.NODE_ENV && process.env.__THEOKIT_USER_NODE_ENV === undefined) {\n process.env.__THEOKIT_USER_NODE_ENV = merged.NODE_ENV\n }\n delete merged.NODE_ENV // never propagate\n\n // EC-8 — dotenv-expand@11 stack-overflows on circular refs (A=${B}, B=${A}).\n // Wrap in try/catch — on overflow, leave the parsed map untouched (literal\n // values survive). Tested via test_loadEnv_circular_expand_no_loop_EC8.\n // Pass a CLONE of process.env (string-only, filtered) so expand can\n // reference real env without mutating it.\n const processEnvClone: DotenvPopulateInput = {}\n for (const [k, v] of Object.entries(process.env)) {\n if (typeof v === 'string') processEnvClone[k] = v\n }\n try {\n expand({ parsed: merged, processEnv: processEnvClone })\n } catch (err) {\n if (err instanceof RangeError) {\n console.warn(\n `[theokit] .env expansion overflow (likely circular reference like A=\\${B}, B=\\${A}). Leaving values as literals.`,\n )\n } else {\n throw err\n }\n }\n\n // Apply: D6 — real process.env wins over file values.\n const loaded: Record<string, string> = {}\n for (const [k, v] of Object.entries(merged)) {\n if (process.env[k] !== undefined) continue // real env wins\n process.env[k] = v\n loaded[k] = v\n }\n\n // Sentinel\n process.env.__THEOKIT_PROCESSED_ENV = 'true'\n\n const result: LoadEnvResult = { loaded, loadedFromFiles }\n cache.set(cacheKey, result)\n return result\n}\n","import superjson from 'superjson'\n\n/**\n * T5.2 — pluggable response/request transformer.\n *\n * `superjson` is the default, preserving Date/Map/Set/BigInt/etc.\n * `json` is the lightweight option (plain JSON.stringify/parse).\n * Users can supply a custom object implementing this contract.\n */\nexport interface TheoTransformer {\n name: string\n serialize: (value: unknown) => string\n deserialize: (raw: string) => unknown\n}\n\nexport const superjsonTransformer: TheoTransformer = {\n name: 'superjson',\n serialize: (v) => JSON.stringify(superjson.serialize(v)),\n deserialize: (raw) => {\n const parsed = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(parsed)\n },\n}\n\nexport const jsonTransformer: TheoTransformer = {\n name: 'json',\n serialize: (v) => JSON.stringify(v),\n deserialize: (raw) => JSON.parse(raw) as unknown,\n}\n\nconst BUILT_INS: Record<string, TheoTransformer> = {\n superjson: superjsonTransformer,\n json: jsonTransformer,\n}\n\nexport function resolveTransformer(\n selector: 'json' | 'superjson' | TheoTransformer,\n): TheoTransformer {\n if (typeof selector === 'string') {\n // selector is 'json' | 'superjson' literal — both keys exist in\n // BUILT_INS by construction. Type system guarantees a hit; we keep\n // a defensive fallback that the compiler cannot see is unreachable\n // at runtime, just in case someone adds a new literal to the union\n // but forgets to register the built-in.\n const built = BUILT_INS[selector]\n // Defensive: the public union ensures `built` is defined, but if a\n // future contributor extends the union without registering the impl,\n // the cast keeps the failure mode loud.\n if ((built as TheoTransformer | undefined) === undefined) {\n throw new Error(\n `Unknown transformer \"${selector}\". Built-in options: ${Object.keys(BUILT_INS).join(', ')}.`,\n )\n }\n return built\n }\n if (\n typeof selector !== 'object' ||\n typeof selector.serialize !== 'function' ||\n typeof selector.deserialize !== 'function'\n ) {\n throw new Error(\n `Custom transformer must have serialize and deserialize functions. Got: ${JSON.stringify(selector)}`,\n )\n }\n return selector\n}\n","/**\n * M33 — the SINGLE route-input validation pipeline, shared by the HTTP path (`web-handler.ts`\n * `runHandler`) and the in-process caller (`in-process-caller.ts` `callProcedure`).\n *\n * Both surfaces validate the same three channels (`query`/`body`/`params`) against the same\n * `RouteConfig` Zod schemas. Extracting the logic here means there is ONE validation pipeline\n * (no duplication, no drift) — each caller only differs in how it MAPS a failure: the HTTP path\n * emits a 400 Response, the in-process path throws a typed error.\n */\nimport type { z } from 'zod'\n\n/** The three request-input channels a route may declare a Zod schema for. */\nexport type RouteInputChannel = 'query' | 'body' | 'params'\n\n/**\n * The minimal structural shape the validator needs: the three optional channel schemas. Both\n * `RouteConfig` (the 5-arity generic contract) and `WebRouteHandlerConfig` (the Web runtime shape)\n * satisfy this — the validator depends only on the schemas, not the full route generic.\n */\nexport interface RouteInputSchemas {\n query?: z.ZodType\n body?: z.ZodType\n params?: z.ZodType\n}\n\n/** Raw (pre-validation) channel values. A channel absent from the config passes through unchanged. */\nexport interface RawRouteInput {\n query?: unknown\n body?: unknown\n params?: unknown\n}\n\n/** Discriminated result — each caller maps `ok:false` to its own surface (Response vs throw). */\nexport type RouteInputValidation =\n | { ok: true; query: unknown; body: unknown; params: unknown }\n | { ok: false; channel: RouteInputChannel; error: z.ZodError }\n\n/**\n * Validate the three input channels against the route's declared Zod schemas. A channel with no\n * declared schema passes its raw value through. First failing channel short-circuits (query → body\n * → params order, matching `runHandler`).\n */\nexport function validateRouteInput(\n config: RouteInputSchemas,\n raw: RawRouteInput,\n): RouteInputValidation {\n let query: unknown = raw.query\n if (config.query !== undefined) {\n const parsed = config.query.safeParse(raw.query)\n if (!parsed.success) return { ok: false, channel: 'query', error: parsed.error }\n query = parsed.data\n }\n let body: unknown = raw.body\n if (config.body !== undefined) {\n const parsed = config.body.safeParse(raw.body)\n if (!parsed.success) return { ok: false, channel: 'body', error: parsed.error }\n body = parsed.data\n }\n let params: unknown = raw.params\n if (config.params !== undefined) {\n const parsed = config.params.safeParse(raw.params)\n if (!parsed.success) return { ok: false, channel: 'params', error: parsed.error }\n params = parsed.data\n }\n return { ok: true, query, body, params }\n}\n","/**\n * T3.2 — Web-Standards middleware runner for the `executeWebRequest` path.\n *\n * The Node request path (`http/execute.ts`) runs middleware via\n * `runMiddlewareAndContext`, which is coupled to Node `req`/`res`. Per G8\n * (Web Standards over Node APIs) the Web path needs a `Request`-shaped runner;\n * this is it. Extracted to a sibling so `web-handler.ts` stays under its LoC\n * budget (G6).\n *\n * Ordering invariant (EC-3): the caller runs the CSRF gate BEFORE invoking this\n * runner, mirroring the Node path (CSRF stage precedes user middleware).\n *\n * NOTE (D4 / EC-12): this is its own middleware contract — `(request, context)`.\n * Full semantic parity with the Node `defineMiddleware` contract is part of the\n * deferred Node→Web pipeline convergence, not this slice.\n */\n\n/** A Web-path middleware: mutate `context`, or return a `Response` to short-circuit. */\nexport type WebMiddleware = (\n request: Request,\n context: Record<string, unknown>,\n // A middleware may mutate `context` and return nothing (void) OR return a\n // `Response` to short-circuit (Express/Koa-style). `void` in this union is\n // intentional — `runWebMiddleware` only inspects `instanceof Response`, so a\n // void return means \"continue to the next middleware / handler\".\n // eslint-disable-next-line @typescript-eslint/no-invalid-void-type\n) => Promise<Response | undefined> | Response | undefined | void\n\n/**\n * Run middleware in order against a shared mutable `context`. The first\n * middleware that returns a `Response` short-circuits the chain (the handler\n * is not reached); its `Response` is returned verbatim so headers like\n * `Set-Cookie` are preserved (EC-11). Returns `undefined` when every\n * middleware passes (the handler should run next).\n */\nexport async function runWebMiddleware(\n request: Request,\n middleware: readonly WebMiddleware[],\n context: Record<string, unknown>,\n): Promise<Response | undefined> {\n for (const mw of middleware) {\n const result = await mw(request, context)\n if (result instanceof Response) return result\n }\n return undefined\n}\n","/**\n * T5a.2 Phase A — Foundation: Web-Standards request handler entry-point.\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase A. Bridges the gap between Web `Request`/`Response` and the\n * existing `defineRoute` config shape (which is consumed today by the Node-\n * shaped `executeRoute`).\n *\n * This is the entry-point T1.2 RED tests expect:\n * `executeWebRequest(request: Request, routeModule: { GET?, POST?, ... }): Promise<Response>`\n *\n * Architecture per ADR-0028 (R3a) — this function accepts a native Web\n * `Request` and returns a native Web `Response`. No `node:*` is required in\n * the implementation (Zod + native Headers/URL/Response cover the surface).\n *\n * **Scope (intentionally narrow):**\n * - Method dispatch (GET/POST/PUT/PATCH/DELETE).\n * - Zod validation for `query` (from URL.searchParams), `body` (from\n * request.json() OR request.text()), `params` (consumer-supplied OR\n * parsed from path).\n * - Handler invocation.\n * - Result → JSON Response (200 default, 204 for void return).\n * - Error → envelope-shaped JSON Response (400 for validation, 500 for\n * handler throws) per G5 boundary translation (serverErrorToEnvelope).\n *\n * **NOT included (deferred to T5a.2 Phase B-G):**\n * - Plugin runner integration (onRequest/preHandler/onResponse hooks).\n * - CSRF / CORS / security headers / rate limiting / cookies / auth.\n * - Middleware chain. SSR rendering. WebSocket upgrade. File upload.\n * - File-system routing scan; consumer provides the route module\n * explicitly (Web Request entry doesn't yet know about scan results).\n *\n * The narrow scope makes this a viable Phase A landing zone — turns the\n * 7 T1.2 RED tests GREEN without prematurely refactoring the full\n * IncomingMessage→Request boundary across server/http/ files.\n */\nimport type { z } from 'zod'\n\nimport { envelopeCodeToStatus } from '../core/contracts/envelope-code-to-status.js'\nimport type { TheoErrorEnvelope } from '../core/contracts/error-envelope.js'\nimport { serverErrorToEnvelope } from '../core/contracts/server-error-to-envelope.js'\nimport { TheoError } from '../core/contracts/theo-error.js'\n\nimport { isZodLike } from './http/execute-stages.js'\nimport { validateRouteInput } from './http/validate-route-input.js'\nimport { runWebMiddleware, type WebMiddleware } from './http/web-middleware-runner.js'\nimport type {\n WebOnErrorHook,\n WebOnRequestHook,\n WebOnResponseHook,\n WebPluginContext,\n WebPluginErrorContext,\n WebPreHandlerHook,\n} from './plugin-types.js'\nimport { validateCsrfRequest } from './security/csrf.js'\n\nexport type { WebMiddleware }\n\n/**\n * Minimal structural type for a `defineRoute` config. Mirrors\n * `core/contracts/route-config.ts` shape but only the fields this entry\n * point needs at runtime (Zod schemas + handler). Kept structural to\n * avoid a hard dep on the full RouteConfig generic chain.\n */\ninterface WebRouteHandlerConfig {\n query?: z.ZodType\n body?: z.ZodType\n params?: z.ZodType\n /** Optional Zod schema validating a plain-object handler return (D1/D2). */\n response?: z.ZodType\n /** Honored for plain-object returns to match the Node runner (D3). */\n status?: number\n handler: (ctx: {\n query: unknown\n body: unknown\n params: unknown\n request: Request\n /** Mutable per-request context populated by the Web middleware chain (T3.2). */\n context: Record<string, unknown>\n }) => unknown\n}\n\n/**\n * The route module exported by a `server/routes/*.ts` file (after T2.6 G6\n * router lockdown). Method-named exports map to `defineRoute` results.\n */\ntype WebRouteModule = Partial<Record<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', unknown>>\n\n/**\n * Coerce URL.searchParams into a plain `{ key: value }` object so Zod\n * `z.object({...})` schemas work without per-route adapters. Repeated keys\n * become arrays (most browsers serialize multi-select that way).\n */\nfunction searchParamsToObject(params: URLSearchParams): Record<string, string | string[]> {\n const out: Record<string, string | string[]> = {}\n for (const [key, value] of params.entries()) {\n if (!Object.hasOwn(out, key)) {\n out[key] = value\n continue\n }\n const existing = out[key]\n if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n out[key] = [existing, value]\n }\n }\n return out\n}\n\n/**\n * Parse request body based on Content-Type. JSON is the canonical path;\n * empty body returns `undefined` (the handler treats as \"no body\").\n *\n * **Inline-only mode (default):** handles `application/json` and `text/*`.\n * Other content-types return `undefined`. Multipart/form-data requires\n * the opt-in `bodyParser: 'full'` mode (T5a.2 Phase E).\n */\nasync function parseBodyInline(request: Request): Promise<unknown> {\n // GET/HEAD have no body by spec; even if the consumer sets one, ignore it\n // (matches Web Request semantics — `body` is null for GET/HEAD anyway).\n if (request.method === 'GET' || request.method === 'HEAD') return undefined\n const contentType = request.headers.get('content-type') ?? ''\n if (contentType.includes('application/json')) {\n const text = await request.text()\n if (text.length === 0) return undefined\n try {\n return JSON.parse(text)\n } catch {\n // Malformed JSON — return undefined; Zod schema (if any) will fail with\n // a more useful \"required\" message than a raw SyntaxError.\n return undefined\n }\n }\n // text/plain or no body: return raw text or undefined\n if (contentType.startsWith('text/')) {\n const text = await request.text()\n return text.length === 0 ? undefined : text\n }\n return undefined\n}\n\n/**\n * T5a.2 Phase E — \"full\" body parser delegating to `parseWebRequestBody`.\n * Returns a `ParsedWebBody` (`{ json?, fields, files }`) for JSON OR\n * multipart, or `undefined` when the body is empty / unparseable.\n *\n * Handler downstream pattern:\n * `body?.json` (JSON requests)\n * `body?.fields` + `body?.files` (multipart upload requests)\n *\n * Limits enforced by parseWebRequestBody:\n * - declared Content-Length cap (default 10MB × maxFiles + 1MB margin)\n * - per-file size cap (default 10MB)\n * - max files (default 10)\n */\nasync function parseBodyFull(request: Request): Promise<unknown> {\n if (request.method === 'GET' || request.method === 'HEAD') return undefined\n const { parseWebRequestBody } = await import('./body-parser-web.js')\n try {\n const parsed = await parseWebRequestBody(request)\n // If nothing parsed (empty body OR unhandled content-type), return undefined\n // so Zod schemas treat it as missing — same semantics as inline parser.\n if (\n parsed.json === undefined &&\n Object.keys(parsed.fields).length === 0 &&\n parsed.files.length === 0\n ) {\n return undefined\n }\n return parsed\n } catch {\n return undefined\n }\n}\n\n/**\n * Build an envelope-shaped 400 Response for a Zod validation failure. Uses\n * the canonical `TheoErrorEnvelope` shape per G5 D3 (boundary translation).\n */\nfunction validationErrorResponse(zodError: z.ZodError, field: string): Response {\n const envelope: TheoErrorEnvelope = {\n code: 'BAD_REQUEST',\n message: `Validation failed: ${field}`,\n ext: {\n fields: zodError.issues.map((issue) => ({\n path: issue.path.join('.'),\n message: issue.message,\n })),\n },\n }\n return new Response(JSON.stringify(envelope), {\n status: 400,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * Run a `defineRoute` config against a parsed Web Request. Returns the raw\n * handler result; serialization to Response happens in the caller.\n *\n * Throws if Zod validation fails (caller catches and emits 400).\n */\nasync function runHandler(\n config: WebRouteHandlerConfig,\n request: Request,\n bodyParser: 'inline' | 'full' = 'inline',\n paramsInput: Record<string, string> = {},\n context: Record<string, unknown> = {},\n): Promise<{ ok: true; result: unknown } | { ok: false; response: Response }> {\n const url = new URL(request.url)\n const queryRaw = searchParamsToObject(url.searchParams)\n const bodyRaw =\n bodyParser === 'full' ? await parseBodyFull(request) : await parseBodyInline(request)\n // T3.1 — route params resolved upstream (matchRoute) and threaded via\n // opts.params. Defaults to `{}` so callers that don't supply params keep the\n // prior behavior (a route declaring config.params then fails validation).\n const paramsRaw = paramsInput\n\n // M33 — validate the three input channels via the SINGLE shared pipeline (`validateRouteInput`),\n // the same one the in-process caller (`callProcedure`) uses. The HTTP path maps a failure to a\n // 400 Response; the in-process path throws. One pipeline, no drift.\n const validated = validateRouteInput(config, {\n query: queryRaw,\n body: bodyRaw,\n params: paramsRaw,\n })\n if (!validated.ok) {\n return { ok: false, response: validationErrorResponse(validated.error, validated.channel) }\n }\n const { query, body, params } = validated\n\n const result = await config.handler({ query, body, params, request, context })\n return validateResponseOutput(config.response, result) ?? { ok: true, result }\n}\n\n/**\n * Validate a plain-object handler return against `config.response` (D1/D2). A\n * mismatch is a SERVER fault → 500 envelope. `Response`-instance returns and\n * `undefined`/`null` (→ 204) skip validation — parity with the Node runner,\n * which validates only in its plain-object branch. Returns `undefined` when no\n * validation applies (caller forwards the raw result).\n */\nfunction validateResponseOutput(\n response: unknown,\n result: unknown,\n): { ok: true; result: unknown } | { ok: false; response: Response } | undefined {\n const validatable = result !== undefined && result !== null && !(result instanceof Response)\n if (!validatable || !isZodLike(response)) return undefined\n const parsed = response.safeParse(result)\n if (parsed.success) return { ok: true, result: parsed.data }\n const err = new TheoError({\n code: 'INTERNAL_SERVER_ERROR',\n message: 'response validation failed',\n ext: { issues: parsed.error?.issues },\n })\n return { ok: false, response: handlerErrorResponse(err) }\n}\n\n/**\n * Serialize a handler return value into a native Web `Response`. Conventions:\n * - `undefined` / `void` → 204 No Content.\n * - existing `Response` instance → pass through unchanged.\n * - everything else → 200 JSON.\n */\nfunction toResponse(result: unknown, status?: number): Response {\n if (result === undefined) {\n return new Response(null, { status: 204 })\n }\n if (result instanceof Response) {\n return result\n }\n return new Response(JSON.stringify(result), {\n status: status ?? 200,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * Build an envelope-shaped 500 Response when a handler throws. Uses\n * `serverErrorToEnvelope` so existing ad-hoc Error classes (AuthRequired,\n * FileTooLarge, etc.) get mapped to canonical envelope codes.\n */\nfunction handlerErrorResponse(err: unknown): Response {\n const envelope = serverErrorToEnvelope(err)\n // Map envelope code → HTTP status when possible. Default to 500 for\n // INTERNAL_SERVER_ERROR. Other codes map per HTTP semantics.\n const status = envelopeCodeToStatus(envelope.code)\n return new Response(JSON.stringify(envelope), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n// envelopeCodeToStatus extracted to core/contracts/envelope-code-to-status.ts\n// (architecture-remediation T1.2, 2026-06-12)\n\n/**\n * Optional behavior knobs for `executeWebRequest`. Each knob defaults to\n * the safe \"no-op\" stance so existing Phase A consumers (T1.2 fixture\n * tests) keep working unchanged.\n *\n * **`csrfMode`** (T5a.2 Phase B slice 1/6) — when set to `'strict'`, the\n * Web-Standards request gate runs `validateCsrfRequest` BEFORE method\n * dispatch on state-changing methods (POST/PUT/PATCH/DELETE) and emits a\n * `403 FORBIDDEN` envelope when the check fails. Default: `'off'` (no\n * CSRF enforcement) to preserve Phase A backward compat. Production\n * consumers SHOULD pass `csrfMode: 'strict'`.\n *\n * Per the T5a.2 plan v1.0 § Phase B header-only leaves: csrf.ts is the\n * first leaf to be migrated (slice 1/6); 5 more sibling leaves remain\n * (csrf-multi-header, csrf-readiness-endpoint, csp-report, cors, cookies).\n */\nexport interface ExecuteWebRequestOptions {\n csrfMode?: 'off' | 'strict'\n /**\n * T3.1 — route params resolved upstream by `matchRoute` (e.g. `{ id: '42' }`\n * for `/users/:id`). Threaded to the handler's `params` input and validated\n * against `config.params` (Zod) when declared. Defaults to `{}` — callers\n * that don't supply params keep the prior behavior (additive, backward-compat).\n */\n params?: Record<string, string>\n /**\n * T3.2 — Web-Standards middleware chain. Runs in order AFTER the CSRF gate\n * (EC-3) and BEFORE the handler. A middleware returning a `Response`\n * short-circuits (handler not reached); mutating `context` passes data to\n * the handler. Omitted → zero overhead (handler runs directly).\n */\n middleware?: readonly WebMiddleware[]\n /**\n * T5a.2 Phase E — body parser strategy.\n *\n * - `'inline'` (default): handle `application/json` + `text/*` only.\n * Returns the parsed value (object for JSON, string for text). Other\n * content-types (e.g., multipart) return `undefined`.\n * - `'full'`: delegate to `parseWebRequestBody` for multipart support\n * + per-file size caps + max-files cap (Web Standards `request.formData()`\n * under the hood). Returns a `ParsedWebBody` object:\n * `{ json?, fields, files }`. Multipart consumers MUST opt into this\n * mode; JSON-only routes pay zero cost staying on `'inline'`.\n */\n bodyParser?: 'inline' | 'full'\n /**\n * T5a.2 Phase G slice 1/N — plugin lifecycle hooks.\n *\n * Adapters (Node, CF Workers, Bun, Deno) wire `WebPluginContext`-shaped\n * hooks at the executeWebRequest lifecycle. Lifecycle order mirrors the\n * Fastify / Hono convention:\n *\n * 1. CSRF check (when opts.csrfMode === 'strict')\n * 2. onRequest — earliest, before body parsing. Plugins can short-circuit\n * by setting `ctx.response` (handler skipped; subsequent hooks see\n * the short-circuit response).\n * 3. body parse (inline OR full per opts.bodyParser)\n * 4. preHandler — after body parsed, before handler runs. Same\n * short-circuit semantic.\n * 5. handler invocation\n * 6. onResponse — after handler returns OR after a hook short-circuit.\n * `ctx.response` is populated.\n * 7. onError — fires if any of (handler, onRequest, preHandler) throws.\n * `ctx.response` is the envelope-shaped error response built via\n * serverErrorToEnvelope.\n *\n * `responseHeaders` is shared across hooks; the final Response merges\n * them with the handler's Response headers (handler headers win on\n * conflict; hook headers add new ones). Decorations made via\n * `ctx.ctx[key] = value` persist across hooks (request-scoped state).\n *\n * `hooks: undefined` (default) → no plugin lifecycle, Phase A behavior\n * preserved. Production consumers wire via the WebPluginRunner facade\n * (a future Phase G slice).\n */\n hooks?: {\n onRequest?: readonly WebOnRequestHook[]\n preHandler?: readonly WebPreHandlerHook[]\n onResponse?: readonly WebOnResponseHook[]\n onError?: readonly WebOnErrorHook[]\n }\n /**\n * Stable request identifier propagated into hook contexts. Adapters\n * resolve via traceparent / x-request-id / generated UUID (see\n * `extractTraceIdFromRequest` from Phase C slice 1/2). Default:\n * `globalThis.crypto.randomUUID()`.\n */\n requestId?: string\n}\n\n/**\n * Methods that require CSRF enforcement when `csrfMode: 'strict'`. GET\n * and HEAD are read-only per HTTP semantics and bypass CSRF (the threat\n * model is state-changing requests forged via cross-origin POSTs); OPTIONS\n * is the CORS preflight and also bypasses.\n */\nexport const CSRF_PROTECTED_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Web-Standards entry-point for executing a route module against a native\n * Web `Request`. Returns a native Web `Response`.\n *\n * Method dispatch: looks up the handler keyed by `request.method`\n * (uppercase). Returns 405 if the method isn't exported.\n *\n * @example\n * import * as users from './app/users/route.js'\n * import { executeWebRequest } from 'theokit/server'\n *\n * const response = await executeWebRequest(\n * new Request('http://localhost/api/users', { method: 'GET' }),\n * users,\n * { csrfMode: 'strict' },\n * )\n */\n/**\n * T5a.2 Phase G slice 1/N — merge hook-mutated response headers into the\n * handler's Response. Handler-set headers win on conflict (the handler\n * has the most context about its own response); hook headers add new\n * entries (e.g., CORS, Set-Cookie). Returns a new Response with the\n * merged headers + same body/status as the source.\n *\n * Set-Cookie is multi-value at the Web spec layer — `getSetCookie()` is\n * the only way to retrieve multiple values. The merge appends ALL hook-\n * set Set-Cookie values to the response (multiple Set-Cookie headers is\n * spec-correct and how browsers expect cookie issuance).\n */\nfunction mergeHookHeaders(response: Response, hookHeaders: Headers): Response {\n if ([...hookHeaders].length === 0) return response\n const merged = new Headers(response.headers)\n for (const [k, v] of hookHeaders.entries()) {\n if (k.toLowerCase() === 'set-cookie') continue // handled separately\n if (!merged.has(k)) merged.set(k, v)\n }\n for (const sc of hookHeaders.getSetCookie()) {\n merged.append('Set-Cookie', sc)\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: merged,\n })\n}\n\n/** Build a 405 envelope Response. */\nfunction methodNotAllowedResponse(method: string): Response {\n const envelope: TheoErrorEnvelope = {\n code: 'METHOD_NOT_ALLOWED',\n message: `Method ${method} not allowed`,\n }\n return new Response(JSON.stringify(envelope), {\n status: 405,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/** Build a 403 CSRF envelope Response. */\nfunction csrfFailedResponse(reason: string): Response {\n const envelope: TheoErrorEnvelope = {\n code: 'FORBIDDEN',\n message: `CSRF check failed: ${reason}`,\n }\n return new Response(JSON.stringify(envelope), {\n status: 403,\n headers: { 'content-type': 'application/json' },\n })\n}\n\nexport async function executeWebRequest(\n request: Request,\n routeModule: WebRouteModule,\n opts: ExecuteWebRequestOptions = {},\n): Promise<Response> {\n const method = request.method.toUpperCase() as keyof WebRouteModule\n const config = routeModule[method] as WebRouteHandlerConfig | undefined\n\n // T5a.2 Phase G slice 1/N — plugin lifecycle hooks.\n // When opts.hooks is undefined, skip the entire hook orchestration to\n // preserve Phase A backward compat (zero overhead for consumers not\n // wiring hooks). In the no-hooks branch, dispatch + CSRF gates run\n // FIRST and 405 short-circuits before the handler runs.\n if (opts.hooks === undefined) {\n if (config === undefined || typeof config.handler !== 'function') {\n return methodNotAllowedResponse(method)\n }\n if (opts.csrfMode === 'strict' && CSRF_PROTECTED_METHODS.has(method)) {\n const csrfCheck = validateCsrfRequest(request)\n if (!csrfCheck.valid) return csrfFailedResponse(csrfCheck.reason)\n }\n try {\n // T3.2 — middleware runs AFTER the CSRF gate (EC-3), BEFORE the handler.\n const context: Record<string, unknown> = {}\n if (opts.middleware?.length) {\n const shortCircuit = await runWebMiddleware(request, opts.middleware, context)\n if (shortCircuit) return shortCircuit\n }\n const outcome = await runHandler(\n config,\n request,\n opts.bodyParser ?? 'inline',\n opts.params ?? {},\n context,\n )\n if (!outcome.ok) return outcome.response\n return toResponse(outcome.result, config.status)\n } catch (err) {\n return handlerErrorResponse(err)\n }\n }\n\n // With hooks: onRequest hooks run BEFORE method dispatch (Hono /\n // Fastify convention) so CORS preflight plugins can intercept OPTIONS\n // requests regardless of route shape. If no hook short-circuits, then\n // 405 fires when the method isn't exported by the route module.\n return runWithHooks(request, config, opts, opts.hooks)\n}\n\n/**\n * Run the request through the full plugin lifecycle. Extracted to keep\n * `executeWebRequest`'s cyclomatic + cognitive complexity under the lint\n * caps (15/20). Pure side-effect surface — same return type as the\n * no-hooks branch.\n */\n/**\n * Pre-handler pipeline: onRequest hooks → CSRF gate → preHandler hooks →\n * method dispatch + handler. Mutates `hookCtx.response` on short-circuit\n * OR on handler completion. Extracted from `runWithHooks` to keep the\n * latter's cyclomatic complexity under the lint cap (15).\n */\nasync function runPreHandlerPipeline(\n hookCtx: WebPluginContext,\n request: Request,\n config: WebRouteHandlerConfig | undefined,\n opts: ExecuteWebRequestOptions,\n hooks: NonNullable<ExecuteWebRequestOptions['hooks']>,\n): Promise<void> {\n const method = request.method.toUpperCase()\n const runList = async (list: readonly WebOnRequestHook[]): Promise<void> => {\n for (const hook of list) {\n if (hookCtx.response !== undefined) return\n await hook(hookCtx)\n }\n }\n // onRequest first (CORS preflight + auth gate intercept before dispatch).\n if (hooks.onRequest) await runList(hooks.onRequest)\n // CSRF gate AFTER onRequest (auth-short-circuit avoids CSRF cost) but\n // BEFORE the handler.\n if (\n hookCtx.response === undefined &&\n opts.csrfMode === 'strict' &&\n CSRF_PROTECTED_METHODS.has(method)\n ) {\n const csrfCheck = validateCsrfRequest(request)\n if (!csrfCheck.valid) hookCtx.response = csrfFailedResponse(csrfCheck.reason)\n }\n if (hookCtx.response === undefined && hooks.preHandler) {\n await runList(hooks.preHandler)\n }\n if (hookCtx.response === undefined) {\n await runHandlerStage(hookCtx, request, config, opts, method)\n }\n}\n\n/**\n * T3.2 — the middleware + handler stage of the hook pipeline. Extracted from\n * `runPreHandlerPipeline` to keep its cyclomatic complexity under the lint cap.\n * Order: 405 check → user middleware (after CSRF + preHandler) → handler.\n */\nasync function runHandlerStage(\n hookCtx: WebPluginContext,\n request: Request,\n config: WebRouteHandlerConfig | undefined,\n opts: ExecuteWebRequestOptions,\n method: string,\n): Promise<void> {\n // 405 if route module doesn't export this method.\n if (config === undefined || typeof config.handler !== 'function') {\n hookCtx.response = methodNotAllowedResponse(method)\n return\n }\n // hookCtx.ctx is the shared per-request context the middleware mutates.\n if (opts.middleware?.length) {\n const shortCircuit = await runWebMiddleware(request, opts.middleware, hookCtx.ctx)\n if (shortCircuit) {\n hookCtx.response = shortCircuit\n return\n }\n }\n const outcome = await runHandler(\n config,\n request,\n opts.bodyParser ?? 'inline',\n opts.params ?? {},\n hookCtx.ctx,\n )\n hookCtx.response = outcome.ok ? toResponse(outcome.result, config.status) : outcome.response\n}\n\nasync function runWithHooks(\n request: Request,\n config: WebRouteHandlerConfig | undefined,\n opts: ExecuteWebRequestOptions,\n hooks: NonNullable<ExecuteWebRequestOptions['hooks']>,\n): Promise<Response> {\n const hookCtx: WebPluginContext = {\n request,\n responseHeaders: new Headers(),\n ctx: {},\n requestId: opts.requestId ?? globalThis.crypto.randomUUID(),\n }\n try {\n await runPreHandlerPipeline(hookCtx, request, config, opts, hooks)\n if (hooks.onResponse) {\n for (const hook of hooks.onResponse) {\n await hook(hookCtx)\n }\n }\n // runPreHandlerPipeline guarantees hookCtx.response is set (via either\n // a hook short-circuit OR handler outcome OR 405). TS doesn't infer this\n // post-mutation; the assertion is safe per the function's contract.\n const finalResponse =\n hookCtx.response ??\n new Response(\n JSON.stringify({ code: 'INTERNAL_SERVER_ERROR', message: 'No response built' }),\n {\n status: 500,\n headers: { 'content-type': 'application/json' },\n },\n )\n return mergeHookHeaders(finalResponse, hookCtx.responseHeaders)\n } catch (err) {\n return runErrorHooks(err, hookCtx, hooks.onError)\n }\n}\n\n/**\n * Run onError hooks against an envelope-shaped error response. EC-9 —\n * each hook throw is swallowed to avoid error-in-error-handler recursion.\n * Returns the merged final Response.\n */\nasync function runErrorHooks(\n err: unknown,\n hookCtx: WebPluginContext,\n onError: readonly WebOnErrorHook[] | undefined,\n): Promise<Response> {\n const errorResponse = handlerErrorResponse(err)\n if (onError !== undefined) {\n const errorCtx: WebPluginErrorContext = {\n ...hookCtx,\n response: errorResponse,\n error: err,\n }\n for (const hook of onError) {\n try {\n await hook(errorCtx)\n } catch {\n // EC-9: error in error handler — swallow to avoid recursion.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