@docyrus/docyrus 0.0.22 → 0.0.24

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 (28) hide show
  1. package/README.md +12 -0
  2. package/main.js +234 -11
  3. package/main.js.map +4 -4
  4. package/package.json +6 -4
  5. package/resources/pi-agent/assets/docyrus-logo.svg +16 -0
  6. package/resources/pi-agent/extensions/architect.ts +771 -0
  7. package/resources/pi-agent/extensions/notify.ts +57 -55
  8. package/resources/pi-agent/extensions/pi-custom-compaction/CHANGELOG.md +27 -0
  9. package/resources/pi-agent/extensions/pi-custom-compaction/LICENSE +21 -0
  10. package/resources/pi-agent/extensions/pi-custom-compaction/README.md +244 -0
  11. package/resources/pi-agent/extensions/pi-custom-compaction/VENDORED_FROM.md +6 -0
  12. package/resources/pi-agent/extensions/pi-custom-compaction/banner.png +0 -0
  13. package/resources/pi-agent/extensions/pi-custom-compaction/commands/register-commands.ts +63 -0
  14. package/resources/pi-agent/extensions/pi-custom-compaction/events/register-events.ts +229 -0
  15. package/resources/pi-agent/extensions/pi-custom-compaction/index.ts +10 -0
  16. package/resources/pi-agent/extensions/pi-custom-compaction/package.json +57 -0
  17. package/resources/pi-agent/extensions/pi-custom-compaction/paths.ts +13 -0
  18. package/resources/pi-agent/extensions/pi-custom-compaction/policy/config.ts +32 -0
  19. package/resources/pi-agent/extensions/pi-custom-compaction/policy/merge.ts +67 -0
  20. package/resources/pi-agent/extensions/pi-custom-compaction/policy/parse.ts +354 -0
  21. package/resources/pi-agent/extensions/pi-custom-compaction/policy/types.ts +131 -0
  22. package/resources/pi-agent/extensions/pi-custom-compaction/runtime/model-resolution.ts +77 -0
  23. package/resources/pi-agent/extensions/pi-custom-compaction/runtime/pure.ts +56 -0
  24. package/resources/pi-agent/extensions/pi-custom-compaction/runtime/session-state.ts +244 -0
  25. package/resources/pi-agent/extensions/pi-custom-compaction/summary/generate.ts +184 -0
  26. package/resources/pi-agent/extensions/pi-custom-compaction/summary/template.ts +124 -0
  27. package/server-loader.js +4017 -0
  28. package/server-loader.js.map +7 -0
