@theokit/http 0.5.4 → 0.6.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/LICENSE +201 -0
- package/dist/app.d.ts +16 -0
- package/dist/app.js +1 -1
- package/dist/{chunk-34KOKJ5M.js → chunk-6W4T4DPJ.js} +2 -2
- package/dist/{chunk-U46H4CGF.js → chunk-ELCXHPAD.js} +2 -2
- package/dist/{chunk-NDD7ANXZ.js → chunk-GQ2UH554.js} +122 -4
- package/dist/chunk-GQ2UH554.js.map +1 -0
- package/dist/{chunk-LKNI6QEP.js → chunk-MQAJWR3K.js} +1 -1
- package/dist/chunk-MQAJWR3K.js.map +1 -0
- package/dist/chunk-RC4V75DI.js +257 -0
- package/dist/chunk-RC4V75DI.js.map +1 -0
- package/dist/{exception-filter-chain-BCSQ3MZ2.js → exception-filter-chain-O45FXGEB.js} +3 -3
- package/dist/index.d.ts +280 -5
- package/dist/index.js +196 -18
- package/dist/index.js.map +1 -1
- package/dist/interceptor-chain-ELSL6KZT.js +9 -0
- package/dist/{middleware-consumer-ljxK1fU_.d.ts → middleware-consumer-DcaksawH.d.ts} +1 -1
- package/dist/theokit-plugin.d.ts +1 -1
- package/dist/theokit-plugin.js +5 -165
- package/dist/theokit-plugin.js.map +1 -1
- package/package.json +19 -17
- package/dist/chunk-LKNI6QEP.js.map +0 -1
- package/dist/chunk-LWCNTZN6.js +0 -87
- package/dist/chunk-LWCNTZN6.js.map +0 -1
- package/dist/chunk-NDD7ANXZ.js.map +0 -1
- package/dist/interceptor-chain-6S3PUV7J.js +0 -9
- /package/dist/{chunk-34KOKJ5M.js.map → chunk-6W4T4DPJ.js.map} +0 -0
- /package/dist/{chunk-U46H4CGF.js.map → chunk-ELCXHPAD.js.map} +0 -0
- /package/dist/{exception-filter-chain-BCSQ3MZ2.js.map → exception-filter-chain-O45FXGEB.js.map} +0 -0
- /package/dist/{interceptor-chain-6S3PUV7J.js.map → interceptor-chain-ELSL6KZT.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.
|
package/dist/app.d.ts
CHANGED
|
@@ -39,11 +39,26 @@ interface TheoAppOptions {
|
|
|
39
39
|
healthPath?: string;
|
|
40
40
|
/** Custom readiness endpoint path (default: '/__theo/ready'). */
|
|
41
41
|
readyPath?: string;
|
|
42
|
+
/**
|
|
43
|
+
* Enable streaming SSR via `renderToReadableStream` (default: false).
|
|
44
|
+
*
|
|
45
|
+
* When `true` AND `root` is provided, the app serves GET / with a streamed
|
|
46
|
+
* HTML response instead of a static `renderToString` result. This enables
|
|
47
|
+
* progressive rendering with React Suspense boundaries.
|
|
48
|
+
*
|
|
49
|
+
* **EC-7 — Error handling difference:** In streaming mode, errors inside
|
|
50
|
+
* Suspense boundaries are caught by React's streaming error handler and
|
|
51
|
+
* activate client-side error boundaries (the shell is already sent). In
|
|
52
|
+
* string mode, errors throw synchronously before any bytes are sent,
|
|
53
|
+
* allowing a full 500 error page.
|
|
54
|
+
*/
|
|
55
|
+
streaming?: boolean;
|
|
42
56
|
}
|
|
43
57
|
declare class TheoApp {
|
|
44
58
|
private serverHandle;
|
|
45
59
|
private readonly routes;
|
|
46
60
|
private frontendHtml?;
|
|
61
|
+
private streamingRoot?;
|
|
47
62
|
private staticHandler?;
|
|
48
63
|
private readonly startTime;
|
|
49
64
|
private readonly healthPath;
|
|
@@ -65,6 +80,7 @@ declare class TheoApp {
|
|
|
65
80
|
private handleReadinessCheck;
|
|
66
81
|
private createFallbackStream;
|
|
67
82
|
private handleRequest;
|
|
83
|
+
private handleRequestInContext;
|
|
68
84
|
private findRoute;
|
|
69
85
|
private buildArgs;
|
|
70
86
|
}
|
package/dist/app.js
CHANGED
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
} from "./chunk-3PGQVQWG.js";
|
|
6
6
|
import {
|
|
7
7
|
resolveOrNew
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-MQAJWR3K.js";
|
|
9
9
|
import {
|
|
10
10
|
__name
|
|
11
11
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -68,4 +68,4 @@ __name(globalFallback, "globalFallback");
|
|
|
68
68
|
export {
|
|
69
69
|
runExceptionFilters
|
|
70
70
|
};
|
|
71
|
-
//# sourceMappingURL=chunk-
|
|
71
|
+
//# sourceMappingURL=chunk-6W4T4DPJ.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveOrNew
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-MQAJWR3K.js";
|
|
4
4
|
import {
|
|
5
5
|
__name
|
|
6
6
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -31,4 +31,4 @@ __name(runInterceptors, "runInterceptors");
|
|
|
31
31
|
export {
|
|
32
32
|
runInterceptors
|
|
33
33
|
};
|
|
34
|
-
//# sourceMappingURL=chunk-
|
|
34
|
+
//# sourceMappingURL=chunk-ELCXHPAD.js.map
|
|
@@ -16,6 +16,26 @@ import {
|
|
|
16
16
|
// src/app.ts
|
|
17
17
|
import "reflect-metadata";
|
|
18
18
|
|
|
19
|
+
// src/request-context.ts
|
|
20
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
21
|
+
var storage = new AsyncLocalStorage();
|
|
22
|
+
function getRequestContext() {
|
|
23
|
+
const ctx = storage.getStore();
|
|
24
|
+
if (!ctx) {
|
|
25
|
+
throw new Error("getRequestContext() called outside a request. This function is only available inside TheoApp request handlers (controllers, guards, interceptors, filters, agents).");
|
|
26
|
+
}
|
|
27
|
+
return ctx;
|
|
28
|
+
}
|
|
29
|
+
__name(getRequestContext, "getRequestContext");
|
|
30
|
+
function tryGetRequestContext() {
|
|
31
|
+
return storage.getStore() ?? null;
|
|
32
|
+
}
|
|
33
|
+
__name(tryGetRequestContext, "tryGetRequestContext");
|
|
34
|
+
async function runWithRequestContext(ctx, fn) {
|
|
35
|
+
return storage.run(ctx, fn);
|
|
36
|
+
}
|
|
37
|
+
__name(runWithRequestContext, "runWithRequestContext");
|
|
38
|
+
|
|
19
39
|
// src/static.ts
|
|
20
40
|
var MIME_TYPES = {
|
|
21
41
|
// Text
|
|
@@ -191,6 +211,81 @@ function createStaticHandler(options) {
|
|
|
191
211
|
}
|
|
192
212
|
__name(createStaticHandler, "createStaticHandler");
|
|
193
213
|
|
|
214
|
+
// src/stream-renderer.ts
|
|
215
|
+
var DOCTYPE = "<!DOCTYPE html>";
|
|
216
|
+
var encoder = new TextEncoder();
|
|
217
|
+
async function renderToStream(options) {
|
|
218
|
+
const { root, waitForAll = false } = options;
|
|
219
|
+
const reactDomServer = await import("react-dom/server");
|
|
220
|
+
if (typeof reactDomServer.renderToReadableStream === "function") {
|
|
221
|
+
return renderWithReadableStream(reactDomServer.renderToReadableStream, root, waitForAll);
|
|
222
|
+
}
|
|
223
|
+
if (typeof reactDomServer.renderToString === "function") {
|
|
224
|
+
console.warn("[theokit] renderToReadableStream not available \u2014 falling back to renderToString. Upgrade to React 18+ for streaming SSR support.");
|
|
225
|
+
return renderWithString(reactDomServer.renderToString, root);
|
|
226
|
+
}
|
|
227
|
+
throw new Error("[theokit] react-dom/server does not export renderToReadableStream or renderToString. Ensure react-dom >= 17 is installed.");
|
|
228
|
+
}
|
|
229
|
+
__name(renderToStream, "renderToStream");
|
|
230
|
+
async function renderWithReadableStream(renderFn, root, waitForAll) {
|
|
231
|
+
const reactStream = await renderFn(root);
|
|
232
|
+
if (waitForAll) {
|
|
233
|
+
await reactStream.allReady;
|
|
234
|
+
}
|
|
235
|
+
const doctypeStream = prependDoctype(reactStream);
|
|
236
|
+
return {
|
|
237
|
+
stream: doctypeStream,
|
|
238
|
+
allReady: reactStream.allReady
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
__name(renderWithReadableStream, "renderWithReadableStream");
|
|
242
|
+
function renderWithString(renderFn, root) {
|
|
243
|
+
const html = DOCTYPE + renderFn(root);
|
|
244
|
+
const bytes = encoder.encode(html);
|
|
245
|
+
const stream = new ReadableStream({
|
|
246
|
+
start(controller) {
|
|
247
|
+
controller.enqueue(bytes);
|
|
248
|
+
controller.close();
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
return {
|
|
252
|
+
stream,
|
|
253
|
+
allReady: Promise.resolve()
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
__name(renderWithString, "renderWithString");
|
|
257
|
+
function prependDoctype(source) {
|
|
258
|
+
const reader = source.getReader();
|
|
259
|
+
let doctypeSent = false;
|
|
260
|
+
return new ReadableStream({
|
|
261
|
+
async pull(controller) {
|
|
262
|
+
if (!doctypeSent) {
|
|
263
|
+
controller.enqueue(encoder.encode(DOCTYPE));
|
|
264
|
+
doctypeSent = true;
|
|
265
|
+
}
|
|
266
|
+
const { value, done } = await reader.read();
|
|
267
|
+
if (done) {
|
|
268
|
+
controller.close();
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
controller.enqueue(value);
|
|
272
|
+
},
|
|
273
|
+
cancel() {
|
|
274
|
+
void reader.cancel();
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
__name(prependDoctype, "prependDoctype");
|
|
279
|
+
function streamToResponse(result) {
|
|
280
|
+
return new Response(result.stream, {
|
|
281
|
+
status: 200,
|
|
282
|
+
headers: {
|
|
283
|
+
"content-type": "text/html; charset=utf-8"
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
__name(streamToResponse, "streamToResponse");
|
|
288
|
+
|
|
194
289
|
// src/app.ts
|
|
195
290
|
var TheoApp = class _TheoApp {
|
|
196
291
|
static {
|
|
@@ -199,6 +294,7 @@ var TheoApp = class _TheoApp {
|
|
|
199
294
|
serverHandle;
|
|
200
295
|
routes = [];
|
|
201
296
|
frontendHtml;
|
|
297
|
+
streamingRoot;
|
|
202
298
|
staticHandler;
|
|
203
299
|
startTime = Date.now();
|
|
204
300
|
healthPath;
|
|
@@ -288,7 +384,9 @@ var TheoApp = class _TheoApp {
|
|
|
288
384
|
entry.compiledParamNames = paramNames;
|
|
289
385
|
entry.needsBody = entry.walk.paramEntries.some((p) => p.source === "body");
|
|
290
386
|
}
|
|
291
|
-
if (opts.root) {
|
|
387
|
+
if (opts.root && opts.streaming) {
|
|
388
|
+
app.streamingRoot = opts.root;
|
|
389
|
+
} else if (opts.root) {
|
|
292
390
|
const { renderToString } = await import("react-dom/server");
|
|
293
391
|
app.frontendHtml = "<!DOCTYPE html>" + renderToString(opts.root);
|
|
294
392
|
} else if (opts.html) {
|
|
@@ -457,6 +555,16 @@ var TheoApp = class _TheoApp {
|
|
|
457
555
|
// ── Web Standard request handler ──────────────────
|
|
458
556
|
async handleRequest(request) {
|
|
459
557
|
const pathname = new URL(request.url).pathname;
|
|
558
|
+
const reqCtx = {
|
|
559
|
+
request,
|
|
560
|
+
pathname,
|
|
561
|
+
method: request.method,
|
|
562
|
+
params: {},
|
|
563
|
+
startedAt: Date.now()
|
|
564
|
+
};
|
|
565
|
+
return runWithRequestContext(reqCtx, () => this.handleRequestInContext(request, pathname, reqCtx));
|
|
566
|
+
}
|
|
567
|
+
async handleRequestInContext(request, pathname, _reqCtx) {
|
|
460
568
|
if (request.method === "GET") {
|
|
461
569
|
if (pathname === this.healthPath) {
|
|
462
570
|
return jsonResponse(200, {
|
|
@@ -470,6 +578,12 @@ var TheoApp = class _TheoApp {
|
|
|
470
578
|
}
|
|
471
579
|
}
|
|
472
580
|
if (request.method === "GET") {
|
|
581
|
+
if ((pathname === "/" || pathname === "/index.html") && this.streamingRoot) {
|
|
582
|
+
const result = await renderToStream({
|
|
583
|
+
root: this.streamingRoot
|
|
584
|
+
});
|
|
585
|
+
return streamToResponse(result);
|
|
586
|
+
}
|
|
473
587
|
if ((pathname === "/" || pathname === "/index.html") && this.frontendHtml) {
|
|
474
588
|
return new Response(this.frontendHtml, {
|
|
475
589
|
status: 200,
|
|
@@ -556,7 +670,7 @@ var TheoApp = class _TheoApp {
|
|
|
556
670
|
const handlerFn = entry.instance[entry.walk.propertyKey];
|
|
557
671
|
let result;
|
|
558
672
|
if (entry.walk.interceptors.length > 0) {
|
|
559
|
-
const { runInterceptors } = await import("./interceptor-chain-
|
|
673
|
+
const { runInterceptors } = await import("./interceptor-chain-ELSL6KZT.js");
|
|
560
674
|
result = await runInterceptors(entry.walk.interceptors, () => handlerFn.apply(entry.instance, args), request);
|
|
561
675
|
} else {
|
|
562
676
|
result = await handlerFn.apply(entry.instance, args);
|
|
@@ -564,7 +678,7 @@ var TheoApp = class _TheoApp {
|
|
|
564
678
|
return buildResponse(result, entry.walk, method);
|
|
565
679
|
} catch (err) {
|
|
566
680
|
if (entry.walk.filters.length > 0) {
|
|
567
|
-
const { runExceptionFilters } = await import("./exception-filter-chain-
|
|
681
|
+
const { runExceptionFilters } = await import("./exception-filter-chain-O45FXGEB.js");
|
|
568
682
|
return runExceptionFilters(err, entry.walk.filters, request);
|
|
569
683
|
}
|
|
570
684
|
if (err instanceof HttpException) {
|
|
@@ -664,9 +778,13 @@ function buildResponse(result, walk, method) {
|
|
|
664
778
|
__name(buildResponse, "buildResponse");
|
|
665
779
|
|
|
666
780
|
export {
|
|
781
|
+
getRequestContext,
|
|
782
|
+
tryGetRequestContext,
|
|
667
783
|
getMimeType,
|
|
668
784
|
isSafePath,
|
|
669
785
|
createStaticHandler,
|
|
786
|
+
renderToStream,
|
|
787
|
+
streamToResponse,
|
|
670
788
|
TheoApp
|
|
671
789
|
};
|
|
672
|
-
//# sourceMappingURL=chunk-
|
|
790
|
+
//# sourceMappingURL=chunk-GQ2UH554.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/app.ts","../src/request-context.ts","../src/static.ts","../src/stream-renderer.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-regexp, complexity, sonarjs/cognitive-complexity, max-depth, sonarjs/no-collapsible-if, max-lines, max-lines-per-function */\nimport 'reflect-metadata'\n\nimport { createExecutionContext, type CanActivate } from './bridge/execution-context.js'\nimport { createNodeAdapter } from './bridge/runtime/node.js'\nimport type { ServerHandle } from './bridge/runtime/types.js'\nimport { walkControllerMetadata, type WalkResult } from './bridge/walk-metadata.js'\nimport type { ParamEntry } from './decorators/params.js'\nimport { ForbiddenException, HttpException } from './exceptions/http-exception.js'\nimport { runWithRequestContext, type TheoRequestContext } from './request-context.js'\nimport { createStaticHandler } from './static.js'\nimport { renderToStream, streamToResponse } from './stream-renderer.js'\n\n/**\n * TheoApp — NestJS/Spring Boot-style application bootstrap.\n *\n * Internally uses Web Standard Request/Response pipeline.\n * Node adapter converts at the HTTP server boundary.\n */\n\n/** Readiness check — async function returning health status. */\nexport type ReadinessCheck = () => Promise<{ name: string; healthy: boolean; message?: string }>\n\nexport interface TheoAppOptions {\n /** Controller classes decorated with @Controller. */\n controllers: Function[]\n /** Agent classes decorated with @Agent — auto-wired with routes + SSE + tools. */\n agents?: Function[]\n /** @Module class for structured DI. */\n module?: Function\n /** Provider/toolbox classes — instantiated and injected into controllers + agents. */\n providers?: Function[]\n /** LLM API key for agent execution (reads OPENROUTER_API_KEY env if not set). */\n llmApiKey?: string\n /** LLM model override (default: from @Agent({ model }) metadata). */\n llmModel?: string\n /** Agent stream factory override (for testing or custom SDK wiring). */\n agentStreamFactory?: (\n walk: unknown,\n tools: unknown[],\n apiKey: string,\n model?: string,\n ) => (message: string, sessionId: string) => AsyncIterable<unknown>\n /** HTML string to serve at GET / (inline frontend). */\n html?: string\n /** React root element — framework renders SSR internally (preferred over html). */\n root?: unknown\n /** Directory for static file serving (default: 'public', false to disable). */\n staticDir?: string | false\n /** Readiness checks for GET /__theo/ready (K8s readiness probe). */\n readinessChecks?: ReadinessCheck[]\n /** Custom health endpoint path (default: '/__theo/health'). */\n healthPath?: string\n /** Custom readiness endpoint path (default: '/__theo/ready'). */\n readyPath?: string\n /**\n * Enable streaming SSR via `renderToReadableStream` (default: false).\n *\n * When `true` AND `root` is provided, the app serves GET / with a streamed\n * HTML response instead of a static `renderToString` result. This enables\n * progressive rendering with React Suspense boundaries.\n *\n * **EC-7 — Error handling difference:** In streaming mode, errors inside\n * Suspense boundaries are caught by React's streaming error handler and\n * activate client-side error boundaries (the shell is already sent). In\n * string mode, errors throw synchronously before any bytes are sent,\n * allowing a full 500 error page.\n */\n streaming?: boolean\n}\n\ninterface RouteEntry {\n walk: WalkResult\n instance: object\n /** Pre-compiled regex + param names (Elysia-inspired: compile once at create, not per-request). */\n compiledPattern?: RegExp\n compiledParamNames?: string[]\n /** Whether handler needs body parsing (skip for GET/DELETE without @Body). */\n needsBody?: boolean\n}\n\nexport class TheoApp {\n private serverHandle: ServerHandle\n private readonly routes: RouteEntry[] = []\n private frontendHtml?: string\n private streamingRoot?: unknown\n private staticHandler?: (request: Request) => Promise<Response | null>\n private readonly startTime = Date.now()\n private readonly healthPath: string\n private readonly readyPath: string\n private readonly readinessChecks: ReadinessCheck[]\n\n private constructor(opts?: Pick<TheoAppOptions, 'readinessChecks' | 'healthPath' | 'readyPath'>) {\n const hp = opts?.healthPath ?? '/__theo/health'\n const rp = opts?.readyPath ?? '/__theo/ready'\n // Security: prevent health paths from colliding with user API routes\n if (hp.startsWith('/api/'))\n throw new Error(\n `[TheoApp] healthPath \"${hp}\" must not start with /api/ — would collide with user routes`,\n )\n if (rp.startsWith('/api/'))\n throw new Error(\n `[TheoApp] readyPath \"${rp}\" must not start with /api/ — would collide with user routes`,\n )\n this.healthPath = hp\n this.readyPath = rp\n this.readinessChecks = opts?.readinessChecks ?? []\n const adapter = createNodeAdapter()\n this.serverHandle = adapter.createServer((request) => this.handleRequest(request))\n }\n\n /**\n * Create a TheoKit application with Spring Boot-style DI.\n *\n * EC-7: async because Container may resolve async factories (Agent.create).\n * EC-2: Registration order guaranteed: providers → controllers → agents.\n */\n static async create(opts: TheoAppOptions): Promise<TheoApp> {\n const app = new TheoApp(opts)\n\n // ── DI Container (replaces manual Map<Function, object>) ──\n // Uses @theokit/di Container for: scopes, lifecycle, async, typed errors.\n // Fallback to manual resolution when @theokit/di is not available.\n const registry = new Map<Function, object>()\n\n // 1. Module resolution (@Module metadata)\n if (opts.module) {\n const moduleMeta = Reflect.getMetadata('usetheo:di:module', opts.module)\n if (moduleMeta) {\n const allModules = [opts.module, ...(moduleMeta.imports ?? [])]\n for (const Mod of allModules) {\n const meta = Reflect.getMetadata('usetheo:di:module', Mod)\n if (!meta) continue\n for (const Prov of (meta.providers ?? []) as Function[]) {\n if (!registry.has(Prov)) {\n registry.set(Prov, new (Prov as new () => object)())\n }\n }\n }\n }\n }\n\n // 2. Inline providers (EC-2: BEFORE controllers and agents)\n if (opts.providers) {\n for (const Prov of opts.providers) {\n if (!registry.has(Prov)) {\n registry.set(Prov, new (Prov as new () => object)())\n }\n }\n }\n\n // 3. Controllers with DI\n for (const Controller of opts.controllers) {\n const paramTypes: Function[] = Reflect.getMetadata('design:paramtypes', Controller) ?? []\n const args = paramTypes.map((pt: Function) => {\n const dep = registry.get(pt)\n if (!dep) {\n throw new Error(\n `[TheoApp] Cannot resolve ${pt.name} for ${Controller.name}. ` +\n `Add ${pt.name} to providers (or to @Module({ providers: [...] })).`,\n )\n }\n return dep\n })\n const instance = new (Controller as new (...a: unknown[]) => object)(...args)\n\n // Lifecycle: call @PostConstruct if present\n const postConstruct = Reflect.getMetadata('usetheo:di:post-construct', Controller)\n if (\n postConstruct &&\n typeof (instance as Record<string, Function>)[postConstruct] === 'function'\n ) {\n const result = (instance as Record<string, Function>)[postConstruct]()\n if (result instanceof Promise) await result // EC-1: await async PostConstruct\n }\n\n const walks = walkControllerMetadata(Controller)\n for (const w of walks) {\n app.routes.push({ walk: w, instance })\n }\n }\n\n // Sort: static before parameterized\n app.routes.sort((a, b) => {\n const aP = a.walk.fullPath.includes(':')\n const bP = b.walk.fullPath.includes(':')\n if (aP !== bP) return aP ? 1 : -1\n return 0\n })\n\n // Pre-compile route patterns (Elysia-inspired: regex built once, not per-request)\n for (const entry of app.routes) {\n const paramNames: string[] = []\n const regexStr = entry.walk.fullPath.replace(/:(\\w+)/g, (_m, name: string) => {\n paramNames.push(name)\n return '([^/]+)'\n })\n entry.compiledPattern = new RegExp(`^${regexStr}$`)\n entry.compiledParamNames = paramNames\n // Determine if handler needs body parsing (skip if no @Body decorator)\n entry.needsBody = entry.walk.paramEntries.some((p) => p.source === 'body')\n }\n\n // Frontend HTML — from root (React SSR) or html string\n if (opts.root && opts.streaming) {\n // Streaming mode: store the root element; render per-request via renderToStream\n app.streamingRoot = opts.root\n } else if (opts.root) {\n const { renderToString } = await import('react-dom/server')\n app.frontendHtml = '<!DOCTYPE html>' + renderToString(opts.root as React.ReactElement)\n } else if (opts.html) {\n app.frontendHtml = opts.html\n }\n\n // Static file serving from public/ (default: enabled)\n if (opts.staticDir !== false) {\n app.staticHandler = createStaticHandler({ root: opts.staticDir ?? 'public' })\n }\n\n // 4. Auto-wire agents (EC-2: AFTER providers and controllers)\n // The framework handles EVERYTHING — walk, compile, mount, stream.\n // Consumer writes: agents: [MyAgent] — and that's it.\n if (opts.agents?.length) {\n await app.autoWireAgents(opts.agents, registry, opts)\n }\n\n return app\n }\n\n async listen(port: number): Promise<void> {\n return new Promise((resolve) => {\n this.serverHandle.listen(port, () => {\n console.log(`TheoKit app listening on http://localhost:${port}`)\n resolve()\n })\n })\n }\n\n getServerHandle(): ServerHandle {\n return this.serverHandle\n }\n\n async close(): Promise<void> {\n return new Promise((resolve) => {\n this.serverHandle.close(() => {\n resolve()\n })\n })\n }\n\n // ── Auto-wire agents (the \"SpringApplication.run()\" moment) ──\n\n private agentRoutes: {\n method: string\n pattern: RegExp\n paramNames: string[]\n handler: (request: Request) => Promise<Response>\n guards: Function[]\n agentClass: Function\n methodName: string | symbol\n }[] = []\n\n private async autoWireAgents(\n agentClasses: Function[],\n registry: Map<Function, object>,\n opts: TheoAppOptions,\n ) {\n // Dynamic import — @theokit/agents is optional peer dependency\n // SECURITY: new Function used for dynamic import of optional peer dep.\n // Argument is HARDCODED ('@theokit/agents'), never user input. Safe.\n // eslint-disable-next-line @typescript-eslint/no-implied-eval -- dynamic import avoids compile-time dependency on optional peer\n const importFn = new Function('specifier', 'return import(specifier)') as (\n s: string,\n ) => Promise<Record<string, Function>>\n let walkAgentMetadata: Function,\n compileAgent: Function,\n generateAgentRoutes: Function,\n getMixins: Function,\n createSdkAgentStreamFn: Function\n try {\n const mod = await importFn('@theokit/agents')\n walkAgentMetadata = mod.walkAgentMetadata\n compileAgent = mod.compileAgent\n generateAgentRoutes = mod.generateAgentRoutes\n getMixins = mod.getMixins\n createSdkAgentStreamFn = mod.createSdkAgentStream\n } catch {\n throw new Error(\n '[TheoApp] @theokit/agents is required when agents[] is provided. Install: npm install @theokit/agents',\n )\n }\n\n const apiKey = opts.llmApiKey ?? process.env.OPENROUTER_API_KEY ?? ''\n\n for (const AgentClass of agentClasses) {\n // 1. Walk metadata (decorators → structured data)\n const mixins = getMixins(AgentClass)\n const allToolboxes = [...mixins]\n\n // Also check providers for @Toolbox classes\n for (const [Cls] of registry) {\n if (Reflect.getMetadata(Symbol.for('theokit:agents:toolbox'), Cls)) {\n if (!allToolboxes.includes(Cls)) allToolboxes.push(Cls)\n }\n }\n\n const walk = walkAgentMetadata(AgentClass, allToolboxes)\n\n // 2. Resolve toolbox instances from registry (DI)\n const toolboxInstances = new Map<Function, object>()\n for (const tb of walk.toolboxes) {\n let instance = registry.get(tb.class)\n if (!instance) {\n instance = new (tb.class as new () => object)()\n registry.set(tb.class, instance)\n }\n toolboxInstances.set(tb.class, instance)\n }\n\n // 3. Compile tools (decorator metadata → defineTool-compatible)\n const compiled = compileAgent(walk, toolboxInstances)\n\n // 4. Create SDK agent stream factory\n let createRun: (message: string, sessionId: string) => AsyncIterable<unknown>\n\n if (opts.agentStreamFactory) {\n createRun = opts.agentStreamFactory(walk, compiled.tools, apiKey, opts.llmModel)\n } else if (apiKey) {\n // SDK adapter: bridges @theokit/agents decorators → @theokit/sdk runtime\n createRun = createSdkAgentStreamFn(walk, compiled.tools, apiKey, opts.llmModel) as (\n m: string,\n s: string,\n ) => AsyncIterable<unknown>\n } else {\n createRun = this.createFallbackStream(walk.agentConfig.name, apiKey)\n }\n\n // 5. Generate routes (POST /chat, GET /runs/:id)\n const routes = generateAgentRoutes({\n walkResult: walk,\n compiledOptions: compiled,\n createRun: createRun as (\n message: string,\n sessionId: string,\n ) => AsyncIterable<{ type: string; [k: string]: unknown }>,\n })\n\n // 6. Mount routes\n for (const route of routes) {\n const paramNames: string[] = []\n const regexStr = route.path.replace(/:(\\w+)/g, (_m: string, name: string) => {\n paramNames.push(name)\n return '([^/]+)'\n })\n this.agentRoutes.push({\n method: route.method,\n pattern: new RegExp(`^${regexStr}$`),\n paramNames,\n handler: route.handler,\n guards: walk.guards ?? [],\n agentClass: AgentClass,\n methodName: walk.mainLoop?.propertyKey ?? 'run',\n })\n }\n\n console.log(\n ` 🤖 Agent \"${walk.agentConfig.name}\" mounted at ${walk.route}/chat (${compiled.tools.length} tools)`,\n )\n }\n }\n\n private async handleReadinessCheck(): Promise<Response> {\n if (this.readinessChecks.length === 0) {\n return jsonResponse(200, { status: 'ready', checks: [] })\n }\n const results = await Promise.all(\n this.readinessChecks.map(async (check) => {\n try {\n return await Promise.race([\n check(),\n new Promise<{ name: string; healthy: boolean; message?: string }>((resolve) =>\n setTimeout(\n () =>\n resolve({\n name: 'unknown',\n healthy: false,\n message: 'Readiness check timed out (5s)',\n }),\n 5000,\n ),\n ),\n ])\n } catch (err) {\n return {\n name: 'unknown',\n healthy: false,\n message: err instanceof Error ? err.message : 'Check failed',\n }\n }\n }),\n )\n const allHealthy = results.every((r) => r.healthy)\n return jsonResponse(allHealthy ? 200 : 503, {\n status: allHealthy ? 'ready' : 'not_ready',\n checks: results,\n })\n }\n\n private createFallbackStream(agentName: string, apiKey: string) {\n const msg = !apiKey\n ? 'Set OPENROUTER_API_KEY environment variable or pass llmApiKey to TheoApp.create()'\n : 'Pass agentStreamFactory to TheoApp.create() to connect your LLM provider'\n return (_message: string, _sessionId: string) => {\n const events = [\n { type: 'run_started', runId: `run-${Date.now()}`, agentName },\n { type: 'error', code: 'AGENT_NOT_WIRED', message: msg, retryable: false },\n ]\n return {\n [Symbol.asyncIterator]: () => {\n let i = 0\n return {\n next: () =>\n Promise.resolve(\n i < events.length\n ? { value: events[i++], done: false as const }\n : { value: undefined, done: true as const },\n ),\n }\n },\n }\n }\n }\n\n // ── Web Standard request handler ──────────────────\n\n private async handleRequest(request: Request): Promise<Response> {\n const pathname = new URL(request.url).pathname\n\n // Wrap entire request in AsyncLocalStorage context\n const reqCtx: TheoRequestContext = {\n request,\n pathname,\n method: request.method,\n params: {},\n startedAt: Date.now(),\n }\n return runWithRequestContext(reqCtx, () =>\n this.handleRequestInContext(request, pathname, reqCtx),\n )\n }\n\n private async handleRequestInContext(\n request: Request,\n pathname: string,\n _reqCtx: TheoRequestContext,\n ): Promise<Response> {\n // ── Health & Readiness probes (bypass guards/interceptors) ──\n if (request.method === 'GET') {\n if (pathname === this.healthPath) {\n return jsonResponse(200, {\n status: 'ok',\n uptime: (Date.now() - this.startTime) / 1000,\n timestamp: Date.now(),\n })\n }\n if (pathname === this.readyPath) {\n return this.handleReadinessCheck()\n }\n }\n\n // Bug #8: Serve frontend HTML at GET /\n if (request.method === 'GET') {\n if ((pathname === '/' || pathname === '/index.html') && this.streamingRoot) {\n const result = await renderToStream({\n root: this.streamingRoot as React.ReactElement,\n })\n return streamToResponse(result)\n }\n if ((pathname === '/' || pathname === '/index.html') && this.frontendHtml) {\n return new Response(this.frontendHtml, {\n status: 200,\n headers: { 'content-type': 'text/html; charset=utf-8' },\n })\n }\n }\n\n // Static files from public/ (runtime-agnostic — Node/Bun/Deno)\n if (this.staticHandler && (request.method === 'GET' || request.method === 'HEAD')) {\n const staticResponse = await this.staticHandler(request)\n if (staticResponse) return staticResponse\n }\n\n // Agent routes (auto-wired — checked first, with guard enforcement per Bug #4)\n for (const route of this.agentRoutes) {\n if (request.method.toUpperCase() === route.method && route.pattern.test(pathname)) {\n // Bug #4 fix: enforce @UseGuards on agent routes (same pipeline as controllers)\n if (route.guards.length > 0) {\n const ctx = createExecutionContext(request, route.agentClass, route.methodName)\n for (const GuardCtor of route.guards) {\n const guard = new (GuardCtor as new () => CanActivate)()\n if (!(await guard.canActivate(ctx))) {\n const ex = new ForbiddenException('Forbidden resource')\n return jsonResponse(ex.statusCode, ex.toJSON())\n }\n }\n }\n return route.handler(request)\n }\n }\n\n const url = new URL(request.url)\n const method = request.method.toUpperCase()\n\n const match = this.findRoute(method, url.pathname)\n if (!match) {\n return jsonResponse(404, {\n error: { code: 'NOT_FOUND', message: `No route for ${method} ${url.pathname}` },\n })\n }\n\n const { entry, params } = match\n\n try {\n // Guards\n const ctx = createExecutionContext(\n request,\n entry.instance.constructor,\n entry.walk.propertyKey,\n )\n for (const GuardCtor of entry.walk.guards) {\n const guard = new (GuardCtor as new () => CanActivate)()\n if (!(await guard.canActivate(ctx))) {\n const ex = new ForbiddenException('Forbidden resource')\n return jsonResponse(ex.statusCode, ex.toJSON())\n }\n }\n\n // Body — skip parsing entirely if handler has no @Body decorator (Elysia-inspired lazy parsing)\n let body: unknown\n if (entry.needsBody && ['POST', 'PUT', 'PATCH'].includes(method)) {\n try {\n const text = await request.text()\n body = text ? JSON.parse(text) : undefined\n } catch {\n body = undefined\n }\n\n if (entry.walk.bodySchema && body !== undefined) {\n const result = entry.walk.bodySchema.safeParse(body)\n if (!result.success) {\n return jsonResponse(422, {\n error: { code: 'VALIDATION_ERROR', issues: result.error.issues },\n })\n }\n body = result.data\n }\n }\n\n // Args\n const args = this.buildArgs(\n entry.walk.paramEntries,\n request,\n body,\n params,\n Object.fromEntries(url.searchParams),\n )\n\n // Redirect\n if (entry.walk.redirect) {\n return new Response(null, {\n status: entry.walk.redirect.status,\n headers: { location: entry.walk.redirect.url },\n })\n }\n\n // Handler — wrapped by interceptor chain (Bug #2 fix)\n const handlerFn = (entry.instance as Record<string | symbol, Function>)[\n entry.walk.propertyKey\n ]\n\n let result: unknown\n if (entry.walk.interceptors.length > 0) {\n // Import runInterceptors dynamically to avoid circular dep\n const { runInterceptors } = await import('./bridge/interceptor-chain.js')\n result = await runInterceptors(\n entry.walk.interceptors,\n () => handlerFn.apply(entry.instance, args) as Promise<unknown>,\n request,\n )\n } else {\n result = await handlerFn.apply(entry.instance, args)\n }\n\n return buildResponse(result, entry.walk, method)\n } catch (err) {\n // Exception filters (Bug #2 fix — filters also wired)\n if (entry.walk.filters.length > 0) {\n const { runExceptionFilters } = await import('./bridge/exception-filter-chain.js')\n return runExceptionFilters(err, entry.walk.filters, request)\n }\n // Fallback: HttpException subclasses (Bug #3 fix)\n if (err instanceof HttpException) {\n return jsonResponse(err.statusCode, err.toJSON())\n }\n // Security: never leak raw error messages to clients\n console.error('[theokit] Internal error:', err instanceof Error ? err.message : err)\n return jsonResponse(500, {\n error: { code: 'INTERNAL_SERVER_ERROR', message: 'Internal Server Error' },\n })\n }\n }\n\n private findRoute(method: string, pathname: string) {\n for (const entry of this.routes) {\n if (entry.walk.verb !== 'ALL' && entry.walk.verb !== method) continue\n // Use pre-compiled regex (built once at create time, not per-request)\n const match = entry.compiledPattern!.exec(pathname)\n if (!match) continue\n const params: Record<string, string> = {}\n entry.compiledParamNames!.forEach((name, i) => {\n params[name] = match[i + 1]\n })\n return { entry, params }\n }\n return null\n }\n\n private buildArgs(\n entries: ParamEntry[],\n request: Request,\n body: unknown,\n params: Record<string, string>,\n query: Record<string, string>,\n ): unknown[] {\n if (entries.length === 0) return []\n const max = Math.max(...entries.map((p) => p.index))\n const args: unknown[] = Array.from({ length: max + 1 }, () => undefined)\n for (const p of entries) {\n switch (p.source) {\n case 'req':\n args[p.index] = request\n break\n case 'body':\n args[p.index] = p.key ? (body as Record<string, unknown>)[p.key] : body\n break\n case 'param':\n args[p.index] = p.key ? params[p.key] : params\n break\n case 'query':\n args[p.index] = p.key ? query[p.key] : query\n break\n case 'headers':\n args[p.index] = p.key\n ? request.headers.get(p.key.toLowerCase())\n : Object.fromEntries(request.headers.entries())\n break\n case 'ip':\n args[p.index] = request.headers.get('x-forwarded-for') ?? '127.0.0.1'\n break\n default:\n args[p.index] = undefined\n }\n }\n return args\n }\n}\n\nfunction jsonResponse(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\nfunction buildResponse(result: unknown, walk: WalkResult, method: string): Response {\n const status = walk.status ?? (method === 'POST' ? 201 : 200)\n const headers: Record<string, string> = { 'content-type': 'application/json' }\n for (const [n, v] of walk.headers) headers[n.toLowerCase()] = v\n\n if (result === undefined || result === null) {\n return new Response(null, { status: status === 200 ? 204 : status, headers })\n }\n if (typeof result === 'string') {\n headers['content-type'] = 'text/plain'\n return new Response(result, { status, headers })\n }\n return new Response(JSON.stringify(result), { status, headers })\n}\n","/**\n * Request Context — per-request state via AsyncLocalStorage.\n *\n * Inspired by Next.js workAsyncStorage pattern (app-render.tsx:3325).\n * Eliminates prop drilling — any code in the request path can access\n * the current request without receiving it as a parameter.\n *\n * Usage:\n * import { getRequestContext } from '@theokit/http'\n * const { request, pathname, method, params } = getRequestContext()\n *\n * The context is populated by TheoApp.handleRequest() and available\n * to guards, interceptors, filters, controllers, agents, and tools.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\nexport interface TheoRequestContext {\n /** The raw Web Standard Request object. */\n request: Request\n /** URL pathname (e.g., '/api/tasks'). */\n pathname: string\n /** HTTP method (e.g., 'GET', 'POST'). */\n method: string\n /** Route params extracted from URL (e.g., { id: '42' }). */\n params: Record<string, string>\n /** Matched controller or agent class name (if resolved). */\n handler?: string\n /** Request start time (ms). */\n startedAt: number\n}\n\nconst storage = new AsyncLocalStorage<TheoRequestContext>()\n\n/**\n * Get the current request context.\n *\n * @throws Error if called outside a request (e.g., at module load time).\n *\n * @example\n * ```typescript\n * import { getRequestContext } from '@theokit/http'\n *\n * class AuthGuard {\n * canActivate() {\n * const { request } = getRequestContext()\n * return request.headers.get('authorization') !== null\n * }\n * }\n * ```\n */\nexport function getRequestContext(): TheoRequestContext {\n const ctx = storage.getStore()\n if (!ctx) {\n throw new Error(\n 'getRequestContext() called outside a request. ' +\n 'This function is only available inside TheoApp request handlers ' +\n '(controllers, guards, interceptors, filters, agents).',\n )\n }\n return ctx\n}\n\n/**\n * Try to get the current request context, or null if not in a request.\n * Useful for code that may run both inside and outside requests.\n */\nexport function tryGetRequestContext(): TheoRequestContext | null {\n return storage.getStore() ?? null\n}\n\n/**\n * Run a function within a request context.\n * Used internally by TheoApp — not part of public API.\n * @internal\n */\nexport async function runWithRequestContext<T>(\n ctx: TheoRequestContext,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn)\n}\n","/**\n * Static file handler — runtime-agnostic (Node/Bun/Deno).\n *\n * Serves files from a root directory (default: `public/`).\n * Derived from Hono's serve-static middleware pattern:\n * - MIME type detection from extension\n * - Path traversal prevention via regex guard\n * - Runtime-agnostic file reading (Bun.file / Deno.readFile / node:fs)\n */\n\n// ── MIME type map (50+ types) ──────────────────────────\n\nconst MIME_TYPES: Record<string, string> = {\n // Text\n '.html': 'text/html; charset=utf-8',\n '.htm': 'text/html; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.xml': 'application/xml; charset=utf-8',\n '.txt': 'text/plain; charset=utf-8',\n '.csv': 'text/csv; charset=utf-8',\n '.md': 'text/markdown; charset=utf-8',\n '.yaml': 'text/yaml; charset=utf-8',\n '.yml': 'text/yaml; charset=utf-8',\n '.ts': 'text/typescript; charset=utf-8',\n '.tsx': 'text/tsx; charset=utf-8',\n '.jsx': 'text/jsx; charset=utf-8',\n\n // Images\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.bmp': 'image/bmp',\n '.tiff': 'image/tiff',\n '.tif': 'image/tiff',\n\n // Fonts\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.eot': 'application/vnd.ms-fontobject',\n\n // Media\n '.mp3': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.ogg': 'audio/ogg',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.avi': 'video/x-msvideo',\n\n // Documents\n '.pdf': 'application/pdf',\n '.zip': 'application/zip',\n '.gz': 'application/gzip',\n '.tar': 'application/x-tar',\n '.wasm': 'application/wasm',\n\n // Misc\n '.map': 'application/json; charset=utf-8',\n '.jsonld': 'application/ld+json; charset=utf-8',\n '.manifest': 'application/manifest+json; charset=utf-8',\n '.webmanifest': 'application/manifest+json; charset=utf-8',\n}\n\n// ── Path traversal guard (Hono-derived regex) ──────────\n\n/**\n * Regex that catches path traversal attacks:\n * - `..` segments (beginning, middle, or end of path)\n * - Double slashes `//`\n * - Backslash sequences `\\\\`\n */\nconst UNSAFE_PATH_RE = /(?:^|[/\\\\])\\.{1,2}(?:$|[/\\\\])|[/\\\\]{2,}/\n\n// ── Public API ─────────────────────────────────────────\n\nexport interface StaticOptions {\n /** Root directory to serve from (default: 'public'). */\n root?: string\n /** Cache-Control max-age in seconds (default: 0 — no caching). */\n maxAge?: number\n}\n\n/**\n * Returns the MIME type for a given file path based on its extension.\n * Falls back to 'application/octet-stream' for unknown extensions.\n */\nexport function getMimeType(filePath: string): string {\n const dot = filePath.lastIndexOf('.')\n if (dot === -1) return 'application/octet-stream'\n const ext = filePath.slice(dot).toLowerCase()\n return MIME_TYPES[ext] ?? 'application/octet-stream'\n}\n\n/**\n * Returns true when the path is safe (no traversal, no double slashes).\n */\nexport function isSafePath(pathname: string): boolean {\n return !UNSAFE_PATH_RE.test(pathname)\n}\n\n// ── Runtime-agnostic file reader ───────────────────────\n\ninterface FileResult {\n content: Uint8Array\n size: number\n}\n\nasync function readFileBun(fullPath: string): Promise<FileResult | null> {\n const g = globalThis as Record<string, unknown>\n const BunRT = g.Bun as {\n file: (path: string) => {\n exists: () => Promise<boolean>\n arrayBuffer: () => Promise<ArrayBuffer>\n size: number\n }\n }\n const file = BunRT.file(fullPath)\n if (!(await file.exists())) return null\n const buf = await file.arrayBuffer()\n return { content: new Uint8Array(buf), size: file.size }\n}\n\nasync function readFileDeno(fullPath: string): Promise<FileResult | null> {\n const g = globalThis as Record<string, unknown>\n const DenoRT = g.Deno as {\n readFile: (path: string) => Promise<Uint8Array>\n stat: (path: string) => Promise<{ isDirectory: boolean }>\n }\n try {\n const stat = await DenoRT.stat(fullPath)\n if (stat.isDirectory) return null\n const content = await DenoRT.readFile(fullPath)\n return { content, size: content.byteLength }\n } catch {\n return null\n }\n}\n\nasync function readFileNode(fullPath: string): Promise<FileResult | null> {\n try {\n const fs = await import('node:fs/promises')\n const stat = await fs.stat(fullPath)\n if (stat.isDirectory()) return null\n const content = await fs.readFile(fullPath)\n return { content: new Uint8Array(content), size: stat.size }\n } catch {\n return null\n }\n}\n\nasync function readFile(fullPath: string): Promise<FileResult | null> {\n const g = globalThis as Record<string, unknown>\n if (g.Bun) return readFileBun(fullPath)\n if (g.Deno) return readFileDeno(fullPath)\n return readFileNode(fullPath)\n}\n\n// ── Resolve root to absolute path ──────────────────────\n\nasync function resolveRoot(root: string): Promise<string> {\n const g = globalThis as Record<string, unknown>\n if (g.Deno) {\n const DenoRT = g.Deno as { cwd: () => string }\n const { join } = await import('node:path')\n return join(DenoRT.cwd(), root)\n }\n const { resolve } = await import('node:path')\n return resolve(root)\n}\n\n// ── Factory ────────────────────────────────────────────\n\n/**\n * Creates a static file handler that serves files from `root` directory.\n *\n * Returns `null` when the request does not match a static file (allowing\n * the caller to fall through to the next handler).\n */\nexport function createStaticHandler(\n options?: StaticOptions,\n): (request: Request) => Promise<Response | null> {\n const root = options?.root ?? 'public'\n const maxAge = options?.maxAge ?? 0\n\n let resolvedRoot: string | undefined\n\n return async (request: Request): Promise<Response | null> => {\n // Only serve GET and HEAD\n const method = request.method.toUpperCase()\n if (method !== 'GET' && method !== 'HEAD') return null\n\n // Extract pathname, strip query params\n const url = new URL(request.url)\n let pathname: string\n try {\n pathname = decodeURIComponent(url.pathname)\n } catch {\n return null // Malformed URL encoding\n }\n\n // Skip framework-reserved paths\n if (pathname.startsWith('/api/') || pathname.startsWith('/@theo/')) return null\n\n // Path traversal guard\n if (!isSafePath(pathname)) return null\n\n // Lazy-resolve root to absolute path (once per handler lifetime)\n resolvedRoot ??= await resolveRoot(root)\n\n // Build full file path\n const { join } = await import('node:path')\n let fullPath = join(resolvedRoot, pathname)\n\n // Directory → try index.html\n let result = await readFile(fullPath)\n if (!result && (pathname.endsWith('/') || !pathname.includes('.'))) {\n fullPath = join(fullPath, 'index.html')\n result = await readFile(fullPath)\n }\n\n if (!result) return null\n\n // Build response headers\n const contentType = getMimeType(fullPath)\n const headers: Record<string, string> = {\n 'content-type': contentType,\n 'content-length': String(result.size),\n }\n if (maxAge > 0) {\n headers['cache-control'] = `public, max-age=${String(maxAge)}`\n }\n\n // HEAD: headers only, no body\n if (method === 'HEAD') {\n return new Response(null, { status: 200, headers })\n }\n\n return new Response(result.content as unknown as BodyInit, { status: 200, headers })\n }\n}\n","/**\n * Streaming SSR — renders a React element tree to a `ReadableStream<Uint8Array>`.\n *\n * Inspired by Next.js `stream-ops.ts`. Uses Web Standard `renderToReadableStream`\n * (works on Node 18+, Bun, Deno). Falls back to `renderToString` wrapped in a\n * ReadableStream when `renderToReadableStream` is not available (React 17 — EC-4).\n *\n * React is loaded via dynamic `import('react-dom/server')` because react-dom\n * is an optional peerDep of @theokit/http (ADR D2).\n */\n\nimport type * as ReactTypes from 'react'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface StreamRenderOptions {\n /** React element to render */\n root: ReactTypes.ReactElement\n /** Whether to wait for all Suspense to resolve (default: false — stream immediately) */\n waitForAll?: boolean\n}\n\nexport interface StreamRenderResult {\n /** The HTML stream */\n stream: ReadableStream<Uint8Array>\n /** Promise that resolves when all content has been flushed */\n allReady: Promise<void>\n}\n\n// ---------------------------------------------------------------------------\n// Doctype prefix\n// ---------------------------------------------------------------------------\n\nconst DOCTYPE = '<!DOCTYPE html>'\nconst encoder = new TextEncoder()\n\n// ---------------------------------------------------------------------------\n// Core\n// ---------------------------------------------------------------------------\n\n/**\n * Renders a React element to a `ReadableStream<Uint8Array>` (Web Standard).\n *\n * 1. Tries `renderToReadableStream` first (React 18+ — Web Standard API).\n * 2. Falls back to `renderToString` wrapped in a ReadableStream when\n * `renderToReadableStream` is not available (React 17 compat — EC-4).\n * 3. Prepends `<!DOCTYPE html>` to the stream.\n *\n * **EC-7 — Streaming error handling:** In streaming mode, errors thrown inside\n * Suspense boundaries are caught by React's streaming error handler and result\n * in a client-side error boundary activation (the shell is already sent). In\n * string mode (`renderToString`), errors throw synchronously before any bytes\n * are sent, allowing a full 500 error page. Choose streaming when you want\n * progressive rendering; choose string mode when you want atomic error handling.\n */\nexport async function renderToStream(options: StreamRenderOptions): Promise<StreamRenderResult> {\n const { root, waitForAll = false } = options\n\n // Dynamic import — react-dom is optional peerDep\n const reactDomServer = await import('react-dom/server')\n\n // Prefer renderToReadableStream (Web Standard — React 18+)\n if (typeof reactDomServer.renderToReadableStream === 'function') {\n return renderWithReadableStream(reactDomServer.renderToReadableStream, root, waitForAll)\n }\n\n // EC-4: Fallback to renderToString wrapped in ReadableStream (React 17)\n if (typeof reactDomServer.renderToString === 'function') {\n console.warn(\n '[theokit] renderToReadableStream not available — falling back to renderToString. ' +\n 'Upgrade to React 18+ for streaming SSR support.',\n )\n return renderWithString(reactDomServer.renderToString, root)\n }\n\n throw new Error(\n '[theokit] react-dom/server does not export renderToReadableStream or renderToString. ' +\n 'Ensure react-dom >= 17 is installed.',\n )\n}\n\n// ---------------------------------------------------------------------------\n// Strategy: Web Standard renderToReadableStream\n// ---------------------------------------------------------------------------\n\nasync function renderWithReadableStream(\n renderFn: (\n element: ReactTypes.ReactElement,\n ) => Promise<ReadableStream & { allReady: Promise<void> }>,\n root: ReactTypes.ReactElement,\n waitForAll: boolean,\n): Promise<StreamRenderResult> {\n const reactStream = await renderFn(root)\n\n // If waitForAll, wait for all Suspense boundaries to resolve before emitting\n if (waitForAll) {\n await reactStream.allReady\n }\n\n // Prepend DOCTYPE\n const doctypeStream = prependDoctype(reactStream)\n\n return {\n stream: doctypeStream,\n allReady: reactStream.allReady,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Strategy: Fallback renderToString (EC-4)\n// ---------------------------------------------------------------------------\n\nfunction renderWithString(\n renderFn: (element: ReactTypes.ReactElement) => string,\n root: ReactTypes.ReactElement,\n): StreamRenderResult {\n const html = DOCTYPE + renderFn(root)\n const bytes = encoder.encode(html)\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(bytes)\n controller.close()\n },\n })\n\n return {\n stream,\n allReady: Promise.resolve(),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Prepends `<!DOCTYPE html>` bytes to a ReadableStream.\n */\nfunction prependDoctype(source: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n const reader = source.getReader()\n let doctypeSent = false\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (!doctypeSent) {\n controller.enqueue(encoder.encode(DOCTYPE))\n doctypeSent = true\n }\n const { value, done } = await reader.read()\n if (done) {\n controller.close()\n return\n }\n controller.enqueue(value)\n },\n cancel() {\n void reader.cancel()\n },\n })\n}\n\n// ---------------------------------------------------------------------------\n// Response helper\n// ---------------------------------------------------------------------------\n\n/**\n * Converts a {@link StreamRenderResult} into a Web Standard `Response`.\n *\n * Convenience wrapper for use in request handlers:\n * ```ts\n * const result = await renderToStream({ root: <App /> })\n * return streamToResponse(result)\n * ```\n */\nexport function streamToResponse(result: StreamRenderResult): Response {\n return new Response(result.stream, {\n status: 200,\n headers: { 'content-type': 'text/html; charset=utf-8' },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;AACA,OAAO;;;ACaP,SAASA,yBAAyB;AAiBlC,IAAMC,UAAU,IAAIC,kBAAAA;AAmBb,SAASC,oBAAAA;AACd,QAAMC,MAAMH,QAAQI,SAAQ;AAC5B,MAAI,CAACD,KAAK;AACR,UAAM,IAAIE,MACR,qKAEE;EAEN;AACA,SAAOF;AACT;AAVgBD;AAgBT,SAASI,uBAAAA;AACd,SAAON,QAAQI,SAAQ,KAAM;AAC/B;AAFgBE;AAShB,eAAsBC,sBACpBJ,KACAK,IAAwB;AAExB,SAAOR,QAAQS,IAAIN,KAAKK,EAAAA;AAC1B;AALsBD;;;AC/DtB,IAAMG,aAAqC;;EAEzC,SAAS;EACT,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,SAAS;EACT,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,SAAS;EACT,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;;EAGR,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,SAAS;EACT,QAAQ;EACR,SAAS;EACT,QAAQ;;EAGR,SAAS;EACT,UAAU;EACV,QAAQ;EACR,QAAQ;EACR,QAAQ;;EAGR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,QAAQ;;EAGR,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,SAAS;;EAGT,QAAQ;EACR,WAAW;EACX,aAAa;E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gB;IAAmB;EAChD,CAAA;AACF;AALS3C;AAOT,SAAS8E,cAAcvK,QAAiBM,MAAkB0E,QAAc;AACtE,QAAMU,SAASpF,KAAKoF,WAAWV,WAAW,SAAS,MAAM;AACzD,QAAMoD,UAAkC;IAAE,gBAAgB;EAAmB;AAC7E,aAAW,CAACoD,GAAGC,CAAAA,KAAMnL,KAAK8H,QAASA,SAAQoD,EAAEF,YAAW,CAAA,IAAMG;AAE9D,MAAIzL,WAAWqH,UAAarH,WAAW,MAAM;AAC3C,WAAO,IAAImI,SAAS,MAAM;MAAEzC,QAAQA,WAAW,MAAM,MAAMA;MAAQ0C;IAAQ,CAAA;EAC7E;AACA,MAAI,OAAOpI,WAAW,UAAU;AAC9BoI,YAAQ,cAAA,IAAkB;AAC1B,WAAO,IAAID,SAASnI,QAAQ;MAAE0F;MAAQ0C;IAAQ,CAAA;EAChD;AACA,SAAO,IAAID,SAASmB,KAAKiC,UAAUvL,MAAAA,GAAS;IAAE0F;IAAQ0C;EAAQ,CAAA;AAChE;AAbSmC;","names":["AsyncLocalStorage","storage","AsyncLocalStorage","getRequestContext","ctx","getStore","Error","tryGetRequestContext","runWithRequestContext","fn","run","MIME_TYPES","UNSAFE_PATH_RE","getMimeType","filePath","dot","lastIndexOf","ext","slice","toLowerCase","isSafePath","pathname","test","readFileBun","fullPath","g","globalThis","BunRT","Bun","file","exists","buf","arrayBuffer","content","Uint8Array","size","readFileDeno","DenoRT","Deno","stat","isDirectory","readFile","byteLength","readFileNode","fs","resolveRoot","root","join","cwd","resolve","createStaticHandler","options","maxAge","resolvedRoot","request","method","toUpperCase","url","URL","decodeURIComponent","startsWith","result","endsWith","includes","contentType","headers","String","Response","status","DOCTYPE","encoder","TextEncoder","renderToStream","options","root","waitForAll","reactDomServer","renderToReadableStream","renderWithReadableStream","renderToString","console","warn","renderWithString","Error","renderFn","reactStream","allReady","doctypeStream","prependDoctype","stream","html","bytes","encode","ReadableStream","start","controller","enqueue","close","Promise","resolve","source","reader","getReader","doctypeSent","pull","value","done","read","cancel","streamToResponse","result","Response","status","headers","TheoApp","serverHandle","routes","frontendHtml","streamingRoot","staticHandler","startTime","Date","now","healthPath","readyPath","readinessChecks","opts","hp","rp","startsWith","Error","adapter","createNodeAdapter","createServer","request","handleRequest","create","app","registry","Map","module","moduleMeta","Reflect","getMetadata","allModules","imports","Mod","meta","Prov","providers","has","set","Controller","controllers","paramTypes","args","map","pt","dep","get","name","instance","postConstruct","result","Promise","walks","walkControllerMetadata","w","push","walk","sort","a","b","aP","fullPath","includes","bP","entry","paramNames","regexStr","replace","_m","compiledPattern","RegExp","compiledParamNames","needsBody","paramEntries","some","p","source","root","streaming","renderToString","html","staticDir","createStaticHandler","agents","length","autoWireAgents","listen","port","resolve","console","log","getServerHandle","close","agentRoutes","agentClasses","importFn","Function","walkAgentMetadata","compileAgent","generateAgentRoutes","getMixins","createSdkAgentStreamFn","mod","createSdkAgentStream","apiKey","llmApiKey","process","env","OPENROUTER_API_KEY","AgentClass","mixins","allToolboxes","Cls","Symbol","for","toolboxInstances","tb","toolboxes","class","compiled","createRun","agentStreamFactory","tools","llmModel","createFallbackStream","agentConfig","walkResult","compiledOptions","route","path","method","pattern","handler","guards","agentClass","methodName","mainLoop","propertyKey","handleReadinessCheck","jsonResponse","status","checks","results","all","check","race","setTimeout","healthy","message","err","allHealthy","every","r","agentName","msg","_message","_sessionId","events","type","runId","code","retryable","asyncIterator","i","next","value","done","undefined","pathname","URL","url","reqCtx","params","startedAt","runWithRequestContext","handleRequestInContext","_reqCtx","uptime","timestamp","renderToStream","streamToResponse","Response","headers","staticResponse","toUpperCase","test","ctx","createExecutionContext","GuardCtor","guard","canActivate","ex","ForbiddenException","statusCode","toJSON","match","findRoute","error","body","text","JSON","parse","bodySchema","safeParse","success","issues","data","buildArgs","Object","fromEntries","searchParams","redirect","location","handlerFn","interceptors","runInterceptors","apply","buildResponse","filters","runExceptionFilters","HttpException","verb","exec","forEach","entries","query","max","Math","index","Array","from","key","toLowerCase","stringify","n","v"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bridge/di-resolve.ts"],"sourcesContent":["/**\n * Shared DI resolution helper for guards, interceptors, and middleware.\n * Extracted to avoid DRY violation (EC-3) — was duplicated in create-server.ts\n * and theokit-plugin.ts.\n */\n\n/** DI container interface — structural match for @theokit/di Container. */\nexport interface DiContainer {\n resolve(token: Function): unknown\n}\n\n/**\n * Resolve a class via DI container if provided; otherwise fall back to bare `new`.\n * Guards, interceptors, and middleware classes all use this pattern.\n */\nexport function resolveOrNew(Ctor: Function, container?: DiContainer): object {\n if (container) {\n try {\n return container.resolve(Ctor) as object\n } catch {\n // MissingInjectableError or similar — fall back to bare new\n }\n }\n return new (Ctor as new () => object)()\n}\n"],"mappings":";;;;;AAeO,SAASA,aAAaC,MAAgBC,WAAuB;AAClE,MAAIA,WAAW;AACb,QAAI;AACF,aAAOA,UAAUC,QAAQF,IAAAA;IAC3B,QAAQ;IAER;EACF;AACA,SAAO,IAAKA,KAAAA;AACd;AATgBD;","names":["resolveOrNew","Ctor","container","resolve"]}
|