@seaveyon/harness-switch 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2968 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __name = (target, name) => {
7
+ Object.defineProperty(target, "name", {
8
+ value: name,
9
+ enumerable: false,
10
+ configurable: true
11
+ });
12
+ return target;
13
+ };
14
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
15
+ var __typeError = (msg) => {
16
+ throw TypeError(msg);
17
+ };
18
+ var __defNormalProp = (obj, key, value) => (key in obj) ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
19
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
20
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
21
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
22
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
23
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
24
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
25
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
26
+ var __expectFn = (fn) => fn !== undefined && typeof fn !== "function" ? __typeError("Function expected") : fn;
27
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({
28
+ kind: __decoratorStrings[kind],
29
+ name,
30
+ metadata,
31
+ addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null))
32
+ });
33
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
34
+ var __runInitializers = (array, flags, self, value) => {
35
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length;i < n; i++)
36
+ flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
37
+ return value;
38
+ };
39
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
40
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
41
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
42
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
43
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : {
44
+ get [name]() {
45
+ return __privateGet(this, extra);
46
+ },
47
+ set [name](x) {
48
+ __privateSet(this, extra, x);
49
+ }
50
+ }, name));
51
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
52
+ for (var i = decorators.length - 1;i >= 0; i--) {
53
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
54
+ if (k) {
55
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => (name in x) };
56
+ if (k ^ 3)
57
+ access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
58
+ if (k > 2)
59
+ access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
60
+ }
61
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? undefined : { get: desc.get, set: desc.set } : target, ctx);
62
+ done._ = 1;
63
+ if (k ^ 4 || it === undefined)
64
+ __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
65
+ else if (typeof it !== "object" || it === null)
66
+ __typeError("Object expected");
67
+ else
68
+ __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
69
+ }
70
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
71
+ };
72
+
73
+ // src/app.ts
74
+ import { existsSync as existsSync3 } from "fs";
75
+ import { join as join4 } from "path";
76
+
77
+ // ../../node_modules/hono/dist/compose.js
78
+ var compose = (middleware, onError, onNotFound) => {
79
+ return (context, next) => {
80
+ let index = -1;
81
+ return dispatch(0);
82
+ async function dispatch(i) {
83
+ if (i <= index) {
84
+ throw new Error("next() called multiple times");
85
+ }
86
+ index = i;
87
+ let res;
88
+ let isError = false;
89
+ let handler;
90
+ if (middleware[i]) {
91
+ handler = middleware[i][0][0];
92
+ context.req.routeIndex = i;
93
+ } else {
94
+ handler = i === middleware.length && next || undefined;
95
+ }
96
+ if (handler) {
97
+ try {
98
+ res = await handler(context, () => dispatch(i + 1));
99
+ } catch (err) {
100
+ if (err instanceof Error && onError) {
101
+ context.error = err;
102
+ res = await onError(err, context);
103
+ isError = true;
104
+ } else {
105
+ throw err;
106
+ }
107
+ }
108
+ } else {
109
+ if (context.finalized === false && onNotFound) {
110
+ res = await onNotFound(context);
111
+ }
112
+ }
113
+ if (res && (context.finalized === false || isError)) {
114
+ context.res = res;
115
+ }
116
+ return context;
117
+ }
118
+ };
119
+ };
120
+
121
+ // ../../node_modules/hono/dist/request/constants.js
122
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
123
+
124
+ // ../../node_modules/hono/dist/utils/buffer.js
125
+ var bufferToFormData = (arrayBuffer, contentType) => {
126
+ const response = new Response(arrayBuffer, {
127
+ headers: {
128
+ "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase())
129
+ }
130
+ });
131
+ return response.formData();
132
+ };
133
+
134
+ // ../../node_modules/hono/dist/utils/body.js
135
+ var isRawRequest = (request) => ("headers" in request);
136
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
137
+ const { all = false, dot = false } = options;
138
+ const headers = isRawRequest(request) ? request.headers : request.raw.headers;
139
+ const contentType = headers.get("Content-Type");
140
+ const mediaType = contentType?.split(";")[0].trim().toLowerCase();
141
+ if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded") {
142
+ return parseFormData(request, { all, dot });
143
+ }
144
+ return {};
145
+ };
146
+ async function parseFormData(request, options) {
147
+ if (!isRawRequest(request) && request.bodyCache.formData) {
148
+ return convertFormDataToBodyData(await request.bodyCache.formData, options);
149
+ }
150
+ const headers = isRawRequest(request) ? request.headers : request.raw.headers;
151
+ const arrayBuffer = await request.arrayBuffer();
152
+ const formDataPromise = bufferToFormData(arrayBuffer, headers.get("Content-Type") || "");
153
+ if (!isRawRequest(request)) {
154
+ request.bodyCache.formData = formDataPromise;
155
+ }
156
+ const formData = await formDataPromise;
157
+ if (formData) {
158
+ return convertFormDataToBodyData(formData, options);
159
+ }
160
+ return {};
161
+ }
162
+ function convertFormDataToBodyData(formData, options) {
163
+ const form = /* @__PURE__ */ Object.create(null);
164
+ formData.forEach((value, key) => {
165
+ const shouldParseAllValues = options.all || key.endsWith("[]");
166
+ if (!shouldParseAllValues) {
167
+ form[key] = value;
168
+ } else {
169
+ handleParsingAllValues(form, key, value);
170
+ }
171
+ });
172
+ if (options.dot) {
173
+ Object.entries(form).forEach(([key, value]) => {
174
+ const shouldParseDotValues = key.includes(".");
175
+ if (shouldParseDotValues) {
176
+ handleParsingNestedValues(form, key, value);
177
+ delete form[key];
178
+ }
179
+ });
180
+ }
181
+ return form;
182
+ }
183
+ var handleParsingAllValues = (form, key, value) => {
184
+ if (form[key] !== undefined) {
185
+ if (Array.isArray(form[key])) {
186
+ form[key].push(value);
187
+ } else {
188
+ form[key] = [form[key], value];
189
+ }
190
+ } else {
191
+ if (!key.endsWith("[]")) {
192
+ form[key] = value;
193
+ } else {
194
+ form[key] = [value];
195
+ }
196
+ }
197
+ };
198
+ var handleParsingNestedValues = (form, key, value) => {
199
+ if (/(?:^|\.)__proto__\./.test(key)) {
200
+ return;
201
+ }
202
+ let nestedForm = form;
203
+ const keys = key.split(".");
204
+ keys.forEach((key2, index) => {
205
+ if (index === keys.length - 1) {
206
+ nestedForm[key2] = value;
207
+ } else {
208
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
209
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
210
+ }
211
+ nestedForm = nestedForm[key2];
212
+ }
213
+ });
214
+ };
215
+
216
+ // ../../node_modules/hono/dist/utils/url.js
217
+ var splitPath = (path) => {
218
+ const paths = path.split("/");
219
+ if (paths[0] === "") {
220
+ paths.shift();
221
+ }
222
+ return paths;
223
+ };
224
+ var splitRoutingPath = (routePath) => {
225
+ const { groups, path } = extractGroupsFromPath(routePath);
226
+ const paths = splitPath(path);
227
+ return replaceGroupMarks(paths, groups);
228
+ };
229
+ var extractGroupsFromPath = (path) => {
230
+ const groups = [];
231
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
232
+ const mark = `@${index}`;
233
+ groups.push([mark, match]);
234
+ return mark;
235
+ });
236
+ return { groups, path };
237
+ };
238
+ var replaceGroupMarks = (paths, groups) => {
239
+ for (let i = groups.length - 1;i >= 0; i--) {
240
+ const [mark] = groups[i];
241
+ for (let j = paths.length - 1;j >= 0; j--) {
242
+ if (paths[j].includes(mark)) {
243
+ paths[j] = paths[j].replace(mark, groups[i][1]);
244
+ break;
245
+ }
246
+ }
247
+ }
248
+ return paths;
249
+ };
250
+ var patternCache = {};
251
+ var getPattern = (label, next) => {
252
+ if (label === "*") {
253
+ return "*";
254
+ }
255
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
256
+ if (match) {
257
+ const cacheKey = `${label}#${next}`;
258
+ if (!patternCache[cacheKey]) {
259
+ if (match[2]) {
260
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
261
+ } else {
262
+ patternCache[cacheKey] = [label, match[1], true];
263
+ }
264
+ }
265
+ return patternCache[cacheKey];
266
+ }
267
+ return null;
268
+ };
269
+ var tryDecode = (str, decoder) => {
270
+ try {
271
+ return decoder(str);
272
+ } catch {
273
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
274
+ try {
275
+ return decoder(match);
276
+ } catch {
277
+ return match;
278
+ }
279
+ });
280
+ }
281
+ };
282
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
283
+ var getPath = (request) => {
284
+ const url = request.url;
285
+ const start = url.indexOf("/", url.indexOf(":") + 4);
286
+ let i = start;
287
+ for (;i < url.length; i++) {
288
+ const charCode = url.charCodeAt(i);
289
+ if (charCode === 37) {
290
+ const queryIndex = url.indexOf("?", i);
291
+ const hashIndex = url.indexOf("#", i);
292
+ const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
293
+ const path = url.slice(start, end);
294
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
295
+ } else if (charCode === 63 || charCode === 35) {
296
+ break;
297
+ }
298
+ }
299
+ return url.slice(start, i);
300
+ };
301
+ var getPathNoStrict = (request) => {
302
+ const result = getPath(request);
303
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
304
+ };
305
+ var mergePath = (base, sub, ...rest) => {
306
+ if (rest.length) {
307
+ sub = mergePath(sub, ...rest);
308
+ }
309
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
310
+ };
311
+ var checkOptionalParameter = (path) => {
312
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
313
+ return null;
314
+ }
315
+ const segments = path.split("/");
316
+ const results = [];
317
+ let basePath = "";
318
+ segments.forEach((segment) => {
319
+ if (segment !== "" && !/\:/.test(segment)) {
320
+ basePath += "/" + segment;
321
+ } else if (/\:/.test(segment)) {
322
+ if (/\?/.test(segment)) {
323
+ if (results.length === 0 && basePath === "") {
324
+ results.push("/");
325
+ } else {
326
+ results.push(basePath);
327
+ }
328
+ const optionalSegment = segment.replace("?", "");
329
+ basePath += "/" + optionalSegment;
330
+ results.push(basePath);
331
+ } else {
332
+ basePath += "/" + segment;
333
+ }
334
+ }
335
+ });
336
+ return results.filter((v, i, a) => a.indexOf(v) === i);
337
+ };
338
+ var tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
339
+ var _decodeURI = (value) => {
340
+ if (value.indexOf("+") !== -1) {
341
+ value = value.replace(/\+/g, " ");
342
+ }
343
+ return tryDecodeURIComponent(value);
344
+ };
345
+ var _getQueryParam = (url, key, multiple) => {
346
+ let encoded;
347
+ if (!multiple && key && key.indexOf("%") === -1 && key.indexOf("+") === -1) {
348
+ let keyIndex2 = url.indexOf("?", 8);
349
+ if (keyIndex2 === -1) {
350
+ return;
351
+ }
352
+ if (!url.startsWith(key, keyIndex2 + 1)) {
353
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
354
+ }
355
+ while (keyIndex2 !== -1) {
356
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
357
+ if (trailingKeyCode === 61) {
358
+ const valueIndex = keyIndex2 + key.length + 2;
359
+ const endIndex = url.indexOf("&", valueIndex);
360
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
361
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
362
+ return "";
363
+ }
364
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
365
+ }
366
+ encoded = /[%+]/.test(url);
367
+ if (!encoded) {
368
+ return;
369
+ }
370
+ }
371
+ const results = /* @__PURE__ */ Object.create(null);
372
+ encoded ??= /[%+]/.test(url);
373
+ let keyIndex = url.indexOf("?", 8);
374
+ while (keyIndex !== -1) {
375
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
376
+ let valueIndex = url.indexOf("=", keyIndex);
377
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
378
+ valueIndex = -1;
379
+ }
380
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
381
+ if (encoded) {
382
+ name = _decodeURI(name);
383
+ }
384
+ keyIndex = nextKeyIndex;
385
+ if (name === "") {
386
+ continue;
387
+ }
388
+ let value;
389
+ if (valueIndex === -1) {
390
+ value = "";
391
+ } else {
392
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
393
+ if (encoded) {
394
+ value = _decodeURI(value);
395
+ }
396
+ }
397
+ if (multiple) {
398
+ if (!(results[name] && Array.isArray(results[name]))) {
399
+ results[name] = [];
400
+ }
401
+ results[name].push(value);
402
+ } else {
403
+ results[name] ??= value;
404
+ }
405
+ }
406
+ return key ? results[key] : results;
407
+ };
408
+ var getQueryParam = _getQueryParam;
409
+ var getQueryParams = (url, key) => {
410
+ return _getQueryParam(url, key, true);
411
+ };
412
+ var decodeURIComponent_ = decodeURIComponent;
413
+
414
+ // ../../node_modules/hono/dist/request.js
415
+ var HonoRequest = class {
416
+ raw;
417
+ #validatedData;
418
+ #matchResult;
419
+ routeIndex = 0;
420
+ path;
421
+ bodyCache = {};
422
+ constructor(request, path = "/", matchResult = [[]]) {
423
+ this.raw = request;
424
+ this.path = path;
425
+ this.#matchResult = matchResult;
426
+ }
427
+ param(key) {
428
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
429
+ }
430
+ #getDecodedParam(key) {
431
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
432
+ const param = this.#getParamValue(paramKey);
433
+ return param && tryDecodeURIComponent(param);
434
+ }
435
+ #getAllDecodedParams() {
436
+ const decoded = {};
437
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
438
+ for (const key of keys) {
439
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
440
+ if (value !== undefined) {
441
+ decoded[key] = tryDecodeURIComponent(value);
442
+ }
443
+ }
444
+ return decoded;
445
+ }
446
+ #getParamValue(paramKey) {
447
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
448
+ }
449
+ query(key) {
450
+ return getQueryParam(this.url, key);
451
+ }
452
+ queries(key) {
453
+ return getQueryParams(this.url, key);
454
+ }
455
+ header(name) {
456
+ if (name) {
457
+ return this.raw.headers.get(name) ?? undefined;
458
+ }
459
+ const headerData = /* @__PURE__ */ Object.create(null);
460
+ this.raw.headers.forEach((value, key) => {
461
+ headerData[key] = value;
462
+ });
463
+ return headerData;
464
+ }
465
+ async parseBody(options) {
466
+ return parseBody(this, options);
467
+ }
468
+ #cachedBody = (key) => {
469
+ const { bodyCache, raw } = this;
470
+ const cachedBody = bodyCache[key];
471
+ if (cachedBody) {
472
+ return cachedBody;
473
+ }
474
+ for (const anyCachedKey in bodyCache) {
475
+ return bodyCache[anyCachedKey].then((body) => {
476
+ if (anyCachedKey === "json") {
477
+ body = JSON.stringify(body);
478
+ }
479
+ return new Response(body)[key]();
480
+ });
481
+ }
482
+ return bodyCache[key] = raw[key]();
483
+ };
484
+ json() {
485
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
486
+ }
487
+ text() {
488
+ return this.#cachedBody("text");
489
+ }
490
+ arrayBuffer() {
491
+ return this.#cachedBody("arrayBuffer");
492
+ }
493
+ bytes() {
494
+ return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
495
+ }
496
+ blob() {
497
+ return this.#cachedBody("blob");
498
+ }
499
+ formData() {
500
+ return this.#cachedBody("formData");
501
+ }
502
+ addValidatedData(target, data) {
503
+ (this.#validatedData ??= {})[target] = data;
504
+ }
505
+ valid(target) {
506
+ return this.#validatedData?.[target];
507
+ }
508
+ get url() {
509
+ return this.raw.url;
510
+ }
511
+ get method() {
512
+ return this.raw.method;
513
+ }
514
+ get [GET_MATCH_RESULT]() {
515
+ return this.#matchResult;
516
+ }
517
+ get matchedRoutes() {
518
+ return this.#matchResult[0].map(([[, route]]) => route);
519
+ }
520
+ get routePath() {
521
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
522
+ }
523
+ };
524
+
525
+ // ../../node_modules/hono/dist/utils/html.js
526
+ var HtmlEscapedCallbackPhase = {
527
+ Stringify: 1,
528
+ BeforeStream: 2,
529
+ Stream: 3
530
+ };
531
+ var raw = (value, callbacks) => {
532
+ const escapedString = new String(value);
533
+ escapedString.isEscaped = true;
534
+ escapedString.callbacks = callbacks;
535
+ return escapedString;
536
+ };
537
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
538
+ if (typeof str === "object" && !(str instanceof String)) {
539
+ if (!(str instanceof Promise)) {
540
+ str = str.toString();
541
+ }
542
+ if (str instanceof Promise) {
543
+ str = await str;
544
+ }
545
+ }
546
+ const callbacks = str.callbacks;
547
+ if (!callbacks?.length) {
548
+ return Promise.resolve(str);
549
+ }
550
+ if (buffer) {
551
+ buffer[0] += str;
552
+ } else {
553
+ buffer = [str];
554
+ }
555
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
556
+ if (preserveCallbacks) {
557
+ return raw(await resStr, callbacks);
558
+ } else {
559
+ return resStr;
560
+ }
561
+ };
562
+
563
+ // ../../node_modules/hono/dist/context.js
564
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
565
+ var setDefaultContentType = (contentType, headers) => {
566
+ return {
567
+ "Content-Type": contentType,
568
+ ...headers
569
+ };
570
+ };
571
+ var createResponseInstance = (body, init) => new Response(body, init);
572
+ var Context = class {
573
+ #rawRequest;
574
+ #req;
575
+ env = {};
576
+ #var;
577
+ finalized = false;
578
+ error;
579
+ #status;
580
+ #executionCtx;
581
+ #res;
582
+ #layout;
583
+ #renderer;
584
+ #notFoundHandler;
585
+ #preparedHeaders;
586
+ #matchResult;
587
+ #path;
588
+ constructor(req, options) {
589
+ this.#rawRequest = req;
590
+ if (options) {
591
+ this.#executionCtx = options.executionCtx;
592
+ this.env = options.env;
593
+ this.#notFoundHandler = options.notFoundHandler;
594
+ this.#path = options.path;
595
+ this.#matchResult = options.matchResult;
596
+ }
597
+ }
598
+ get req() {
599
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
600
+ return this.#req;
601
+ }
602
+ get event() {
603
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
604
+ return this.#executionCtx;
605
+ } else {
606
+ throw Error("This context has no FetchEvent");
607
+ }
608
+ }
609
+ get executionCtx() {
610
+ if (this.#executionCtx) {
611
+ return this.#executionCtx;
612
+ } else {
613
+ throw Error("This context has no ExecutionContext");
614
+ }
615
+ }
616
+ get res() {
617
+ return this.#res ||= createResponseInstance(null, {
618
+ headers: this.#preparedHeaders ??= new Headers
619
+ });
620
+ }
621
+ set res(_res) {
622
+ if (this.#res && _res) {
623
+ _res = createResponseInstance(_res.body, _res);
624
+ for (const [k, v] of this.#res.headers.entries()) {
625
+ if (k === "content-type") {
626
+ continue;
627
+ }
628
+ if (k === "set-cookie") {
629
+ const cookies = this.#res.headers.getSetCookie();
630
+ _res.headers.delete("set-cookie");
631
+ for (const cookie of cookies) {
632
+ _res.headers.append("set-cookie", cookie);
633
+ }
634
+ } else {
635
+ _res.headers.set(k, v);
636
+ }
637
+ }
638
+ }
639
+ this.#res = _res;
640
+ this.finalized = true;
641
+ }
642
+ render = (...args) => {
643
+ this.#renderer ??= (content) => this.html(content);
644
+ return this.#renderer(...args);
645
+ };
646
+ setLayout = (layout) => this.#layout = layout;
647
+ getLayout = () => this.#layout;
648
+ setRenderer = (renderer) => {
649
+ this.#renderer = renderer;
650
+ };
651
+ header = (name, value, options) => {
652
+ if (this.finalized) {
653
+ this.#res = createResponseInstance(this.#res.body, this.#res);
654
+ }
655
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
656
+ if (value === undefined) {
657
+ headers.delete(name);
658
+ } else if (options?.append) {
659
+ headers.append(name, value);
660
+ } else {
661
+ headers.set(name, value);
662
+ }
663
+ };
664
+ status = (status) => {
665
+ this.#status = status;
666
+ };
667
+ set = (key, value) => {
668
+ this.#var ??= /* @__PURE__ */ new Map;
669
+ this.#var.set(key, value);
670
+ };
671
+ get = (key) => {
672
+ return this.#var ? this.#var.get(key) : undefined;
673
+ };
674
+ get var() {
675
+ if (!this.#var) {
676
+ return {};
677
+ }
678
+ return Object.fromEntries(this.#var);
679
+ }
680
+ #newResponse(data, arg, headers) {
681
+ let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;
682
+ if (typeof arg === "object" && arg.headers) {
683
+ responseHeaders ??= new Headers;
684
+ for (const [key, value] of new Headers(arg.headers)) {
685
+ if (key === "set-cookie") {
686
+ responseHeaders.append(key, value);
687
+ } else {
688
+ responseHeaders.set(key, value);
689
+ }
690
+ }
691
+ }
692
+ if (headers) {
693
+ if (!responseHeaders) {
694
+ let count = 0;
695
+ for (const k in headers) {
696
+ if (++count > 1 || typeof headers[k] !== "string") {
697
+ responseHeaders = new Headers;
698
+ break;
699
+ }
700
+ }
701
+ }
702
+ if (responseHeaders) {
703
+ for (const k in headers) {
704
+ const v = headers[k];
705
+ if (typeof v === "string") {
706
+ responseHeaders.set(k, v);
707
+ } else {
708
+ responseHeaders.delete(k);
709
+ for (const v2 of v) {
710
+ responseHeaders.append(k, v2);
711
+ }
712
+ }
713
+ }
714
+ }
715
+ }
716
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
717
+ return createResponseInstance(data, {
718
+ status,
719
+ headers: responseHeaders ?? headers
720
+ });
721
+ }
722
+ newResponse = (...args) => this.#newResponse(...args);
723
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
724
+ text = (text, arg, headers) => {
725
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
726
+ };
727
+ json = (object, arg, headers) => {
728
+ return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
729
+ };
730
+ html = (html, arg, headers) => {
731
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
732
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
733
+ };
734
+ redirect = (location, status) => {
735
+ const locationString = String(location);
736
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
737
+ return this.newResponse(null, status ?? 302);
738
+ };
739
+ notFound = () => {
740
+ this.#notFoundHandler ??= () => createResponseInstance();
741
+ return this.#notFoundHandler(this);
742
+ };
743
+ };
744
+
745
+ // ../../node_modules/hono/dist/router.js
746
+ var METHOD_NAME_ALL = "ALL";
747
+ var METHOD_NAME_ALL_LOWERCASE = "all";
748
+ var METHODS = ["get", "post", "put", "delete", "options", "patch", "query"];
749
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
750
+ var UnsupportedPathError = class extends Error {
751
+ };
752
+
753
+ // ../../node_modules/hono/dist/utils/constants.js
754
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
755
+
756
+ // ../../node_modules/hono/dist/hono-base.js
757
+ var notFoundHandler = (c) => {
758
+ return c.text("404 Not Found", 404);
759
+ };
760
+ var errorHandler = (err, c) => {
761
+ if ("getResponse" in err) {
762
+ const res = err.getResponse();
763
+ return c.newResponse(res.body, res);
764
+ }
765
+ console.error(err);
766
+ return c.text("Internal Server Error", 500);
767
+ };
768
+ var Hono = class _Hono {
769
+ get;
770
+ post;
771
+ put;
772
+ delete;
773
+ options;
774
+ patch;
775
+ query;
776
+ all;
777
+ on;
778
+ use;
779
+ router;
780
+ getPath;
781
+ _basePath = "/";
782
+ #path = "/";
783
+ routes = [];
784
+ constructor(options = {}) {
785
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
786
+ allMethods.forEach((method) => {
787
+ this[method] = (args1, ...args) => {
788
+ if (typeof args1 === "string") {
789
+ this.#path = args1;
790
+ } else {
791
+ this.#addRoute(method, this.#path, args1);
792
+ }
793
+ args.forEach((handler) => {
794
+ this.#addRoute(method, this.#path, handler);
795
+ });
796
+ return this;
797
+ };
798
+ });
799
+ this.on = (method, path, ...handlers) => {
800
+ for (const p of [path].flat()) {
801
+ this.#path = p;
802
+ for (const m of [method].flat()) {
803
+ handlers.map((handler) => {
804
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
805
+ });
806
+ }
807
+ }
808
+ return this;
809
+ };
810
+ this.use = (arg1, ...handlers) => {
811
+ if (typeof arg1 === "string") {
812
+ this.#path = arg1;
813
+ } else {
814
+ this.#path = "*";
815
+ handlers.unshift(arg1);
816
+ }
817
+ handlers.forEach((handler) => {
818
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
819
+ });
820
+ return this;
821
+ };
822
+ const { strict, ...optionsWithoutStrict } = options;
823
+ Object.assign(this, optionsWithoutStrict);
824
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
825
+ }
826
+ #clone() {
827
+ const clone = new _Hono({
828
+ router: this.router,
829
+ getPath: this.getPath
830
+ });
831
+ clone.errorHandler = this.errorHandler;
832
+ clone.#notFoundHandler = this.#notFoundHandler;
833
+ clone.routes = this.routes;
834
+ return clone;
835
+ }
836
+ #notFoundHandler = notFoundHandler;
837
+ errorHandler = errorHandler;
838
+ route(path, app) {
839
+ const subApp = this.basePath(path);
840
+ app.routes.map((r) => {
841
+ let handler;
842
+ if (app.errorHandler === errorHandler) {
843
+ handler = r.handler;
844
+ } else {
845
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
846
+ handler[COMPOSED_HANDLER] = r.handler;
847
+ }
848
+ subApp.#addRoute(r.method, r.path, handler, r.basePath);
849
+ });
850
+ return this;
851
+ }
852
+ basePath(path) {
853
+ const subApp = this.#clone();
854
+ subApp._basePath = mergePath(this._basePath, path);
855
+ return subApp;
856
+ }
857
+ onError = (handler) => {
858
+ this.errorHandler = handler;
859
+ return this;
860
+ };
861
+ notFound = (handler) => {
862
+ this.#notFoundHandler = handler;
863
+ return this;
864
+ };
865
+ mount(path, applicationHandler, options) {
866
+ let replaceRequest;
867
+ let optionHandler;
868
+ if (options) {
869
+ if (typeof options === "function") {
870
+ optionHandler = options;
871
+ } else {
872
+ optionHandler = options.optionHandler;
873
+ if (options.replaceRequest === false) {
874
+ replaceRequest = (request) => request;
875
+ } else {
876
+ replaceRequest = options.replaceRequest;
877
+ }
878
+ }
879
+ }
880
+ const getOptions = optionHandler ? (c) => {
881
+ const options2 = optionHandler(c);
882
+ return Array.isArray(options2) ? options2 : [options2];
883
+ } : (c) => {
884
+ let executionContext = undefined;
885
+ try {
886
+ executionContext = c.executionCtx;
887
+ } catch {}
888
+ return [c.env, executionContext];
889
+ };
890
+ replaceRequest ||= (() => {
891
+ const mergedPath = mergePath(this._basePath, path);
892
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
893
+ return (request) => {
894
+ const url = new URL(request.url);
895
+ url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
896
+ return new Request(url, request);
897
+ };
898
+ })();
899
+ const handler = async (c, next) => {
900
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
901
+ if (res) {
902
+ return res;
903
+ }
904
+ await next();
905
+ };
906
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
907
+ return this;
908
+ }
909
+ #addRoute(method, path, handler, baseRoutePath) {
910
+ method = method.toUpperCase();
911
+ path = mergePath(this._basePath, path);
912
+ const r = {
913
+ basePath: baseRoutePath !== undefined ? mergePath(this._basePath, baseRoutePath) : this._basePath,
914
+ path,
915
+ method,
916
+ handler
917
+ };
918
+ this.router.add(method, path, [handler, r]);
919
+ this.routes.push(r);
920
+ }
921
+ #handleError(err, c) {
922
+ if (err instanceof Error) {
923
+ return this.errorHandler(err, c);
924
+ }
925
+ throw err;
926
+ }
927
+ #dispatch(request, executionCtx, env, method) {
928
+ if (method === "HEAD") {
929
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
930
+ }
931
+ const path = this.getPath(request, { env });
932
+ const matchResult = this.router.match(method, path);
933
+ const c = new Context(request, {
934
+ path,
935
+ matchResult,
936
+ env,
937
+ executionCtx,
938
+ notFoundHandler: this.#notFoundHandler
939
+ });
940
+ if (matchResult[0].length === 1) {
941
+ let res;
942
+ try {
943
+ res = matchResult[0][0][0][0](c, async () => {
944
+ c.res = await this.#notFoundHandler(c);
945
+ });
946
+ } catch (err) {
947
+ return this.#handleError(err, c);
948
+ }
949
+ return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
950
+ }
951
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
952
+ return (async () => {
953
+ try {
954
+ const context = await composed(c);
955
+ if (!context.finalized) {
956
+ throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
957
+ }
958
+ return context.res;
959
+ } catch (err) {
960
+ return this.#handleError(err, c);
961
+ }
962
+ })();
963
+ }
964
+ fetch = (request, ...rest) => {
965
+ return this.#dispatch(request, rest[1], rest[0], request.method);
966
+ };
967
+ request = (input, requestInit, Env, executionCtx) => {
968
+ if (input instanceof Request) {
969
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
970
+ }
971
+ input = input.toString();
972
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
973
+ };
974
+ fire = () => {
975
+ addEventListener("fetch", (event) => {
976
+ event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
977
+ });
978
+ };
979
+ };
980
+
981
+ // ../../node_modules/hono/dist/router/reg-exp-router/matcher.js
982
+ var emptyParam = [];
983
+ function match(method, path) {
984
+ const matchers = this.buildAllMatchers();
985
+ const match2 = (method2, path2) => {
986
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
987
+ const staticMatch = matcher[2][path2];
988
+ if (staticMatch) {
989
+ return staticMatch;
990
+ }
991
+ const match3 = path2.match(matcher[0]);
992
+ if (!match3) {
993
+ return [[], emptyParam];
994
+ }
995
+ const index = match3.indexOf("", 1);
996
+ return [matcher[1][index], match3];
997
+ };
998
+ this.match = match2;
999
+ return match2(method, path);
1000
+ }
1001
+
1002
+ // ../../node_modules/hono/dist/router/reg-exp-router/node.js
1003
+ var LABEL_REG_EXP_STR = "[^/]+";
1004
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
1005
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1006
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
1007
+ var regExpMetaChars = new Set(".\\+*[^]$()");
1008
+ function compareKey(a, b) {
1009
+ if (a.length === 1) {
1010
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
1011
+ }
1012
+ if (b.length === 1) {
1013
+ return 1;
1014
+ }
1015
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
1016
+ return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 1;
1017
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
1018
+ return -1;
1019
+ }
1020
+ if (a === LABEL_REG_EXP_STR) {
1021
+ return 1;
1022
+ } else if (b === LABEL_REG_EXP_STR) {
1023
+ return -1;
1024
+ }
1025
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
1026
+ }
1027
+ var Node = class _Node {
1028
+ #index;
1029
+ #varIndex;
1030
+ #children = /* @__PURE__ */ Object.create(null);
1031
+ insert(tokens, index, paramMap, context, isStatic) {
1032
+ let node = this;
1033
+ for (let i = 0, len = tokens.length;i < len; i++) {
1034
+ const token = tokens[i];
1035
+ const pattern = token.length === 1 ? token === "*" ? i === len - 1 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : null : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1036
+ let nextNode;
1037
+ if (pattern) {
1038
+ const name = pattern[1];
1039
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
1040
+ if (name && pattern[2]) {
1041
+ if (regexpStr === ".*") {
1042
+ throw PATH_ERROR;
1043
+ }
1044
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
1045
+ if (/\((?!\?:)/.test(regexpStr)) {
1046
+ throw PATH_ERROR;
1047
+ }
1048
+ if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) {
1049
+ throw PATH_ERROR;
1050
+ }
1051
+ }
1052
+ nextNode = node.#children[regexpStr];
1053
+ if (!nextNode) {
1054
+ if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) {
1055
+ for (const k in node.#children) {
1056
+ if ((regexpStr.length > 1 || k.length > 1) && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR) {
1057
+ throw PATH_ERROR;
1058
+ }
1059
+ }
1060
+ }
1061
+ nextNode = node.#children[regexpStr] = new _Node;
1062
+ }
1063
+ if (name !== "") {
1064
+ nextNode.#varIndex ??= context.varIndex++;
1065
+ paramMap.push([name, nextNode.#varIndex]);
1066
+ }
1067
+ } else {
1068
+ nextNode = node.#children[token];
1069
+ if (!nextNode) {
1070
+ for (const k in node.#children) {
1071
+ if (k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR) {
1072
+ throw PATH_ERROR;
1073
+ }
1074
+ }
1075
+ nextNode = node.#children[token] = new _Node;
1076
+ }
1077
+ }
1078
+ node = nextNode;
1079
+ }
1080
+ if (node.#index !== undefined) {
1081
+ throw PATH_ERROR;
1082
+ }
1083
+ node.#index = isStatic ? -1 : index;
1084
+ }
1085
+ buildRegExpStr() {
1086
+ const childKeys = Object.keys(this.#children).sort(compareKey);
1087
+ const strList = childKeys.map((k) => {
1088
+ const c = this.#children[k];
1089
+ const childStr = c.buildRegExpStr();
1090
+ return childStr === "" ? "" : (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + childStr;
1091
+ }).filter(Boolean);
1092
+ if (typeof this.#index === "number" && this.#index !== -1) {
1093
+ strList.unshift(`#${this.#index}`);
1094
+ }
1095
+ if (strList.length === 0) {
1096
+ return "";
1097
+ }
1098
+ if (strList.length === 1) {
1099
+ return strList[0];
1100
+ }
1101
+ return "(?:" + strList.join("|") + ")";
1102
+ }
1103
+ };
1104
+
1105
+ // ../../node_modules/hono/dist/router/reg-exp-router/trie.js
1106
+ var Trie = class {
1107
+ #context = { varIndex: 0 };
1108
+ #root = new Node;
1109
+ #index = 0;
1110
+ paths = /* @__PURE__ */ Object.create(null);
1111
+ insert(path, isStatic) {
1112
+ if (isStatic) {
1113
+ this.#root.insert(path.split(""), 0, [], this.#context, true);
1114
+ return;
1115
+ }
1116
+ const paramAssoc = [];
1117
+ const groups = [];
1118
+ let markedPath = path;
1119
+ for (let i = 0;; ) {
1120
+ let replaced = false;
1121
+ markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {
1122
+ const mark = `@\\${i}`;
1123
+ groups[i] = [mark, m];
1124
+ i++;
1125
+ replaced = true;
1126
+ return mark;
1127
+ });
1128
+ if (!replaced) {
1129
+ break;
1130
+ }
1131
+ }
1132
+ const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1133
+ for (let i = groups.length - 1;i >= 0; i--) {
1134
+ const [mark] = groups[i];
1135
+ for (let j = tokens.length - 1;j >= 0; j--) {
1136
+ if (tokens[j].indexOf(mark) !== -1) {
1137
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1138
+ break;
1139
+ }
1140
+ }
1141
+ }
1142
+ this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);
1143
+ this.paths[path] = [this.#index++, paramAssoc];
1144
+ }
1145
+ buildRegExp() {
1146
+ let regexp = this.#root.buildRegExpStr();
1147
+ if (regexp === "") {
1148
+ return [/^$/, [], []];
1149
+ }
1150
+ let captureIndex = 0;
1151
+ const indexReplacementMap = [];
1152
+ const paramReplacementMap = [];
1153
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1154
+ if (handlerIndex !== undefined) {
1155
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1156
+ return "$()";
1157
+ }
1158
+ if (paramIndex !== undefined) {
1159
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1160
+ return "";
1161
+ }
1162
+ return "";
1163
+ });
1164
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1165
+ }
1166
+ };
1167
+
1168
+ // ../../node_modules/hono/dist/router/reg-exp-router/router.js
1169
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1170
+ function buildWildcardRegExp(path) {
1171
+ return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
1172
+ }
1173
+ function clearWildcardRegExpCache() {
1174
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1175
+ }
1176
+ function findMiddleware(middleware, path) {
1177
+ if (!middleware) {
1178
+ return;
1179
+ }
1180
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1181
+ if (buildWildcardRegExp(k).test(path)) {
1182
+ return [...middleware[k]];
1183
+ }
1184
+ }
1185
+ return;
1186
+ }
1187
+ var RegExpRouter = class {
1188
+ name = "RegExpRouter";
1189
+ #middleware;
1190
+ #routes;
1191
+ #tries;
1192
+ constructor() {
1193
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1194
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1195
+ this.#tries = { [METHOD_NAME_ALL]: new Trie };
1196
+ }
1197
+ #insertPath(method, path) {
1198
+ try {
1199
+ this.#tries[method].insert(path, !/\*|\/:/.test(path));
1200
+ } catch (e) {
1201
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
1202
+ }
1203
+ }
1204
+ add(method, path, handler) {
1205
+ const middleware = this.#middleware;
1206
+ const routes = this.#routes;
1207
+ if (!middleware || !routes) {
1208
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1209
+ }
1210
+ if (!middleware[method]) {
1211
+ this.#tries[method] = new Trie;
1212
+ [middleware, routes].forEach((handlerMap) => {
1213
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
1214
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
1215
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
1216
+ this.#insertPath(method, p);
1217
+ });
1218
+ });
1219
+ }
1220
+ if (path === "/*") {
1221
+ path = "*";
1222
+ }
1223
+ const paramCount = (path.match(/\/:/g) || []).length;
1224
+ if (/\*$/.test(path)) {
1225
+ const re = buildWildcardRegExp(path);
1226
+ Object.keys(middleware).forEach((m) => {
1227
+ if ((method === METHOD_NAME_ALL || method === m) && !middleware[m][path]) {
1228
+ this.#insertPath(m, path);
1229
+ middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1230
+ }
1231
+ });
1232
+ Object.keys(middleware).forEach((m) => {
1233
+ if (method === METHOD_NAME_ALL || method === m) {
1234
+ Object.keys(middleware[m]).forEach((p) => {
1235
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
1236
+ });
1237
+ }
1238
+ });
1239
+ Object.keys(routes).forEach((m) => {
1240
+ if (method === METHOD_NAME_ALL || method === m) {
1241
+ Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
1242
+ }
1243
+ });
1244
+ return;
1245
+ }
1246
+ const paths = checkOptionalParameter(path) || [path];
1247
+ for (let i = 0, len = paths.length;i < len; i++) {
1248
+ const path2 = paths[i];
1249
+ Object.keys(routes).forEach((m) => {
1250
+ if (method === METHOD_NAME_ALL || method === m) {
1251
+ if (!routes[m][path2]) {
1252
+ this.#insertPath(m, path2);
1253
+ routes[m][path2] = [
1254
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
1255
+ ];
1256
+ }
1257
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
1258
+ }
1259
+ });
1260
+ }
1261
+ }
1262
+ match = match;
1263
+ buildAllMatchers() {
1264
+ const matchers = /* @__PURE__ */ Object.create(null);
1265
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1266
+ matchers[method] ||= this.#buildMatcher(method);
1267
+ });
1268
+ this.#middleware = this.#routes = this.#tries = undefined;
1269
+ clearWildcardRegExpCache();
1270
+ return matchers;
1271
+ }
1272
+ #buildMatcher(method) {
1273
+ const middleware = this.#middleware[method];
1274
+ const routes = this.#routes[method];
1275
+ const trie = this.#tries[method];
1276
+ const staticMap = /* @__PURE__ */ Object.create(null);
1277
+ const handlerData = [];
1278
+ [middleware, routes].forEach((r) => {
1279
+ for (const path in r) {
1280
+ const handlers = r[path];
1281
+ const pathData = trie.paths[path];
1282
+ if (!pathData) {
1283
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1284
+ continue;
1285
+ }
1286
+ const paramAssoc = pathData[1];
1287
+ handlerData[pathData[0]] = handlers.map(([h, paramCount]) => {
1288
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
1289
+ paramCount -= 1;
1290
+ for (;paramCount >= 0; paramCount--) {
1291
+ const [key, value] = paramAssoc[paramCount];
1292
+ paramIndexMap[key] = value;
1293
+ }
1294
+ return [h, paramIndexMap];
1295
+ });
1296
+ }
1297
+ });
1298
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1299
+ for (let i = 0, len = handlerData.length;i < len; i++) {
1300
+ for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
1301
+ const map = handlerData[i][j]?.[1];
1302
+ if (!map) {
1303
+ continue;
1304
+ }
1305
+ const keys = Object.keys(map);
1306
+ for (let k = 0, len3 = keys.length;k < len3; k++) {
1307
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
1308
+ }
1309
+ }
1310
+ }
1311
+ const handlerMap = [];
1312
+ for (const i in indexReplacementMap) {
1313
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1314
+ }
1315
+ return [regexp, handlerMap, staticMap];
1316
+ }
1317
+ };
1318
+
1319
+ // ../../node_modules/hono/dist/router/reg-exp-router/prepared-router.js
1320
+ var PreparedRegExpRouter = class {
1321
+ name = "PreparedRegExpRouter";
1322
+ #matchers;
1323
+ #relocateMap;
1324
+ constructor(matchers, relocateMap) {
1325
+ this.#matchers = matchers;
1326
+ this.#relocateMap = relocateMap;
1327
+ }
1328
+ #addWildcard(method, handlerData) {
1329
+ const matcher = this.#matchers[method];
1330
+ matcher[1].forEach((list) => list && list.push(handlerData));
1331
+ Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
1332
+ }
1333
+ #addPath(method, path, handler, indexes, map) {
1334
+ const matcher = this.#matchers[method];
1335
+ if (!map) {
1336
+ matcher[2][path][0].push([handler, {}]);
1337
+ } else {
1338
+ indexes.forEach((index) => {
1339
+ if (typeof index === "number") {
1340
+ matcher[1][index].push([handler, map]);
1341
+ } else {
1342
+ matcher[2][index || path][0].push([handler, map]);
1343
+ }
1344
+ });
1345
+ }
1346
+ }
1347
+ add(method, path, handler) {
1348
+ if (!this.#matchers[method]) {
1349
+ const all = this.#matchers[METHOD_NAME_ALL];
1350
+ const staticMap = {};
1351
+ for (const key in all[2]) {
1352
+ staticMap[key] = [all[2][key][0].slice(), emptyParam];
1353
+ }
1354
+ this.#matchers[method] = [
1355
+ all[0],
1356
+ all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
1357
+ staticMap
1358
+ ];
1359
+ }
1360
+ if (path === "/*" || path === "*") {
1361
+ const handlerData = [handler, {}];
1362
+ if (method === METHOD_NAME_ALL) {
1363
+ for (const m in this.#matchers) {
1364
+ this.#addWildcard(m, handlerData);
1365
+ }
1366
+ } else {
1367
+ this.#addWildcard(method, handlerData);
1368
+ }
1369
+ return;
1370
+ }
1371
+ const data = this.#relocateMap[path];
1372
+ if (!data) {
1373
+ throw new Error(`Path ${path} is not registered`);
1374
+ }
1375
+ for (const [indexes, map] of data) {
1376
+ if (method === METHOD_NAME_ALL) {
1377
+ for (const m in this.#matchers) {
1378
+ this.#addPath(m, path, handler, indexes, map);
1379
+ }
1380
+ } else {
1381
+ this.#addPath(method, path, handler, indexes, map);
1382
+ }
1383
+ }
1384
+ }
1385
+ buildAllMatchers() {
1386
+ return this.#matchers;
1387
+ }
1388
+ match = match;
1389
+ };
1390
+
1391
+ // ../../node_modules/hono/dist/router/smart-router/router.js
1392
+ var SmartRouter = class {
1393
+ name = "SmartRouter";
1394
+ #routers = [];
1395
+ #routes = [];
1396
+ constructor(init) {
1397
+ this.#routers = init.routers;
1398
+ }
1399
+ add(method, path, handler) {
1400
+ if (!this.#routes) {
1401
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1402
+ }
1403
+ this.#routes.push([method, path, handler]);
1404
+ }
1405
+ match(method, path) {
1406
+ if (!this.#routes) {
1407
+ throw new Error("Fatal error");
1408
+ }
1409
+ const routers = this.#routers;
1410
+ const routes = this.#routes;
1411
+ const len = routers.length;
1412
+ let i = 0;
1413
+ let res;
1414
+ for (;i < len; i++) {
1415
+ const router = routers[i];
1416
+ try {
1417
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
1418
+ router.add(...routes[i2]);
1419
+ }
1420
+ res = router.match(method, path);
1421
+ } catch (e) {
1422
+ if (e instanceof UnsupportedPathError) {
1423
+ continue;
1424
+ }
1425
+ throw e;
1426
+ }
1427
+ this.match = router.match.bind(router);
1428
+ this.#routers = [router];
1429
+ this.#routes = undefined;
1430
+ break;
1431
+ }
1432
+ if (i === len) {
1433
+ throw new Error("Fatal error");
1434
+ }
1435
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
1436
+ return res;
1437
+ }
1438
+ get activeRouter() {
1439
+ if (this.#routes || this.#routers.length !== 1) {
1440
+ throw new Error("No active router has been determined yet.");
1441
+ }
1442
+ return this.#routers[0];
1443
+ }
1444
+ };
1445
+
1446
+ // ../../node_modules/hono/dist/router/trie-router/node.js
1447
+ var emptyParams = /* @__PURE__ */ Object.create(null);
1448
+ var hasChildren = (children) => {
1449
+ for (const _ in children) {
1450
+ return true;
1451
+ }
1452
+ return false;
1453
+ };
1454
+ var Node2 = class _Node2 {
1455
+ #methods;
1456
+ #children;
1457
+ #patterns;
1458
+ #order = 0;
1459
+ #params = emptyParams;
1460
+ constructor(method, handler, children) {
1461
+ this.#children = children || /* @__PURE__ */ Object.create(null);
1462
+ this.#methods = [];
1463
+ if (method && handler) {
1464
+ const m = /* @__PURE__ */ Object.create(null);
1465
+ m[method] = { handler, possibleKeys: [], score: 0 };
1466
+ this.#methods = [m];
1467
+ }
1468
+ this.#patterns = [];
1469
+ }
1470
+ insert(method, path, handler) {
1471
+ this.#order = ++this.#order;
1472
+ let curNode = this;
1473
+ const parts = splitRoutingPath(path);
1474
+ const possibleKeys = [];
1475
+ for (let i = 0, len = parts.length;i < len; i++) {
1476
+ const p = parts[i];
1477
+ const nextP = parts[i + 1];
1478
+ const pattern = getPattern(p, nextP);
1479
+ const key = Array.isArray(pattern) ? pattern[0] : p;
1480
+ if (key in curNode.#children) {
1481
+ curNode = curNode.#children[key];
1482
+ if (pattern) {
1483
+ possibleKeys.push(pattern[1]);
1484
+ }
1485
+ continue;
1486
+ }
1487
+ curNode.#children[key] = new _Node2;
1488
+ if (pattern) {
1489
+ curNode.#patterns.push(pattern);
1490
+ possibleKeys.push(pattern[1]);
1491
+ }
1492
+ curNode = curNode.#children[key];
1493
+ }
1494
+ curNode.#methods.push({
1495
+ [method]: {
1496
+ handler,
1497
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
1498
+ score: this.#order
1499
+ }
1500
+ });
1501
+ return curNode;
1502
+ }
1503
+ #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
1504
+ for (let i = 0, len = node.#methods.length;i < len; i++) {
1505
+ const m = node.#methods[i];
1506
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
1507
+ const processedSet = {};
1508
+ if (handlerSet !== undefined) {
1509
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
1510
+ handlerSets.push(handlerSet);
1511
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
1512
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
1513
+ const key = handlerSet.possibleKeys[i2];
1514
+ const processed = processedSet[handlerSet.score];
1515
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
1516
+ processedSet[handlerSet.score] = true;
1517
+ }
1518
+ }
1519
+ }
1520
+ }
1521
+ }
1522
+ search(method, path) {
1523
+ const handlerSets = [];
1524
+ this.#params = emptyParams;
1525
+ const curNode = this;
1526
+ let curNodes = [curNode];
1527
+ const parts = splitPath(path);
1528
+ const curNodesQueue = [];
1529
+ const len = parts.length;
1530
+ let partOffsets = null;
1531
+ for (let i = 0;i < len; i++) {
1532
+ const part = parts[i];
1533
+ const isLast = i === len - 1;
1534
+ const tempNodes = [];
1535
+ for (let j = 0, len2 = curNodes.length;j < len2; j++) {
1536
+ const node = curNodes[j];
1537
+ const nextNode = node.#children[part];
1538
+ if (nextNode) {
1539
+ nextNode.#params = node.#params;
1540
+ if (isLast) {
1541
+ if (nextNode.#children["*"]) {
1542
+ this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
1543
+ }
1544
+ this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
1545
+ } else {
1546
+ tempNodes.push(nextNode);
1547
+ }
1548
+ }
1549
+ for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
1550
+ const pattern = node.#patterns[k];
1551
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
1552
+ if (pattern === "*") {
1553
+ const astNode = node.#children["*"];
1554
+ if (astNode) {
1555
+ this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
1556
+ astNode.#params = params;
1557
+ tempNodes.push(astNode);
1558
+ }
1559
+ continue;
1560
+ }
1561
+ const [key, name, matcher] = pattern;
1562
+ if (!part && !(matcher instanceof RegExp)) {
1563
+ continue;
1564
+ }
1565
+ const child = node.#children[key];
1566
+ if (matcher instanceof RegExp) {
1567
+ if (partOffsets === null) {
1568
+ partOffsets = new Array(len);
1569
+ let offset = path[0] === "/" ? 1 : 0;
1570
+ for (let p = 0;p < len; p++) {
1571
+ partOffsets[p] = offset;
1572
+ offset += parts[p].length + 1;
1573
+ }
1574
+ }
1575
+ const restPathString = path.substring(partOffsets[i]);
1576
+ const m = matcher.exec(restPathString);
1577
+ if (m) {
1578
+ params[name] = m[0];
1579
+ this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
1580
+ if (m[0].length === restPathString.length && child.#children["*"]) {
1581
+ this.#pushHandlerSets(handlerSets, child.#children["*"], method, node.#params, params);
1582
+ }
1583
+ if (hasChildren(child.#children)) {
1584
+ child.#params = params;
1585
+ const componentCount = m[0].match(/\//g)?.length ?? 0;
1586
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
1587
+ targetCurNodes.push(child);
1588
+ }
1589
+ continue;
1590
+ }
1591
+ }
1592
+ if (matcher === true || matcher.test(part)) {
1593
+ params[name] = part;
1594
+ if (isLast) {
1595
+ this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
1596
+ if (child.#children["*"]) {
1597
+ this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
1598
+ }
1599
+ } else {
1600
+ child.#params = params;
1601
+ tempNodes.push(child);
1602
+ }
1603
+ }
1604
+ }
1605
+ }
1606
+ const shifted = curNodesQueue.shift();
1607
+ curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
1608
+ }
1609
+ if (handlerSets.length > 1) {
1610
+ handlerSets.sort((a, b) => {
1611
+ return a.score - b.score;
1612
+ });
1613
+ }
1614
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
1615
+ }
1616
+ };
1617
+
1618
+ // ../../node_modules/hono/dist/router/trie-router/router.js
1619
+ var TrieRouter = class {
1620
+ name = "TrieRouter";
1621
+ #node;
1622
+ constructor() {
1623
+ this.#node = new Node2;
1624
+ }
1625
+ add(method, path, handler) {
1626
+ const results = checkOptionalParameter(path);
1627
+ if (results) {
1628
+ for (let i = 0, len = results.length;i < len; i++) {
1629
+ this.#node.insert(method, results[i], handler);
1630
+ }
1631
+ return;
1632
+ }
1633
+ this.#node.insert(method, path, handler);
1634
+ }
1635
+ match(method, path) {
1636
+ return this.#node.search(method, path);
1637
+ }
1638
+ };
1639
+
1640
+ // ../../node_modules/hono/dist/hono.js
1641
+ var Hono2 = class extends Hono {
1642
+ constructor(options = {}) {
1643
+ super(options);
1644
+ this.router = options.router ?? new SmartRouter({
1645
+ routers: [new RegExpRouter, new TrieRouter]
1646
+ });
1647
+ }
1648
+ };
1649
+
1650
+ // ../../node_modules/hono/dist/adapter/bun/serve-static.js
1651
+ import { stat } from "fs/promises";
1652
+ import { join } from "path";
1653
+
1654
+ // ../../node_modules/hono/dist/utils/compress.js
1655
+ var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml|msgpack))(?:[;\s]|$)/i;
1656
+
1657
+ // ../../node_modules/hono/dist/utils/mime.js
1658
+ var getMimeType = (filename, mimes = baseMimes) => {
1659
+ const regexp = /\.([a-zA-Z0-9]+?)$/;
1660
+ const match2 = filename.match(regexp);
1661
+ if (!match2) {
1662
+ return;
1663
+ }
1664
+ return mimes[match2[1].toLowerCase()];
1665
+ };
1666
+ var _baseMimes = {
1667
+ aac: "audio/aac",
1668
+ avi: "video/x-msvideo",
1669
+ avif: "image/avif",
1670
+ av1: "video/av1",
1671
+ bin: "application/octet-stream",
1672
+ bmp: "image/bmp",
1673
+ css: "text/css; charset=utf-8",
1674
+ csv: "text/csv; charset=utf-8",
1675
+ eot: "application/vnd.ms-fontobject",
1676
+ epub: "application/epub+zip",
1677
+ gif: "image/gif",
1678
+ gz: "application/gzip",
1679
+ htm: "text/html; charset=utf-8",
1680
+ html: "text/html; charset=utf-8",
1681
+ ico: "image/x-icon",
1682
+ ics: "text/calendar; charset=utf-8",
1683
+ jpeg: "image/jpeg",
1684
+ jpg: "image/jpeg",
1685
+ js: "text/javascript; charset=utf-8",
1686
+ json: "application/json",
1687
+ jsonld: "application/ld+json",
1688
+ map: "application/json",
1689
+ mid: "audio/x-midi",
1690
+ midi: "audio/x-midi",
1691
+ mjs: "text/javascript; charset=utf-8",
1692
+ mp3: "audio/mpeg",
1693
+ mp4: "video/mp4",
1694
+ mpeg: "video/mpeg",
1695
+ oga: "audio/ogg",
1696
+ ogv: "video/ogg",
1697
+ ogx: "application/ogg",
1698
+ opus: "audio/opus",
1699
+ otf: "font/otf",
1700
+ pdf: "application/pdf",
1701
+ png: "image/png",
1702
+ rtf: "application/rtf",
1703
+ svg: "image/svg+xml; charset=utf-8",
1704
+ tif: "image/tiff",
1705
+ tiff: "image/tiff",
1706
+ ts: "video/mp2t",
1707
+ ttf: "font/ttf",
1708
+ txt: "text/plain; charset=utf-8",
1709
+ wasm: "application/wasm",
1710
+ webm: "video/webm",
1711
+ weba: "audio/webm",
1712
+ webmanifest: "application/manifest+json",
1713
+ webp: "image/webp",
1714
+ woff: "font/woff",
1715
+ woff2: "font/woff2",
1716
+ xhtml: "application/xhtml+xml; charset=utf-8",
1717
+ xml: "application/xml; charset=utf-8",
1718
+ zip: "application/zip",
1719
+ "3gp": "video/3gpp",
1720
+ "3g2": "video/3gpp2",
1721
+ gltf: "model/gltf+json",
1722
+ glb: "model/gltf-binary"
1723
+ };
1724
+ var baseMimes = _baseMimes;
1725
+
1726
+ // ../../node_modules/hono/dist/middleware/serve-static/path.js
1727
+ var defaultJoin = (...paths) => {
1728
+ let result = paths.filter((p) => p !== "").join("/");
1729
+ result = result.replace(/(?<=\/)\/+/g, "");
1730
+ const segments = result.split("/");
1731
+ const resolved = [];
1732
+ for (const segment of segments) {
1733
+ if (segment === ".." && resolved.length > 0 && resolved.at(-1) !== "..") {
1734
+ resolved.pop();
1735
+ } else if (segment !== ".") {
1736
+ resolved.push(segment);
1737
+ }
1738
+ }
1739
+ return resolved.join("/") || ".";
1740
+ };
1741
+
1742
+ // ../../node_modules/hono/dist/middleware/serve-static/index.js
1743
+ var ENCODINGS = {
1744
+ br: ".br",
1745
+ zstd: ".zst",
1746
+ gzip: ".gz"
1747
+ };
1748
+ var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
1749
+ var DEFAULT_DOCUMENT = "index.html";
1750
+ var serveStatic = (options) => {
1751
+ const root = options.root ?? "./";
1752
+ const optionPath = options.path;
1753
+ const join = options.join ?? defaultJoin;
1754
+ return async (c, next) => {
1755
+ if (c.finalized) {
1756
+ return next();
1757
+ }
1758
+ let filename;
1759
+ if (options.path) {
1760
+ filename = options.path;
1761
+ } else {
1762
+ try {
1763
+ filename = tryDecodeURI(c.req.path);
1764
+ if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) {
1765
+ throw new Error;
1766
+ }
1767
+ } catch {
1768
+ await options.onNotFound?.(c.req.path, c);
1769
+ return next();
1770
+ }
1771
+ }
1772
+ let path = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename);
1773
+ if (options.isDir && await options.isDir(path)) {
1774
+ path = join(path, DEFAULT_DOCUMENT);
1775
+ }
1776
+ const getContent = options.getContent;
1777
+ let content = await getContent(path, c);
1778
+ if (content instanceof Response) {
1779
+ return c.newResponse(content.body, content);
1780
+ }
1781
+ if (content != null) {
1782
+ const mimeType = options.mimes && getMimeType(path, options.mimes) || getMimeType(path);
1783
+ c.header("Content-Type", mimeType || "application/octet-stream");
1784
+ if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
1785
+ const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
1786
+ for (const encoding of ENCODINGS_ORDERED_KEYS) {
1787
+ if (!acceptEncodingSet.has(encoding)) {
1788
+ continue;
1789
+ }
1790
+ const compressedContent = await getContent(path + ENCODINGS[encoding], c);
1791
+ if (compressedContent) {
1792
+ content = compressedContent;
1793
+ c.header("Content-Encoding", encoding);
1794
+ c.header("Vary", "Accept-Encoding", { append: true });
1795
+ break;
1796
+ }
1797
+ }
1798
+ }
1799
+ await options.onFound?.(path, c);
1800
+ return c.body(content);
1801
+ }
1802
+ await options.onNotFound?.(path, c);
1803
+ await next();
1804
+ return;
1805
+ };
1806
+ };
1807
+
1808
+ // ../../node_modules/hono/dist/adapter/bun/serve-static.js
1809
+ var serveStatic2 = (options = {}) => {
1810
+ return async function serveStatic22(c, next) {
1811
+ const getContent = async (path) => {
1812
+ const file = Bun.file(path);
1813
+ return await file.exists() ? file : null;
1814
+ };
1815
+ const isDir = async (path) => {
1816
+ let isDir2;
1817
+ try {
1818
+ const stats = await stat(path);
1819
+ isDir2 = stats.isDirectory();
1820
+ } catch {}
1821
+ return isDir2;
1822
+ };
1823
+ return serveStatic({
1824
+ ...options,
1825
+ getContent,
1826
+ join,
1827
+ isDir
1828
+ })(c, next);
1829
+ };
1830
+ };
1831
+
1832
+ // ../../node_modules/hono/dist/helper/ssg/middleware.js
1833
+ var X_HONO_DISABLE_SSG_HEADER_KEY = "x-hono-disable-ssg";
1834
+ var SSG_DISABLED_RESPONSE = (() => {
1835
+ try {
1836
+ return new Response("SSG is disabled", {
1837
+ status: 404,
1838
+ headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: "true" }
1839
+ });
1840
+ } catch {
1841
+ return null;
1842
+ }
1843
+ })();
1844
+ // ../../node_modules/hono/dist/adapter/bun/ssg.js
1845
+ var { write } = Bun;
1846
+
1847
+ // ../../node_modules/hono/dist/helper/websocket/index.js
1848
+ var WSContext = class {
1849
+ #init;
1850
+ constructor(init) {
1851
+ this.#init = init;
1852
+ this.raw = init.raw;
1853
+ this.url = init.url ? new URL(init.url) : null;
1854
+ this.protocol = init.protocol ?? null;
1855
+ }
1856
+ send(source, options) {
1857
+ this.#init.send(source, options ?? {});
1858
+ }
1859
+ raw;
1860
+ binaryType = "arraybuffer";
1861
+ get readyState() {
1862
+ return this.#init.readyState;
1863
+ }
1864
+ url;
1865
+ protocol;
1866
+ close(code, reason) {
1867
+ this.#init.close(code, reason);
1868
+ }
1869
+ };
1870
+ var defineWebSocketHelper = (handler) => {
1871
+ return (...args) => {
1872
+ if (typeof args[0] === "function") {
1873
+ const [createEvents, options] = args;
1874
+ return async function upgradeWebSocket(c, next) {
1875
+ const events = await createEvents(c);
1876
+ const result = await handler(c, events, options);
1877
+ if (result) {
1878
+ return result;
1879
+ }
1880
+ await next();
1881
+ };
1882
+ } else {
1883
+ const [c, events, options] = args;
1884
+ return (async () => {
1885
+ const upgraded = await handler(c, events, options);
1886
+ if (!upgraded) {
1887
+ throw new Error("Failed to upgrade WebSocket");
1888
+ }
1889
+ return upgraded;
1890
+ })();
1891
+ }
1892
+ };
1893
+ };
1894
+
1895
+ // ../../node_modules/hono/dist/adapter/bun/server.js
1896
+ var getBunServer = (c) => ("server" in c.env) ? c.env.server : c.env;
1897
+
1898
+ // ../../node_modules/hono/dist/adapter/bun/websocket.js
1899
+ var upgradeWebSocket = defineWebSocketHelper((c, events) => {
1900
+ const server = getBunServer(c);
1901
+ if (!server) {
1902
+ throw new TypeError("env has to include the 2nd argument of fetch.");
1903
+ }
1904
+ const upgradeResult = server.upgrade(c.req.raw, {
1905
+ data: {
1906
+ events,
1907
+ url: new URL(c.req.url),
1908
+ protocol: c.req.header("sec-websocket-protocol")?.split(",")[0]?.trim() ?? ""
1909
+ }
1910
+ });
1911
+ if (upgradeResult) {
1912
+ return new Response(null);
1913
+ }
1914
+ return;
1915
+ });
1916
+
1917
+ // src/common/errors.ts
1918
+ class HttpError extends Error {
1919
+ status;
1920
+ constructor(status, message) {
1921
+ super(message);
1922
+ this.status = status;
1923
+ this.name = "HttpError";
1924
+ }
1925
+ }
1926
+
1927
+ // ../../node_modules/hono/dist/utils/cookie.js
1928
+ var validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
1929
+ var relaxedCookieNameRegEx = /^[!#-:<>-[\]-~]+$/;
1930
+ var validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
1931
+ var trimCookieWhitespace = (value) => {
1932
+ let start = 0;
1933
+ let end = value.length;
1934
+ while (start < end) {
1935
+ const charCode = value.charCodeAt(start);
1936
+ if (charCode !== 32 && charCode !== 9) {
1937
+ break;
1938
+ }
1939
+ start++;
1940
+ }
1941
+ while (end > start) {
1942
+ const charCode = value.charCodeAt(end - 1);
1943
+ if (charCode !== 32 && charCode !== 9) {
1944
+ break;
1945
+ }
1946
+ end--;
1947
+ }
1948
+ return start === 0 && end === value.length ? value : value.slice(start, end);
1949
+ };
1950
+ var parse = (cookie, name) => {
1951
+ if (name && cookie.indexOf(name) === -1) {
1952
+ return {};
1953
+ }
1954
+ const pairs = cookie.split(";");
1955
+ const parsedCookie = /* @__PURE__ */ Object.create(null);
1956
+ for (const pairStr of pairs) {
1957
+ const valueStartPos = pairStr.indexOf("=");
1958
+ if (valueStartPos === -1) {
1959
+ continue;
1960
+ }
1961
+ const cookieName = trimCookieWhitespace(pairStr.substring(0, valueStartPos));
1962
+ if (name && name !== cookieName || !relaxedCookieNameRegEx.test(cookieName) || cookieName in parsedCookie) {
1963
+ continue;
1964
+ }
1965
+ let cookieValue = trimCookieWhitespace(pairStr.substring(valueStartPos + 1));
1966
+ if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
1967
+ cookieValue = cookieValue.slice(1, -1);
1968
+ }
1969
+ if (validCookieValueRegEx.test(cookieValue)) {
1970
+ parsedCookie[cookieName] = tryDecodeURIComponent(cookieValue);
1971
+ if (name) {
1972
+ break;
1973
+ }
1974
+ }
1975
+ }
1976
+ return parsedCookie;
1977
+ };
1978
+ var _serialize = (name, value, opt = {}) => {
1979
+ if (!validCookieNameRegEx.test(name)) {
1980
+ throw new Error("Invalid cookie name");
1981
+ }
1982
+ let cookie = `${name}=${value}`;
1983
+ if (name.startsWith("__Secure-") && !opt.secure) {
1984
+ throw new Error("__Secure- Cookie must have Secure attributes");
1985
+ }
1986
+ if (name.startsWith("__Host-")) {
1987
+ if (!opt.secure) {
1988
+ throw new Error("__Host- Cookie must have Secure attributes");
1989
+ }
1990
+ if (opt.path !== "/") {
1991
+ throw new Error('__Host- Cookie must have Path attributes with "/"');
1992
+ }
1993
+ if (opt.domain) {
1994
+ throw new Error("__Host- Cookie must not have Domain attributes");
1995
+ }
1996
+ }
1997
+ for (const key of ["domain", "path", "sameSite", "priority"]) {
1998
+ if (opt[key] && /[;\r\n]/.test(opt[key])) {
1999
+ throw new Error(`${key} must not contain ";", "\\r", or "\\n"`);
2000
+ }
2001
+ }
2002
+ if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) {
2003
+ if (opt.maxAge > 34560000) {
2004
+ throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");
2005
+ }
2006
+ cookie += `; Max-Age=${opt.maxAge | 0}`;
2007
+ }
2008
+ if (opt.domain && opt.prefix !== "host") {
2009
+ cookie += `; Domain=${opt.domain}`;
2010
+ }
2011
+ if (opt.path) {
2012
+ cookie += `; Path=${opt.path}`;
2013
+ }
2014
+ if (opt.expires) {
2015
+ if (opt.expires.getTime() - Date.now() > 34560000000) {
2016
+ throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");
2017
+ }
2018
+ cookie += `; Expires=${opt.expires.toUTCString()}`;
2019
+ }
2020
+ if (opt.httpOnly) {
2021
+ cookie += "; HttpOnly";
2022
+ }
2023
+ if (opt.secure) {
2024
+ cookie += "; Secure";
2025
+ }
2026
+ if (opt.sameSite) {
2027
+ cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;
2028
+ }
2029
+ if (opt.priority) {
2030
+ cookie += `; Priority=${opt.priority.charAt(0).toUpperCase() + opt.priority.slice(1)}`;
2031
+ }
2032
+ if (opt.partitioned) {
2033
+ if (!opt.secure) {
2034
+ throw new Error("Partitioned Cookie must have Secure attributes");
2035
+ }
2036
+ cookie += "; Partitioned";
2037
+ }
2038
+ return cookie;
2039
+ };
2040
+ var serialize = (name, value, opt) => {
2041
+ value = encodeURIComponent(value);
2042
+ return _serialize(name, value, opt);
2043
+ };
2044
+
2045
+ // ../../node_modules/hono/dist/helper/cookie/index.js
2046
+ var getCookie = (c, key, prefix) => {
2047
+ const cookie = c.req.raw.headers.get("Cookie");
2048
+ if (typeof key === "string") {
2049
+ if (!cookie) {
2050
+ return;
2051
+ }
2052
+ let finalKey = key;
2053
+ if (prefix === "secure") {
2054
+ finalKey = "__Secure-" + key;
2055
+ } else if (prefix === "host") {
2056
+ finalKey = "__Host-" + key;
2057
+ }
2058
+ const obj2 = parse(cookie, finalKey);
2059
+ return obj2[finalKey];
2060
+ }
2061
+ if (!cookie) {
2062
+ return {};
2063
+ }
2064
+ const obj = parse(cookie);
2065
+ return obj;
2066
+ };
2067
+ var generateCookie = (name, value, opt) => {
2068
+ let cookie;
2069
+ if (opt?.prefix === "secure") {
2070
+ cookie = serialize("__Secure-" + name, value, { path: "/", ...opt, secure: true });
2071
+ } else if (opt?.prefix === "host") {
2072
+ cookie = serialize("__Host-" + name, value, {
2073
+ ...opt,
2074
+ path: "/",
2075
+ secure: true,
2076
+ domain: undefined
2077
+ });
2078
+ } else {
2079
+ cookie = serialize(name, value, { path: "/", ...opt });
2080
+ }
2081
+ return cookie;
2082
+ };
2083
+ var setCookie = (c, name, value, opt) => {
2084
+ const cookie = generateCookie(name, value, opt);
2085
+ c.header("Set-Cookie", cookie, { append: true });
2086
+ };
2087
+ var deleteCookie = (c, name, opt) => {
2088
+ const deletedCookie = getCookie(c, name, opt?.prefix);
2089
+ setCookie(c, name, "", { ...opt, maxAge: 0 });
2090
+ return deletedCookie;
2091
+ };
2092
+
2093
+ // src/services/auth.ts
2094
+ import { randomBytes as randomBytes3 } from "crypto";
2095
+
2096
+ // src/di/collection.ts
2097
+ class ServiceCollection {
2098
+ entries = new Map;
2099
+ constructor(...entries) {
2100
+ for (const [id, service] of entries) {
2101
+ this.set(id, service);
2102
+ }
2103
+ }
2104
+ set(id, instanceOrDescriptor) {
2105
+ const previous = this.entries.get(id);
2106
+ this.entries.set(id, instanceOrDescriptor);
2107
+ return previous;
2108
+ }
2109
+ has(id) {
2110
+ return this.entries.has(id);
2111
+ }
2112
+ get(id) {
2113
+ return this.entries.get(id);
2114
+ }
2115
+ forEach(callback) {
2116
+ for (const [id, value] of this.entries) {
2117
+ callback(id, value);
2118
+ }
2119
+ }
2120
+ }
2121
+ // src/di/decorator.ts
2122
+ var DI_TARGET = "$di$target";
2123
+ var DI_DEPENDENCIES = "$di$dependencies";
2124
+ var serviceIds = new Map;
2125
+ function storeServiceDependency(id, target, index) {
2126
+ const ctor = target;
2127
+ if (ctor[DI_TARGET] === target) {
2128
+ ctor[DI_DEPENDENCIES].push({ id, index });
2129
+ return;
2130
+ }
2131
+ ctor[DI_DEPENDENCIES] = [{ id, index }];
2132
+ ctor[DI_TARGET] = target;
2133
+ }
2134
+ function createDecorator(serviceId) {
2135
+ const existing = serviceIds.get(serviceId);
2136
+ if (existing) {
2137
+ return existing;
2138
+ }
2139
+ const id = function(target, _key, index) {
2140
+ if (arguments.length !== 3) {
2141
+ throw new Error(`@${serviceId} can only decorate a constructor parameter`);
2142
+ }
2143
+ storeServiceDependency(id, target, index);
2144
+ };
2145
+ id.toString = () => serviceId;
2146
+ serviceIds.set(serviceId, id);
2147
+ return id;
2148
+ }
2149
+ function getServiceDependencies(ctor) {
2150
+ const target = ctor;
2151
+ if (target[DI_TARGET] === ctor) {
2152
+ return [...target[DI_DEPENDENCIES] ?? []].toSorted((a, b) => a.index - b.index);
2153
+ }
2154
+ return [];
2155
+ }
2156
+ function inject(...ids) {
2157
+ return (ctor) => {
2158
+ const target = ctor;
2159
+ target[DI_DEPENDENCIES] = ids.map((id, index) => ({ id, index }));
2160
+ target[DI_TARGET] = ctor;
2161
+ };
2162
+ }
2163
+ // src/di/descriptors.ts
2164
+ class SyncDescriptor {
2165
+ ctor;
2166
+ staticArguments;
2167
+ supportsDelayedInstantiation;
2168
+ constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) {
2169
+ this.ctor = ctor;
2170
+ this.staticArguments = staticArguments;
2171
+ this.supportsDelayedInstantiation = supportsDelayedInstantiation;
2172
+ }
2173
+ }
2174
+ // src/di/instantiation.ts
2175
+ var IInstantiationService = createDecorator("instantiationService");
2176
+
2177
+ class InstantiationService {
2178
+ services;
2179
+ activeCreates = new Set;
2180
+ constructor(services) {
2181
+ this.services = services;
2182
+ this.services.set(IInstantiationService, this);
2183
+ }
2184
+ get(id) {
2185
+ return this.resolve(id);
2186
+ }
2187
+ invokeFunction(fn) {
2188
+ return fn({ get: (id) => this.get(id) });
2189
+ }
2190
+ createInstance(ctorOrDescriptor, ...rest) {
2191
+ if (ctorOrDescriptor instanceof SyncDescriptor) {
2192
+ return this.createFromDescriptor(ctorOrDescriptor);
2193
+ }
2194
+ return this.construct(ctorOrDescriptor, rest);
2195
+ }
2196
+ resolve(id) {
2197
+ const entry = this.services.get(id);
2198
+ if (!entry) {
2199
+ throw new Error(`Service '${id}' is not registered`);
2200
+ }
2201
+ if (entry instanceof SyncDescriptor) {
2202
+ const serviceId = String(id);
2203
+ if (this.activeCreates.has(serviceId)) {
2204
+ throw new Error(`Cyclic service dependency around '${serviceId}'`);
2205
+ }
2206
+ this.activeCreates.add(serviceId);
2207
+ try {
2208
+ const instance = this.createFromDescriptor(entry);
2209
+ this.services.set(id, instance);
2210
+ return instance;
2211
+ } finally {
2212
+ this.activeCreates.delete(serviceId);
2213
+ }
2214
+ }
2215
+ return entry;
2216
+ }
2217
+ createFromDescriptor(descriptor) {
2218
+ return this.construct(descriptor.ctor, descriptor.staticArguments);
2219
+ }
2220
+ construct(ctor, staticArgs) {
2221
+ const dependencies = getServiceDependencies(ctor);
2222
+ if (dependencies.length === 0 && staticArgs.length === 0) {
2223
+ return new ctor;
2224
+ }
2225
+ const args = [];
2226
+ let staticIndex = 0;
2227
+ const lastIndex = Math.max(dependencies.at(-1)?.index ?? -1, staticArgs.length + dependencies.length - 1);
2228
+ for (let index = 0;index <= lastIndex; index += 1) {
2229
+ const dependency = dependencies.find((item) => item.index === index);
2230
+ if (dependency) {
2231
+ args[index] = this.resolve(dependency.id);
2232
+ } else if (staticIndex < staticArgs.length) {
2233
+ args[index] = staticArgs[staticIndex];
2234
+ staticIndex += 1;
2235
+ }
2236
+ }
2237
+ return new ctor(...args);
2238
+ }
2239
+ }
2240
+ // src/services/crypto.ts
2241
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
2242
+
2243
+ // src/services/environment.ts
2244
+ import { existsSync, mkdirSync } from "fs";
2245
+ import { homedir } from "os";
2246
+ import { join as join2 } from "path";
2247
+ var IEnvironmentService = createDecorator("environmentService");
2248
+
2249
+ class EnvironmentService {
2250
+ host = process.env.HOST || "127.0.0.1";
2251
+ port = Number(process.env.PORT || 8787);
2252
+ homeDir = process.env.HSW_HOME_DIR || homedir();
2253
+ dataDir = process.env.HSW_DATA_DIR || join2(this.homeDir, ".harness-switch");
2254
+ publicDir = process.env.HSW_PUBLIC_DIR || resolvePublicDir();
2255
+ sessionTtlMs = 24 * 60 * 60 * 1000;
2256
+ cookieName = "hsw_session";
2257
+ files = {
2258
+ profiles: join2(this.dataDir, "profiles.json"),
2259
+ active: join2(this.dataDir, "active.json"),
2260
+ password: join2(this.dataDir, "web_password"),
2261
+ key: join2(this.dataDir, "aes-256-gcm.key"),
2262
+ env: join2(this.dataDir, "env.sh")
2263
+ };
2264
+ ensureDataDir() {
2265
+ mkdirSync(this.dataDir, { recursive: true, mode: 448 });
2266
+ }
2267
+ }
2268
+ function resolvePublicDir() {
2269
+ const candidates = [
2270
+ join2(import.meta.dir, "../public"),
2271
+ join2(import.meta.dir, "../../public"),
2272
+ join2(import.meta.dir, "public")
2273
+ ];
2274
+ return candidates.find((dir) => existsSync(join2(dir, "index.html"))) ?? candidates[0];
2275
+ }
2276
+
2277
+ // src/services/files.ts
2278
+ import { randomBytes } from "crypto";
2279
+ import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync, renameSync, writeFileSync } from "fs";
2280
+ import { dirname as dirname2 } from "path";
2281
+ var IFileService = createDecorator("fileService");
2282
+ var _dec = [
2283
+ inject(IEnvironmentService)
2284
+ ];
2285
+ var _init = __decoratorStart(undefined);
2286
+
2287
+ class FileService {
2288
+ environment;
2289
+ constructor(environment) {
2290
+ this.environment = environment;
2291
+ }
2292
+ exists(file) {
2293
+ return existsSync2(file);
2294
+ }
2295
+ readText(file) {
2296
+ return readFileSync(file, "utf8");
2297
+ }
2298
+ writeSecure(file, text) {
2299
+ this.environment.ensureDataDir();
2300
+ this.ensureDir(dirname2(file));
2301
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
2302
+ writeFileSync(tmp, text, { encoding: "utf8", mode: 384 });
2303
+ renameSync(tmp, file);
2304
+ try {
2305
+ chmodSync(file, 384);
2306
+ } catch {}
2307
+ }
2308
+ readJson(file, fallback) {
2309
+ try {
2310
+ return JSON.parse(this.readText(file));
2311
+ } catch {
2312
+ return fallback;
2313
+ }
2314
+ }
2315
+ writeJson(file, value) {
2316
+ this.writeSecure(file, `${JSON.stringify(value, null, 2)}
2317
+ `);
2318
+ }
2319
+ ensureDir(dir) {
2320
+ mkdirSync2(dir, { recursive: true, mode: 448 });
2321
+ }
2322
+ }
2323
+ FileService = __decorateElement(_init, 0, "FileService", _dec, FileService);
2324
+ __runInitializers(_init, 1, FileService);
2325
+ __decoratorMetadata(_init, FileService);
2326
+ let _FileService = FileService;
2327
+
2328
+ // src/services/crypto.ts
2329
+ var ICryptoService = createDecorator("cryptoService");
2330
+ var _dec = [
2331
+ inject(IEnvironmentService, IFileService)
2332
+ ];
2333
+ var _init = __decoratorStart(undefined);
2334
+
2335
+ class CryptoService {
2336
+ environment;
2337
+ files;
2338
+ constructor(environment, files) {
2339
+ this.environment = environment;
2340
+ this.files = files;
2341
+ }
2342
+ encrypt(plain) {
2343
+ const key = this.getKey();
2344
+ const iv = randomBytes2(12);
2345
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
2346
+ const ciphertext = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
2347
+ return {
2348
+ iv: iv.toString("base64url"),
2349
+ tag: cipher.getAuthTag().toString("base64url"),
2350
+ data: ciphertext.toString("base64url")
2351
+ };
2352
+ }
2353
+ decrypt(value) {
2354
+ try {
2355
+ const payload = value;
2356
+ if (!payload?.iv || !payload?.tag || !payload?.data) {
2357
+ return "";
2358
+ }
2359
+ const key = this.getKey();
2360
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(payload.iv, "base64url"));
2361
+ decipher.setAuthTag(Buffer.from(payload.tag, "base64url"));
2362
+ return Buffer.concat([
2363
+ decipher.update(Buffer.from(payload.data, "base64url")),
2364
+ decipher.final()
2365
+ ]).toString("utf8");
2366
+ } catch {
2367
+ return "";
2368
+ }
2369
+ }
2370
+ randomPassword(bytes = 18) {
2371
+ return randomBytes2(bytes).toString("base64url");
2372
+ }
2373
+ timingSafeEqual(left, right) {
2374
+ const leftBuffer = Buffer.from(left);
2375
+ const rightBuffer = Buffer.from(right);
2376
+ if (leftBuffer.byteLength !== rightBuffer.byteLength) {
2377
+ return false;
2378
+ }
2379
+ return timingSafeEqual(leftBuffer, rightBuffer);
2380
+ }
2381
+ getKey() {
2382
+ const file = this.environment.files.key;
2383
+ if (!this.files.exists(file)) {
2384
+ this.files.writeSecure(file, `${randomBytes2(32).toString("base64url")}
2385
+ `);
2386
+ }
2387
+ return Buffer.from(this.files.readText(file).trim(), "base64url");
2388
+ }
2389
+ }
2390
+ CryptoService = __decorateElement(_init, 0, "CryptoService", _dec, CryptoService);
2391
+ __runInitializers(_init, 1, CryptoService);
2392
+ __decoratorMetadata(_init, CryptoService);
2393
+ let _CryptoService = CryptoService;
2394
+
2395
+ // src/services/log.ts
2396
+ var ILogService = createDecorator("logService");
2397
+
2398
+ class LogService {
2399
+ info(message) {
2400
+ console.log(`[harness-switch] ${message}`);
2401
+ }
2402
+ warn(message) {
2403
+ console.warn(`[harness-switch] ${message}`);
2404
+ }
2405
+ error(message, error) {
2406
+ if (error) {
2407
+ console.error(`[harness-switch] ${message}`, error);
2408
+ return;
2409
+ }
2410
+ console.error(`[harness-switch] ${message}`);
2411
+ }
2412
+ }
2413
+
2414
+ // src/services/auth.ts
2415
+ var IAuthService = createDecorator("authService");
2416
+ var _dec = [
2417
+ inject(IEnvironmentService, IFileService, ICryptoService, ILogService)
2418
+ ];
2419
+ var _init = __decoratorStart(undefined);
2420
+
2421
+ class AuthService {
2422
+ environment;
2423
+ files;
2424
+ crypto;
2425
+ log;
2426
+ sessions = new Map;
2427
+ constructor(environment, files, crypto2, log) {
2428
+ this.environment = environment;
2429
+ this.files = files;
2430
+ this.crypto = crypto2;
2431
+ this.log = log;
2432
+ }
2433
+ ensurePassword() {
2434
+ const file = this.environment.files.password;
2435
+ if (!this.files.exists(file)) {
2436
+ const password = this.crypto.randomPassword();
2437
+ this.files.writeSecure(file, `${password}
2438
+ `);
2439
+ this.log.info(`Initial web password: ${password}`);
2440
+ }
2441
+ return this.files.readText(file).trim();
2442
+ }
2443
+ login(password) {
2444
+ const expected = this.ensurePassword();
2445
+ if (!this.crypto.timingSafeEqual(password, expected)) {
2446
+ return null;
2447
+ }
2448
+ const token = randomBytes3(32).toString("base64url");
2449
+ this.sessions.set(token, { expires: Date.now() + this.environment.sessionTtlMs });
2450
+ return token;
2451
+ }
2452
+ logout(token) {
2453
+ if (token) {
2454
+ this.sessions.delete(token);
2455
+ }
2456
+ }
2457
+ isAuthenticated(token) {
2458
+ if (!token) {
2459
+ return false;
2460
+ }
2461
+ const session = this.sessions.get(token);
2462
+ if (!session || session.expires < Date.now()) {
2463
+ this.sessions.delete(token);
2464
+ return false;
2465
+ }
2466
+ return true;
2467
+ }
2468
+ }
2469
+ AuthService = __decorateElement(_init, 0, "AuthService", _dec, AuthService);
2470
+ __runInitializers(_init, 1, AuthService);
2471
+ __decoratorMetadata(_init, AuthService);
2472
+ let _AuthService = AuthService;
2473
+
2474
+ // src/http/middleware.ts
2475
+ function createServiceMiddleware(services) {
2476
+ return async (c, next) => {
2477
+ c.set("services", services);
2478
+ await next();
2479
+ };
2480
+ }
2481
+ function createOriginGuard() {
2482
+ return async (c, next) => {
2483
+ if (c.req.method !== "GET" && c.req.method !== "HEAD" && c.req.method !== "OPTIONS") {
2484
+ const origin = c.req.header("origin");
2485
+ if (origin) {
2486
+ const host = c.req.header("host");
2487
+ const allowed = [`http://${host}`, `https://${host}`];
2488
+ if (!allowed.includes(origin)) {
2489
+ throw new HttpError(403, "cross-origin request denied");
2490
+ }
2491
+ }
2492
+ }
2493
+ await next();
2494
+ };
2495
+ }
2496
+ function createAuthGuard(services) {
2497
+ const auth = services.get(IAuthService);
2498
+ const environment = services.get(IEnvironmentService);
2499
+ return async (c, next) => {
2500
+ const token = getCookie(c, environment.cookieName);
2501
+ if (!auth.isAuthenticated(token)) {
2502
+ throw new HttpError(401, "authentication required");
2503
+ }
2504
+ await next();
2505
+ };
2506
+ }
2507
+
2508
+ // src/http/routes/auth.ts
2509
+ function createAuthRoutes(services) {
2510
+ const app = new Hono2;
2511
+ const auth = services.get(IAuthService);
2512
+ const environment = services.get(IEnvironmentService);
2513
+ app.post("/login", async (c) => {
2514
+ const body = await c.req.json().catch(() => ({}));
2515
+ const token = auth.login(String(body.password ?? ""));
2516
+ if (!token) {
2517
+ throw new HttpError(401, "invalid password");
2518
+ }
2519
+ setCookie(c, environment.cookieName, token, {
2520
+ httpOnly: true,
2521
+ sameSite: "Lax",
2522
+ path: "/",
2523
+ maxAge: environment.sessionTtlMs / 1000
2524
+ });
2525
+ return c.json({ authenticated: true });
2526
+ });
2527
+ app.post("/logout", (c) => {
2528
+ auth.logout(getCookie(c, environment.cookieName));
2529
+ deleteCookie(c, environment.cookieName, { path: "/" });
2530
+ return c.json({ ok: true });
2531
+ });
2532
+ app.get("/session", (c) => {
2533
+ const token = getCookie(c, environment.cookieName);
2534
+ if (!auth.isAuthenticated(token)) {
2535
+ throw new HttpError(401, "authentication required");
2536
+ }
2537
+ return c.json({ authenticated: true });
2538
+ });
2539
+ return app;
2540
+ }
2541
+
2542
+ // src/services/activation.ts
2543
+ import { join as join3 } from "path";
2544
+
2545
+ // ../../packages/shared/src/harnesses.ts
2546
+ var HARNESS_IDS = ["claude", "pi", "codex", "zcode", "kimi"];
2547
+ var HARNESS_LABELS = {
2548
+ claude: "Claude Code",
2549
+ pi: "pi",
2550
+ codex: "Codex",
2551
+ zcode: "zcode",
2552
+ kimi: "Kimi Code"
2553
+ };
2554
+ function isHarnessId(value) {
2555
+ return HARNESS_IDS.includes(value);
2556
+ }
2557
+ // src/services/registry.ts
2558
+ var IHarnessRegistry = createDecorator("harnessRegistry");
2559
+
2560
+ class HarnessRegistry {
2561
+ list() {
2562
+ return HARNESS_IDS.map((id) => ({ id, label: HARNESS_LABELS[id] }));
2563
+ }
2564
+ has(id) {
2565
+ return isHarnessId(id);
2566
+ }
2567
+ require(id) {
2568
+ if (!this.has(id)) {
2569
+ throw new HttpError(404, "unknown harness");
2570
+ }
2571
+ return id;
2572
+ }
2573
+ label(id) {
2574
+ return HARNESS_LABELS[id];
2575
+ }
2576
+ }
2577
+
2578
+ // src/services/profiles.ts
2579
+ var IProfileService = createDecorator("profileService");
2580
+ var _dec = [
2581
+ inject(IEnvironmentService, IFileService, ICryptoService, IHarnessRegistry)
2582
+ ];
2583
+ var _init = __decoratorStart(undefined);
2584
+
2585
+ class ProfileService {
2586
+ environment;
2587
+ files;
2588
+ crypto;
2589
+ harnesses;
2590
+ constructor(environment, files, crypto2, harnesses) {
2591
+ this.environment = environment;
2592
+ this.files = files;
2593
+ this.crypto = crypto2;
2594
+ this.harnesses = harnesses;
2595
+ }
2596
+ list(harness) {
2597
+ const store = this.read();
2598
+ return Object.entries(store[harness] ?? {}).map(([name, profile]) => this.toPublic(harness, name, profile));
2599
+ }
2600
+ get(harness, name) {
2601
+ const stored = this.read()[harness]?.[name];
2602
+ return stored ? this.toPublic(harness, name, stored) : undefined;
2603
+ }
2604
+ upsert(harness, input, isCreate) {
2605
+ this.harnesses.require(harness);
2606
+ const name = input.name.trim();
2607
+ this.assertName(name);
2608
+ const store = this.read();
2609
+ store[harness] ||= {};
2610
+ const prior = store[harness][name];
2611
+ if (isCreate && prior) {
2612
+ throw new HttpError(409, "profile already exists");
2613
+ }
2614
+ if (!isCreate && !prior) {
2615
+ throw new HttpError(404, "profile not found");
2616
+ }
2617
+ const apiKey = input.apiKey || (prior ? this.crypto.decrypt(prior.api_key) : "");
2618
+ if (isCreate && !apiKey) {
2619
+ throw new HttpError(400, "apiKey is required");
2620
+ }
2621
+ store[harness][name] = {
2622
+ base_url: (input.baseUrl ?? prior?.base_url ?? "").trim(),
2623
+ api_key: this.crypto.encrypt(apiKey),
2624
+ model: (input.model ?? prior?.model ?? "").trim(),
2625
+ notes: input.notes ?? prior?.notes ?? "",
2626
+ updated_at: new Date().toISOString()
2627
+ };
2628
+ this.files.writeJson(this.environment.files.profiles, store);
2629
+ return this.toPublic(harness, name, store[harness][name]);
2630
+ }
2631
+ remove(harness, name) {
2632
+ const store = this.read();
2633
+ if (!store[harness]?.[name]) {
2634
+ throw new HttpError(404, "profile not found");
2635
+ }
2636
+ delete store[harness][name];
2637
+ this.files.writeJson(this.environment.files.profiles, store);
2638
+ }
2639
+ decrypt(harness, name) {
2640
+ const stored = this.read()[harness]?.[name];
2641
+ if (!stored) {
2642
+ throw new HttpError(404, "profile not found");
2643
+ }
2644
+ return {
2645
+ name,
2646
+ baseUrl: stored.base_url || "",
2647
+ apiKey: this.crypto.decrypt(stored.api_key),
2648
+ model: stored.model || ""
2649
+ };
2650
+ }
2651
+ read() {
2652
+ return this.files.readJson(this.environment.files.profiles, {});
2653
+ }
2654
+ toPublic(harness, name, profile) {
2655
+ return {
2656
+ harness,
2657
+ name,
2658
+ baseUrl: profile.base_url || "",
2659
+ model: profile.model || "",
2660
+ notes: profile.notes || "",
2661
+ updatedAt: profile.updated_at || ""
2662
+ };
2663
+ }
2664
+ assertName(name) {
2665
+ if (!name) {
2666
+ throw new HttpError(400, "name is required");
2667
+ }
2668
+ if (name.includes("/") || name.includes("\\")) {
2669
+ throw new HttpError(400, "name cannot contain slashes");
2670
+ }
2671
+ if (name.length > 120) {
2672
+ throw new HttpError(400, "name is too long");
2673
+ }
2674
+ }
2675
+ }
2676
+ ProfileService = __decorateElement(_init, 0, "ProfileService", _dec, ProfileService);
2677
+ __runInitializers(_init, 1, ProfileService);
2678
+ __decoratorMetadata(_init, ProfileService);
2679
+ let _ProfileService = ProfileService;
2680
+
2681
+ // src/services/activation.ts
2682
+ var ENV_MAP = {
2683
+ claude: {
2684
+ ANTHROPIC_BASE_URL: "baseUrl",
2685
+ ANTHROPIC_API_KEY: "apiKey",
2686
+ ANTHROPIC_MODEL: "model"
2687
+ },
2688
+ codex: {
2689
+ OPENAI_BASE_URL: "baseUrl",
2690
+ OPENAI_API_KEY: "apiKey",
2691
+ CODEX_MODEL: "model"
2692
+ },
2693
+ pi: {
2694
+ PI_API_BASE: "baseUrl",
2695
+ PI_API_KEY: "apiKey",
2696
+ PI_MODEL: "model"
2697
+ },
2698
+ zcode: {
2699
+ ZCODE_BASE_URL: "baseUrl",
2700
+ ZCODE_API_KEY: "apiKey",
2701
+ ZCODE_MODEL: "model"
2702
+ },
2703
+ kimi: {
2704
+ KIMI_BASE_URL: "baseUrl",
2705
+ KIMI_API_KEY: "apiKey",
2706
+ KIMI_MODEL: "model"
2707
+ }
2708
+ };
2709
+ var IActivationService = createDecorator("activationService");
2710
+ var _dec = [
2711
+ inject(IEnvironmentService, IFileService, IHarnessRegistry, IProfileService)
2712
+ ];
2713
+ var _init = __decoratorStart(undefined);
2714
+
2715
+ class ActivationService {
2716
+ environment;
2717
+ files;
2718
+ harnesses;
2719
+ profiles;
2720
+ constructor(environment, files, harnesses, profiles) {
2721
+ this.environment = environment;
2722
+ this.files = files;
2723
+ this.harnesses = harnesses;
2724
+ this.profiles = profiles;
2725
+ }
2726
+ getActive(harness) {
2727
+ const stored = this.read()[harness];
2728
+ if (!stored) {
2729
+ return null;
2730
+ }
2731
+ return {
2732
+ name: stored.name,
2733
+ baseUrl: stored.base_url || "",
2734
+ model: stored.model || ""
2735
+ };
2736
+ }
2737
+ activate(harness, name) {
2738
+ const profile = this.profiles.decrypt(harness, name);
2739
+ const active = this.read();
2740
+ active[harness] = {
2741
+ name: profile.name,
2742
+ base_url: profile.baseUrl,
2743
+ api_key: profile.apiKey,
2744
+ model: profile.model
2745
+ };
2746
+ this.files.writeJson(this.environment.files.active, active);
2747
+ this.writeNativeConfig(harness, profile.baseUrl, profile.apiKey, profile.model);
2748
+ this.writeEnv(active);
2749
+ return this.environment.files.env;
2750
+ }
2751
+ read() {
2752
+ return this.files.readJson(this.environment.files.active, {});
2753
+ }
2754
+ writeEnv(active) {
2755
+ const lines = [
2756
+ "# Generated by harness-switch. Source this file in the shell where you launch your harness.",
2757
+ "# This file contains secrets. Do not commit it."
2758
+ ];
2759
+ for (const [harness, profile] of Object.entries(active)) {
2760
+ if (!this.harnesses.has(harness)) {
2761
+ continue;
2762
+ }
2763
+ lines.push(`# ${this.harnesses.label(harness)} / ${profile.name}`);
2764
+ const values = {
2765
+ baseUrl: profile.base_url,
2766
+ apiKey: profile.api_key,
2767
+ model: profile.model
2768
+ };
2769
+ for (const [env, field] of Object.entries(ENV_MAP[harness])) {
2770
+ if (values[field]) {
2771
+ lines.push(`export ${env}=${shellQuote(values[field])}`);
2772
+ }
2773
+ }
2774
+ }
2775
+ this.files.writeSecure(this.environment.files.env, `${lines.join(`
2776
+ `)}
2777
+ `);
2778
+ }
2779
+ writeNativeConfig(harness, baseUrl, apiKey, model) {
2780
+ const home = this.environment.homeDir;
2781
+ if (harness === "claude") {
2782
+ const target = join3(home, ".claude", "settings.json");
2783
+ this.files.ensureDir(join3(home, ".claude"));
2784
+ const current = this.files.readJson(target, {});
2785
+ const env = {
2786
+ ...current.env,
2787
+ ANTHROPIC_BASE_URL: baseUrl,
2788
+ ANTHROPIC_API_KEY: apiKey
2789
+ };
2790
+ if (model) {
2791
+ env.ANTHROPIC_MODEL = model;
2792
+ }
2793
+ current.env = env;
2794
+ this.files.writeSecure(target, `${JSON.stringify(current, null, 2)}
2795
+ `);
2796
+ }
2797
+ if (harness === "kimi") {
2798
+ const target = join3(home, ".kimi", "config.toml");
2799
+ const selected = model || "kimi-for-coding";
2800
+ this.files.ensureDir(join3(home, ".kimi"));
2801
+ const content = `default_model = "${escapeToml(selected)}"
2802
+
2803
+ [providers.harness_switch]
2804
+ type = "kimi"
2805
+ base_url = "${escapeToml(baseUrl)}"
2806
+ api_key = "${escapeToml(apiKey)}"
2807
+
2808
+ [models.harness_switch_model]
2809
+ provider = "harness_switch"
2810
+ model = "${escapeToml(selected)}"
2811
+ max_context_size = 262144
2812
+ `;
2813
+ this.files.writeSecure(target, content);
2814
+ }
2815
+ }
2816
+ }
2817
+ ActivationService = __decorateElement(_init, 0, "ActivationService", _dec, ActivationService);
2818
+ __runInitializers(_init, 1, ActivationService);
2819
+ __decoratorMetadata(_init, ActivationService);
2820
+ let _ActivationService = ActivationService;
2821
+ function shellQuote(value) {
2822
+ return `'${String(value || "").replace(/'/g, `'"'"'`)}'`;
2823
+ }
2824
+ function escapeToml(value) {
2825
+ return String(value || "").replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
2826
+ }
2827
+
2828
+ // src/http/routes/harnesses.ts
2829
+ function createHarnessRoutes(services) {
2830
+ const app = new Hono2;
2831
+ const harnesses = services.get(IHarnessRegistry);
2832
+ const profiles = services.get(IProfileService);
2833
+ const activation = services.get(IActivationService);
2834
+ const environment = services.get(IEnvironmentService);
2835
+ app.get("/", (c) => {
2836
+ return c.json({
2837
+ envFile: environment.files.env,
2838
+ items: harnesses.list().map((item) => ({
2839
+ id: item.id,
2840
+ label: item.label,
2841
+ active: activation.getActive(item.id),
2842
+ profiles: profiles.list(item.id)
2843
+ }))
2844
+ });
2845
+ });
2846
+ app.get("/:harnessId", (c) => {
2847
+ const harnessId = harnesses.require(c.req.param("harnessId"));
2848
+ return c.json({
2849
+ id: harnessId,
2850
+ label: harnesses.label(harnessId),
2851
+ active: activation.getActive(harnessId),
2852
+ profiles: profiles.list(harnessId)
2853
+ });
2854
+ });
2855
+ app.post("/:harnessId/profiles", async (c) => {
2856
+ const harnessId = harnesses.require(c.req.param("harnessId"));
2857
+ const body = await c.req.json().catch(() => {
2858
+ throw new HttpError(400, "invalid json");
2859
+ });
2860
+ const profile = profiles.upsert(harnessId, {
2861
+ name: String(body.name ?? ""),
2862
+ baseUrl: body.baseUrl,
2863
+ apiKey: body.apiKey,
2864
+ model: body.model,
2865
+ notes: body.notes
2866
+ }, true);
2867
+ return c.json(profile, 201);
2868
+ });
2869
+ app.patch("/:harnessId/profiles/:name", async (c) => {
2870
+ const harnessId = harnesses.require(c.req.param("harnessId"));
2871
+ const name = decodeURIComponent(c.req.param("name"));
2872
+ const body = await c.req.json().catch(() => {
2873
+ throw new HttpError(400, "invalid json");
2874
+ });
2875
+ const profile = profiles.upsert(harnessId, {
2876
+ name,
2877
+ baseUrl: body.baseUrl,
2878
+ apiKey: body.apiKey,
2879
+ model: body.model,
2880
+ notes: body.notes
2881
+ }, false);
2882
+ return c.json(profile);
2883
+ });
2884
+ app.delete("/:harnessId/profiles/:name", (c) => {
2885
+ const harnessId = harnesses.require(c.req.param("harnessId"));
2886
+ profiles.remove(harnessId, decodeURIComponent(c.req.param("name")));
2887
+ return c.json({ ok: true });
2888
+ });
2889
+ app.post("/:harnessId/profiles/:name/activate", (c) => {
2890
+ const harnessId = harnesses.require(c.req.param("harnessId"));
2891
+ const envFile = activation.activate(harnessId, decodeURIComponent(c.req.param("name")));
2892
+ return c.json({ ok: true, envFile });
2893
+ });
2894
+ return app;
2895
+ }
2896
+
2897
+ // src/app.ts
2898
+ function createApp(services) {
2899
+ const app = new Hono2;
2900
+ const environment = services.get(IEnvironmentService);
2901
+ const log = services.get(ILogService);
2902
+ app.use("*", createServiceMiddleware(services));
2903
+ app.get("/healthz", (c) => c.json({ ok: true }));
2904
+ const api = new Hono2;
2905
+ api.use("*", createOriginGuard());
2906
+ api.route("/auth", createAuthRoutes(services));
2907
+ api.use("/harnesses/*", createAuthGuard(services));
2908
+ api.use("/harnesses", createAuthGuard(services));
2909
+ api.route("/harnesses", createHarnessRoutes(services));
2910
+ app.route("/api", api);
2911
+ const publicDir = environment.publicDir;
2912
+ if (existsSync3(publicDir)) {
2913
+ app.use("/assets/*", serveStatic2({ root: publicDir }));
2914
+ app.get("*", async (c, next) => {
2915
+ if (c.req.path.startsWith("/api") || c.req.path === "/healthz") {
2916
+ return next();
2917
+ }
2918
+ const assetPath = join4(publicDir, c.req.path.replace(/^\//, ""));
2919
+ if (c.req.path !== "/" && existsSync3(assetPath)) {
2920
+ return serveStatic2({ root: publicDir })(c, next);
2921
+ }
2922
+ const index = join4(publicDir, "index.html");
2923
+ if (existsSync3(index)) {
2924
+ return c.html(await Bun.file(index).text());
2925
+ }
2926
+ return c.text("frontend not built", 503);
2927
+ });
2928
+ }
2929
+ app.notFound((c) => c.json({ error: "not found" }, 404));
2930
+ app.onError((error, c) => {
2931
+ if (error instanceof HttpError) {
2932
+ return c.json({ error: error.message }, error.status);
2933
+ }
2934
+ log.error("unhandled error", error);
2935
+ return c.json({ error: "internal server error" }, 500);
2936
+ });
2937
+ return app;
2938
+ }
2939
+
2940
+ // src/bootstrap.ts
2941
+ function createServices() {
2942
+ const collection = new ServiceCollection;
2943
+ collection.set(ILogService, new SyncDescriptor(LogService));
2944
+ collection.set(IEnvironmentService, new SyncDescriptor(EnvironmentService));
2945
+ collection.set(IFileService, new SyncDescriptor(FileService));
2946
+ collection.set(ICryptoService, new SyncDescriptor(CryptoService));
2947
+ collection.set(IAuthService, new SyncDescriptor(AuthService));
2948
+ collection.set(IHarnessRegistry, new SyncDescriptor(HarnessRegistry));
2949
+ collection.set(IProfileService, new SyncDescriptor(ProfileService));
2950
+ collection.set(IActivationService, new SyncDescriptor(ActivationService));
2951
+ return new InstantiationService(collection);
2952
+ }
2953
+
2954
+ // src/main.ts
2955
+ var services = createServices();
2956
+ var environment = services.get(IEnvironmentService);
2957
+ var log = services.get(ILogService);
2958
+ var auth = services.get(IAuthService);
2959
+ environment.ensureDataDir();
2960
+ auth.ensurePassword();
2961
+ var app = createApp(services);
2962
+ var server = Bun.serve({
2963
+ hostname: environment.host,
2964
+ port: environment.port,
2965
+ fetch: app.fetch
2966
+ });
2967
+ log.info(`data directory: ${environment.dataDir}`);
2968
+ log.info(`listening on http://${server.hostname}:${server.port}`);