@@ -0,0 +1,4017 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+
35
+ // ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
36
+ var require_picocolors = __commonJS({
37
+ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2, module2) {
38
+ "use strict";
39
+ var p = process || {};
40
+ var argv = p.argv || [];
41
+ var env = p.env || {};
42
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
43
+ var formatter = (open, close, replace = open) => (input) => {
44
+ let string = "" + input, index = string.indexOf(close, open.length);
45
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
46
+ };
47
+ var replaceClose = (string, close, replace, index) => {
48
+ let result = "", cursor = 0;
49
+ do {
50
+ result += string.substring(cursor, index) + replace;
51
+ cursor = index + close.length;
52
+ index = string.indexOf(close, cursor);
53
+ } while (~index);
54
+ return result + string.substring(cursor);
55
+ };
56
+ var createColors = (enabled = isColorSupported) => {
57
+ let f = enabled ? formatter : () => String;
58
+ return {
59
+ isColorSupported: enabled,
60
+ reset: f("\x1B[0m", "\x1B[0m"),
61
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
62
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
63
+ italic: f("\x1B[3m", "\x1B[23m"),
64
+ underline: f("\x1B[4m", "\x1B[24m"),
65
+ inverse: f("\x1B[7m", "\x1B[27m"),
66
+ hidden: f("\x1B[8m", "\x1B[28m"),
67
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
68
+ black: f("\x1B[30m", "\x1B[39m"),
69
+ red: f("\x1B[31m", "\x1B[39m"),
70
+ green: f("\x1B[32m", "\x1B[39m"),
71
+ yellow: f("\x1B[33m", "\x1B[39m"),
72
+ blue: f("\x1B[34m", "\x1B[39m"),
73
+ magenta: f("\x1B[35m", "\x1B[39m"),
74
+ cyan: f("\x1B[36m", "\x1B[39m"),
75
+ white: f("\x1B[37m", "\x1B[39m"),
76
+ gray: f("\x1B[90m", "\x1B[39m"),
77
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
78
+ bgRed: f("\x1B[41m", "\x1B[49m"),
79
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
80
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
81
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
82
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
83
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
84
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
85
+ blackBright: f("\x1B[90m", "\x1B[39m"),
86
+ redBright: f("\x1B[91m", "\x1B[39m"),
87
+ greenBright: f("\x1B[92m", "\x1B[39m"),
88
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
89
+ blueBright: f("\x1B[94m", "\x1B[39m"),
90
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
91
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
92
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
93
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
94
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
95
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
96
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
97
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
98
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
99
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
100
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
101
+ };
102
+ };
103
+ module2.exports = createColors();
104
+ module2.exports.createColors = createColors;
105
+ }
106
+ });
107
+
108
+ // ../../node_modules/.pnpm/@hono+node-server@1.19.11_hono@4.12.8/node_modules/@hono/node-server/dist/index.mjs
109
+ var dist_exports = {};
110
+ __export(dist_exports, {
111
+ RequestError: () => RequestError,
112
+ createAdaptorServer: () => createAdaptorServer,
113
+ getRequestListener: () => getRequestListener,
114
+ serve: () => serve
115
+ });
116
+ async function readWithoutBlocking(readPromise) {
117
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
118
+ }
119
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
120
+ const cancel = (error) => {
121
+ reader.cancel(error).catch(() => {
122
+ });
123
+ };
124
+ writable.on("close", cancel);
125
+ writable.on("error", cancel);
126
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
127
+ return reader.closed.finally(() => {
128
+ writable.off("close", cancel);
129
+ writable.off("error", cancel);
130
+ });
131
+ function handleStreamError(error) {
132
+ if (error) {
133
+ writable.destroy(error);
134
+ }
135
+ }
136
+ function onDrain() {
137
+ reader.read().then(flow, handleStreamError);
138
+ }
139
+ function flow({ done, value }) {
140
+ try {
141
+ if (done) {
142
+ writable.end();
143
+ } else if (!writable.write(value)) {
144
+ writable.once("drain", onDrain);
145
+ } else {
146
+ return reader.read().then(flow, handleStreamError);
147
+ }
148
+ } catch (e) {
149
+ handleStreamError(e);
150
+ }
151
+ }
152
+ }
153
+ function writeFromReadableStream(stream, writable) {
154
+ if (stream.locked) {
155
+ throw new TypeError("ReadableStream is locked.");
156
+ } else if (writable.destroyed) {
157
+ return;
158
+ }
159
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
160
+ }
161
+ var import_http, import_http2, import_http22, import_stream, import_crypto, RequestError, toRequestError, GlobalRequest, Request2, newHeadersFromIncoming, wrapBodyStream, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, headersKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, outgoingEnded, handleRequestError, handleFetchError, handleResponseError, flushHeaders, responseViaCache, isPromise, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
162
+ var init_dist = __esm({
163
+ "../../node_modules/.pnpm/@hono+node-server@1.19.11_hono@4.12.8/node_modules/@hono/node-server/dist/index.mjs"() {
164
+ "use strict";
165
+ import_http = require("http");
166
+ import_http2 = require("http2");
167
+ import_http22 = require("http2");
168
+ import_stream = require("stream");
169
+ import_crypto = __toESM(require("crypto"), 1);
170
+ RequestError = class extends Error {
171
+ constructor(message, options) {
172
+ super(message, options);
173
+ this.name = "RequestError";
174
+ }
175
+ };
176
+ toRequestError = (e) => {
177
+ if (e instanceof RequestError) {
178
+ return e;
179
+ }
180
+ return new RequestError(e.message, { cause: e });
181
+ };
182
+ GlobalRequest = global.Request;
183
+ Request2 = class extends GlobalRequest {
184
+ constructor(input, options) {
185
+ if (typeof input === "object" && getRequestCache in input) {
186
+ input = input[getRequestCache]();
187
+ }
188
+ if (typeof options?.body?.getReader !== "undefined") {
189
+ ;
190
+ options.duplex ??= "half";
191
+ }
192
+ super(input, options);
193
+ }
194
+ };
195
+ newHeadersFromIncoming = (incoming) => {
196
+ const headerRecord = [];
197
+ const rawHeaders = incoming.rawHeaders;
198
+ for (let i = 0; i < rawHeaders.length; i += 2) {
199
+ const { [i]: key, [i + 1]: value } = rawHeaders;
200
+ if (key.charCodeAt(0) !== /*:*/
201
+ 58) {
202
+ headerRecord.push([key, value]);
203
+ }
204
+ }
205
+ return new Headers(headerRecord);
206
+ };
207
+ wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream");
208
+ newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
209
+ const init = {
210
+ method,
211
+ headers,
212
+ signal: abortController.signal
213
+ };
214
+ if (method === "TRACE") {
215
+ init.method = "GET";
216
+ const req = new Request2(url, init);
217
+ Object.defineProperty(req, "method", {
218
+ get() {
219
+ return "TRACE";
220
+ }
221
+ });
222
+ return req;
223
+ }
224
+ if (!(method === "GET" || method === "HEAD")) {
225
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
226
+ init.body = new ReadableStream({
227
+ start(controller) {
228
+ controller.enqueue(incoming.rawBody);
229
+ controller.close();
230
+ }
231
+ });
232
+ } else if (incoming[wrapBodyStream]) {
233
+ let reader;
234
+ init.body = new ReadableStream({
235
+ async pull(controller) {
236
+ try {
237
+ reader ||= import_stream.Readable.toWeb(incoming).getReader();
238
+ const { done, value } = await reader.read();
239
+ if (done) {
240
+ controller.close();
241
+ } else {
242
+ controller.enqueue(value);
243
+ }
244
+ } catch (error) {
245
+ controller.error(error);
246
+ }
247
+ }
248
+ });
249
+ } else {
250
+ init.body = import_stream.Readable.toWeb(incoming);
251
+ }
252
+ }
253
+ return new Request2(url, init);
254
+ };
255
+ getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
256
+ requestCache = /* @__PURE__ */ Symbol("requestCache");
257
+ incomingKey = /* @__PURE__ */ Symbol("incomingKey");
258
+ urlKey = /* @__PURE__ */ Symbol("urlKey");
259
+ headersKey = /* @__PURE__ */ Symbol("headersKey");
260
+ abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
261
+ getAbortController = /* @__PURE__ */ Symbol("getAbortController");
262
+ requestPrototype = {
263
+ get method() {
264
+ return this[incomingKey].method || "GET";
265
+ },
266
+ get url() {
267
+ return this[urlKey];
268
+ },
269
+ get headers() {
270
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
271
+ },
272
+ [getAbortController]() {
273
+ this[getRequestCache]();
274
+ return this[abortControllerKey];
275
+ },
276
+ [getRequestCache]() {
277
+ this[abortControllerKey] ||= new AbortController();
278
+ return this[requestCache] ||= newRequestFromIncoming(
279
+ this.method,
280
+ this[urlKey],
281
+ this.headers,
282
+ this[incomingKey],
283
+ this[abortControllerKey]
284
+ );
285
+ }
286
+ };
287
+ [
288
+ "body",
289
+ "bodyUsed",
290
+ "cache",
291
+ "credentials",
292
+ "destination",
293
+ "integrity",
294
+ "mode",
295
+ "redirect",
296
+ "referrer",
297
+ "referrerPolicy",
298
+ "signal",
299
+ "keepalive"
300
+ ].forEach((k) => {
301
+ Object.defineProperty(requestPrototype, k, {
302
+ get() {
303
+ return this[getRequestCache]()[k];
304
+ }
305
+ });
306
+ });
307
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
308
+ Object.defineProperty(requestPrototype, k, {
309
+ value: function() {
310
+ return this[getRequestCache]()[k]();
311
+ }
312
+ });
313
+ });
314
+ Object.setPrototypeOf(requestPrototype, Request2.prototype);
315
+ newRequest = (incoming, defaultHostname) => {
316
+ const req = Object.create(requestPrototype);
317
+ req[incomingKey] = incoming;
318
+ const incomingUrl = incoming.url || "";
319
+ if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
320
+ (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
321
+ if (incoming instanceof import_http22.Http2ServerRequest) {
322
+ throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
323
+ }
324
+ try {
325
+ const url2 = new URL(incomingUrl);
326
+ req[urlKey] = url2.href;
327
+ } catch (e) {
328
+ throw new RequestError("Invalid absolute URL", { cause: e });
329
+ }
330
+ return req;
331
+ }
332
+ const host = (incoming instanceof import_http22.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
333
+ if (!host) {
334
+ throw new RequestError("Missing host header");
335
+ }
336
+ let scheme;
337
+ if (incoming instanceof import_http22.Http2ServerRequest) {
338
+ scheme = incoming.scheme;
339
+ if (!(scheme === "http" || scheme === "https")) {
340
+ throw new RequestError("Unsupported scheme");
341
+ }
342
+ } else {
343
+ scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
344
+ }
345
+ const url = new URL(`${scheme}://${host}${incomingUrl}`);
346
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
347
+ throw new RequestError("Invalid host header");
348
+ }
349
+ req[urlKey] = url.href;
350
+ return req;
351
+ };
352
+ responseCache = /* @__PURE__ */ Symbol("responseCache");
353
+ getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
354
+ cacheKey = /* @__PURE__ */ Symbol("cache");
355
+ GlobalResponse = global.Response;
356
+ Response2 = class _Response {
357
+ #body;
358
+ #init;
359
+ [getResponseCache]() {
360
+ delete this[cacheKey];
361
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
362
+ }
363
+ constructor(body, init) {
364
+ let headers;
365
+ this.#body = body;
366
+ if (init instanceof _Response) {
367
+ const cachedGlobalResponse = init[responseCache];
368
+ if (cachedGlobalResponse) {
369
+ this.#init = cachedGlobalResponse;
370
+ this[getResponseCache]();
371
+ return;
372
+ } else {
373
+ this.#init = init.#init;
374
+ headers = new Headers(init.#init.headers);
375
+ }
376
+ } else {
377
+ this.#init = init;
378
+ }
379
+ if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
380
+ ;
381
+ this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
382
+ }
383
+ }
384
+ get headers() {
385
+ const cache = this[cacheKey];
386
+ if (cache) {
387
+ if (!(cache[2] instanceof Headers)) {
388
+ cache[2] = new Headers(
389
+ cache[2] || { "content-type": "text/plain; charset=UTF-8" }
390
+ );
391
+ }
392
+ return cache[2];
393
+ }
394
+ return this[getResponseCache]().headers;
395
+ }
396
+ get status() {
397
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
398
+ }
399
+ get ok() {
400
+ const status = this.status;
401
+ return status >= 200 && status < 300;
402
+ }
403
+ };
404
+ ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
405
+ Object.defineProperty(Response2.prototype, k, {
406
+ get() {
407
+ return this[getResponseCache]()[k];
408
+ }
409
+ });
410
+ });
411
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
412
+ Object.defineProperty(Response2.prototype, k, {
413
+ value: function() {
414
+ return this[getResponseCache]()[k]();
415
+ }
416
+ });
417
+ });
418
+ Object.setPrototypeOf(Response2, GlobalResponse);
419
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
420
+ buildOutgoingHttpHeaders = (headers) => {
421
+ const res = {};
422
+ if (!(headers instanceof Headers)) {
423
+ headers = new Headers(headers ?? void 0);
424
+ }
425
+ const cookies = [];
426
+ for (const [k, v] of headers) {
427
+ if (k === "set-cookie") {
428
+ cookies.push(v);
429
+ } else {
430
+ res[k] = v;
431
+ }
432
+ }
433
+ if (cookies.length > 0) {
434
+ res["set-cookie"] = cookies;
435
+ }
436
+ res["content-type"] ??= "text/plain; charset=UTF-8";
437
+ return res;
438
+ };
439
+ X_ALREADY_SENT = "x-hono-already-sent";
440
+ if (typeof global.crypto === "undefined") {
441
+ global.crypto = import_crypto.default;
442
+ }
443
+ outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
444
+ handleRequestError = () => new Response(null, {
445
+ status: 400
446
+ });
447
+ handleFetchError = (e) => new Response(null, {
448
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
449
+ });
450
+ handleResponseError = (e, outgoing) => {
451
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
452
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
453
+ console.info("The user aborted a request.");
454
+ } else {
455
+ console.error(e);
456
+ if (!outgoing.headersSent) {
457
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
458
+ }
459
+ outgoing.end(`Error: ${err.message}`);
460
+ outgoing.destroy(err);
461
+ }
462
+ };
463
+ flushHeaders = (outgoing) => {
464
+ if ("flushHeaders" in outgoing && outgoing.writable) {
465
+ outgoing.flushHeaders();
466
+ }
467
+ };
468
+ responseViaCache = async (res, outgoing) => {
469
+ let [status, body, header] = res[cacheKey];
470
+ let hasContentLength = false;
471
+ if (!header) {
472
+ header = { "content-type": "text/plain; charset=UTF-8" };
473
+ } else if (header instanceof Headers) {
474
+ hasContentLength = header.has("content-length");
475
+ header = buildOutgoingHttpHeaders(header);
476
+ } else if (Array.isArray(header)) {
477
+ const headerObj = new Headers(header);
478
+ hasContentLength = headerObj.has("content-length");
479
+ header = buildOutgoingHttpHeaders(headerObj);
480
+ } else {
481
+ for (const key in header) {
482
+ if (key.length === 14 && key.toLowerCase() === "content-length") {
483
+ hasContentLength = true;
484
+ break;
485
+ }
486
+ }
487
+ }
488
+ if (!hasContentLength) {
489
+ if (typeof body === "string") {
490
+ header["Content-Length"] = Buffer.byteLength(body);
491
+ } else if (body instanceof Uint8Array) {
492
+ header["Content-Length"] = body.byteLength;
493
+ } else if (body instanceof Blob) {
494
+ header["Content-Length"] = body.size;
495
+ }
496
+ }
497
+ outgoing.writeHead(status, header);
498
+ if (typeof body === "string" || body instanceof Uint8Array) {
499
+ outgoing.end(body);
500
+ } else if (body instanceof Blob) {
501
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
502
+ } else {
503
+ flushHeaders(outgoing);
504
+ await writeFromReadableStream(body, outgoing)?.catch(
505
+ (e) => handleResponseError(e, outgoing)
506
+ );
507
+ }
508
+ ;
509
+ outgoing[outgoingEnded]?.();
510
+ };
511
+ isPromise = (res) => typeof res.then === "function";
512
+ responseViaResponseObject = async (res, outgoing, options = {}) => {
513
+ if (isPromise(res)) {
514
+ if (options.errorHandler) {
515
+ try {
516
+ res = await res;
517
+ } catch (err) {
518
+ const errRes = await options.errorHandler(err);
519
+ if (!errRes) {
520
+ return;
521
+ }
522
+ res = errRes;
523
+ }
524
+ } else {
525
+ res = await res.catch(handleFetchError);
526
+ }
527
+ }
528
+ if (cacheKey in res) {
529
+ return responseViaCache(res, outgoing);
530
+ }
531
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
532
+ if (res.body) {
533
+ const reader = res.body.getReader();
534
+ const values = [];
535
+ let done = false;
536
+ let currentReadPromise = void 0;
537
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
538
+ let maxReadCount = 2;
539
+ for (let i = 0; i < maxReadCount; i++) {
540
+ currentReadPromise ||= reader.read();
541
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
542
+ console.error(e);
543
+ done = true;
544
+ });
545
+ if (!chunk) {
546
+ if (i === 1) {
547
+ await new Promise((resolve2) => setTimeout(resolve2));
548
+ maxReadCount = 3;
549
+ continue;
550
+ }
551
+ break;
552
+ }
553
+ currentReadPromise = void 0;
554
+ if (chunk.value) {
555
+ values.push(chunk.value);
556
+ }
557
+ if (chunk.done) {
558
+ done = true;
559
+ break;
560
+ }
561
+ }
562
+ if (done && !("content-length" in resHeaderRecord)) {
563
+ resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
564
+ }
565
+ }
566
+ outgoing.writeHead(res.status, resHeaderRecord);
567
+ values.forEach((value) => {
568
+ ;
569
+ outgoing.write(value);
570
+ });
571
+ if (done) {
572
+ outgoing.end();
573
+ } else {
574
+ if (values.length === 0) {
575
+ flushHeaders(outgoing);
576
+ }
577
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
578
+ }
579
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {
580
+ } else {
581
+ outgoing.writeHead(res.status, resHeaderRecord);
582
+ outgoing.end();
583
+ }
584
+ ;
585
+ outgoing[outgoingEnded]?.();
586
+ };
587
+ getRequestListener = (fetchCallback, options = {}) => {
588
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
589
+ if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
590
+ Object.defineProperty(global, "Request", {
591
+ value: Request2
592
+ });
593
+ Object.defineProperty(global, "Response", {
594
+ value: Response2
595
+ });
596
+ }
597
+ return async (incoming, outgoing) => {
598
+ let res, req;
599
+ try {
600
+ req = newRequest(incoming, options.hostname);
601
+ let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
602
+ if (!incomingEnded) {
603
+ ;
604
+ incoming[wrapBodyStream] = true;
605
+ incoming.on("end", () => {
606
+ incomingEnded = true;
607
+ });
608
+ if (incoming instanceof import_http2.Http2ServerRequest) {
609
+ ;
610
+ outgoing[outgoingEnded] = () => {
611
+ if (!incomingEnded) {
612
+ setTimeout(() => {
613
+ if (!incomingEnded) {
614
+ setTimeout(() => {
615
+ incoming.destroy();
616
+ outgoing.destroy();
617
+ });
618
+ }
619
+ });
620
+ }
621
+ };
622
+ }
623
+ }
624
+ outgoing.on("close", () => {
625
+ const abortController = req[abortControllerKey];
626
+ if (abortController) {
627
+ if (incoming.errored) {
628
+ req[abortControllerKey].abort(incoming.errored.toString());
629
+ } else if (!outgoing.writableFinished) {
630
+ req[abortControllerKey].abort("Client connection prematurely closed.");
631
+ }
632
+ }
633
+ if (!incomingEnded) {
634
+ setTimeout(() => {
635
+ if (!incomingEnded) {
636
+ setTimeout(() => {
637
+ incoming.destroy();
638
+ });
639
+ }
640
+ });
641
+ }
642
+ });
643
+ res = fetchCallback(req, { incoming, outgoing });
644
+ if (cacheKey in res) {
645
+ return responseViaCache(res, outgoing);
646
+ }
647
+ } catch (e) {
648
+ if (!res) {
649
+ if (options.errorHandler) {
650
+ res = await options.errorHandler(req ? e : toRequestError(e));
651
+ if (!res) {
652
+ return;
653
+ }
654
+ } else if (!req) {
655
+ res = handleRequestError();
656
+ } else {
657
+ res = handleFetchError(e);
658
+ }
659
+ } else {
660
+ return handleResponseError(e, outgoing);
661
+ }
662
+ }
663
+ try {
664
+ return await responseViaResponseObject(res, outgoing, options);
665
+ } catch (e) {
666
+ return handleResponseError(e, outgoing);
667
+ }
668
+ };
669
+ };
670
+ createAdaptorServer = (options) => {
671
+ const fetchCallback = options.fetch;
672
+ const requestListener = getRequestListener(fetchCallback, {
673
+ hostname: options.hostname,
674
+ overrideGlobalObjects: options.overrideGlobalObjects,
675
+ autoCleanupIncoming: options.autoCleanupIncoming
676
+ });
677
+ const createServer = options.createServer || import_http.createServer;
678
+ const server = createServer(options.serverOptions || {}, requestListener);
679
+ return server;
680
+ };
681
+ serve = (options, listeningListener) => {
682
+ const server = createAdaptorServer(options);
683
+ server.listen(options?.port ?? 3e3, options.hostname, () => {
684
+ const serverInfo = server.address();
685
+ listeningListener && listeningListener(serverInfo);
686
+ });
687
+ return server;
688
+ };
689
+ }
690
+ });
691
+
692
+ // src/server/server-loader.ts
693
+ var import_node_fs = require("node:fs");
694
+ var import_node_url = require("node:url");
695
+ var import_node_path3 = require("node:path");
696
+ var import_picocolors = __toESM(require_picocolors());
697
+
698
+ // src/agent/envStore.ts
699
+ var import_promises = require("node:fs/promises");
700
+ var import_node_path = require("node:path");
701
+ function createDefaultState() {
702
+ return {
703
+ version: 1,
704
+ values: {}
705
+ };
706
+ }
707
+ function normalizeState(state) {
708
+ const values = {};
709
+ for (const [key, value] of Object.entries(state.values || {})) {
710
+ const normalizedKey = key.trim();
711
+ const normalizedValue = value.trim();
712
+ if (!normalizedKey || !normalizedValue) {
713
+ continue;
714
+ }
715
+ values[normalizedKey] = normalizedValue;
716
+ }
717
+ return {
718
+ version: 1,
719
+ values
720
+ };
721
+ }
722
+ var AgentEnvStore = class {
723
+ constructor(filePath) {
724
+ this.filePath = filePath;
725
+ }
726
+ getFilePath() {
727
+ return this.filePath;
728
+ }
729
+ async readState() {
730
+ try {
731
+ const raw2 = await (0, import_promises.readFile)(this.filePath, "utf8");
732
+ const parsed = JSON.parse(raw2);
733
+ if (!parsed || parsed.version !== 1 || typeof parsed.values !== "object" || parsed.values === null) {
734
+ return createDefaultState();
735
+ }
736
+ return normalizeState(parsed);
737
+ } catch (error) {
738
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
739
+ return createDefaultState();
740
+ }
741
+ return createDefaultState();
742
+ }
743
+ }
744
+ async writeState(state) {
745
+ const normalized = normalizeState(state);
746
+ const directory = (0, import_node_path.dirname)(this.filePath);
747
+ await (0, import_promises.mkdir)(directory, {
748
+ recursive: true,
749
+ mode: 448
750
+ });
751
+ await (0, import_promises.writeFile)(this.filePath, `${JSON.stringify(normalized, null, 2)}
752
+ `, {
753
+ encoding: "utf8",
754
+ mode: 384
755
+ });
756
+ await (0, import_promises.chmod)(this.filePath, 384);
757
+ }
758
+ async setMany(values) {
759
+ const state = await this.readState();
760
+ await this.writeState({
761
+ version: 1,
762
+ values: {
763
+ ...state.values,
764
+ ...Object.fromEntries(
765
+ Object.entries(values).map(([key, value]) => [key.trim(), value.trim()]).filter(([key, value]) => key.length > 0 && value.length > 0)
766
+ )
767
+ }
768
+ });
769
+ }
770
+ async removeMany(keys) {
771
+ const state = await this.readState();
772
+ const nextValues = { ...state.values };
773
+ for (const key of keys) {
774
+ delete nextValues[key];
775
+ }
776
+ await this.writeState({
777
+ version: 1,
778
+ values: nextValues
779
+ });
780
+ }
781
+ async hydrateProcessEnv(env = process.env) {
782
+ const state = await this.readState();
783
+ for (const [key, value] of Object.entries(state.values)) {
784
+ if (!env[key]) {
785
+ env[key] = value;
786
+ }
787
+ }
788
+ return state.values;
789
+ }
790
+ async hasAny(keys) {
791
+ const state = await this.readState();
792
+ return keys.some((key) => Boolean(state.values[key] || process.env[key]));
793
+ }
794
+ };
795
+
796
+ // src/server/agentServer.ts
797
+ var import_node_child_process = require("node:child_process");
798
+ var import_promises2 = require("node:fs/promises");
799
+ var import_node_path2 = require("node:path");
800
+
801
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/compose.js
802
+ var compose = (middleware, onError, onNotFound) => {
803
+ return (context, next) => {
804
+ let index = -1;
805
+ return dispatch(0);
806
+ async function dispatch(i) {
807
+ if (i <= index) {
808
+ throw new Error("next() called multiple times");
809
+ }
810
+ index = i;
811
+ let res;
812
+ let isError = false;
813
+ let handler;
814
+ if (middleware[i]) {
815
+ handler = middleware[i][0][0];
816
+ context.req.routeIndex = i;
817
+ } else {
818
+ handler = i === middleware.length && next || void 0;
819
+ }
820
+ if (handler) {
821
+ try {
822
+ res = await handler(context, () => dispatch(i + 1));
823
+ } catch (err) {
824
+ if (err instanceof Error && onError) {
825
+ context.error = err;
826
+ res = await onError(err, context);
827
+ isError = true;
828
+ } else {
829
+ throw err;
830
+ }
831
+ }
832
+ } else {
833
+ if (context.finalized === false && onNotFound) {
834
+ res = await onNotFound(context);
835
+ }
836
+ }
837
+ if (res && (context.finalized === false || isError)) {
838
+ context.res = res;
839
+ }
840
+ return context;
841
+ }
842
+ };
843
+ };
844
+
845
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/request/constants.js
846
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
847
+
848
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/utils/body.js
849
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
850
+ const { all = false, dot = false } = options;
851
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
852
+ const contentType = headers.get("Content-Type");
853
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
854
+ return parseFormData(request, { all, dot });
855
+ }
856
+ return {};
857
+ };
858
+ async function parseFormData(request, options) {
859
+ const formData = await request.formData();
860
+ if (formData) {
861
+ return convertFormDataToBodyData(formData, options);
862
+ }
863
+ return {};
864
+ }
865
+ function convertFormDataToBodyData(formData, options) {
866
+ const form = /* @__PURE__ */ Object.create(null);
867
+ formData.forEach((value, key) => {
868
+ const shouldParseAllValues = options.all || key.endsWith("[]");
869
+ if (!shouldParseAllValues) {
870
+ form[key] = value;
871
+ } else {
872
+ handleParsingAllValues(form, key, value);
873
+ }
874
+ });
875
+ if (options.dot) {
876
+ Object.entries(form).forEach(([key, value]) => {
877
+ const shouldParseDotValues = key.includes(".");
878
+ if (shouldParseDotValues) {
879
+ handleParsingNestedValues(form, key, value);
880
+ delete form[key];
881
+ }
882
+ });
883
+ }
884
+ return form;
885
+ }
886
+ var handleParsingAllValues = (form, key, value) => {
887
+ if (form[key] !== void 0) {
888
+ if (Array.isArray(form[key])) {
889
+ ;
890
+ form[key].push(value);
891
+ } else {
892
+ form[key] = [form[key], value];
893
+ }
894
+ } else {
895
+ if (!key.endsWith("[]")) {
896
+ form[key] = value;
897
+ } else {
898
+ form[key] = [value];
899
+ }
900
+ }
901
+ };
902
+ var handleParsingNestedValues = (form, key, value) => {
903
+ if (/(?:^|\.)__proto__\./.test(key)) {
904
+ return;
905
+ }
906
+ let nestedForm = form;
907
+ const keys = key.split(".");
908
+ keys.forEach((key2, index) => {
909
+ if (index === keys.length - 1) {
910
+ nestedForm[key2] = value;
911
+ } else {
912
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
913
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
914
+ }
915
+ nestedForm = nestedForm[key2];
916
+ }
917
+ });
918
+ };
919
+
920
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/utils/url.js
921
+ var splitPath = (path) => {
922
+ const paths = path.split("/");
923
+ if (paths[0] === "") {
924
+ paths.shift();
925
+ }
926
+ return paths;
927
+ };
928
+ var splitRoutingPath = (routePath) => {
929
+ const { groups, path } = extractGroupsFromPath(routePath);
930
+ const paths = splitPath(path);
931
+ return replaceGroupMarks(paths, groups);
932
+ };
933
+ var extractGroupsFromPath = (path) => {
934
+ const groups = [];
935
+ path = path.replace(/\{[^}]+\}/g, (match2, index) => {
936
+ const mark = `@${index}`;
937
+ groups.push([mark, match2]);
938
+ return mark;
939
+ });
940
+ return { groups, path };
941
+ };
942
+ var replaceGroupMarks = (paths, groups) => {
943
+ for (let i = groups.length - 1; i >= 0; i--) {
944
+ const [mark] = groups[i];
945
+ for (let j = paths.length - 1; j >= 0; j--) {
946
+ if (paths[j].includes(mark)) {
947
+ paths[j] = paths[j].replace(mark, groups[i][1]);
948
+ break;
949
+ }
950
+ }
951
+ }
952
+ return paths;
953
+ };
954
+ var patternCache = {};
955
+ var getPattern = (label, next) => {
956
+ if (label === "*") {
957
+ return "*";
958
+ }
959
+ const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
960
+ if (match2) {
961
+ const cacheKey2 = `${label}#${next}`;
962
+ if (!patternCache[cacheKey2]) {
963
+ if (match2[2]) {
964
+ patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
965
+ } else {
966
+ patternCache[cacheKey2] = [label, match2[1], true];
967
+ }
968
+ }
969
+ return patternCache[cacheKey2];
970
+ }
971
+ return null;
972
+ };
973
+ var tryDecode = (str, decoder) => {
974
+ try {
975
+ return decoder(str);
976
+ } catch {
977
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
978
+ try {
979
+ return decoder(match2);
980
+ } catch {
981
+ return match2;
982
+ }
983
+ });
984
+ }
985
+ };
986
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
987
+ var getPath = (request) => {
988
+ const url = request.url;
989
+ const start = url.indexOf("/", url.indexOf(":") + 4);
990
+ let i = start;
991
+ for (; i < url.length; i++) {
992
+ const charCode = url.charCodeAt(i);
993
+ if (charCode === 37) {
994
+ const queryIndex = url.indexOf("?", i);
995
+ const hashIndex = url.indexOf("#", i);
996
+ const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
997
+ const path = url.slice(start, end);
998
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
999
+ } else if (charCode === 63 || charCode === 35) {
1000
+ break;
1001
+ }
1002
+ }
1003
+ return url.slice(start, i);
1004
+ };
1005
+ var getPathNoStrict = (request) => {
1006
+ const result = getPath(request);
1007
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
1008
+ };
1009
+ var mergePath = (base, sub, ...rest) => {
1010
+ if (rest.length) {
1011
+ sub = mergePath(sub, ...rest);
1012
+ }
1013
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
1014
+ };
1015
+ var checkOptionalParameter = (path) => {
1016
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
1017
+ return null;
1018
+ }
1019
+ const segments = path.split("/");
1020
+ const results = [];
1021
+ let basePath = "";
1022
+ segments.forEach((segment) => {
1023
+ if (segment !== "" && !/\:/.test(segment)) {
1024
+ basePath += "/" + segment;
1025
+ } else if (/\:/.test(segment)) {
1026
+ if (/\?/.test(segment)) {
1027
+ if (results.length === 0 && basePath === "") {
1028
+ results.push("/");
1029
+ } else {
1030
+ results.push(basePath);
1031
+ }
1032
+ const optionalSegment = segment.replace("?", "");
1033
+ basePath += "/" + optionalSegment;
1034
+ results.push(basePath);
1035
+ } else {
1036
+ basePath += "/" + segment;
1037
+ }
1038
+ }
1039
+ });
1040
+ return results.filter((v, i, a) => a.indexOf(v) === i);
1041
+ };
1042
+ var _decodeURI = (value) => {
1043
+ if (!/[%+]/.test(value)) {
1044
+ return value;
1045
+ }
1046
+ if (value.indexOf("+") !== -1) {
1047
+ value = value.replace(/\+/g, " ");
1048
+ }
1049
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
1050
+ };
1051
+ var _getQueryParam = (url, key, multiple) => {
1052
+ let encoded;
1053
+ if (!multiple && key && !/[%+]/.test(key)) {
1054
+ let keyIndex2 = url.indexOf("?", 8);
1055
+ if (keyIndex2 === -1) {
1056
+ return void 0;
1057
+ }
1058
+ if (!url.startsWith(key, keyIndex2 + 1)) {
1059
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1060
+ }
1061
+ while (keyIndex2 !== -1) {
1062
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
1063
+ if (trailingKeyCode === 61) {
1064
+ const valueIndex = keyIndex2 + key.length + 2;
1065
+ const endIndex = url.indexOf("&", valueIndex);
1066
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
1067
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
1068
+ return "";
1069
+ }
1070
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1071
+ }
1072
+ encoded = /[%+]/.test(url);
1073
+ if (!encoded) {
1074
+ return void 0;
1075
+ }
1076
+ }
1077
+ const results = {};
1078
+ encoded ??= /[%+]/.test(url);
1079
+ let keyIndex = url.indexOf("?", 8);
1080
+ while (keyIndex !== -1) {
1081
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
1082
+ let valueIndex = url.indexOf("=", keyIndex);
1083
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
1084
+ valueIndex = -1;
1085
+ }
1086
+ let name = url.slice(
1087
+ keyIndex + 1,
1088
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
1089
+ );
1090
+ if (encoded) {
1091
+ name = _decodeURI(name);
1092
+ }
1093
+ keyIndex = nextKeyIndex;
1094
+ if (name === "") {
1095
+ continue;
1096
+ }
1097
+ let value;
1098
+ if (valueIndex === -1) {
1099
+ value = "";
1100
+ } else {
1101
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
1102
+ if (encoded) {
1103
+ value = _decodeURI(value);
1104
+ }
1105
+ }
1106
+ if (multiple) {
1107
+ if (!(results[name] && Array.isArray(results[name]))) {
1108
+ results[name] = [];
1109
+ }
1110
+ ;
1111
+ results[name].push(value);
1112
+ } else {
1113
+ results[name] ??= value;
1114
+ }
1115
+ }
1116
+ return key ? results[key] : results;
1117
+ };
1118
+ var getQueryParam = _getQueryParam;
1119
+ var getQueryParams = (url, key) => {
1120
+ return _getQueryParam(url, key, true);
1121
+ };
1122
+ var decodeURIComponent_ = decodeURIComponent;
1123
+
1124
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/request.js
1125
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
1126
+ var HonoRequest = class {
1127
+ /**
1128
+ * `.raw` can get the raw Request object.
1129
+ *
1130
+ * @see {@link https://hono.dev/docs/api/request#raw}
1131
+ *
1132
+ * @example
1133
+ * ```ts
1134
+ * // For Cloudflare Workers
1135
+ * app.post('/', async (c) => {
1136
+ * const metadata = c.req.raw.cf?.hostMetadata?
1137
+ * ...
1138
+ * })
1139
+ * ```
1140
+ */
1141
+ raw;
1142
+ #validatedData;
1143
+ // Short name of validatedData
1144
+ #matchResult;
1145
+ routeIndex = 0;
1146
+ /**
1147
+ * `.path` can get the pathname of the request.
1148
+ *
1149
+ * @see {@link https://hono.dev/docs/api/request#path}
1150
+ *
1151
+ * @example
1152
+ * ```ts
1153
+ * app.get('/about/me', (c) => {
1154
+ * const pathname = c.req.path // `/about/me`
1155
+ * })
1156
+ * ```
1157
+ */
1158
+ path;
1159
+ bodyCache = {};
1160
+ constructor(request, path = "/", matchResult = [[]]) {
1161
+ this.raw = request;
1162
+ this.path = path;
1163
+ this.#matchResult = matchResult;
1164
+ this.#validatedData = {};
1165
+ }
1166
+ param(key) {
1167
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
1168
+ }
1169
+ #getDecodedParam(key) {
1170
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
1171
+ const param = this.#getParamValue(paramKey);
1172
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
1173
+ }
1174
+ #getAllDecodedParams() {
1175
+ const decoded = {};
1176
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
1177
+ for (const key of keys) {
1178
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
1179
+ if (value !== void 0) {
1180
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
1181
+ }
1182
+ }
1183
+ return decoded;
1184
+ }
1185
+ #getParamValue(paramKey) {
1186
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
1187
+ }
1188
+ query(key) {
1189
+ return getQueryParam(this.url, key);
1190
+ }
1191
+ queries(key) {
1192
+ return getQueryParams(this.url, key);
1193
+ }
1194
+ header(name) {
1195
+ if (name) {
1196
+ return this.raw.headers.get(name) ?? void 0;
1197
+ }
1198
+ const headerData = {};
1199
+ this.raw.headers.forEach((value, key) => {
1200
+ headerData[key] = value;
1201
+ });
1202
+ return headerData;
1203
+ }
1204
+ async parseBody(options) {
1205
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
1206
+ }
1207
+ #cachedBody = (key) => {
1208
+ const { bodyCache, raw: raw2 } = this;
1209
+ const cachedBody = bodyCache[key];
1210
+ if (cachedBody) {
1211
+ return cachedBody;
1212
+ }
1213
+ const anyCachedKey = Object.keys(bodyCache)[0];
1214
+ if (anyCachedKey) {
1215
+ return bodyCache[anyCachedKey].then((body) => {
1216
+ if (anyCachedKey === "json") {
1217
+ body = JSON.stringify(body);
1218
+ }
1219
+ return new Response(body)[key]();
1220
+ });
1221
+ }
1222
+ return bodyCache[key] = raw2[key]();
1223
+ };
1224
+ /**
1225
+ * `.json()` can parse Request body of type `application/json`
1226
+ *
1227
+ * @see {@link https://hono.dev/docs/api/request#json}
1228
+ *
1229
+ * @example
1230
+ * ```ts
1231
+ * app.post('/entry', async (c) => {
1232
+ * const body = await c.req.json()
1233
+ * })
1234
+ * ```
1235
+ */
1236
+ json() {
1237
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
1238
+ }
1239
+ /**
1240
+ * `.text()` can parse Request body of type `text/plain`
1241
+ *
1242
+ * @see {@link https://hono.dev/docs/api/request#text}
1243
+ *
1244
+ * @example
1245
+ * ```ts
1246
+ * app.post('/entry', async (c) => {
1247
+ * const body = await c.req.text()
1248
+ * })
1249
+ * ```
1250
+ */
1251
+ text() {
1252
+ return this.#cachedBody("text");
1253
+ }
1254
+ /**
1255
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
1256
+ *
1257
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
1258
+ *
1259
+ * @example
1260
+ * ```ts
1261
+ * app.post('/entry', async (c) => {
1262
+ * const body = await c.req.arrayBuffer()
1263
+ * })
1264
+ * ```
1265
+ */
1266
+ arrayBuffer() {
1267
+ return this.#cachedBody("arrayBuffer");
1268
+ }
1269
+ /**
1270
+ * Parses the request body as a `Blob`.
1271
+ * @example
1272
+ * ```ts
1273
+ * app.post('/entry', async (c) => {
1274
+ * const body = await c.req.blob();
1275
+ * });
1276
+ * ```
1277
+ * @see https://hono.dev/docs/api/request#blob
1278
+ */
1279
+ blob() {
1280
+ return this.#cachedBody("blob");
1281
+ }
1282
+ /**
1283
+ * Parses the request body as `FormData`.
1284
+ * @example
1285
+ * ```ts
1286
+ * app.post('/entry', async (c) => {
1287
+ * const body = await c.req.formData();
1288
+ * });
1289
+ * ```
1290
+ * @see https://hono.dev/docs/api/request#formdata
1291
+ */
1292
+ formData() {
1293
+ return this.#cachedBody("formData");
1294
+ }
1295
+ /**
1296
+ * Adds validated data to the request.
1297
+ *
1298
+ * @param target - The target of the validation.
1299
+ * @param data - The validated data to add.
1300
+ */
1301
+ addValidatedData(target, data) {
1302
+ this.#validatedData[target] = data;
1303
+ }
1304
+ valid(target) {
1305
+ return this.#validatedData[target];
1306
+ }
1307
+ /**
1308
+ * `.url()` can get the request url strings.
1309
+ *
1310
+ * @see {@link https://hono.dev/docs/api/request#url}
1311
+ *
1312
+ * @example
1313
+ * ```ts
1314
+ * app.get('/about/me', (c) => {
1315
+ * const url = c.req.url // `http://localhost:8787/about/me`
1316
+ * ...
1317
+ * })
1318
+ * ```
1319
+ */
1320
+ get url() {
1321
+ return this.raw.url;
1322
+ }
1323
+ /**
1324
+ * `.method()` can get the method name of the request.
1325
+ *
1326
+ * @see {@link https://hono.dev/docs/api/request#method}
1327
+ *
1328
+ * @example
1329
+ * ```ts
1330
+ * app.get('/about/me', (c) => {
1331
+ * const method = c.req.method // `GET`
1332
+ * })
1333
+ * ```
1334
+ */
1335
+ get method() {
1336
+ return this.raw.method;
1337
+ }
1338
+ get [GET_MATCH_RESULT]() {
1339
+ return this.#matchResult;
1340
+ }
1341
+ /**
1342
+ * `.matchedRoutes()` can return a matched route in the handler
1343
+ *
1344
+ * @deprecated
1345
+ *
1346
+ * Use matchedRoutes helper defined in "hono/route" instead.
1347
+ *
1348
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
1349
+ *
1350
+ * @example
1351
+ * ```ts
1352
+ * app.use('*', async function logger(c, next) {
1353
+ * await next()
1354
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
1355
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
1356
+ * console.log(
1357
+ * method,
1358
+ * ' ',
1359
+ * path,
1360
+ * ' '.repeat(Math.max(10 - path.length, 0)),
1361
+ * name,
1362
+ * i === c.req.routeIndex ? '<- respond from here' : ''
1363
+ * )
1364
+ * })
1365
+ * })
1366
+ * ```
1367
+ */
1368
+ get matchedRoutes() {
1369
+ return this.#matchResult[0].map(([[, route]]) => route);
1370
+ }
1371
+ /**
1372
+ * `routePath()` can retrieve the path registered within the handler
1373
+ *
1374
+ * @deprecated
1375
+ *
1376
+ * Use routePath helper defined in "hono/route" instead.
1377
+ *
1378
+ * @see {@link https://hono.dev/docs/api/request#routepath}
1379
+ *
1380
+ * @example
1381
+ * ```ts
1382
+ * app.get('/posts/:id', (c) => {
1383
+ * return c.json({ path: c.req.routePath })
1384
+ * })
1385
+ * ```
1386
+ */
1387
+ get routePath() {
1388
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
1389
+ }
1390
+ };
1391
+
1392
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/utils/html.js
1393
+ var HtmlEscapedCallbackPhase = {
1394
+ Stringify: 1,
1395
+ BeforeStream: 2,
1396
+ Stream: 3
1397
+ };
1398
+ var raw = (value, callbacks) => {
1399
+ const escapedString = new String(value);
1400
+ escapedString.isEscaped = true;
1401
+ escapedString.callbacks = callbacks;
1402
+ return escapedString;
1403
+ };
1404
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
1405
+ if (typeof str === "object" && !(str instanceof String)) {
1406
+ if (!(str instanceof Promise)) {
1407
+ str = str.toString();
1408
+ }
1409
+ if (str instanceof Promise) {
1410
+ str = await str;
1411
+ }
1412
+ }
1413
+ const callbacks = str.callbacks;
1414
+ if (!callbacks?.length) {
1415
+ return Promise.resolve(str);
1416
+ }
1417
+ if (buffer) {
1418
+ buffer[0] += str;
1419
+ } else {
1420
+ buffer = [str];
1421
+ }
1422
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
1423
+ (res) => Promise.all(
1424
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
1425
+ ).then(() => buffer[0])
1426
+ );
1427
+ if (preserveCallbacks) {
1428
+ return raw(await resStr, callbacks);
1429
+ } else {
1430
+ return resStr;
1431
+ }
1432
+ };
1433
+
1434
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/context.js
1435
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
1436
+ var setDefaultContentType = (contentType, headers) => {
1437
+ return {
1438
+ "Content-Type": contentType,
1439
+ ...headers
1440
+ };
1441
+ };
1442
+ var createResponseInstance = (body, init) => new Response(body, init);
1443
+ var Context = class {
1444
+ #rawRequest;
1445
+ #req;
1446
+ /**
1447
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
1448
+ *
1449
+ * @see {@link https://hono.dev/docs/api/context#env}
1450
+ *
1451
+ * @example
1452
+ * ```ts
1453
+ * // Environment object for Cloudflare Workers
1454
+ * app.get('*', async c => {
1455
+ * const counter = c.env.COUNTER
1456
+ * })
1457
+ * ```
1458
+ */
1459
+ env = {};
1460
+ #var;
1461
+ finalized = false;
1462
+ /**
1463
+ * `.error` can get the error object from the middleware if the Handler throws an error.
1464
+ *
1465
+ * @see {@link https://hono.dev/docs/api/context#error}
1466
+ *
1467
+ * @example
1468
+ * ```ts
1469
+ * app.use('*', async (c, next) => {
1470
+ * await next()
1471
+ * if (c.error) {
1472
+ * // do something...
1473
+ * }
1474
+ * })
1475
+ * ```
1476
+ */
1477
+ error;
1478
+ #status;
1479
+ #executionCtx;
1480
+ #res;
1481
+ #layout;
1482
+ #renderer;
1483
+ #notFoundHandler;
1484
+ #preparedHeaders;
1485
+ #matchResult;
1486
+ #path;
1487
+ /**
1488
+ * Creates an instance of the Context class.
1489
+ *
1490
+ * @param req - The Request object.
1491
+ * @param options - Optional configuration options for the context.
1492
+ */
1493
+ constructor(req, options) {
1494
+ this.#rawRequest = req;
1495
+ if (options) {
1496
+ this.#executionCtx = options.executionCtx;
1497
+ this.env = options.env;
1498
+ this.#notFoundHandler = options.notFoundHandler;
1499
+ this.#path = options.path;
1500
+ this.#matchResult = options.matchResult;
1501
+ }
1502
+ }
1503
+ /**
1504
+ * `.req` is the instance of {@link HonoRequest}.
1505
+ */
1506
+ get req() {
1507
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
1508
+ return this.#req;
1509
+ }
1510
+ /**
1511
+ * @see {@link https://hono.dev/docs/api/context#event}
1512
+ * The FetchEvent associated with the current request.
1513
+ *
1514
+ * @throws Will throw an error if the context does not have a FetchEvent.
1515
+ */
1516
+ get event() {
1517
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
1518
+ return this.#executionCtx;
1519
+ } else {
1520
+ throw Error("This context has no FetchEvent");
1521
+ }
1522
+ }
1523
+ /**
1524
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
1525
+ * The ExecutionContext associated with the current request.
1526
+ *
1527
+ * @throws Will throw an error if the context does not have an ExecutionContext.
1528
+ */
1529
+ get executionCtx() {
1530
+ if (this.#executionCtx) {
1531
+ return this.#executionCtx;
1532
+ } else {
1533
+ throw Error("This context has no ExecutionContext");
1534
+ }
1535
+ }
1536
+ /**
1537
+ * @see {@link https://hono.dev/docs/api/context#res}
1538
+ * The Response object for the current request.
1539
+ */
1540
+ get res() {
1541
+ return this.#res ||= createResponseInstance(null, {
1542
+ headers: this.#preparedHeaders ??= new Headers()
1543
+ });
1544
+ }
1545
+ /**
1546
+ * Sets the Response object for the current request.
1547
+ *
1548
+ * @param _res - The Response object to set.
1549
+ */
1550
+ set res(_res) {
1551
+ if (this.#res && _res) {
1552
+ _res = createResponseInstance(_res.body, _res);
1553
+ for (const [k, v] of this.#res.headers.entries()) {
1554
+ if (k === "content-type") {
1555
+ continue;
1556
+ }
1557
+ if (k === "set-cookie") {
1558
+ const cookies = this.#res.headers.getSetCookie();
1559
+ _res.headers.delete("set-cookie");
1560
+ for (const cookie of cookies) {
1561
+ _res.headers.append("set-cookie", cookie);
1562
+ }
1563
+ } else {
1564
+ _res.headers.set(k, v);
1565
+ }
1566
+ }
1567
+ }
1568
+ this.#res = _res;
1569
+ this.finalized = true;
1570
+ }
1571
+ /**
1572
+ * `.render()` can create a response within a layout.
1573
+ *
1574
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1575
+ *
1576
+ * @example
1577
+ * ```ts
1578
+ * app.get('/', (c) => {
1579
+ * return c.render('Hello!')
1580
+ * })
1581
+ * ```
1582
+ */
1583
+ render = (...args) => {
1584
+ this.#renderer ??= (content) => this.html(content);
1585
+ return this.#renderer(...args);
1586
+ };
1587
+ /**
1588
+ * Sets the layout for the response.
1589
+ *
1590
+ * @param layout - The layout to set.
1591
+ * @returns The layout function.
1592
+ */
1593
+ setLayout = (layout) => this.#layout = layout;
1594
+ /**
1595
+ * Gets the current layout for the response.
1596
+ *
1597
+ * @returns The current layout function.
1598
+ */
1599
+ getLayout = () => this.#layout;
1600
+ /**
1601
+ * `.setRenderer()` can set the layout in the custom middleware.
1602
+ *
1603
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1604
+ *
1605
+ * @example
1606
+ * ```tsx
1607
+ * app.use('*', async (c, next) => {
1608
+ * c.setRenderer((content) => {
1609
+ * return c.html(
1610
+ * <html>
1611
+ * <body>
1612
+ * <p>{content}</p>
1613
+ * </body>
1614
+ * </html>
1615
+ * )
1616
+ * })
1617
+ * await next()
1618
+ * })
1619
+ * ```
1620
+ */
1621
+ setRenderer = (renderer) => {
1622
+ this.#renderer = renderer;
1623
+ };
1624
+ /**
1625
+ * `.header()` can set headers.
1626
+ *
1627
+ * @see {@link https://hono.dev/docs/api/context#header}
1628
+ *
1629
+ * @example
1630
+ * ```ts
1631
+ * app.get('/welcome', (c) => {
1632
+ * // Set headers
1633
+ * c.header('X-Message', 'Hello!')
1634
+ * c.header('Content-Type', 'text/plain')
1635
+ *
1636
+ * return c.body('Thank you for coming')
1637
+ * })
1638
+ * ```
1639
+ */
1640
+ header = (name, value, options) => {
1641
+ if (this.finalized) {
1642
+ this.#res = createResponseInstance(this.#res.body, this.#res);
1643
+ }
1644
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
1645
+ if (value === void 0) {
1646
+ headers.delete(name);
1647
+ } else if (options?.append) {
1648
+ headers.append(name, value);
1649
+ } else {
1650
+ headers.set(name, value);
1651
+ }
1652
+ };
1653
+ status = (status) => {
1654
+ this.#status = status;
1655
+ };
1656
+ /**
1657
+ * `.set()` can set the value specified by the key.
1658
+ *
1659
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1660
+ *
1661
+ * @example
1662
+ * ```ts
1663
+ * app.use('*', async (c, next) => {
1664
+ * c.set('message', 'Hono is hot!!')
1665
+ * await next()
1666
+ * })
1667
+ * ```
1668
+ */
1669
+ set = (key, value) => {
1670
+ this.#var ??= /* @__PURE__ */ new Map();
1671
+ this.#var.set(key, value);
1672
+ };
1673
+ /**
1674
+ * `.get()` can use the value specified by the key.
1675
+ *
1676
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1677
+ *
1678
+ * @example
1679
+ * ```ts
1680
+ * app.get('/', (c) => {
1681
+ * const message = c.get('message')
1682
+ * return c.text(`The message is "${message}"`)
1683
+ * })
1684
+ * ```
1685
+ */
1686
+ get = (key) => {
1687
+ return this.#var ? this.#var.get(key) : void 0;
1688
+ };
1689
+ /**
1690
+ * `.var` can access the value of a variable.
1691
+ *
1692
+ * @see {@link https://hono.dev/docs/api/context#var}
1693
+ *
1694
+ * @example
1695
+ * ```ts
1696
+ * const result = c.var.client.oneMethod()
1697
+ * ```
1698
+ */
1699
+ // c.var.propName is a read-only
1700
+ get var() {
1701
+ if (!this.#var) {
1702
+ return {};
1703
+ }
1704
+ return Object.fromEntries(this.#var);
1705
+ }
1706
+ #newResponse(data, arg, headers) {
1707
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
1708
+ if (typeof arg === "object" && "headers" in arg) {
1709
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
1710
+ for (const [key, value] of argHeaders) {
1711
+ if (key.toLowerCase() === "set-cookie") {
1712
+ responseHeaders.append(key, value);
1713
+ } else {
1714
+ responseHeaders.set(key, value);
1715
+ }
1716
+ }
1717
+ }
1718
+ if (headers) {
1719
+ for (const [k, v] of Object.entries(headers)) {
1720
+ if (typeof v === "string") {
1721
+ responseHeaders.set(k, v);
1722
+ } else {
1723
+ responseHeaders.delete(k);
1724
+ for (const v2 of v) {
1725
+ responseHeaders.append(k, v2);
1726
+ }
1727
+ }
1728
+ }
1729
+ }
1730
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
1731
+ return createResponseInstance(data, { status, headers: responseHeaders });
1732
+ }
1733
+ newResponse = (...args) => this.#newResponse(...args);
1734
+ /**
1735
+ * `.body()` can return the HTTP response.
1736
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
1737
+ * This can also be set in `.text()`, `.json()` and so on.
1738
+ *
1739
+ * @see {@link https://hono.dev/docs/api/context#body}
1740
+ *
1741
+ * @example
1742
+ * ```ts
1743
+ * app.get('/welcome', (c) => {
1744
+ * // Set headers
1745
+ * c.header('X-Message', 'Hello!')
1746
+ * c.header('Content-Type', 'text/plain')
1747
+ * // Set HTTP status code
1748
+ * c.status(201)
1749
+ *
1750
+ * // Return the response body
1751
+ * return c.body('Thank you for coming')
1752
+ * })
1753
+ * ```
1754
+ */
1755
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
1756
+ /**
1757
+ * `.text()` can render text as `Content-Type:text/plain`.
1758
+ *
1759
+ * @see {@link https://hono.dev/docs/api/context#text}
1760
+ *
1761
+ * @example
1762
+ * ```ts
1763
+ * app.get('/say', (c) => {
1764
+ * return c.text('Hello!')
1765
+ * })
1766
+ * ```
1767
+ */
1768
+ text = (text, arg, headers) => {
1769
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
1770
+ text,
1771
+ arg,
1772
+ setDefaultContentType(TEXT_PLAIN, headers)
1773
+ );
1774
+ };
1775
+ /**
1776
+ * `.json()` can render JSON as `Content-Type:application/json`.
1777
+ *
1778
+ * @see {@link https://hono.dev/docs/api/context#json}
1779
+ *
1780
+ * @example
1781
+ * ```ts
1782
+ * app.get('/api', (c) => {
1783
+ * return c.json({ message: 'Hello!' })
1784
+ * })
1785
+ * ```
1786
+ */
1787
+ json = (object, arg, headers) => {
1788
+ return this.#newResponse(
1789
+ JSON.stringify(object),
1790
+ arg,
1791
+ setDefaultContentType("application/json", headers)
1792
+ );
1793
+ };
1794
+ html = (html, arg, headers) => {
1795
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
1796
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
1797
+ };
1798
+ /**
1799
+ * `.redirect()` can Redirect, default status code is 302.
1800
+ *
1801
+ * @see {@link https://hono.dev/docs/api/context#redirect}
1802
+ *
1803
+ * @example
1804
+ * ```ts
1805
+ * app.get('/redirect', (c) => {
1806
+ * return c.redirect('/')
1807
+ * })
1808
+ * app.get('/redirect-permanently', (c) => {
1809
+ * return c.redirect('/', 301)
1810
+ * })
1811
+ * ```
1812
+ */
1813
+ redirect = (location, status) => {
1814
+ const locationString = String(location);
1815
+ this.header(
1816
+ "Location",
1817
+ // Multibyes should be encoded
1818
+ // eslint-disable-next-line no-control-regex
1819
+ !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
1820
+ );
1821
+ return this.newResponse(null, status ?? 302);
1822
+ };
1823
+ /**
1824
+ * `.notFound()` can return the Not Found Response.
1825
+ *
1826
+ * @see {@link https://hono.dev/docs/api/context#notfound}
1827
+ *
1828
+ * @example
1829
+ * ```ts
1830
+ * app.get('/notfound', (c) => {
1831
+ * return c.notFound()
1832
+ * })
1833
+ * ```
1834
+ */
1835
+ notFound = () => {
1836
+ this.#notFoundHandler ??= () => createResponseInstance();
1837
+ return this.#notFoundHandler(this);
1838
+ };
1839
+ };
1840
+
1841
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router.js
1842
+ var METHOD_NAME_ALL = "ALL";
1843
+ var METHOD_NAME_ALL_LOWERCASE = "all";
1844
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1845
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1846
+ var UnsupportedPathError = class extends Error {
1847
+ };
1848
+
1849
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/utils/constants.js
1850
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1851
+
1852
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/hono-base.js
1853
+ var notFoundHandler = (c) => {
1854
+ return c.text("404 Not Found", 404);
1855
+ };
1856
+ var errorHandler = (err, c) => {
1857
+ if ("getResponse" in err) {
1858
+ const res = err.getResponse();
1859
+ return c.newResponse(res.body, res);
1860
+ }
1861
+ console.error(err);
1862
+ return c.text("Internal Server Error", 500);
1863
+ };
1864
+ var Hono = class _Hono {
1865
+ get;
1866
+ post;
1867
+ put;
1868
+ delete;
1869
+ options;
1870
+ patch;
1871
+ all;
1872
+ on;
1873
+ use;
1874
+ /*
1875
+ This class is like an abstract class and does not have a router.
1876
+ To use it, inherit the class and implement router in the constructor.
1877
+ */
1878
+ router;
1879
+ getPath;
1880
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1881
+ _basePath = "/";
1882
+ #path = "/";
1883
+ routes = [];
1884
+ constructor(options = {}) {
1885
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1886
+ allMethods.forEach((method) => {
1887
+ this[method] = (args1, ...args) => {
1888
+ if (typeof args1 === "string") {
1889
+ this.#path = args1;
1890
+ } else {
1891
+ this.#addRoute(method, this.#path, args1);
1892
+ }
1893
+ args.forEach((handler) => {
1894
+ this.#addRoute(method, this.#path, handler);
1895
+ });
1896
+ return this;
1897
+ };
1898
+ });
1899
+ this.on = (method, path, ...handlers) => {
1900
+ for (const p of [path].flat()) {
1901
+ this.#path = p;
1902
+ for (const m of [method].flat()) {
1903
+ handlers.map((handler) => {
1904
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1905
+ });
1906
+ }
1907
+ }
1908
+ return this;
1909
+ };
1910
+ this.use = (arg1, ...handlers) => {
1911
+ if (typeof arg1 === "string") {
1912
+ this.#path = arg1;
1913
+ } else {
1914
+ this.#path = "*";
1915
+ handlers.unshift(arg1);
1916
+ }
1917
+ handlers.forEach((handler) => {
1918
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1919
+ });
1920
+ return this;
1921
+ };
1922
+ const { strict, ...optionsWithoutStrict } = options;
1923
+ Object.assign(this, optionsWithoutStrict);
1924
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1925
+ }
1926
+ #clone() {
1927
+ const clone = new _Hono({
1928
+ router: this.router,
1929
+ getPath: this.getPath
1930
+ });
1931
+ clone.errorHandler = this.errorHandler;
1932
+ clone.#notFoundHandler = this.#notFoundHandler;
1933
+ clone.routes = this.routes;
1934
+ return clone;
1935
+ }
1936
+ #notFoundHandler = notFoundHandler;
1937
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1938
+ errorHandler = errorHandler;
1939
+ /**
1940
+ * `.route()` allows grouping other Hono instance in routes.
1941
+ *
1942
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
1943
+ *
1944
+ * @param {string} path - base Path
1945
+ * @param {Hono} app - other Hono instance
1946
+ * @returns {Hono} routed Hono instance
1947
+ *
1948
+ * @example
1949
+ * ```ts
1950
+ * const app = new Hono()
1951
+ * const app2 = new Hono()
1952
+ *
1953
+ * app2.get("/user", (c) => c.text("user"))
1954
+ * app.route("/api", app2) // GET /api/user
1955
+ * ```
1956
+ */
1957
+ route(path, app) {
1958
+ const subApp = this.basePath(path);
1959
+ app.routes.map((r) => {
1960
+ let handler;
1961
+ if (app.errorHandler === errorHandler) {
1962
+ handler = r.handler;
1963
+ } else {
1964
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
1965
+ handler[COMPOSED_HANDLER] = r.handler;
1966
+ }
1967
+ subApp.#addRoute(r.method, r.path, handler);
1968
+ });
1969
+ return this;
1970
+ }
1971
+ /**
1972
+ * `.basePath()` allows base paths to be specified.
1973
+ *
1974
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
1975
+ *
1976
+ * @param {string} path - base Path
1977
+ * @returns {Hono} changed Hono instance
1978
+ *
1979
+ * @example
1980
+ * ```ts
1981
+ * const api = new Hono().basePath('/api')
1982
+ * ```
1983
+ */
1984
+ basePath(path) {
1985
+ const subApp = this.#clone();
1986
+ subApp._basePath = mergePath(this._basePath, path);
1987
+ return subApp;
1988
+ }
1989
+ /**
1990
+ * `.onError()` handles an error and returns a customized Response.
1991
+ *
1992
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
1993
+ *
1994
+ * @param {ErrorHandler} handler - request Handler for error
1995
+ * @returns {Hono} changed Hono instance
1996
+ *
1997
+ * @example
1998
+ * ```ts
1999
+ * app.onError((err, c) => {
2000
+ * console.error(`${err}`)
2001
+ * return c.text('Custom Error Message', 500)
2002
+ * })
2003
+ * ```
2004
+ */
2005
+ onError = (handler) => {
2006
+ this.errorHandler = handler;
2007
+ return this;
2008
+ };
2009
+ /**
2010
+ * `.notFound()` allows you to customize a Not Found Response.
2011
+ *
2012
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
2013
+ *
2014
+ * @param {NotFoundHandler} handler - request handler for not-found
2015
+ * @returns {Hono} changed Hono instance
2016
+ *
2017
+ * @example
2018
+ * ```ts
2019
+ * app.notFound((c) => {
2020
+ * return c.text('Custom 404 Message', 404)
2021
+ * })
2022
+ * ```
2023
+ */
2024
+ notFound = (handler) => {
2025
+ this.#notFoundHandler = handler;
2026
+ return this;
2027
+ };
2028
+ /**
2029
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
2030
+ *
2031
+ * @see {@link https://hono.dev/docs/api/hono#mount}
2032
+ *
2033
+ * @param {string} path - base Path
2034
+ * @param {Function} applicationHandler - other Request Handler
2035
+ * @param {MountOptions} [options] - options of `.mount()`
2036
+ * @returns {Hono} mounted Hono instance
2037
+ *
2038
+ * @example
2039
+ * ```ts
2040
+ * import { Router as IttyRouter } from 'itty-router'
2041
+ * import { Hono } from 'hono'
2042
+ * // Create itty-router application
2043
+ * const ittyRouter = IttyRouter()
2044
+ * // GET /itty-router/hello
2045
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
2046
+ *
2047
+ * const app = new Hono()
2048
+ * app.mount('/itty-router', ittyRouter.handle)
2049
+ * ```
2050
+ *
2051
+ * @example
2052
+ * ```ts
2053
+ * const app = new Hono()
2054
+ * // Send the request to another application without modification.
2055
+ * app.mount('/app', anotherApp, {
2056
+ * replaceRequest: (req) => req,
2057
+ * })
2058
+ * ```
2059
+ */
2060
+ mount(path, applicationHandler, options) {
2061
+ let replaceRequest;
2062
+ let optionHandler;
2063
+ if (options) {
2064
+ if (typeof options === "function") {
2065
+ optionHandler = options;
2066
+ } else {
2067
+ optionHandler = options.optionHandler;
2068
+ if (options.replaceRequest === false) {
2069
+ replaceRequest = (request) => request;
2070
+ } else {
2071
+ replaceRequest = options.replaceRequest;
2072
+ }
2073
+ }
2074
+ }
2075
+ const getOptions = optionHandler ? (c) => {
2076
+ const options2 = optionHandler(c);
2077
+ return Array.isArray(options2) ? options2 : [options2];
2078
+ } : (c) => {
2079
+ let executionContext = void 0;
2080
+ try {
2081
+ executionContext = c.executionCtx;
2082
+ } catch {
2083
+ }
2084
+ return [c.env, executionContext];
2085
+ };
2086
+ replaceRequest ||= (() => {
2087
+ const mergedPath = mergePath(this._basePath, path);
2088
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
2089
+ return (request) => {
2090
+ const url = new URL(request.url);
2091
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
2092
+ return new Request(url, request);
2093
+ };
2094
+ })();
2095
+ const handler = async (c, next) => {
2096
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
2097
+ if (res) {
2098
+ return res;
2099
+ }
2100
+ await next();
2101
+ };
2102
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
2103
+ return this;
2104
+ }
2105
+ #addRoute(method, path, handler) {
2106
+ method = method.toUpperCase();
2107
+ path = mergePath(this._basePath, path);
2108
+ const r = { basePath: this._basePath, path, method, handler };
2109
+ this.router.add(method, path, [handler, r]);
2110
+ this.routes.push(r);
2111
+ }
2112
+ #handleError(err, c) {
2113
+ if (err instanceof Error) {
2114
+ return this.errorHandler(err, c);
2115
+ }
2116
+ throw err;
2117
+ }
2118
+ #dispatch(request, executionCtx, env, method) {
2119
+ if (method === "HEAD") {
2120
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
2121
+ }
2122
+ const path = this.getPath(request, { env });
2123
+ const matchResult = this.router.match(method, path);
2124
+ const c = new Context(request, {
2125
+ path,
2126
+ matchResult,
2127
+ env,
2128
+ executionCtx,
2129
+ notFoundHandler: this.#notFoundHandler
2130
+ });
2131
+ if (matchResult[0].length === 1) {
2132
+ let res;
2133
+ try {
2134
+ res = matchResult[0][0][0][0](c, async () => {
2135
+ c.res = await this.#notFoundHandler(c);
2136
+ });
2137
+ } catch (err) {
2138
+ return this.#handleError(err, c);
2139
+ }
2140
+ return res instanceof Promise ? res.then(
2141
+ (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
2142
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
2143
+ }
2144
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
2145
+ return (async () => {
2146
+ try {
2147
+ const context = await composed(c);
2148
+ if (!context.finalized) {
2149
+ throw new Error(
2150
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
2151
+ );
2152
+ }
2153
+ return context.res;
2154
+ } catch (err) {
2155
+ return this.#handleError(err, c);
2156
+ }
2157
+ })();
2158
+ }
2159
+ /**
2160
+ * `.fetch()` will be entry point of your app.
2161
+ *
2162
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
2163
+ *
2164
+ * @param {Request} request - request Object of request
2165
+ * @param {Env} Env - env Object
2166
+ * @param {ExecutionContext} - context of execution
2167
+ * @returns {Response | Promise<Response>} response of request
2168
+ *
2169
+ */
2170
+ fetch = (request, ...rest) => {
2171
+ return this.#dispatch(request, rest[1], rest[0], request.method);
2172
+ };
2173
+ /**
2174
+ * `.request()` is a useful method for testing.
2175
+ * You can pass a URL or pathname to send a GET request.
2176
+ * app will return a Response object.
2177
+ * ```ts
2178
+ * test('GET /hello is ok', async () => {
2179
+ * const res = await app.request('/hello')
2180
+ * expect(res.status).toBe(200)
2181
+ * })
2182
+ * ```
2183
+ * @see https://hono.dev/docs/api/hono#request
2184
+ */
2185
+ request = (input, requestInit, Env, executionCtx) => {
2186
+ if (input instanceof Request) {
2187
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
2188
+ }
2189
+ input = input.toString();
2190
+ return this.fetch(
2191
+ new Request(
2192
+ /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
2193
+ requestInit
2194
+ ),
2195
+ Env,
2196
+ executionCtx
2197
+ );
2198
+ };
2199
+ /**
2200
+ * `.fire()` automatically adds a global fetch event listener.
2201
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
2202
+ * @deprecated
2203
+ * Use `fire` from `hono/service-worker` instead.
2204
+ * ```ts
2205
+ * import { Hono } from 'hono'
2206
+ * import { fire } from 'hono/service-worker'
2207
+ *
2208
+ * const app = new Hono()
2209
+ * // ...
2210
+ * fire(app)
2211
+ * ```
2212
+ * @see https://hono.dev/docs/api/hono#fire
2213
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
2214
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
2215
+ */
2216
+ fire = () => {
2217
+ addEventListener("fetch", (event) => {
2218
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
2219
+ });
2220
+ };
2221
+ };
2222
+
2223
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router/reg-exp-router/matcher.js
2224
+ var emptyParam = [];
2225
+ function match(method, path) {
2226
+ const matchers = this.buildAllMatchers();
2227
+ const match2 = ((method2, path2) => {
2228
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
2229
+ const staticMatch = matcher[2][path2];
2230
+ if (staticMatch) {
2231
+ return staticMatch;
2232
+ }
2233
+ const match3 = path2.match(matcher[0]);
2234
+ if (!match3) {
2235
+ return [[], emptyParam];
2236
+ }
2237
+ const index = match3.indexOf("", 1);
2238
+ return [matcher[1][index], match3];
2239
+ });
2240
+ this.match = match2;
2241
+ return match2(method, path);
2242
+ }
2243
+
2244
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router/reg-exp-router/node.js
2245
+ var LABEL_REG_EXP_STR = "[^/]+";
2246
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
2247
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
2248
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
2249
+ var regExpMetaChars = new Set(".\\+*[^]$()");
2250
+ function compareKey(a, b) {
2251
+ if (a.length === 1) {
2252
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
2253
+ }
2254
+ if (b.length === 1) {
2255
+ return 1;
2256
+ }
2257
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2258
+ return 1;
2259
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2260
+ return -1;
2261
+ }
2262
+ if (a === LABEL_REG_EXP_STR) {
2263
+ return 1;
2264
+ } else if (b === LABEL_REG_EXP_STR) {
2265
+ return -1;
2266
+ }
2267
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2268
+ }
2269
+ var Node = class _Node {
2270
+ #index;
2271
+ #varIndex;
2272
+ #children = /* @__PURE__ */ Object.create(null);
2273
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2274
+ if (tokens.length === 0) {
2275
+ if (this.#index !== void 0) {
2276
+ throw PATH_ERROR;
2277
+ }
2278
+ if (pathErrorCheckOnly) {
2279
+ return;
2280
+ }
2281
+ this.#index = index;
2282
+ return;
2283
+ }
2284
+ const [token, ...restTokens] = tokens;
2285
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2286
+ let node;
2287
+ if (pattern) {
2288
+ const name = pattern[1];
2289
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2290
+ if (name && pattern[2]) {
2291
+ if (regexpStr === ".*") {
2292
+ throw PATH_ERROR;
2293
+ }
2294
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2295
+ if (/\((?!\?:)/.test(regexpStr)) {
2296
+ throw PATH_ERROR;
2297
+ }
2298
+ }
2299
+ node = this.#children[regexpStr];
2300
+ if (!node) {
2301
+ if (Object.keys(this.#children).some(
2302
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2303
+ )) {
2304
+ throw PATH_ERROR;
2305
+ }
2306
+ if (pathErrorCheckOnly) {
2307
+ return;
2308
+ }
2309
+ node = this.#children[regexpStr] = new _Node();
2310
+ if (name !== "") {
2311
+ node.#varIndex = context.varIndex++;
2312
+ }
2313
+ }
2314
+ if (!pathErrorCheckOnly && name !== "") {
2315
+ paramMap.push([name, node.#varIndex]);
2316
+ }
2317
+ } else {
2318
+ node = this.#children[token];
2319
+ if (!node) {
2320
+ if (Object.keys(this.#children).some(
2321
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2322
+ )) {
2323
+ throw PATH_ERROR;
2324
+ }
2325
+ if (pathErrorCheckOnly) {
2326
+ return;
2327
+ }
2328
+ node = this.#children[token] = new _Node();
2329
+ }
2330
+ }
2331
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
2332
+ }
2333
+ buildRegExpStr() {
2334
+ const childKeys = Object.keys(this.#children).sort(compareKey);
2335
+ const strList = childKeys.map((k) => {
2336
+ const c = this.#children[k];
2337
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
2338
+ });
2339
+ if (typeof this.#index === "number") {
2340
+ strList.unshift(`#${this.#index}`);
2341
+ }
2342
+ if (strList.length === 0) {
2343
+ return "";
2344
+ }
2345
+ if (strList.length === 1) {
2346
+ return strList[0];
2347
+ }
2348
+ return "(?:" + strList.join("|") + ")";
2349
+ }
2350
+ };
2351
+
2352
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router/reg-exp-router/trie.js
2353
+ var Trie = class {
2354
+ #context = { varIndex: 0 };
2355
+ #root = new Node();
2356
+ insert(path, index, pathErrorCheckOnly) {
2357
+ const paramAssoc = [];
2358
+ const groups = [];
2359
+ for (let i = 0; ; ) {
2360
+ let replaced = false;
2361
+ path = path.replace(/\{[^}]+\}/g, (m) => {
2362
+ const mark = `@\\${i}`;
2363
+ groups[i] = [mark, m];
2364
+ i++;
2365
+ replaced = true;
2366
+ return mark;
2367
+ });
2368
+ if (!replaced) {
2369
+ break;
2370
+ }
2371
+ }
2372
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2373
+ for (let i = groups.length - 1; i >= 0; i--) {
2374
+ const [mark] = groups[i];
2375
+ for (let j = tokens.length - 1; j >= 0; j--) {
2376
+ if (tokens[j].indexOf(mark) !== -1) {
2377
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
2378
+ break;
2379
+ }
2380
+ }
2381
+ }
2382
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
2383
+ return paramAssoc;
2384
+ }
2385
+ buildRegExp() {
2386
+ let regexp = this.#root.buildRegExpStr();
2387
+ if (regexp === "") {
2388
+ return [/^$/, [], []];
2389
+ }
2390
+ let captureIndex = 0;
2391
+ const indexReplacementMap = [];
2392
+ const paramReplacementMap = [];
2393
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
2394
+ if (handlerIndex !== void 0) {
2395
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
2396
+ return "$()";
2397
+ }
2398
+ if (paramIndex !== void 0) {
2399
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
2400
+ return "";
2401
+ }
2402
+ return "";
2403
+ });
2404
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
2405
+ }
2406
+ };
2407
+
2408
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router/reg-exp-router/router.js
2409
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2410
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2411
+ function buildWildcardRegExp(path) {
2412
+ return wildcardRegExpCache[path] ??= new RegExp(
2413
+ path === "*" ? "" : `^${path.replace(
2414
+ /\/\*$|([.\\+*[^\]$()])/g,
2415
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
2416
+ )}$`
2417
+ );
2418
+ }
2419
+ function clearWildcardRegExpCache() {
2420
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2421
+ }
2422
+ function buildMatcherFromPreprocessedRoutes(routes) {
2423
+ const trie = new Trie();
2424
+ const handlerData = [];
2425
+ if (routes.length === 0) {
2426
+ return nullMatcher;
2427
+ }
2428
+ const routesWithStaticPathFlag = routes.map(
2429
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
2430
+ ).sort(
2431
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
2432
+ );
2433
+ const staticMap = /* @__PURE__ */ Object.create(null);
2434
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
2435
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
2436
+ if (pathErrorCheckOnly) {
2437
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
2438
+ } else {
2439
+ j++;
2440
+ }
2441
+ let paramAssoc;
2442
+ try {
2443
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
2444
+ } catch (e) {
2445
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
2446
+ }
2447
+ if (pathErrorCheckOnly) {
2448
+ continue;
2449
+ }
2450
+ handlerData[j] = handlers.map(([h, paramCount]) => {
2451
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
2452
+ paramCount -= 1;
2453
+ for (; paramCount >= 0; paramCount--) {
2454
+ const [key, value] = paramAssoc[paramCount];
2455
+ paramIndexMap[key] = value;
2456
+ }
2457
+ return [h, paramIndexMap];
2458
+ });
2459
+ }
2460
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
2461
+ for (let i = 0, len = handlerData.length; i < len; i++) {
2462
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
2463
+ const map = handlerData[i][j]?.[1];
2464
+ if (!map) {
2465
+ continue;
2466
+ }
2467
+ const keys = Object.keys(map);
2468
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
2469
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
2470
+ }
2471
+ }
2472
+ }
2473
+ const handlerMap = [];
2474
+ for (const i in indexReplacementMap) {
2475
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
2476
+ }
2477
+ return [regexp, handlerMap, staticMap];
2478
+ }
2479
+ function findMiddleware(middleware, path) {
2480
+ if (!middleware) {
2481
+ return void 0;
2482
+ }
2483
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
2484
+ if (buildWildcardRegExp(k).test(path)) {
2485
+ return [...middleware[k]];
2486
+ }
2487
+ }
2488
+ return void 0;
2489
+ }
2490
+ var RegExpRouter = class {
2491
+ name = "RegExpRouter";
2492
+ #middleware;
2493
+ #routes;
2494
+ constructor() {
2495
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2496
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2497
+ }
2498
+ add(method, path, handler) {
2499
+ const middleware = this.#middleware;
2500
+ const routes = this.#routes;
2501
+ if (!middleware || !routes) {
2502
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2503
+ }
2504
+ if (!middleware[method]) {
2505
+ ;
2506
+ [middleware, routes].forEach((handlerMap) => {
2507
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
2508
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
2509
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
2510
+ });
2511
+ });
2512
+ }
2513
+ if (path === "/*") {
2514
+ path = "*";
2515
+ }
2516
+ const paramCount = (path.match(/\/:/g) || []).length;
2517
+ if (/\*$/.test(path)) {
2518
+ const re = buildWildcardRegExp(path);
2519
+ if (method === METHOD_NAME_ALL) {
2520
+ Object.keys(middleware).forEach((m) => {
2521
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2522
+ });
2523
+ } else {
2524
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2525
+ }
2526
+ Object.keys(middleware).forEach((m) => {
2527
+ if (method === METHOD_NAME_ALL || method === m) {
2528
+ Object.keys(middleware[m]).forEach((p) => {
2529
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
2530
+ });
2531
+ }
2532
+ });
2533
+ Object.keys(routes).forEach((m) => {
2534
+ if (method === METHOD_NAME_ALL || method === m) {
2535
+ Object.keys(routes[m]).forEach(
2536
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
2537
+ );
2538
+ }
2539
+ });
2540
+ return;
2541
+ }
2542
+ const paths = checkOptionalParameter(path) || [path];
2543
+ for (let i = 0, len = paths.length; i < len; i++) {
2544
+ const path2 = paths[i];
2545
+ Object.keys(routes).forEach((m) => {
2546
+ if (method === METHOD_NAME_ALL || method === m) {
2547
+ routes[m][path2] ||= [
2548
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
2549
+ ];
2550
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
2551
+ }
2552
+ });
2553
+ }
2554
+ }
2555
+ match = match;
2556
+ buildAllMatchers() {
2557
+ const matchers = /* @__PURE__ */ Object.create(null);
2558
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
2559
+ matchers[method] ||= this.#buildMatcher(method);
2560
+ });
2561
+ this.#middleware = this.#routes = void 0;
2562
+ clearWildcardRegExpCache();
2563
+ return matchers;
2564
+ }
2565
+ #buildMatcher(method) {
2566
+ const routes = [];
2567
+ let hasOwnRoute = method === METHOD_NAME_ALL;
2568
+ [this.#middleware, this.#routes].forEach((r) => {
2569
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
2570
+ if (ownRoute.length !== 0) {
2571
+ hasOwnRoute ||= true;
2572
+ routes.push(...ownRoute);
2573
+ } else if (method !== METHOD_NAME_ALL) {
2574
+ routes.push(
2575
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
2576
+ );
2577
+ }
2578
+ });
2579
+ if (!hasOwnRoute) {
2580
+ return null;
2581
+ } else {
2582
+ return buildMatcherFromPreprocessedRoutes(routes);
2583
+ }
2584
+ }
2585
+ };
2586
+
2587
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router/smart-router/router.js
2588
+ var SmartRouter = class {
2589
+ name = "SmartRouter";
2590
+ #routers = [];
2591
+ #routes = [];
2592
+ constructor(init) {
2593
+ this.#routers = init.routers;
2594
+ }
2595
+ add(method, path, handler) {
2596
+ if (!this.#routes) {
2597
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2598
+ }
2599
+ this.#routes.push([method, path, handler]);
2600
+ }
2601
+ match(method, path) {
2602
+ if (!this.#routes) {
2603
+ throw new Error("Fatal error");
2604
+ }
2605
+ const routers = this.#routers;
2606
+ const routes = this.#routes;
2607
+ const len = routers.length;
2608
+ let i = 0;
2609
+ let res;
2610
+ for (; i < len; i++) {
2611
+ const router = routers[i];
2612
+ try {
2613
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
2614
+ router.add(...routes[i2]);
2615
+ }
2616
+ res = router.match(method, path);
2617
+ } catch (e) {
2618
+ if (e instanceof UnsupportedPathError) {
2619
+ continue;
2620
+ }
2621
+ throw e;
2622
+ }
2623
+ this.match = router.match.bind(router);
2624
+ this.#routers = [router];
2625
+ this.#routes = void 0;
2626
+ break;
2627
+ }
2628
+ if (i === len) {
2629
+ throw new Error("Fatal error");
2630
+ }
2631
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
2632
+ return res;
2633
+ }
2634
+ get activeRouter() {
2635
+ if (this.#routes || this.#routers.length !== 1) {
2636
+ throw new Error("No active router has been determined yet.");
2637
+ }
2638
+ return this.#routers[0];
2639
+ }
2640
+ };
2641
+
2642
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router/trie-router/node.js
2643
+ var emptyParams = /* @__PURE__ */ Object.create(null);
2644
+ var hasChildren = (children) => {
2645
+ for (const _ in children) {
2646
+ return true;
2647
+ }
2648
+ return false;
2649
+ };
2650
+ var Node2 = class _Node2 {
2651
+ #methods;
2652
+ #children;
2653
+ #patterns;
2654
+ #order = 0;
2655
+ #params = emptyParams;
2656
+ constructor(method, handler, children) {
2657
+ this.#children = children || /* @__PURE__ */ Object.create(null);
2658
+ this.#methods = [];
2659
+ if (method && handler) {
2660
+ const m = /* @__PURE__ */ Object.create(null);
2661
+ m[method] = { handler, possibleKeys: [], score: 0 };
2662
+ this.#methods = [m];
2663
+ }
2664
+ this.#patterns = [];
2665
+ }
2666
+ insert(method, path, handler) {
2667
+ this.#order = ++this.#order;
2668
+ let curNode = this;
2669
+ const parts = splitRoutingPath(path);
2670
+ const possibleKeys = [];
2671
+ for (let i = 0, len = parts.length; i < len; i++) {
2672
+ const p = parts[i];
2673
+ const nextP = parts[i + 1];
2674
+ const pattern = getPattern(p, nextP);
2675
+ const key = Array.isArray(pattern) ? pattern[0] : p;
2676
+ if (key in curNode.#children) {
2677
+ curNode = curNode.#children[key];
2678
+ if (pattern) {
2679
+ possibleKeys.push(pattern[1]);
2680
+ }
2681
+ continue;
2682
+ }
2683
+ curNode.#children[key] = new _Node2();
2684
+ if (pattern) {
2685
+ curNode.#patterns.push(pattern);
2686
+ possibleKeys.push(pattern[1]);
2687
+ }
2688
+ curNode = curNode.#children[key];
2689
+ }
2690
+ curNode.#methods.push({
2691
+ [method]: {
2692
+ handler,
2693
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
2694
+ score: this.#order
2695
+ }
2696
+ });
2697
+ return curNode;
2698
+ }
2699
+ #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
2700
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
2701
+ const m = node.#methods[i];
2702
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
2703
+ const processedSet = {};
2704
+ if (handlerSet !== void 0) {
2705
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
2706
+ handlerSets.push(handlerSet);
2707
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
2708
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
2709
+ const key = handlerSet.possibleKeys[i2];
2710
+ const processed = processedSet[handlerSet.score];
2711
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
2712
+ processedSet[handlerSet.score] = true;
2713
+ }
2714
+ }
2715
+ }
2716
+ }
2717
+ }
2718
+ search(method, path) {
2719
+ const handlerSets = [];
2720
+ this.#params = emptyParams;
2721
+ const curNode = this;
2722
+ let curNodes = [curNode];
2723
+ const parts = splitPath(path);
2724
+ const curNodesQueue = [];
2725
+ const len = parts.length;
2726
+ let partOffsets = null;
2727
+ for (let i = 0; i < len; i++) {
2728
+ const part = parts[i];
2729
+ const isLast = i === len - 1;
2730
+ const tempNodes = [];
2731
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
2732
+ const node = curNodes[j];
2733
+ const nextNode = node.#children[part];
2734
+ if (nextNode) {
2735
+ nextNode.#params = node.#params;
2736
+ if (isLast) {
2737
+ if (nextNode.#children["*"]) {
2738
+ this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
2739
+ }
2740
+ this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
2741
+ } else {
2742
+ tempNodes.push(nextNode);
2743
+ }
2744
+ }
2745
+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
2746
+ const pattern = node.#patterns[k];
2747
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
2748
+ if (pattern === "*") {
2749
+ const astNode = node.#children["*"];
2750
+ if (astNode) {
2751
+ this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
2752
+ astNode.#params = params;
2753
+ tempNodes.push(astNode);
2754
+ }
2755
+ continue;
2756
+ }
2757
+ const [key, name, matcher] = pattern;
2758
+ if (!part && !(matcher instanceof RegExp)) {
2759
+ continue;
2760
+ }
2761
+ const child = node.#children[key];
2762
+ if (matcher instanceof RegExp) {
2763
+ if (partOffsets === null) {
2764
+ partOffsets = new Array(len);
2765
+ let offset = path[0] === "/" ? 1 : 0;
2766
+ for (let p = 0; p < len; p++) {
2767
+ partOffsets[p] = offset;
2768
+ offset += parts[p].length + 1;
2769
+ }
2770
+ }
2771
+ const restPathString = path.substring(partOffsets[i]);
2772
+ const m = matcher.exec(restPathString);
2773
+ if (m) {
2774
+ params[name] = m[0];
2775
+ this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
2776
+ if (hasChildren(child.#children)) {
2777
+ child.#params = params;
2778
+ const componentCount = m[0].match(/\//)?.length ?? 0;
2779
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
2780
+ targetCurNodes.push(child);
2781
+ }
2782
+ continue;
2783
+ }
2784
+ }
2785
+ if (matcher === true || matcher.test(part)) {
2786
+ params[name] = part;
2787
+ if (isLast) {
2788
+ this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
2789
+ if (child.#children["*"]) {
2790
+ this.#pushHandlerSets(
2791
+ handlerSets,
2792
+ child.#children["*"],
2793
+ method,
2794
+ params,
2795
+ node.#params
2796
+ );
2797
+ }
2798
+ } else {
2799
+ child.#params = params;
2800
+ tempNodes.push(child);
2801
+ }
2802
+ }
2803
+ }
2804
+ }
2805
+ const shifted = curNodesQueue.shift();
2806
+ curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
2807
+ }
2808
+ if (handlerSets.length > 1) {
2809
+ handlerSets.sort((a, b) => {
2810
+ return a.score - b.score;
2811
+ });
2812
+ }
2813
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
2814
+ }
2815
+ };
2816
+
2817
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/router/trie-router/router.js
2818
+ var TrieRouter = class {
2819
+ name = "TrieRouter";
2820
+ #node;
2821
+ constructor() {
2822
+ this.#node = new Node2();
2823
+ }
2824
+ add(method, path, handler) {
2825
+ const results = checkOptionalParameter(path);
2826
+ if (results) {
2827
+ for (let i = 0, len = results.length; i < len; i++) {
2828
+ this.#node.insert(method, results[i], handler);
2829
+ }
2830
+ return;
2831
+ }
2832
+ this.#node.insert(method, path, handler);
2833
+ }
2834
+ match(method, path) {
2835
+ return this.#node.search(method, path);
2836
+ }
2837
+ };
2838
+
2839
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/hono.js
2840
+ var Hono2 = class extends Hono {
2841
+ /**
2842
+ * Creates an instance of the Hono class.
2843
+ *
2844
+ * @param options - Optional configuration options for the Hono instance.
2845
+ */
2846
+ constructor(options = {}) {
2847
+ super(options);
2848
+ this.router = options.router ?? new SmartRouter({
2849
+ routers: [new RegExpRouter(), new TrieRouter()]
2850
+ });
2851
+ }
2852
+ };
2853
+
2854
+ // ../../node_modules/.pnpm/hono@4.12.8/node_modules/hono/dist/middleware/cors/index.js
2855
+ var cors = (options) => {
2856
+ const defaults = {
2857
+ origin: "*",
2858
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
2859
+ allowHeaders: [],
2860
+ exposeHeaders: []
2861
+ };
2862
+ const opts = {
2863
+ ...defaults,
2864
+ ...options
2865
+ };
2866
+ const findAllowOrigin = ((optsOrigin) => {
2867
+ if (typeof optsOrigin === "string") {
2868
+ if (optsOrigin === "*") {
2869
+ return () => optsOrigin;
2870
+ } else {
2871
+ return (origin) => optsOrigin === origin ? origin : null;
2872
+ }
2873
+ } else if (typeof optsOrigin === "function") {
2874
+ return optsOrigin;
2875
+ } else {
2876
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
2877
+ }
2878
+ })(opts.origin);
2879
+ const findAllowMethods = ((optsAllowMethods) => {
2880
+ if (typeof optsAllowMethods === "function") {
2881
+ return optsAllowMethods;
2882
+ } else if (Array.isArray(optsAllowMethods)) {
2883
+ return () => optsAllowMethods;
2884
+ } else {
2885
+ return () => [];
2886
+ }
2887
+ })(opts.allowMethods);
2888
+ return async function cors2(c, next) {
2889
+ function set(key, value) {
2890
+ c.res.headers.set(key, value);
2891
+ }
2892
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
2893
+ if (allowOrigin) {
2894
+ set("Access-Control-Allow-Origin", allowOrigin);
2895
+ }
2896
+ if (opts.credentials) {
2897
+ set("Access-Control-Allow-Credentials", "true");
2898
+ }
2899
+ if (opts.exposeHeaders?.length) {
2900
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
2901
+ }
2902
+ if (c.req.method === "OPTIONS") {
2903
+ if (opts.origin !== "*") {
2904
+ set("Vary", "Origin");
2905
+ }
2906
+ if (opts.maxAge != null) {
2907
+ set("Access-Control-Max-Age", opts.maxAge.toString());
2908
+ }
2909
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
2910
+ if (allowMethods.length) {
2911
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
2912
+ }
2913
+ let headers = opts.allowHeaders;
2914
+ if (!headers?.length) {
2915
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
2916
+ if (requestHeaders) {
2917
+ headers = requestHeaders.split(/\s*,\s*/);
2918
+ }
2919
+ }
2920
+ if (headers?.length) {
2921
+ set("Access-Control-Allow-Headers", headers.join(","));
2922
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
2923
+ }
2924
+ c.res.headers.delete("Content-Length");
2925
+ c.res.headers.delete("Content-Type");
2926
+ return new Response(null, {
2927
+ headers: c.res.headers,
2928
+ status: 204,
2929
+ statusText: "No Content"
2930
+ });
2931
+ }
2932
+ await next();
2933
+ if (opts.origin !== "*") {
2934
+ c.header("Vary", "Origin", { append: true });
2935
+ }
2936
+ };
2937
+ };
2938
+
2939
+ // src/server/eventBridge.ts
2940
+ function createEventBridge(params) {
2941
+ const { messageId, onChunk, onDone, onError } = params;
2942
+ const activeToolCalls = /* @__PURE__ */ new Map();
2943
+ function handleEvent(event) {
2944
+ switch (event.type) {
2945
+ case "message_update": {
2946
+ handleMessageUpdate(event);
2947
+ break;
2948
+ }
2949
+ case "tool_execution_end": {
2950
+ handleToolExecutionEnd(event);
2951
+ break;
2952
+ }
2953
+ case "agent_end": {
2954
+ onDone();
2955
+ break;
2956
+ }
2957
+ }
2958
+ }
2959
+ function handleMessageUpdate(event) {
2960
+ const assistantEvent = event.assistantMessageEvent;
2961
+ if (!assistantEvent) {
2962
+ return;
2963
+ }
2964
+ switch (assistantEvent.type) {
2965
+ case "text_start": {
2966
+ onChunk({ type: "text-start", id: messageId });
2967
+ break;
2968
+ }
2969
+ case "text_delta": {
2970
+ onChunk({ type: "text-delta", id: messageId, delta: assistantEvent.delta ?? "" });
2971
+ break;
2972
+ }
2973
+ case "text_end": {
2974
+ onChunk({ type: "text-end", id: messageId });
2975
+ break;
2976
+ }
2977
+ case "thinking_start": {
2978
+ onChunk({ type: "reasoning-start", id: messageId });
2979
+ break;
2980
+ }
2981
+ case "thinking_delta": {
2982
+ onChunk({ type: "reasoning-delta", id: messageId, delta: assistantEvent.delta ?? "" });
2983
+ break;
2984
+ }
2985
+ case "thinking_end": {
2986
+ onChunk({ type: "reasoning-end", id: messageId });
2987
+ break;
2988
+ }
2989
+ case "toolcall_start": {
2990
+ const contentIndex = assistantEvent.contentIndex ?? 0;
2991
+ const contentBlock = assistantEvent.partial?.content?.[contentIndex];
2992
+ activeToolCalls.set(contentIndex, {
2993
+ toolCallId: contentBlock?.id ?? `tool_${contentIndex}`,
2994
+ toolName: contentBlock?.name ?? "unknown",
2995
+ inputJson: ""
2996
+ });
2997
+ break;
2998
+ }
2999
+ case "toolcall_delta": {
3000
+ const contentIndex = assistantEvent.contentIndex ?? 0;
3001
+ const toolState = activeToolCalls.get(contentIndex);
3002
+ if (toolState) {
3003
+ toolState.inputJson += assistantEvent.delta ?? "";
3004
+ }
3005
+ break;
3006
+ }
3007
+ case "toolcall_end": {
3008
+ const contentIndex = assistantEvent.contentIndex ?? 0;
3009
+ const toolState = activeToolCalls.get(contentIndex);
3010
+ if (!toolState) {
3011
+ break;
3012
+ }
3013
+ const toolCall = assistantEvent.toolCall;
3014
+ const toolCallId = toolCall?.id ?? toolState.toolCallId;
3015
+ const toolName = toolCall?.name ?? toolState.toolName;
3016
+ let parsedInput = {};
3017
+ try {
3018
+ if (toolCall?.input !== void 0) {
3019
+ parsedInput = toolCall.input;
3020
+ } else if (toolState.inputJson.length > 0) {
3021
+ parsedInput = JSON.parse(toolState.inputJson);
3022
+ }
3023
+ } catch {
3024
+ parsedInput = {};
3025
+ }
3026
+ onChunk({ type: "tool-input-start", toolCallId, toolName });
3027
+ onChunk({ type: "tool-input-available", toolCallId, toolName, input: parsedInput });
3028
+ activeToolCalls.delete(contentIndex);
3029
+ break;
3030
+ }
3031
+ case "error": {
3032
+ const errorMessage = assistantEvent.error instanceof Error ? assistantEvent.error.message : typeof assistantEvent.error === "string" ? assistantEvent.error : "Unknown agent error";
3033
+ onError(errorMessage);
3034
+ break;
3035
+ }
3036
+ }
3037
+ }
3038
+ function handleToolExecutionEnd(event) {
3039
+ const toolCallId = event.toolCallId;
3040
+ if (!toolCallId) {
3041
+ return;
3042
+ }
3043
+ if (event.isError) {
3044
+ const errorText = typeof event.result === "string" ? event.result : JSON.stringify(event.result ?? "Tool execution failed");
3045
+ onChunk({ type: "tool-output-error", toolCallId, errorText });
3046
+ } else {
3047
+ onChunk({ type: "tool-output-available", toolCallId, output: event.result });
3048
+ }
3049
+ }
3050
+ return { handleEvent };
3051
+ }
3052
+
3053
+ // src/server/agentServer.ts
3054
+ function generateMessageId() {
3055
+ return `msg_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
3056
+ }
3057
+ function extractLastUserText(messages) {
3058
+ if (messages.length === 0) {
3059
+ return void 0;
3060
+ }
3061
+ const lastMessage = messages[messages.length - 1];
3062
+ if (lastMessage.role !== "user") {
3063
+ return void 0;
3064
+ }
3065
+ for (const part of lastMessage.parts) {
3066
+ if (part.type === "text" && typeof part.text === "string") {
3067
+ return part.text;
3068
+ }
3069
+ }
3070
+ return void 0;
3071
+ }
3072
+ async function waitForIdle(session, timeoutMs = 3e4) {
3073
+ if (!session.isStreaming) {
3074
+ return;
3075
+ }
3076
+ return new Promise((resolve2, reject) => {
3077
+ const timer = setTimeout(() => {
3078
+ unsubscribe();
3079
+ reject(new Error("Timed out waiting for session to become idle"));
3080
+ }, timeoutMs);
3081
+ const unsubscribe = session.subscribe((event) => {
3082
+ if (event.type === "agent_end") {
3083
+ clearTimeout(timer);
3084
+ unsubscribe();
3085
+ resolve2();
3086
+ }
3087
+ });
3088
+ if (!session.isStreaming) {
3089
+ clearTimeout(timer);
3090
+ unsubscribe();
3091
+ resolve2();
3092
+ }
3093
+ });
3094
+ }
3095
+ var FS_IGNORE = /* @__PURE__ */ new Set([
3096
+ "node_modules",
3097
+ ".git",
3098
+ ".next",
3099
+ ".nuxt",
3100
+ "dist",
3101
+ "build",
3102
+ ".docyrus",
3103
+ ".pi",
3104
+ "__pycache__",
3105
+ ".cache",
3106
+ "coverage",
3107
+ ".turbo",
3108
+ ".vercel",
3109
+ ".output",
3110
+ ".svelte-kit"
3111
+ ]);
3112
+ function resolveSafePath(cwd, requestPath) {
3113
+ const resolved = (0, import_node_path2.resolve)(cwd, requestPath);
3114
+ const normalizedCwd = cwd.endsWith(import_node_path2.sep) ? cwd : cwd + import_node_path2.sep;
3115
+ if (resolved !== cwd && !resolved.startsWith(normalizedCwd)) {
3116
+ throw new Error("Path escapes working directory");
3117
+ }
3118
+ return resolved;
3119
+ }
3120
+ function globToRegex(pattern) {
3121
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0").replace(/\*/g, "[^/]*").replace(/\0/g, ".*").replace(/\?/g, "[^/]");
3122
+ return new RegExp(`^${escaped}$`);
3123
+ }
3124
+ async function buildTree(params) {
3125
+ const { dir, cwd, depth, maxDepth, maxFiles, counter, ignore } = params;
3126
+ if (depth >= maxDepth || counter.value >= maxFiles) {
3127
+ return [];
3128
+ }
3129
+ let entries;
3130
+ try {
3131
+ entries = await (0, import_promises2.readdir)(dir, { withFileTypes: true });
3132
+ } catch {
3133
+ return [];
3134
+ }
3135
+ entries.sort((a, b) => {
3136
+ const aIsDir = a.isDirectory();
3137
+ const bIsDir = b.isDirectory();
3138
+ if (aIsDir !== bIsDir) {
3139
+ return aIsDir ? -1 : 1;
3140
+ }
3141
+ return a.name.localeCompare(b.name);
3142
+ });
3143
+ const result = [];
3144
+ for (const entry of entries) {
3145
+ if (counter.value >= maxFiles) {
3146
+ break;
3147
+ }
3148
+ if (ignore.has(entry.name)) {
3149
+ continue;
3150
+ }
3151
+ const fullPath = (0, import_node_path2.join)(dir, entry.name);
3152
+ const relativePath = (0, import_node_path2.relative)(cwd, fullPath);
3153
+ if (entry.isDirectory()) {
3154
+ const children = await buildTree({
3155
+ dir: fullPath,
3156
+ cwd,
3157
+ depth: depth + 1,
3158
+ maxDepth,
3159
+ maxFiles,
3160
+ counter,
3161
+ ignore
3162
+ });
3163
+ result.push({ name: entry.name, path: relativePath, type: "directory", children });
3164
+ } else if (entry.isFile()) {
3165
+ counter.value++;
3166
+ result.push({ name: entry.name, path: relativePath, type: "file" });
3167
+ }
3168
+ }
3169
+ return result;
3170
+ }
3171
+ async function walkFiles(params) {
3172
+ const { dir, cwd, pattern, ignore, maxResults, results } = params;
3173
+ if (results.length >= maxResults) {
3174
+ return;
3175
+ }
3176
+ let entries;
3177
+ try {
3178
+ entries = await (0, import_promises2.readdir)(dir, { withFileTypes: true });
3179
+ } catch {
3180
+ return;
3181
+ }
3182
+ for (const entry of entries) {
3183
+ if (results.length >= maxResults) {
3184
+ break;
3185
+ }
3186
+ if (ignore.has(entry.name)) {
3187
+ continue;
3188
+ }
3189
+ const fullPath = (0, import_node_path2.join)(dir, entry.name);
3190
+ const relativePath = (0, import_node_path2.relative)(cwd, fullPath);
3191
+ if (entry.isDirectory()) {
3192
+ await walkFiles({ dir: fullPath, cwd, pattern, ignore, maxResults, results });
3193
+ } else if (entry.isFile() && pattern.test(relativePath)) {
3194
+ results.push(relativePath);
3195
+ }
3196
+ }
3197
+ }
3198
+ async function createAgentServer(params) {
3199
+ const { port, sessionManager, modelRegistry, context, onResumeSession } = params;
3200
+ let activeSession = params.session;
3201
+ const app = new Hono2();
3202
+ app.use("/*", cors({ origin: "*" }));
3203
+ app.get("/api/health", (c) => {
3204
+ return c.json({ ok: true });
3205
+ });
3206
+ app.get("/api/status", (c) => {
3207
+ return c.json({
3208
+ isStreaming: activeSession.isStreaming,
3209
+ model: activeSession.model ? { provider: activeSession.model.provider, id: activeSession.model.id } : null
3210
+ });
3211
+ });
3212
+ app.post("/api/chat", async (c) => {
3213
+ const body = await c.req.json();
3214
+ const messages = body.messages ?? [];
3215
+ const userMessage = extractLastUserText(messages);
3216
+ if (!userMessage) {
3217
+ return c.json({ error: "No user message found" }, 400);
3218
+ }
3219
+ if (activeSession.isStreaming) {
3220
+ await activeSession.abort();
3221
+ await waitForIdle(activeSession);
3222
+ }
3223
+ const messageId = generateMessageId();
3224
+ const encoder = new TextEncoder();
3225
+ const stream = new ReadableStream({
3226
+ start(controller) {
3227
+ function writeChunk(chunk) {
3228
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}
3229
+
3230
+ `));
3231
+ }
3232
+ writeChunk({ type: "start" });
3233
+ writeChunk({ type: "start-step" });
3234
+ const bridge = createEventBridge({
3235
+ messageId,
3236
+ onChunk: writeChunk,
3237
+ onDone: () => {
3238
+ writeChunk({ type: "finish-step" });
3239
+ writeChunk({ type: "finish" });
3240
+ controller.close();
3241
+ },
3242
+ onError: (errorText) => {
3243
+ writeChunk({ type: "error", errorText });
3244
+ writeChunk({ type: "finish-step" });
3245
+ writeChunk({ type: "finish" });
3246
+ controller.close();
3247
+ }
3248
+ });
3249
+ const unsubscribe = activeSession.subscribe((event) => {
3250
+ bridge.handleEvent(event);
3251
+ if (event.type === "agent_end") {
3252
+ unsubscribe();
3253
+ }
3254
+ });
3255
+ activeSession.prompt(userMessage).catch((error) => {
3256
+ const errorMessage = error instanceof Error ? error.message : String(error);
3257
+ writeChunk({ type: "error", errorText: errorMessage });
3258
+ writeChunk({ type: "finish-step" });
3259
+ writeChunk({ type: "finish" });
3260
+ unsubscribe();
3261
+ controller.close();
3262
+ });
3263
+ }
3264
+ });
3265
+ return c.body(stream, {
3266
+ headers: {
3267
+ "Content-Type": "text/event-stream",
3268
+ "Cache-Control": "no-cache",
3269
+ "Connection": "keep-alive",
3270
+ "x-vercel-ai-ui-message-stream": "v1"
3271
+ }
3272
+ });
3273
+ });
3274
+ app.get("/api/sessions", async (c) => {
3275
+ try {
3276
+ const sessions = await sessionManager.list();
3277
+ const mapped = sessions.map((s) => ({
3278
+ id: s.id,
3279
+ path: s.path,
3280
+ cwd: s.cwd,
3281
+ name: s.name ?? null,
3282
+ parentSessionPath: s.parentSessionPath ?? null,
3283
+ created: s.created.toISOString(),
3284
+ modified: s.modified.toISOString(),
3285
+ messageCount: s.messageCount,
3286
+ firstMessage: s.firstMessage
3287
+ })).sort((a, b) => b.modified.localeCompare(a.modified));
3288
+ return c.json({ sessions: mapped });
3289
+ } catch (error) {
3290
+ const message = error instanceof Error ? error.message : String(error);
3291
+ return c.json({ error: message }, 500);
3292
+ }
3293
+ });
3294
+ app.get("/api/sessions/:sessionId/messages", async (c) => {
3295
+ const sessionId = c.req.param("sessionId");
3296
+ try {
3297
+ const sessions = await sessionManager.list();
3298
+ const match2 = sessions.find((s) => s.id === sessionId);
3299
+ if (!match2) {
3300
+ return c.json({ error: "Session not found" }, 404);
3301
+ }
3302
+ const opened = sessionManager.open(match2.path);
3303
+ const sessionContext = opened.buildSessionContext();
3304
+ const entries = opened.getBranch();
3305
+ return c.json({
3306
+ sessionId: opened.getSessionId(),
3307
+ sessionName: opened.getSessionName() ?? null,
3308
+ cwd: opened.getCwd(),
3309
+ model: sessionContext.model ?? null,
3310
+ thinkingLevel: sessionContext.thinkingLevel ?? null,
3311
+ entries
3312
+ });
3313
+ } catch (error) {
3314
+ const message = error instanceof Error ? error.message : String(error);
3315
+ return c.json({ error: message }, 500);
3316
+ }
3317
+ });
3318
+ app.get("/api/context", (c) => {
3319
+ return c.json({
3320
+ cwd: context.cwd,
3321
+ profile: context.profile,
3322
+ agentDir: context.agentDir,
3323
+ version: context.version,
3324
+ sessionDir: context.sessionDir,
3325
+ thinkingLevel: context.thinkingLevel
3326
+ });
3327
+ });
3328
+ app.get("/api/models", (c) => {
3329
+ return c.json({
3330
+ current: activeSession.model ? { provider: activeSession.model.provider, id: activeSession.model.id } : null,
3331
+ available: modelRegistry.getAvailable()
3332
+ });
3333
+ });
3334
+ app.post("/api/sessions/:sessionId/resume", async (c) => {
3335
+ const sessionId = c.req.param("sessionId");
3336
+ try {
3337
+ if (activeSession.isStreaming) {
3338
+ await activeSession.abort();
3339
+ await waitForIdle(activeSession);
3340
+ }
3341
+ activeSession = await onResumeSession(sessionId);
3342
+ return c.json({
3343
+ ok: true,
3344
+ sessionId,
3345
+ model: activeSession.model ? { provider: activeSession.model.provider, id: activeSession.model.id } : null
3346
+ });
3347
+ } catch (error) {
3348
+ const message = error instanceof Error ? error.message : String(error);
3349
+ return c.json({ error: message }, 500);
3350
+ }
3351
+ });
3352
+ app.get("/api/fs/tree", async (c) => {
3353
+ const requestPath = c.req.query("path") ?? ".";
3354
+ const maxDepth = Math.min(Number(c.req.query("depth") ?? 4), 10);
3355
+ const maxFiles = Math.min(Number(c.req.query("maxFiles") ?? 2e3), 1e4);
3356
+ try {
3357
+ const dir = resolveSafePath(context.cwd, requestPath);
3358
+ const nodes = await buildTree({
3359
+ dir,
3360
+ cwd: context.cwd,
3361
+ depth: 0,
3362
+ maxDepth,
3363
+ maxFiles,
3364
+ counter: { value: 0 },
3365
+ ignore: FS_IGNORE
3366
+ });
3367
+ return c.json({ cwd: context.cwd, path: requestPath, tree: nodes });
3368
+ } catch (error) {
3369
+ const message = error instanceof Error ? error.message : String(error);
3370
+ return c.json({ error: message }, 400);
3371
+ }
3372
+ });
3373
+ app.get("/api/fs/search", async (c) => {
3374
+ const pattern = c.req.query("pattern");
3375
+ if (!pattern) {
3376
+ return c.json({ error: "Missing required query parameter: pattern" }, 400);
3377
+ }
3378
+ const basePath = c.req.query("path") ?? ".";
3379
+ const maxResults = Math.min(Number(c.req.query("maxResults") ?? 200), 5e3);
3380
+ try {
3381
+ const dir = resolveSafePath(context.cwd, basePath);
3382
+ const regex = globToRegex(pattern);
3383
+ const results = [];
3384
+ await walkFiles({ dir, cwd: dir, pattern: regex, ignore: FS_IGNORE, maxResults, results });
3385
+ return c.json({ pattern, path: basePath, files: results });
3386
+ } catch (error) {
3387
+ const message = error instanceof Error ? error.message : String(error);
3388
+ return c.json({ error: message }, 400);
3389
+ }
3390
+ });
3391
+ app.get("/api/fs/read", async (c) => {
3392
+ const filePath = c.req.query("path");
3393
+ if (!filePath) {
3394
+ return c.json({ error: "Missing required query parameter: path" }, 400);
3395
+ }
3396
+ try {
3397
+ const resolved = resolveSafePath(context.cwd, filePath);
3398
+ const fileStat = await (0, import_promises2.stat)(resolved);
3399
+ if (!fileStat.isFile()) {
3400
+ return c.json({ error: "Path is not a file" }, 400);
3401
+ }
3402
+ const content = await (0, import_promises2.readFile)(resolved, "utf-8");
3403
+ return c.json({
3404
+ path: filePath,
3405
+ content,
3406
+ size: fileStat.size,
3407
+ modified: fileStat.mtime.toISOString()
3408
+ });
3409
+ } catch (error) {
3410
+ const message = error instanceof Error ? error.message : String(error);
3411
+ const status = message.includes("ENOENT") ? 404 : 400;
3412
+ return c.json({ error: message }, status);
3413
+ }
3414
+ });
3415
+ app.post("/api/fs/write", async (c) => {
3416
+ const body = await c.req.json();
3417
+ if (!body.path || typeof body.content !== "string") {
3418
+ return c.json({ error: "Missing required fields: path, content" }, 400);
3419
+ }
3420
+ try {
3421
+ const resolved = resolveSafePath(context.cwd, body.path);
3422
+ await (0, import_promises2.mkdir)((0, import_node_path2.join)(resolved, ".."), { recursive: true });
3423
+ await (0, import_promises2.writeFile)(resolved, body.content, "utf-8");
3424
+ const fileStat = await (0, import_promises2.stat)(resolved);
3425
+ return c.json({ ok: true, path: body.path, size: fileStat.size });
3426
+ } catch (error) {
3427
+ const message = error instanceof Error ? error.message : String(error);
3428
+ return c.json({ error: message }, 400);
3429
+ }
3430
+ });
3431
+ app.post("/api/fs/mkdir", async (c) => {
3432
+ const body = await c.req.json();
3433
+ if (!body.path) {
3434
+ return c.json({ error: "Missing required field: path" }, 400);
3435
+ }
3436
+ try {
3437
+ const resolved = resolveSafePath(context.cwd, body.path);
3438
+ await (0, import_promises2.mkdir)(resolved, { recursive: true });
3439
+ return c.json({ ok: true, path: body.path });
3440
+ } catch (error) {
3441
+ const message = error instanceof Error ? error.message : String(error);
3442
+ return c.json({ error: message }, 400);
3443
+ }
3444
+ });
3445
+ app.post("/api/fs/rename", async (c) => {
3446
+ const body = await c.req.json();
3447
+ if (!body.from || !body.to) {
3448
+ return c.json({ error: "Missing required fields: from, to" }, 400);
3449
+ }
3450
+ try {
3451
+ const resolvedFrom = resolveSafePath(context.cwd, body.from);
3452
+ const resolvedTo = resolveSafePath(context.cwd, body.to);
3453
+ await (0, import_promises2.mkdir)((0, import_node_path2.join)(resolvedTo, ".."), { recursive: true });
3454
+ await (0, import_promises2.rename)(resolvedFrom, resolvedTo);
3455
+ return c.json({ ok: true, from: body.from, to: body.to });
3456
+ } catch (error) {
3457
+ const message = error instanceof Error ? error.message : String(error);
3458
+ const status = message.includes("ENOENT") ? 404 : 400;
3459
+ return c.json({ error: message }, status);
3460
+ }
3461
+ });
3462
+ app.delete("/api/fs", async (c) => {
3463
+ const filePath = c.req.query("path");
3464
+ if (!filePath) {
3465
+ return c.json({ error: "Missing required query parameter: path" }, 400);
3466
+ }
3467
+ try {
3468
+ const resolved = resolveSafePath(context.cwd, filePath);
3469
+ if (resolved === context.cwd) {
3470
+ return c.json({ error: "Cannot delete working directory" }, 400);
3471
+ }
3472
+ const fileStat = await (0, import_promises2.stat)(resolved);
3473
+ await (0, import_promises2.rm)(resolved, { recursive: fileStat.isDirectory() });
3474
+ return c.json({ ok: true, path: filePath });
3475
+ } catch (error) {
3476
+ const message = error instanceof Error ? error.message : String(error);
3477
+ const status = message.includes("ENOENT") ? 404 : 400;
3478
+ return c.json({ error: message }, status);
3479
+ }
3480
+ });
3481
+ let devProcess = null;
3482
+ let devUrl = null;
3483
+ const DEV_URL_PATTERN = /https?:\/\/(?:localhost|127\.0\.0\.1):\d+/;
3484
+ const DEV_STARTUP_TIMEOUT_MS = 3e4;
3485
+ const DEV_PROBE_TIMEOUT_MS = 3e3;
3486
+ async function probeUrl(url) {
3487
+ try {
3488
+ const res = await fetch(url, { signal: AbortSignal.timeout(DEV_PROBE_TIMEOUT_MS) });
3489
+ return res.status;
3490
+ } catch {
3491
+ return null;
3492
+ }
3493
+ }
3494
+ async function detectDevPort(cwd) {
3495
+ try {
3496
+ const pkg = JSON.parse(await (0, import_promises2.readFile)((0, import_node_path2.join)(cwd, "package.json"), "utf-8"));
3497
+ const devScript = pkg.scripts?.dev;
3498
+ if (devScript) {
3499
+ const portFlag = devScript.match(/--port\s+(\d+)/);
3500
+ if (portFlag) {
3501
+ return Number(portFlag[1]);
3502
+ }
3503
+ const dashP = devScript.match(/(?:^|\s)-p\s+(\d+)/);
3504
+ if (dashP) {
3505
+ return Number(dashP[1]);
3506
+ }
3507
+ }
3508
+ } catch {
3509
+ }
3510
+ for (const name of ["vite.config.ts", "vite.config.mts", "vite.config.js"]) {
3511
+ try {
3512
+ const content = await (0, import_promises2.readFile)((0, import_node_path2.join)(cwd, name), "utf-8");
3513
+ const portMatch = content.match(/port\s*:\s*(\d+)/);
3514
+ if (portMatch) {
3515
+ return Number(portMatch[1]);
3516
+ }
3517
+ } catch {
3518
+ }
3519
+ }
3520
+ for (const name of ["next.config.ts", "next.config.mts", "next.config.js", "next.config.mjs"]) {
3521
+ try {
3522
+ await (0, import_promises2.stat)((0, import_node_path2.join)(cwd, name));
3523
+ return 3e3;
3524
+ } catch {
3525
+ }
3526
+ }
3527
+ try {
3528
+ await (0, import_promises2.stat)((0, import_node_path2.join)(cwd, "angular.json"));
3529
+ return 4200;
3530
+ } catch {
3531
+ }
3532
+ for (const name of ["nuxt.config.ts", "nuxt.config.js"]) {
3533
+ try {
3534
+ await (0, import_promises2.stat)((0, import_node_path2.join)(cwd, name));
3535
+ return 3e3;
3536
+ } catch {
3537
+ }
3538
+ }
3539
+ return null;
3540
+ }
3541
+ app.get("/api/env/status", async (c) => {
3542
+ if (devProcess && devProcess.exitCode === null && devUrl) {
3543
+ const httpStatus = await probeUrl(devUrl);
3544
+ return c.json({
3545
+ status: httpStatus !== null ? "running" : "starting",
3546
+ url: devUrl,
3547
+ managed: true,
3548
+ ...httpStatus !== null ? { httpStatus } : {}
3549
+ });
3550
+ }
3551
+ if (devProcess && devProcess.exitCode !== null) {
3552
+ const exitCode = devProcess.exitCode;
3553
+ devProcess = null;
3554
+ const stoppedUrl = devUrl;
3555
+ devUrl = null;
3556
+ return c.json({ status: "stopped", url: stoppedUrl, exitCode, managed: true });
3557
+ }
3558
+ const explicitUrl = c.req.query("url");
3559
+ const explicitPort = c.req.query("port");
3560
+ let probeTarget = null;
3561
+ if (explicitUrl) {
3562
+ probeTarget = explicitUrl;
3563
+ } else if (explicitPort) {
3564
+ probeTarget = `http://localhost:${explicitPort}`;
3565
+ } else {
3566
+ const detected = await detectDevPort(context.cwd);
3567
+ if (detected) {
3568
+ probeTarget = `http://localhost:${detected}`;
3569
+ }
3570
+ }
3571
+ if (probeTarget) {
3572
+ const httpStatus = await probeUrl(probeTarget);
3573
+ return c.json({
3574
+ status: httpStatus !== null ? "running" : "stopped",
3575
+ url: probeTarget,
3576
+ httpStatus: httpStatus ?? void 0,
3577
+ managed: false
3578
+ });
3579
+ }
3580
+ return c.json({ status: "stopped", url: null, managed: false });
3581
+ });
3582
+ app.post("/api/env/serve", (c) => {
3583
+ if (devProcess && devProcess.exitCode === null) {
3584
+ return c.json({ status: "running", url: devUrl });
3585
+ }
3586
+ devUrl = null;
3587
+ const proc = (0, import_node_child_process.spawn)("pnpm", ["dev"], {
3588
+ cwd: context.cwd,
3589
+ shell: true,
3590
+ stdio: ["ignore", "pipe", "pipe"]
3591
+ });
3592
+ devProcess = proc;
3593
+ return new Promise((resolveResponse) => {
3594
+ let stderr = "";
3595
+ let resolved = false;
3596
+ function settle(response) {
3597
+ if (resolved) {
3598
+ return;
3599
+ }
3600
+ resolved = true;
3601
+ resolveResponse(response);
3602
+ }
3603
+ function checkOutput(text) {
3604
+ const match2 = text.match(DEV_URL_PATTERN);
3605
+ if (match2) {
3606
+ devUrl = match2[0];
3607
+ settle(c.json({ status: "running", url: devUrl }));
3608
+ }
3609
+ }
3610
+ proc.stdout?.on("data", (chunk) => checkOutput(chunk.toString()));
3611
+ proc.stderr?.on("data", (chunk) => {
3612
+ const text = chunk.toString();
3613
+ stderr += text;
3614
+ checkOutput(text);
3615
+ });
3616
+ proc.on("close", (code) => {
3617
+ settle(c.json({ status: "error", error: stderr || `Process exited with code ${code}` }, 500));
3618
+ });
3619
+ proc.on("error", (err) => {
3620
+ settle(c.json({ status: "error", error: err.message }, 500));
3621
+ });
3622
+ setTimeout(() => {
3623
+ settle(c.json({ status: "error", error: stderr || "Timed out waiting for dev server URL" }, 500));
3624
+ }, DEV_STARTUP_TIMEOUT_MS);
3625
+ });
3626
+ });
3627
+ app.post("/api/env/stop", (c) => {
3628
+ if (!devProcess || devProcess.exitCode !== null) {
3629
+ devProcess = null;
3630
+ devUrl = null;
3631
+ return c.json({ status: "stopped" });
3632
+ }
3633
+ const pid = devProcess.pid;
3634
+ devProcess.kill("SIGTERM");
3635
+ devProcess = null;
3636
+ const stoppedUrl = devUrl;
3637
+ devUrl = null;
3638
+ return c.json({ status: "stopped", url: stoppedUrl, pid });
3639
+ });
3640
+ const CLI_EXEC = process.env.DOCYRUS_CLI_EXECUTABLE || process.execPath;
3641
+ const CLI_ENTRY = process.env.DOCYRUS_CLI_ENTRY;
3642
+ const CLI_SCOPE = process.env.DOCYRUS_CLI_SCOPE;
3643
+ const CLI_TIMEOUT_MS = 3e4;
3644
+ const BOOLEAN_CLI_FLAGS = /* @__PURE__ */ new Set(["json", "verbose", "global", "noAuth", "expand", "i"]);
3645
+ function buildCliArgs(pathSegments, query, body) {
3646
+ const args = [...pathSegments, "--json"];
3647
+ for (const [key, value] of Object.entries(query)) {
3648
+ if (key === "json") {
3649
+ continue;
3650
+ }
3651
+ const flag = key.length === 1 ? `-${key}` : `--${key}`;
3652
+ if (BOOLEAN_CLI_FLAGS.has(key) || value === "" || value === "true") {
3653
+ args.push(flag);
3654
+ } else {
3655
+ args.push(flag, value);
3656
+ }
3657
+ }
3658
+ if (body) {
3659
+ if (body.data !== void 0) {
3660
+ args.push("--data", typeof body.data === "string" ? body.data : JSON.stringify(body.data));
3661
+ }
3662
+ if (typeof body.fromFile === "string") {
3663
+ args.push("--from-file", body.fromFile);
3664
+ }
3665
+ for (const [key, value] of Object.entries(body)) {
3666
+ if (key === "data" || key === "fromFile") {
3667
+ continue;
3668
+ }
3669
+ const flag = key.length === 1 ? `-${key}` : `--${key}`;
3670
+ if (typeof value === "boolean") {
3671
+ if (value) {
3672
+ args.push(flag);
3673
+ }
3674
+ } else if (value !== void 0 && value !== null) {
3675
+ args.push(flag, String(value));
3676
+ }
3677
+ }
3678
+ }
3679
+ return args;
3680
+ }
3681
+ app.all("/api/cli/*", async (c) => {
3682
+ if (!CLI_ENTRY) {
3683
+ return c.json({ error: "CLI entry path not available (DOCYRUS_CLI_ENTRY not set)" }, 500);
3684
+ }
3685
+ const pathSegments = c.req.path.replace(/^\/api\/cli\/?/, "").split("/").filter(Boolean);
3686
+ if (pathSegments.length === 0) {
3687
+ return c.json({ error: "No command specified. Usage: /api/cli/<command>/[subcommand]/[args...]" }, 400);
3688
+ }
3689
+ const query = {};
3690
+ for (const [key, value] of Object.entries(c.req.query())) {
3691
+ if (typeof value === "string") {
3692
+ query[key] = value;
3693
+ }
3694
+ }
3695
+ let body;
3696
+ if (c.req.method === "POST" || c.req.method === "PUT") {
3697
+ try {
3698
+ body = await c.req.json();
3699
+ } catch {
3700
+ }
3701
+ }
3702
+ const cliArgs = buildCliArgs(pathSegments, query, body);
3703
+ return new Promise((resolveResponse) => {
3704
+ const scopeArgs = CLI_SCOPE ? ["--scope", CLI_SCOPE] : [];
3705
+ const proc = (0, import_node_child_process.spawn)(CLI_EXEC, [CLI_ENTRY, ...scopeArgs, ...cliArgs], {
3706
+ cwd: context.cwd,
3707
+ stdio: ["ignore", "pipe", "pipe"],
3708
+ timeout: CLI_TIMEOUT_MS
3709
+ });
3710
+ let stdout = "";
3711
+ let stderr = "";
3712
+ proc.stdout?.on("data", (chunk) => {
3713
+ stdout += chunk.toString();
3714
+ });
3715
+ proc.stderr?.on("data", (chunk) => {
3716
+ stderr += chunk.toString();
3717
+ });
3718
+ proc.on("close", (code) => {
3719
+ if (code !== 0) {
3720
+ resolveResponse(c.json({
3721
+ error: stderr.trim() || `Command exited with code ${code}`,
3722
+ command: `docyrus ${cliArgs.join(" ")}`,
3723
+ exitCode: code
3724
+ }, 500));
3725
+ return;
3726
+ }
3727
+ try {
3728
+ const parsed = JSON.parse(stdout);
3729
+ resolveResponse(c.json(parsed));
3730
+ } catch {
3731
+ resolveResponse(c.json({ output: stdout.trim(), command: `docyrus ${cliArgs.join(" ")}` }));
3732
+ }
3733
+ });
3734
+ proc.on("error", (err) => {
3735
+ resolveResponse(c.json({ error: err.message, command: `docyrus ${cliArgs.join(" ")}` }, 500));
3736
+ });
3737
+ });
3738
+ });
3739
+ const { serve: serve2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
3740
+ serve2({
3741
+ fetch: app.fetch,
3742
+ port
3743
+ }, (info) => {
3744
+ process.stderr.write(`
3745
+ Agent server listening on http://localhost:${info.port}
3746
+
3747
+ `);
3748
+ process.stderr.write(` POST /api/chat \u2014 send chat messages (SSE UIMessage stream)
3749
+ `);
3750
+ process.stderr.write(` GET /api/health \u2014 health check
3751
+ `);
3752
+ process.stderr.write(` GET /api/status \u2014 session status
3753
+ `);
3754
+ process.stderr.write(` GET /api/sessions \u2014 list sessions
3755
+ `);
3756
+ process.stderr.write(` GET /api/sessions/:sessionId/messages \u2014 session messages
3757
+ `);
3758
+ process.stderr.write(` POST /api/sessions/:sessionId/resume \u2014 resume a session
3759
+ `);
3760
+ process.stderr.write(` GET /api/context \u2014 server context
3761
+ `);
3762
+ process.stderr.write(` GET /api/models \u2014 available models
3763
+ `);
3764
+ process.stderr.write(` GET /api/fs/tree \u2014 directory tree
3765
+ `);
3766
+ process.stderr.write(` GET /api/fs/search \u2014 search files by glob
3767
+ `);
3768
+ process.stderr.write(` GET /api/fs/read \u2014 read file contents
3769
+ `);
3770
+ process.stderr.write(` POST /api/fs/write \u2014 write file
3771
+ `);
3772
+ process.stderr.write(` POST /api/fs/mkdir \u2014 create directory
3773
+ `);
3774
+ process.stderr.write(` POST /api/fs/rename \u2014 rename/move file
3775
+ `);
3776
+ process.stderr.write(` DEL /api/fs \u2014 delete file or directory
3777
+ `);
3778
+ process.stderr.write(` GET /api/env/status \u2014 dev server status
3779
+ `);
3780
+ process.stderr.write(` POST /api/env/serve \u2014 start dev server (pnpm dev)
3781
+ `);
3782
+ process.stderr.write(` POST /api/env/stop \u2014 stop dev server
3783
+ `);
3784
+ process.stderr.write(` * /api/cli/** \u2014 proxy any docyrus CLI command
3785
+
3786
+ `);
3787
+ });
3788
+ }
3789
+
3790
+ // src/server/server-loader.ts
3791
+ function readRequiredEnv(name) {
3792
+ const value = process.env[name];
3793
+ if (!value || value.trim().length === 0) {
3794
+ throw new Error(`Missing required environment variable: ${name}`);
3795
+ }
3796
+ return value;
3797
+ }
3798
+ function readLoaderRequest() {
3799
+ return JSON.parse(readRequiredEnv("DOCYRUS_PI_REQUEST"));
3800
+ }
3801
+ async function loadPiExports() {
3802
+ const piPackageDir = readRequiredEnv("PI_PACKAGE_DIR");
3803
+ const moduleUrl = (0, import_node_url.pathToFileURL)((0, import_node_path3.join)(piPackageDir, "dist", "index.js")).href;
3804
+ return await import(moduleUrl);
3805
+ }
3806
+ function resolvePackagedPiResourceRoot() {
3807
+ const candidates = [
3808
+ (0, import_node_path3.resolve)(process.cwd(), "apps/api-cli/resources/pi-agent"),
3809
+ (0, import_node_path3.resolve)(__dirname, "../resources/pi-agent"),
3810
+ (0, import_node_path3.resolve)(__dirname, "resources/pi-agent"),
3811
+ (0, import_node_path3.resolve)(process.cwd(), "dist/apps/api-cli/resources/pi-agent")
3812
+ ];
3813
+ const resolved = candidates.find((candidate) => (0, import_node_fs.existsSync)(candidate));
3814
+ if (!resolved) {
3815
+ throw new Error(`Unable to locate pi agent resources. Checked: ${candidates.join(", ")}`);
3816
+ }
3817
+ return resolved;
3818
+ }
3819
+ function resolvePackagedExtensionPaths(resourceRoot) {
3820
+ const extensionsRoot = (0, import_node_path3.join)(resourceRoot, "extensions");
3821
+ if (!(0, import_node_fs.existsSync)(extensionsRoot)) {
3822
+ return [];
3823
+ }
3824
+ return (0, import_node_fs.readdirSync)(extensionsRoot, {
3825
+ withFileTypes: true
3826
+ }).filter((entry) => entry.isDirectory() || entry.isFile() && (entry.name.endsWith(".ts") || entry.name.endsWith(".js"))).map((entry) => (0, import_node_path3.join)(extensionsRoot, entry.name)).sort((left, right) => left.localeCompare(right));
3827
+ }
3828
+ function setProcessArgValue(flag, value) {
3829
+ const existingIndex = process.argv.indexOf(flag);
3830
+ if (existingIndex >= 0) {
3831
+ if (existingIndex + 1 < process.argv.length) {
3832
+ process.argv[existingIndex + 1] = value;
3833
+ return;
3834
+ }
3835
+ process.argv.push(value);
3836
+ return;
3837
+ }
3838
+ process.argv.push(flag, value);
3839
+ }
3840
+ function buildTools(profile, cwd, pi) {
3841
+ if (profile === "agent") {
3842
+ return [
3843
+ pi.createReadTool(cwd),
3844
+ pi.createBashTool(cwd),
3845
+ pi.createGrepTool(cwd),
3846
+ pi.createFindTool(cwd),
3847
+ pi.createLsTool(cwd)
3848
+ ];
3849
+ }
3850
+ return [
3851
+ pi.createReadTool(cwd),
3852
+ pi.createBashTool(cwd),
3853
+ pi.createEditTool(cwd),
3854
+ pi.createWriteTool(cwd),
3855
+ pi.createGrepTool(cwd),
3856
+ pi.createFindTool(cwd),
3857
+ pi.createLsTool(cwd)
3858
+ ];
3859
+ }
3860
+ function resolveRequestedModel(params) {
3861
+ const { request, modelRegistry } = params;
3862
+ const requestedProvider = request.provider?.trim();
3863
+ const requestedModel = request.model?.trim();
3864
+ if (!requestedProvider && !requestedModel) {
3865
+ return void 0;
3866
+ }
3867
+ if (requestedProvider && requestedModel) {
3868
+ const normalizedModelId = requestedModel.startsWith(`${requestedProvider}/`) ? requestedModel.slice(requestedProvider.length + 1) : requestedModel;
3869
+ return modelRegistry.find(requestedProvider, normalizedModelId);
3870
+ }
3871
+ if (requestedModel && requestedModel.includes("/")) {
3872
+ const slashIndex = requestedModel.indexOf("/");
3873
+ return modelRegistry.find(requestedModel.slice(0, slashIndex).trim(), requestedModel.slice(slashIndex + 1).trim());
3874
+ }
3875
+ if (requestedModel) {
3876
+ const availableModels = modelRegistry.getAvailable();
3877
+ const exactMatches = availableModels.filter((model) => model.id === requestedModel);
3878
+ if (exactMatches.length === 1) {
3879
+ return exactMatches[0];
3880
+ }
3881
+ return availableModels.find((model) => model.id.includes(requestedModel));
3882
+ }
3883
+ return void 0;
3884
+ }
3885
+ function renderStartupSplash(version) {
3886
+ process.stderr.write(
3887
+ `
3888
+ ${import_picocolors.default.bold("DOCYRUS SERVER")} ${import_picocolors.default.dim(`v${version}`)}
3889
+ ${import_picocolors.default.green("Starting agent server...")}
3890
+ `
3891
+ );
3892
+ }
3893
+ async function main() {
3894
+ const request = readLoaderRequest();
3895
+ const pi = await loadPiExports();
3896
+ const cwd = process.cwd();
3897
+ const agentDir = readRequiredEnv("PI_CODING_AGENT_DIR");
3898
+ const version = process.env.DOCYRUS_PI_VERSION || "dev";
3899
+ const resourceRoot = resolvePackagedPiResourceRoot();
3900
+ const packagedExtensionPaths = resolvePackagedExtensionPaths(resourceRoot);
3901
+ const mcpConfigPath = (0, import_node_path3.join)(agentDir, "mcp.json");
3902
+ const hasPackagedMcpAdapter = packagedExtensionPaths.some((extensionPath) => extensionPath.includes("pi-mcp-adapter"));
3903
+ const envStore = new AgentEnvStore((0, import_node_path3.join)(agentDir, "env.json"));
3904
+ await envStore.hydrateProcessEnv(process.env);
3905
+ if (hasPackagedMcpAdapter) {
3906
+ setProcessArgValue("--mcp-config", mcpConfigPath);
3907
+ }
3908
+ const authStorage = pi.AuthStorage.create((0, import_node_path3.join)(agentDir, "auth.json"));
3909
+ const settingsManager = pi.SettingsManager.create(cwd, agentDir);
3910
+ const modelsJsonPath = (0, import_node_path3.join)(agentDir, "models.json");
3911
+ const modelRegistry = new pi.ModelRegistry(authStorage, modelsJsonPath);
3912
+ const quietStartup = !request.verbose;
3913
+ if (quietStartup) {
3914
+ process.env.PI_SKIP_VERSION_CHECK = "1";
3915
+ settingsManager.setQuietStartup(true);
3916
+ settingsManager.setCollapseChangelog(true);
3917
+ settingsManager.setLastChangelogVersion(version);
3918
+ }
3919
+ renderStartupSplash(version);
3920
+ const requestedModel = resolveRequestedModel({
3921
+ request,
3922
+ modelRegistry
3923
+ });
3924
+ if (request.apiKey) {
3925
+ const apiKeyProvider = request.provider?.trim() || requestedModel?.provider;
3926
+ if (!apiKeyProvider) {
3927
+ throw new Error("--api-key requires a provider or a resolvable model.");
3928
+ }
3929
+ authStorage.setRuntimeApiKey(apiKeyProvider, request.apiKey);
3930
+ }
3931
+ const sessionManager = pi.SessionManager.create(cwd, request.sessionDir);
3932
+ const resourceLoader = new pi.DefaultResourceLoader({
3933
+ cwd,
3934
+ agentDir,
3935
+ settingsManager,
3936
+ additionalExtensionPaths: packagedExtensionPaths,
3937
+ systemPrompt: (0, import_node_path3.join)(
3938
+ resourceRoot,
3939
+ "prompts",
3940
+ request.profile === "agent" ? "agent-system.md" : "coder-system.md"
3941
+ )
3942
+ });
3943
+ await resourceLoader.reload();
3944
+ const { session, extensionsResult } = await pi.createAgentSession({
3945
+ cwd,
3946
+ agentDir,
3947
+ authStorage,
3948
+ modelRegistry,
3949
+ resourceLoader,
3950
+ settingsManager,
3951
+ sessionManager,
3952
+ tools: buildTools(request.profile, cwd, pi),
3953
+ model: requestedModel,
3954
+ thinkingLevel: request.thinking
3955
+ });
3956
+ if (hasPackagedMcpAdapter) {
3957
+ extensionsResult.runtime.flagValues.set("mcp-config", mcpConfigPath);
3958
+ }
3959
+ if (!session.model) {
3960
+ throw new Error(
3961
+ `No models available.
3962
+
3963
+ Set an API key environment variable:
3964
+ ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, etc.
3965
+
3966
+ Or create ${modelsJsonPath}`
3967
+ );
3968
+ }
3969
+ await createAgentServer({
3970
+ session,
3971
+ port: request.port,
3972
+ sessionManager: {
3973
+ list: () => pi.SessionManager.list(cwd, request.sessionDir),
3974
+ open: (path) => pi.SessionManager.open(path, request.sessionDir)
3975
+ },
3976
+ modelRegistry: {
3977
+ getAvailable: () => modelRegistry.getAvailable()
3978
+ },
3979
+ context: {
3980
+ cwd,
3981
+ profile: request.profile,
3982
+ agentDir,
3983
+ version,
3984
+ sessionDir: request.sessionDir ?? null,
3985
+ thinkingLevel: request.thinking ?? null
3986
+ },
3987
+ onResumeSession: async (sessionId) => {
3988
+ const sessions = await pi.SessionManager.list(cwd, request.sessionDir);
3989
+ const match2 = sessions.find((s) => s.id === sessionId);
3990
+ if (!match2) {
3991
+ throw new Error(`Session not found: ${sessionId}`);
3992
+ }
3993
+ const resumeCwd = match2.cwd || cwd;
3994
+ const { session: resumedSession } = await pi.createAgentSession({
3995
+ cwd: resumeCwd,
3996
+ agentDir,
3997
+ authStorage,
3998
+ modelRegistry,
3999
+ resourceLoader,
4000
+ settingsManager,
4001
+ sessionManager,
4002
+ tools: buildTools(request.profile, resumeCwd, pi),
4003
+ model: requestedModel,
4004
+ thinkingLevel: request.thinking,
4005
+ resumeSessionId: sessionId
4006
+ });
4007
+ return resumedSession;
4008
+ }
4009
+ });
4010
+ }
4011
+ void main().catch((error) => {
4012
+ const message = error instanceof Error ? error.message : String(error);
4013
+ process.stderr.write(`${message}
4014
+ `);
4015
+ process.exitCode = 1;
4016
+ });
4017
+ //# sourceMappingURL=server-loader.js.map