@dirathea/busical 0.1.3

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,2322 @@
1
+ var compose = (middleware, onError, onNotFound) => {
2
+ return (context, next) => {
3
+ let index2 = -1;
4
+ return dispatch(0);
5
+ async function dispatch(i) {
6
+ if (i <= index2) {
7
+ throw new Error("next() called multiple times");
8
+ }
9
+ index2 = i;
10
+ let res;
11
+ let isError = false;
12
+ let handler;
13
+ if (middleware[i]) {
14
+ handler = middleware[i][0][0];
15
+ context.req.routeIndex = i;
16
+ } else {
17
+ handler = i === middleware.length && next || void 0;
18
+ }
19
+ if (handler) {
20
+ try {
21
+ res = await handler(context, () => dispatch(i + 1));
22
+ } catch (err) {
23
+ if (err instanceof Error && onError) {
24
+ context.error = err;
25
+ res = await onError(err, context);
26
+ isError = true;
27
+ } else {
28
+ throw err;
29
+ }
30
+ }
31
+ } else {
32
+ if (context.finalized === false && onNotFound) {
33
+ res = await onNotFound(context);
34
+ }
35
+ }
36
+ if (res && (context.finalized === false || isError)) {
37
+ context.res = res;
38
+ }
39
+ return context;
40
+ }
41
+ };
42
+ };
43
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
44
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
45
+ const { all = false, dot = false } = options;
46
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
47
+ const contentType = headers.get("Content-Type");
48
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
49
+ return parseFormData(request, { all, dot });
50
+ }
51
+ return {};
52
+ };
53
+ async function parseFormData(request, options) {
54
+ const formData = await request.formData();
55
+ if (formData) {
56
+ return convertFormDataToBodyData(formData, options);
57
+ }
58
+ return {};
59
+ }
60
+ function convertFormDataToBodyData(formData, options) {
61
+ const form = /* @__PURE__ */ Object.create(null);
62
+ formData.forEach((value, key) => {
63
+ const shouldParseAllValues = options.all || key.endsWith("[]");
64
+ if (!shouldParseAllValues) {
65
+ form[key] = value;
66
+ } else {
67
+ handleParsingAllValues(form, key, value);
68
+ }
69
+ });
70
+ if (options.dot) {
71
+ Object.entries(form).forEach(([key, value]) => {
72
+ const shouldParseDotValues = key.includes(".");
73
+ if (shouldParseDotValues) {
74
+ handleParsingNestedValues(form, key, value);
75
+ delete form[key];
76
+ }
77
+ });
78
+ }
79
+ return form;
80
+ }
81
+ var handleParsingAllValues = (form, key, value) => {
82
+ if (form[key] !== void 0) {
83
+ if (Array.isArray(form[key])) {
84
+ form[key].push(value);
85
+ } else {
86
+ form[key] = [form[key], value];
87
+ }
88
+ } else {
89
+ if (!key.endsWith("[]")) {
90
+ form[key] = value;
91
+ } else {
92
+ form[key] = [value];
93
+ }
94
+ }
95
+ };
96
+ var handleParsingNestedValues = (form, key, value) => {
97
+ let nestedForm = form;
98
+ const keys = key.split(".");
99
+ keys.forEach((key2, index2) => {
100
+ if (index2 === keys.length - 1) {
101
+ nestedForm[key2] = value;
102
+ } else {
103
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
104
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
105
+ }
106
+ nestedForm = nestedForm[key2];
107
+ }
108
+ });
109
+ };
110
+ var splitPath = (path) => {
111
+ const paths = path.split("/");
112
+ if (paths[0] === "") {
113
+ paths.shift();
114
+ }
115
+ return paths;
116
+ };
117
+ var splitRoutingPath = (routePath) => {
118
+ const { groups, path } = extractGroupsFromPath(routePath);
119
+ const paths = splitPath(path);
120
+ return replaceGroupMarks(paths, groups);
121
+ };
122
+ var extractGroupsFromPath = (path) => {
123
+ const groups = [];
124
+ path = path.replace(/\{[^}]+\}/g, (match2, index2) => {
125
+ const mark = `@${index2}`;
126
+ groups.push([mark, match2]);
127
+ return mark;
128
+ });
129
+ return { groups, path };
130
+ };
131
+ var replaceGroupMarks = (paths, groups) => {
132
+ for (let i = groups.length - 1; i >= 0; i--) {
133
+ const [mark] = groups[i];
134
+ for (let j = paths.length - 1; j >= 0; j--) {
135
+ if (paths[j].includes(mark)) {
136
+ paths[j] = paths[j].replace(mark, groups[i][1]);
137
+ break;
138
+ }
139
+ }
140
+ }
141
+ return paths;
142
+ };
143
+ var patternCache = {};
144
+ var getPattern = (label, next) => {
145
+ if (label === "*") {
146
+ return "*";
147
+ }
148
+ const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
149
+ if (match2) {
150
+ const cacheKey = `${label}#${next}`;
151
+ if (!patternCache[cacheKey]) {
152
+ if (match2[2]) {
153
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
154
+ } else {
155
+ patternCache[cacheKey] = [label, match2[1], true];
156
+ }
157
+ }
158
+ return patternCache[cacheKey];
159
+ }
160
+ return null;
161
+ };
162
+ var tryDecode = (str, decoder) => {
163
+ try {
164
+ return decoder(str);
165
+ } catch {
166
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
167
+ try {
168
+ return decoder(match2);
169
+ } catch {
170
+ return match2;
171
+ }
172
+ });
173
+ }
174
+ };
175
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
176
+ var getPath = (request) => {
177
+ const url = request.url;
178
+ const start = url.indexOf("/", url.indexOf(":") + 4);
179
+ let i = start;
180
+ for (; i < url.length; i++) {
181
+ const charCode = url.charCodeAt(i);
182
+ if (charCode === 37) {
183
+ const queryIndex = url.indexOf("?", i);
184
+ const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
185
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
186
+ } else if (charCode === 63) {
187
+ break;
188
+ }
189
+ }
190
+ return url.slice(start, i);
191
+ };
192
+ var getPathNoStrict = (request) => {
193
+ const result = getPath(request);
194
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
195
+ };
196
+ var mergePath = (base, sub, ...rest) => {
197
+ if (rest.length) {
198
+ sub = mergePath(sub, ...rest);
199
+ }
200
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
201
+ };
202
+ var checkOptionalParameter = (path) => {
203
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
204
+ return null;
205
+ }
206
+ const segments = path.split("/");
207
+ const results = [];
208
+ let basePath = "";
209
+ segments.forEach((segment) => {
210
+ if (segment !== "" && !/\:/.test(segment)) {
211
+ basePath += "/" + segment;
212
+ } else if (/\:/.test(segment)) {
213
+ if (/\?/.test(segment)) {
214
+ if (results.length === 0 && basePath === "") {
215
+ results.push("/");
216
+ } else {
217
+ results.push(basePath);
218
+ }
219
+ const optionalSegment = segment.replace("?", "");
220
+ basePath += "/" + optionalSegment;
221
+ results.push(basePath);
222
+ } else {
223
+ basePath += "/" + segment;
224
+ }
225
+ }
226
+ });
227
+ return results.filter((v, i, a) => a.indexOf(v) === i);
228
+ };
229
+ var _decodeURI = (value) => {
230
+ if (!/[%+]/.test(value)) {
231
+ return value;
232
+ }
233
+ if (value.indexOf("+") !== -1) {
234
+ value = value.replace(/\+/g, " ");
235
+ }
236
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
237
+ };
238
+ var _getQueryParam = (url, key, multiple) => {
239
+ let encoded;
240
+ if (!multiple && key && !/[%+]/.test(key)) {
241
+ let keyIndex2 = url.indexOf("?", 8);
242
+ if (keyIndex2 === -1) {
243
+ return void 0;
244
+ }
245
+ if (!url.startsWith(key, keyIndex2 + 1)) {
246
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
247
+ }
248
+ while (keyIndex2 !== -1) {
249
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
250
+ if (trailingKeyCode === 61) {
251
+ const valueIndex = keyIndex2 + key.length + 2;
252
+ const endIndex = url.indexOf("&", valueIndex);
253
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
254
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
255
+ return "";
256
+ }
257
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
258
+ }
259
+ encoded = /[%+]/.test(url);
260
+ if (!encoded) {
261
+ return void 0;
262
+ }
263
+ }
264
+ const results = {};
265
+ encoded ??= /[%+]/.test(url);
266
+ let keyIndex = url.indexOf("?", 8);
267
+ while (keyIndex !== -1) {
268
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
269
+ let valueIndex = url.indexOf("=", keyIndex);
270
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
271
+ valueIndex = -1;
272
+ }
273
+ let name = url.slice(
274
+ keyIndex + 1,
275
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
276
+ );
277
+ if (encoded) {
278
+ name = _decodeURI(name);
279
+ }
280
+ keyIndex = nextKeyIndex;
281
+ if (name === "") {
282
+ continue;
283
+ }
284
+ let value;
285
+ if (valueIndex === -1) {
286
+ value = "";
287
+ } else {
288
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
289
+ if (encoded) {
290
+ value = _decodeURI(value);
291
+ }
292
+ }
293
+ if (multiple) {
294
+ if (!(results[name] && Array.isArray(results[name]))) {
295
+ results[name] = [];
296
+ }
297
+ results[name].push(value);
298
+ } else {
299
+ results[name] ??= value;
300
+ }
301
+ }
302
+ return key ? results[key] : results;
303
+ };
304
+ var getQueryParam = _getQueryParam;
305
+ var getQueryParams = (url, key) => {
306
+ return _getQueryParam(url, key, true);
307
+ };
308
+ var decodeURIComponent_ = decodeURIComponent;
309
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
310
+ var HonoRequest = class {
311
+ /**
312
+ * `.raw` can get the raw Request object.
313
+ *
314
+ * @see {@link https://hono.dev/docs/api/request#raw}
315
+ *
316
+ * @example
317
+ * ```ts
318
+ * // For Cloudflare Workers
319
+ * app.post('/', async (c) => {
320
+ * const metadata = c.req.raw.cf?.hostMetadata?
321
+ * ...
322
+ * })
323
+ * ```
324
+ */
325
+ raw;
326
+ #validatedData;
327
+ // Short name of validatedData
328
+ #matchResult;
329
+ routeIndex = 0;
330
+ /**
331
+ * `.path` can get the pathname of the request.
332
+ *
333
+ * @see {@link https://hono.dev/docs/api/request#path}
334
+ *
335
+ * @example
336
+ * ```ts
337
+ * app.get('/about/me', (c) => {
338
+ * const pathname = c.req.path // `/about/me`
339
+ * })
340
+ * ```
341
+ */
342
+ path;
343
+ bodyCache = {};
344
+ constructor(request, path = "/", matchResult = [[]]) {
345
+ this.raw = request;
346
+ this.path = path;
347
+ this.#matchResult = matchResult;
348
+ this.#validatedData = {};
349
+ }
350
+ param(key) {
351
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
352
+ }
353
+ #getDecodedParam(key) {
354
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
355
+ const param = this.#getParamValue(paramKey);
356
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
357
+ }
358
+ #getAllDecodedParams() {
359
+ const decoded = {};
360
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
361
+ for (const key of keys) {
362
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
363
+ if (value !== void 0) {
364
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
365
+ }
366
+ }
367
+ return decoded;
368
+ }
369
+ #getParamValue(paramKey) {
370
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
371
+ }
372
+ query(key) {
373
+ return getQueryParam(this.url, key);
374
+ }
375
+ queries(key) {
376
+ return getQueryParams(this.url, key);
377
+ }
378
+ header(name) {
379
+ if (name) {
380
+ return this.raw.headers.get(name) ?? void 0;
381
+ }
382
+ const headerData = {};
383
+ this.raw.headers.forEach((value, key) => {
384
+ headerData[key] = value;
385
+ });
386
+ return headerData;
387
+ }
388
+ async parseBody(options) {
389
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
390
+ }
391
+ #cachedBody = (key) => {
392
+ const { bodyCache, raw } = this;
393
+ const cachedBody = bodyCache[key];
394
+ if (cachedBody) {
395
+ return cachedBody;
396
+ }
397
+ const anyCachedKey = Object.keys(bodyCache)[0];
398
+ if (anyCachedKey) {
399
+ return bodyCache[anyCachedKey].then((body) => {
400
+ if (anyCachedKey === "json") {
401
+ body = JSON.stringify(body);
402
+ }
403
+ return new Response(body)[key]();
404
+ });
405
+ }
406
+ return bodyCache[key] = raw[key]();
407
+ };
408
+ /**
409
+ * `.json()` can parse Request body of type `application/json`
410
+ *
411
+ * @see {@link https://hono.dev/docs/api/request#json}
412
+ *
413
+ * @example
414
+ * ```ts
415
+ * app.post('/entry', async (c) => {
416
+ * const body = await c.req.json()
417
+ * })
418
+ * ```
419
+ */
420
+ json() {
421
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
422
+ }
423
+ /**
424
+ * `.text()` can parse Request body of type `text/plain`
425
+ *
426
+ * @see {@link https://hono.dev/docs/api/request#text}
427
+ *
428
+ * @example
429
+ * ```ts
430
+ * app.post('/entry', async (c) => {
431
+ * const body = await c.req.text()
432
+ * })
433
+ * ```
434
+ */
435
+ text() {
436
+ return this.#cachedBody("text");
437
+ }
438
+ /**
439
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
440
+ *
441
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * app.post('/entry', async (c) => {
446
+ * const body = await c.req.arrayBuffer()
447
+ * })
448
+ * ```
449
+ */
450
+ arrayBuffer() {
451
+ return this.#cachedBody("arrayBuffer");
452
+ }
453
+ /**
454
+ * Parses the request body as a `Blob`.
455
+ * @example
456
+ * ```ts
457
+ * app.post('/entry', async (c) => {
458
+ * const body = await c.req.blob();
459
+ * });
460
+ * ```
461
+ * @see https://hono.dev/docs/api/request#blob
462
+ */
463
+ blob() {
464
+ return this.#cachedBody("blob");
465
+ }
466
+ /**
467
+ * Parses the request body as `FormData`.
468
+ * @example
469
+ * ```ts
470
+ * app.post('/entry', async (c) => {
471
+ * const body = await c.req.formData();
472
+ * });
473
+ * ```
474
+ * @see https://hono.dev/docs/api/request#formdata
475
+ */
476
+ formData() {
477
+ return this.#cachedBody("formData");
478
+ }
479
+ /**
480
+ * Adds validated data to the request.
481
+ *
482
+ * @param target - The target of the validation.
483
+ * @param data - The validated data to add.
484
+ */
485
+ addValidatedData(target, data) {
486
+ this.#validatedData[target] = data;
487
+ }
488
+ valid(target) {
489
+ return this.#validatedData[target];
490
+ }
491
+ /**
492
+ * `.url()` can get the request url strings.
493
+ *
494
+ * @see {@link https://hono.dev/docs/api/request#url}
495
+ *
496
+ * @example
497
+ * ```ts
498
+ * app.get('/about/me', (c) => {
499
+ * const url = c.req.url // `http://localhost:8787/about/me`
500
+ * ...
501
+ * })
502
+ * ```
503
+ */
504
+ get url() {
505
+ return this.raw.url;
506
+ }
507
+ /**
508
+ * `.method()` can get the method name of the request.
509
+ *
510
+ * @see {@link https://hono.dev/docs/api/request#method}
511
+ *
512
+ * @example
513
+ * ```ts
514
+ * app.get('/about/me', (c) => {
515
+ * const method = c.req.method // `GET`
516
+ * })
517
+ * ```
518
+ */
519
+ get method() {
520
+ return this.raw.method;
521
+ }
522
+ get [GET_MATCH_RESULT]() {
523
+ return this.#matchResult;
524
+ }
525
+ /**
526
+ * `.matchedRoutes()` can return a matched route in the handler
527
+ *
528
+ * @deprecated
529
+ *
530
+ * Use matchedRoutes helper defined in "hono/route" instead.
531
+ *
532
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
533
+ *
534
+ * @example
535
+ * ```ts
536
+ * app.use('*', async function logger(c, next) {
537
+ * await next()
538
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
539
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
540
+ * console.log(
541
+ * method,
542
+ * ' ',
543
+ * path,
544
+ * ' '.repeat(Math.max(10 - path.length, 0)),
545
+ * name,
546
+ * i === c.req.routeIndex ? '<- respond from here' : ''
547
+ * )
548
+ * })
549
+ * })
550
+ * ```
551
+ */
552
+ get matchedRoutes() {
553
+ return this.#matchResult[0].map(([[, route]]) => route);
554
+ }
555
+ /**
556
+ * `routePath()` can retrieve the path registered within the handler
557
+ *
558
+ * @deprecated
559
+ *
560
+ * Use routePath helper defined in "hono/route" instead.
561
+ *
562
+ * @see {@link https://hono.dev/docs/api/request#routepath}
563
+ *
564
+ * @example
565
+ * ```ts
566
+ * app.get('/posts/:id', (c) => {
567
+ * return c.json({ path: c.req.routePath })
568
+ * })
569
+ * ```
570
+ */
571
+ get routePath() {
572
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
573
+ }
574
+ };
575
+ var HtmlEscapedCallbackPhase = {
576
+ Stringify: 1
577
+ };
578
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
579
+ if (typeof str === "object" && !(str instanceof String)) {
580
+ if (!(str instanceof Promise)) {
581
+ str = str.toString();
582
+ }
583
+ if (str instanceof Promise) {
584
+ str = await str;
585
+ }
586
+ }
587
+ const callbacks = str.callbacks;
588
+ if (!callbacks?.length) {
589
+ return Promise.resolve(str);
590
+ }
591
+ if (buffer) {
592
+ buffer[0] += str;
593
+ } else {
594
+ buffer = [str];
595
+ }
596
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
597
+ (res) => Promise.all(
598
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
599
+ ).then(() => buffer[0])
600
+ );
601
+ {
602
+ return resStr;
603
+ }
604
+ };
605
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
606
+ var setDefaultContentType = (contentType, headers) => {
607
+ return {
608
+ "Content-Type": contentType,
609
+ ...headers
610
+ };
611
+ };
612
+ var Context = class {
613
+ #rawRequest;
614
+ #req;
615
+ /**
616
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
617
+ *
618
+ * @see {@link https://hono.dev/docs/api/context#env}
619
+ *
620
+ * @example
621
+ * ```ts
622
+ * // Environment object for Cloudflare Workers
623
+ * app.get('*', async c => {
624
+ * const counter = c.env.COUNTER
625
+ * })
626
+ * ```
627
+ */
628
+ env = {};
629
+ #var;
630
+ finalized = false;
631
+ /**
632
+ * `.error` can get the error object from the middleware if the Handler throws an error.
633
+ *
634
+ * @see {@link https://hono.dev/docs/api/context#error}
635
+ *
636
+ * @example
637
+ * ```ts
638
+ * app.use('*', async (c, next) => {
639
+ * await next()
640
+ * if (c.error) {
641
+ * // do something...
642
+ * }
643
+ * })
644
+ * ```
645
+ */
646
+ error;
647
+ #status;
648
+ #executionCtx;
649
+ #res;
650
+ #layout;
651
+ #renderer;
652
+ #notFoundHandler;
653
+ #preparedHeaders;
654
+ #matchResult;
655
+ #path;
656
+ /**
657
+ * Creates an instance of the Context class.
658
+ *
659
+ * @param req - The Request object.
660
+ * @param options - Optional configuration options for the context.
661
+ */
662
+ constructor(req, options) {
663
+ this.#rawRequest = req;
664
+ if (options) {
665
+ this.#executionCtx = options.executionCtx;
666
+ this.env = options.env;
667
+ this.#notFoundHandler = options.notFoundHandler;
668
+ this.#path = options.path;
669
+ this.#matchResult = options.matchResult;
670
+ }
671
+ }
672
+ /**
673
+ * `.req` is the instance of {@link HonoRequest}.
674
+ */
675
+ get req() {
676
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
677
+ return this.#req;
678
+ }
679
+ /**
680
+ * @see {@link https://hono.dev/docs/api/context#event}
681
+ * The FetchEvent associated with the current request.
682
+ *
683
+ * @throws Will throw an error if the context does not have a FetchEvent.
684
+ */
685
+ get event() {
686
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
687
+ return this.#executionCtx;
688
+ } else {
689
+ throw Error("This context has no FetchEvent");
690
+ }
691
+ }
692
+ /**
693
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
694
+ * The ExecutionContext associated with the current request.
695
+ *
696
+ * @throws Will throw an error if the context does not have an ExecutionContext.
697
+ */
698
+ get executionCtx() {
699
+ if (this.#executionCtx) {
700
+ return this.#executionCtx;
701
+ } else {
702
+ throw Error("This context has no ExecutionContext");
703
+ }
704
+ }
705
+ /**
706
+ * @see {@link https://hono.dev/docs/api/context#res}
707
+ * The Response object for the current request.
708
+ */
709
+ get res() {
710
+ return this.#res ||= new Response(null, {
711
+ headers: this.#preparedHeaders ??= new Headers()
712
+ });
713
+ }
714
+ /**
715
+ * Sets the Response object for the current request.
716
+ *
717
+ * @param _res - The Response object to set.
718
+ */
719
+ set res(_res) {
720
+ if (this.#res && _res) {
721
+ _res = new Response(_res.body, _res);
722
+ for (const [k, v] of this.#res.headers.entries()) {
723
+ if (k === "content-type") {
724
+ continue;
725
+ }
726
+ if (k === "set-cookie") {
727
+ const cookies = this.#res.headers.getSetCookie();
728
+ _res.headers.delete("set-cookie");
729
+ for (const cookie of cookies) {
730
+ _res.headers.append("set-cookie", cookie);
731
+ }
732
+ } else {
733
+ _res.headers.set(k, v);
734
+ }
735
+ }
736
+ }
737
+ this.#res = _res;
738
+ this.finalized = true;
739
+ }
740
+ /**
741
+ * `.render()` can create a response within a layout.
742
+ *
743
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
744
+ *
745
+ * @example
746
+ * ```ts
747
+ * app.get('/', (c) => {
748
+ * return c.render('Hello!')
749
+ * })
750
+ * ```
751
+ */
752
+ render = (...args) => {
753
+ this.#renderer ??= (content) => this.html(content);
754
+ return this.#renderer(...args);
755
+ };
756
+ /**
757
+ * Sets the layout for the response.
758
+ *
759
+ * @param layout - The layout to set.
760
+ * @returns The layout function.
761
+ */
762
+ setLayout = (layout) => this.#layout = layout;
763
+ /**
764
+ * Gets the current layout for the response.
765
+ *
766
+ * @returns The current layout function.
767
+ */
768
+ getLayout = () => this.#layout;
769
+ /**
770
+ * `.setRenderer()` can set the layout in the custom middleware.
771
+ *
772
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
773
+ *
774
+ * @example
775
+ * ```tsx
776
+ * app.use('*', async (c, next) => {
777
+ * c.setRenderer((content) => {
778
+ * return c.html(
779
+ * <html>
780
+ * <body>
781
+ * <p>{content}</p>
782
+ * </body>
783
+ * </html>
784
+ * )
785
+ * })
786
+ * await next()
787
+ * })
788
+ * ```
789
+ */
790
+ setRenderer = (renderer) => {
791
+ this.#renderer = renderer;
792
+ };
793
+ /**
794
+ * `.header()` can set headers.
795
+ *
796
+ * @see {@link https://hono.dev/docs/api/context#header}
797
+ *
798
+ * @example
799
+ * ```ts
800
+ * app.get('/welcome', (c) => {
801
+ * // Set headers
802
+ * c.header('X-Message', 'Hello!')
803
+ * c.header('Content-Type', 'text/plain')
804
+ *
805
+ * return c.body('Thank you for coming')
806
+ * })
807
+ * ```
808
+ */
809
+ header = (name, value, options) => {
810
+ if (this.finalized) {
811
+ this.#res = new Response(this.#res.body, this.#res);
812
+ }
813
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
814
+ if (value === void 0) {
815
+ headers.delete(name);
816
+ } else if (options?.append) {
817
+ headers.append(name, value);
818
+ } else {
819
+ headers.set(name, value);
820
+ }
821
+ };
822
+ status = (status) => {
823
+ this.#status = status;
824
+ };
825
+ /**
826
+ * `.set()` can set the value specified by the key.
827
+ *
828
+ * @see {@link https://hono.dev/docs/api/context#set-get}
829
+ *
830
+ * @example
831
+ * ```ts
832
+ * app.use('*', async (c, next) => {
833
+ * c.set('message', 'Hono is hot!!')
834
+ * await next()
835
+ * })
836
+ * ```
837
+ */
838
+ set = (key, value) => {
839
+ this.#var ??= /* @__PURE__ */ new Map();
840
+ this.#var.set(key, value);
841
+ };
842
+ /**
843
+ * `.get()` can use the value specified by the key.
844
+ *
845
+ * @see {@link https://hono.dev/docs/api/context#set-get}
846
+ *
847
+ * @example
848
+ * ```ts
849
+ * app.get('/', (c) => {
850
+ * const message = c.get('message')
851
+ * return c.text(`The message is "${message}"`)
852
+ * })
853
+ * ```
854
+ */
855
+ get = (key) => {
856
+ return this.#var ? this.#var.get(key) : void 0;
857
+ };
858
+ /**
859
+ * `.var` can access the value of a variable.
860
+ *
861
+ * @see {@link https://hono.dev/docs/api/context#var}
862
+ *
863
+ * @example
864
+ * ```ts
865
+ * const result = c.var.client.oneMethod()
866
+ * ```
867
+ */
868
+ // c.var.propName is a read-only
869
+ get var() {
870
+ if (!this.#var) {
871
+ return {};
872
+ }
873
+ return Object.fromEntries(this.#var);
874
+ }
875
+ #newResponse(data, arg, headers) {
876
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
877
+ if (typeof arg === "object" && "headers" in arg) {
878
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
879
+ for (const [key, value] of argHeaders) {
880
+ if (key.toLowerCase() === "set-cookie") {
881
+ responseHeaders.append(key, value);
882
+ } else {
883
+ responseHeaders.set(key, value);
884
+ }
885
+ }
886
+ }
887
+ if (headers) {
888
+ for (const [k, v] of Object.entries(headers)) {
889
+ if (typeof v === "string") {
890
+ responseHeaders.set(k, v);
891
+ } else {
892
+ responseHeaders.delete(k);
893
+ for (const v2 of v) {
894
+ responseHeaders.append(k, v2);
895
+ }
896
+ }
897
+ }
898
+ }
899
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
900
+ return new Response(data, { status, headers: responseHeaders });
901
+ }
902
+ newResponse = (...args) => this.#newResponse(...args);
903
+ /**
904
+ * `.body()` can return the HTTP response.
905
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
906
+ * This can also be set in `.text()`, `.json()` and so on.
907
+ *
908
+ * @see {@link https://hono.dev/docs/api/context#body}
909
+ *
910
+ * @example
911
+ * ```ts
912
+ * app.get('/welcome', (c) => {
913
+ * // Set headers
914
+ * c.header('X-Message', 'Hello!')
915
+ * c.header('Content-Type', 'text/plain')
916
+ * // Set HTTP status code
917
+ * c.status(201)
918
+ *
919
+ * // Return the response body
920
+ * return c.body('Thank you for coming')
921
+ * })
922
+ * ```
923
+ */
924
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
925
+ /**
926
+ * `.text()` can render text as `Content-Type:text/plain`.
927
+ *
928
+ * @see {@link https://hono.dev/docs/api/context#text}
929
+ *
930
+ * @example
931
+ * ```ts
932
+ * app.get('/say', (c) => {
933
+ * return c.text('Hello!')
934
+ * })
935
+ * ```
936
+ */
937
+ text = (text, arg, headers) => {
938
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
939
+ text,
940
+ arg,
941
+ setDefaultContentType(TEXT_PLAIN, headers)
942
+ );
943
+ };
944
+ /**
945
+ * `.json()` can render JSON as `Content-Type:application/json`.
946
+ *
947
+ * @see {@link https://hono.dev/docs/api/context#json}
948
+ *
949
+ * @example
950
+ * ```ts
951
+ * app.get('/api', (c) => {
952
+ * return c.json({ message: 'Hello!' })
953
+ * })
954
+ * ```
955
+ */
956
+ json = (object, arg, headers) => {
957
+ return this.#newResponse(
958
+ JSON.stringify(object),
959
+ arg,
960
+ setDefaultContentType("application/json", headers)
961
+ );
962
+ };
963
+ html = (html, arg, headers) => {
964
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
965
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
966
+ };
967
+ /**
968
+ * `.redirect()` can Redirect, default status code is 302.
969
+ *
970
+ * @see {@link https://hono.dev/docs/api/context#redirect}
971
+ *
972
+ * @example
973
+ * ```ts
974
+ * app.get('/redirect', (c) => {
975
+ * return c.redirect('/')
976
+ * })
977
+ * app.get('/redirect-permanently', (c) => {
978
+ * return c.redirect('/', 301)
979
+ * })
980
+ * ```
981
+ */
982
+ redirect = (location, status) => {
983
+ const locationString = String(location);
984
+ this.header(
985
+ "Location",
986
+ // Multibyes should be encoded
987
+ // eslint-disable-next-line no-control-regex
988
+ !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
989
+ );
990
+ return this.newResponse(null, status ?? 302);
991
+ };
992
+ /**
993
+ * `.notFound()` can return the Not Found Response.
994
+ *
995
+ * @see {@link https://hono.dev/docs/api/context#notfound}
996
+ *
997
+ * @example
998
+ * ```ts
999
+ * app.get('/notfound', (c) => {
1000
+ * return c.notFound()
1001
+ * })
1002
+ * ```
1003
+ */
1004
+ notFound = () => {
1005
+ this.#notFoundHandler ??= () => new Response();
1006
+ return this.#notFoundHandler(this);
1007
+ };
1008
+ };
1009
+ var METHOD_NAME_ALL = "ALL";
1010
+ var METHOD_NAME_ALL_LOWERCASE = "all";
1011
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1012
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1013
+ var UnsupportedPathError = class extends Error {
1014
+ };
1015
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1016
+ var notFoundHandler = (c) => {
1017
+ return c.text("404 Not Found", 404);
1018
+ };
1019
+ var errorHandler = (err, c) => {
1020
+ if ("getResponse" in err) {
1021
+ const res = err.getResponse();
1022
+ return c.newResponse(res.body, res);
1023
+ }
1024
+ console.error(err);
1025
+ return c.text("Internal Server Error", 500);
1026
+ };
1027
+ var Hono$1 = class _Hono {
1028
+ get;
1029
+ post;
1030
+ put;
1031
+ delete;
1032
+ options;
1033
+ patch;
1034
+ all;
1035
+ on;
1036
+ use;
1037
+ /*
1038
+ This class is like an abstract class and does not have a router.
1039
+ To use it, inherit the class and implement router in the constructor.
1040
+ */
1041
+ router;
1042
+ getPath;
1043
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1044
+ _basePath = "/";
1045
+ #path = "/";
1046
+ routes = [];
1047
+ constructor(options = {}) {
1048
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1049
+ allMethods.forEach((method) => {
1050
+ this[method] = (args1, ...args) => {
1051
+ if (typeof args1 === "string") {
1052
+ this.#path = args1;
1053
+ } else {
1054
+ this.#addRoute(method, this.#path, args1);
1055
+ }
1056
+ args.forEach((handler) => {
1057
+ this.#addRoute(method, this.#path, handler);
1058
+ });
1059
+ return this;
1060
+ };
1061
+ });
1062
+ this.on = (method, path, ...handlers) => {
1063
+ for (const p of [path].flat()) {
1064
+ this.#path = p;
1065
+ for (const m of [method].flat()) {
1066
+ handlers.map((handler) => {
1067
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1068
+ });
1069
+ }
1070
+ }
1071
+ return this;
1072
+ };
1073
+ this.use = (arg1, ...handlers) => {
1074
+ if (typeof arg1 === "string") {
1075
+ this.#path = arg1;
1076
+ } else {
1077
+ this.#path = "*";
1078
+ handlers.unshift(arg1);
1079
+ }
1080
+ handlers.forEach((handler) => {
1081
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1082
+ });
1083
+ return this;
1084
+ };
1085
+ const { strict, ...optionsWithoutStrict } = options;
1086
+ Object.assign(this, optionsWithoutStrict);
1087
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1088
+ }
1089
+ #clone() {
1090
+ const clone = new _Hono({
1091
+ router: this.router,
1092
+ getPath: this.getPath
1093
+ });
1094
+ clone.errorHandler = this.errorHandler;
1095
+ clone.#notFoundHandler = this.#notFoundHandler;
1096
+ clone.routes = this.routes;
1097
+ return clone;
1098
+ }
1099
+ #notFoundHandler = notFoundHandler;
1100
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1101
+ errorHandler = errorHandler;
1102
+ /**
1103
+ * `.route()` allows grouping other Hono instance in routes.
1104
+ *
1105
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
1106
+ *
1107
+ * @param {string} path - base Path
1108
+ * @param {Hono} app - other Hono instance
1109
+ * @returns {Hono} routed Hono instance
1110
+ *
1111
+ * @example
1112
+ * ```ts
1113
+ * const app = new Hono()
1114
+ * const app2 = new Hono()
1115
+ *
1116
+ * app2.get("/user", (c) => c.text("user"))
1117
+ * app.route("/api", app2) // GET /api/user
1118
+ * ```
1119
+ */
1120
+ route(path, app) {
1121
+ const subApp = this.basePath(path);
1122
+ app.routes.map((r) => {
1123
+ let handler;
1124
+ if (app.errorHandler === errorHandler) {
1125
+ handler = r.handler;
1126
+ } else {
1127
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
1128
+ handler[COMPOSED_HANDLER] = r.handler;
1129
+ }
1130
+ subApp.#addRoute(r.method, r.path, handler);
1131
+ });
1132
+ return this;
1133
+ }
1134
+ /**
1135
+ * `.basePath()` allows base paths to be specified.
1136
+ *
1137
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
1138
+ *
1139
+ * @param {string} path - base Path
1140
+ * @returns {Hono} changed Hono instance
1141
+ *
1142
+ * @example
1143
+ * ```ts
1144
+ * const api = new Hono().basePath('/api')
1145
+ * ```
1146
+ */
1147
+ basePath(path) {
1148
+ const subApp = this.#clone();
1149
+ subApp._basePath = mergePath(this._basePath, path);
1150
+ return subApp;
1151
+ }
1152
+ /**
1153
+ * `.onError()` handles an error and returns a customized Response.
1154
+ *
1155
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
1156
+ *
1157
+ * @param {ErrorHandler} handler - request Handler for error
1158
+ * @returns {Hono} changed Hono instance
1159
+ *
1160
+ * @example
1161
+ * ```ts
1162
+ * app.onError((err, c) => {
1163
+ * console.error(`${err}`)
1164
+ * return c.text('Custom Error Message', 500)
1165
+ * })
1166
+ * ```
1167
+ */
1168
+ onError = (handler) => {
1169
+ this.errorHandler = handler;
1170
+ return this;
1171
+ };
1172
+ /**
1173
+ * `.notFound()` allows you to customize a Not Found Response.
1174
+ *
1175
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
1176
+ *
1177
+ * @param {NotFoundHandler} handler - request handler for not-found
1178
+ * @returns {Hono} changed Hono instance
1179
+ *
1180
+ * @example
1181
+ * ```ts
1182
+ * app.notFound((c) => {
1183
+ * return c.text('Custom 404 Message', 404)
1184
+ * })
1185
+ * ```
1186
+ */
1187
+ notFound = (handler) => {
1188
+ this.#notFoundHandler = handler;
1189
+ return this;
1190
+ };
1191
+ /**
1192
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
1193
+ *
1194
+ * @see {@link https://hono.dev/docs/api/hono#mount}
1195
+ *
1196
+ * @param {string} path - base Path
1197
+ * @param {Function} applicationHandler - other Request Handler
1198
+ * @param {MountOptions} [options] - options of `.mount()`
1199
+ * @returns {Hono} mounted Hono instance
1200
+ *
1201
+ * @example
1202
+ * ```ts
1203
+ * import { Router as IttyRouter } from 'itty-router'
1204
+ * import { Hono } from 'hono'
1205
+ * // Create itty-router application
1206
+ * const ittyRouter = IttyRouter()
1207
+ * // GET /itty-router/hello
1208
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
1209
+ *
1210
+ * const app = new Hono()
1211
+ * app.mount('/itty-router', ittyRouter.handle)
1212
+ * ```
1213
+ *
1214
+ * @example
1215
+ * ```ts
1216
+ * const app = new Hono()
1217
+ * // Send the request to another application without modification.
1218
+ * app.mount('/app', anotherApp, {
1219
+ * replaceRequest: (req) => req,
1220
+ * })
1221
+ * ```
1222
+ */
1223
+ mount(path, applicationHandler, options) {
1224
+ let replaceRequest;
1225
+ let optionHandler;
1226
+ if (options) {
1227
+ if (typeof options === "function") {
1228
+ optionHandler = options;
1229
+ } else {
1230
+ optionHandler = options.optionHandler;
1231
+ if (options.replaceRequest === false) {
1232
+ replaceRequest = (request) => request;
1233
+ } else {
1234
+ replaceRequest = options.replaceRequest;
1235
+ }
1236
+ }
1237
+ }
1238
+ const getOptions = optionHandler ? (c) => {
1239
+ const options2 = optionHandler(c);
1240
+ return Array.isArray(options2) ? options2 : [options2];
1241
+ } : (c) => {
1242
+ let executionContext = void 0;
1243
+ try {
1244
+ executionContext = c.executionCtx;
1245
+ } catch {
1246
+ }
1247
+ return [c.env, executionContext];
1248
+ };
1249
+ replaceRequest ||= (() => {
1250
+ const mergedPath = mergePath(this._basePath, path);
1251
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1252
+ return (request) => {
1253
+ const url = new URL(request.url);
1254
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
1255
+ return new Request(url, request);
1256
+ };
1257
+ })();
1258
+ const handler = async (c, next) => {
1259
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1260
+ if (res) {
1261
+ return res;
1262
+ }
1263
+ await next();
1264
+ };
1265
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
1266
+ return this;
1267
+ }
1268
+ #addRoute(method, path, handler) {
1269
+ method = method.toUpperCase();
1270
+ path = mergePath(this._basePath, path);
1271
+ const r = { basePath: this._basePath, path, method, handler };
1272
+ this.router.add(method, path, [handler, r]);
1273
+ this.routes.push(r);
1274
+ }
1275
+ #handleError(err, c) {
1276
+ if (err instanceof Error) {
1277
+ return this.errorHandler(err, c);
1278
+ }
1279
+ throw err;
1280
+ }
1281
+ #dispatch(request, executionCtx, env, method) {
1282
+ if (method === "HEAD") {
1283
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1284
+ }
1285
+ const path = this.getPath(request, { env });
1286
+ const matchResult = this.router.match(method, path);
1287
+ const c = new Context(request, {
1288
+ path,
1289
+ matchResult,
1290
+ env,
1291
+ executionCtx,
1292
+ notFoundHandler: this.#notFoundHandler
1293
+ });
1294
+ if (matchResult[0].length === 1) {
1295
+ let res;
1296
+ try {
1297
+ res = matchResult[0][0][0][0](c, async () => {
1298
+ c.res = await this.#notFoundHandler(c);
1299
+ });
1300
+ } catch (err) {
1301
+ return this.#handleError(err, c);
1302
+ }
1303
+ return res instanceof Promise ? res.then(
1304
+ (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
1305
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
1306
+ }
1307
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1308
+ return (async () => {
1309
+ try {
1310
+ const context = await composed(c);
1311
+ if (!context.finalized) {
1312
+ throw new Error(
1313
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
1314
+ );
1315
+ }
1316
+ return context.res;
1317
+ } catch (err) {
1318
+ return this.#handleError(err, c);
1319
+ }
1320
+ })();
1321
+ }
1322
+ /**
1323
+ * `.fetch()` will be entry point of your app.
1324
+ *
1325
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
1326
+ *
1327
+ * @param {Request} request - request Object of request
1328
+ * @param {Env} Env - env Object
1329
+ * @param {ExecutionContext} - context of execution
1330
+ * @returns {Response | Promise<Response>} response of request
1331
+ *
1332
+ */
1333
+ fetch = (request, ...rest) => {
1334
+ return this.#dispatch(request, rest[1], rest[0], request.method);
1335
+ };
1336
+ /**
1337
+ * `.request()` is a useful method for testing.
1338
+ * You can pass a URL or pathname to send a GET request.
1339
+ * app will return a Response object.
1340
+ * ```ts
1341
+ * test('GET /hello is ok', async () => {
1342
+ * const res = await app.request('/hello')
1343
+ * expect(res.status).toBe(200)
1344
+ * })
1345
+ * ```
1346
+ * @see https://hono.dev/docs/api/hono#request
1347
+ */
1348
+ request = (input, requestInit, Env, executionCtx) => {
1349
+ if (input instanceof Request) {
1350
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
1351
+ }
1352
+ input = input.toString();
1353
+ return this.fetch(
1354
+ new Request(
1355
+ /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
1356
+ requestInit
1357
+ ),
1358
+ Env,
1359
+ executionCtx
1360
+ );
1361
+ };
1362
+ /**
1363
+ * `.fire()` automatically adds a global fetch event listener.
1364
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
1365
+ * @deprecated
1366
+ * Use `fire` from `hono/service-worker` instead.
1367
+ * ```ts
1368
+ * import { Hono } from 'hono'
1369
+ * import { fire } from 'hono/service-worker'
1370
+ *
1371
+ * const app = new Hono()
1372
+ * // ...
1373
+ * fire(app)
1374
+ * ```
1375
+ * @see https://hono.dev/docs/api/hono#fire
1376
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
1377
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
1378
+ */
1379
+ fire = () => {
1380
+ addEventListener("fetch", (event) => {
1381
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
1382
+ });
1383
+ };
1384
+ };
1385
+ var emptyParam = [];
1386
+ function match(method, path) {
1387
+ const matchers = this.buildAllMatchers();
1388
+ const match2 = ((method2, path2) => {
1389
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
1390
+ const staticMatch = matcher[2][path2];
1391
+ if (staticMatch) {
1392
+ return staticMatch;
1393
+ }
1394
+ const match3 = path2.match(matcher[0]);
1395
+ if (!match3) {
1396
+ return [[], emptyParam];
1397
+ }
1398
+ const index2 = match3.indexOf("", 1);
1399
+ return [matcher[1][index2], match3];
1400
+ });
1401
+ this.match = match2;
1402
+ return match2(method, path);
1403
+ }
1404
+ var LABEL_REG_EXP_STR = "[^/]+";
1405
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
1406
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1407
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
1408
+ var regExpMetaChars = new Set(".\\+*[^]$()");
1409
+ function compareKey(a, b) {
1410
+ if (a.length === 1) {
1411
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
1412
+ }
1413
+ if (b.length === 1) {
1414
+ return 1;
1415
+ }
1416
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
1417
+ return 1;
1418
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
1419
+ return -1;
1420
+ }
1421
+ if (a === LABEL_REG_EXP_STR) {
1422
+ return 1;
1423
+ } else if (b === LABEL_REG_EXP_STR) {
1424
+ return -1;
1425
+ }
1426
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
1427
+ }
1428
+ var Node$1 = class _Node {
1429
+ #index;
1430
+ #varIndex;
1431
+ #children = /* @__PURE__ */ Object.create(null);
1432
+ insert(tokens, index2, paramMap, context, pathErrorCheckOnly) {
1433
+ if (tokens.length === 0) {
1434
+ if (this.#index !== void 0) {
1435
+ throw PATH_ERROR;
1436
+ }
1437
+ if (pathErrorCheckOnly) {
1438
+ return;
1439
+ }
1440
+ this.#index = index2;
1441
+ return;
1442
+ }
1443
+ const [token, ...restTokens] = tokens;
1444
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1445
+ let node;
1446
+ if (pattern) {
1447
+ const name = pattern[1];
1448
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
1449
+ if (name && pattern[2]) {
1450
+ if (regexpStr === ".*") {
1451
+ throw PATH_ERROR;
1452
+ }
1453
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
1454
+ if (/\((?!\?:)/.test(regexpStr)) {
1455
+ throw PATH_ERROR;
1456
+ }
1457
+ }
1458
+ node = this.#children[regexpStr];
1459
+ if (!node) {
1460
+ if (Object.keys(this.#children).some(
1461
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
1462
+ )) {
1463
+ throw PATH_ERROR;
1464
+ }
1465
+ if (pathErrorCheckOnly) {
1466
+ return;
1467
+ }
1468
+ node = this.#children[regexpStr] = new _Node();
1469
+ if (name !== "") {
1470
+ node.#varIndex = context.varIndex++;
1471
+ }
1472
+ }
1473
+ if (!pathErrorCheckOnly && name !== "") {
1474
+ paramMap.push([name, node.#varIndex]);
1475
+ }
1476
+ } else {
1477
+ node = this.#children[token];
1478
+ if (!node) {
1479
+ if (Object.keys(this.#children).some(
1480
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
1481
+ )) {
1482
+ throw PATH_ERROR;
1483
+ }
1484
+ if (pathErrorCheckOnly) {
1485
+ return;
1486
+ }
1487
+ node = this.#children[token] = new _Node();
1488
+ }
1489
+ }
1490
+ node.insert(restTokens, index2, paramMap, context, pathErrorCheckOnly);
1491
+ }
1492
+ buildRegExpStr() {
1493
+ const childKeys = Object.keys(this.#children).sort(compareKey);
1494
+ const strList = childKeys.map((k) => {
1495
+ const c = this.#children[k];
1496
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
1497
+ });
1498
+ if (typeof this.#index === "number") {
1499
+ strList.unshift(`#${this.#index}`);
1500
+ }
1501
+ if (strList.length === 0) {
1502
+ return "";
1503
+ }
1504
+ if (strList.length === 1) {
1505
+ return strList[0];
1506
+ }
1507
+ return "(?:" + strList.join("|") + ")";
1508
+ }
1509
+ };
1510
+ var Trie = class {
1511
+ #context = { varIndex: 0 };
1512
+ #root = new Node$1();
1513
+ insert(path, index2, pathErrorCheckOnly) {
1514
+ const paramAssoc = [];
1515
+ const groups = [];
1516
+ for (let i = 0; ; ) {
1517
+ let replaced = false;
1518
+ path = path.replace(/\{[^}]+\}/g, (m) => {
1519
+ const mark = `@\\${i}`;
1520
+ groups[i] = [mark, m];
1521
+ i++;
1522
+ replaced = true;
1523
+ return mark;
1524
+ });
1525
+ if (!replaced) {
1526
+ break;
1527
+ }
1528
+ }
1529
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1530
+ for (let i = groups.length - 1; i >= 0; i--) {
1531
+ const [mark] = groups[i];
1532
+ for (let j = tokens.length - 1; j >= 0; j--) {
1533
+ if (tokens[j].indexOf(mark) !== -1) {
1534
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1535
+ break;
1536
+ }
1537
+ }
1538
+ }
1539
+ this.#root.insert(tokens, index2, paramAssoc, this.#context, pathErrorCheckOnly);
1540
+ return paramAssoc;
1541
+ }
1542
+ buildRegExp() {
1543
+ let regexp = this.#root.buildRegExpStr();
1544
+ if (regexp === "") {
1545
+ return [/^$/, [], []];
1546
+ }
1547
+ let captureIndex = 0;
1548
+ const indexReplacementMap = [];
1549
+ const paramReplacementMap = [];
1550
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1551
+ if (handlerIndex !== void 0) {
1552
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1553
+ return "$()";
1554
+ }
1555
+ if (paramIndex !== void 0) {
1556
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1557
+ return "";
1558
+ }
1559
+ return "";
1560
+ });
1561
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1562
+ }
1563
+ };
1564
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1565
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1566
+ function buildWildcardRegExp(path) {
1567
+ return wildcardRegExpCache[path] ??= new RegExp(
1568
+ path === "*" ? "" : `^${path.replace(
1569
+ /\/\*$|([.\\+*[^\]$()])/g,
1570
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
1571
+ )}$`
1572
+ );
1573
+ }
1574
+ function clearWildcardRegExpCache() {
1575
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1576
+ }
1577
+ function buildMatcherFromPreprocessedRoutes(routes) {
1578
+ const trie = new Trie();
1579
+ const handlerData = [];
1580
+ if (routes.length === 0) {
1581
+ return nullMatcher;
1582
+ }
1583
+ const routesWithStaticPathFlag = routes.map(
1584
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
1585
+ ).sort(
1586
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
1587
+ );
1588
+ const staticMap = /* @__PURE__ */ Object.create(null);
1589
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
1590
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
1591
+ if (pathErrorCheckOnly) {
1592
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1593
+ } else {
1594
+ j++;
1595
+ }
1596
+ let paramAssoc;
1597
+ try {
1598
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
1599
+ } catch (e) {
1600
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
1601
+ }
1602
+ if (pathErrorCheckOnly) {
1603
+ continue;
1604
+ }
1605
+ handlerData[j] = handlers.map(([h, paramCount]) => {
1606
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
1607
+ paramCount -= 1;
1608
+ for (; paramCount >= 0; paramCount--) {
1609
+ const [key, value] = paramAssoc[paramCount];
1610
+ paramIndexMap[key] = value;
1611
+ }
1612
+ return [h, paramIndexMap];
1613
+ });
1614
+ }
1615
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1616
+ for (let i = 0, len = handlerData.length; i < len; i++) {
1617
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
1618
+ const map = handlerData[i][j]?.[1];
1619
+ if (!map) {
1620
+ continue;
1621
+ }
1622
+ const keys = Object.keys(map);
1623
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
1624
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
1625
+ }
1626
+ }
1627
+ }
1628
+ const handlerMap = [];
1629
+ for (const i in indexReplacementMap) {
1630
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1631
+ }
1632
+ return [regexp, handlerMap, staticMap];
1633
+ }
1634
+ function findMiddleware(middleware, path) {
1635
+ if (!middleware) {
1636
+ return void 0;
1637
+ }
1638
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1639
+ if (buildWildcardRegExp(k).test(path)) {
1640
+ return [...middleware[k]];
1641
+ }
1642
+ }
1643
+ return void 0;
1644
+ }
1645
+ var RegExpRouter = class {
1646
+ name = "RegExpRouter";
1647
+ #middleware;
1648
+ #routes;
1649
+ constructor() {
1650
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1651
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1652
+ }
1653
+ add(method, path, handler) {
1654
+ const middleware = this.#middleware;
1655
+ const routes = this.#routes;
1656
+ if (!middleware || !routes) {
1657
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1658
+ }
1659
+ if (!middleware[method]) {
1660
+ [middleware, routes].forEach((handlerMap) => {
1661
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
1662
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
1663
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
1664
+ });
1665
+ });
1666
+ }
1667
+ if (path === "/*") {
1668
+ path = "*";
1669
+ }
1670
+ const paramCount = (path.match(/\/:/g) || []).length;
1671
+ if (/\*$/.test(path)) {
1672
+ const re = buildWildcardRegExp(path);
1673
+ if (method === METHOD_NAME_ALL) {
1674
+ Object.keys(middleware).forEach((m) => {
1675
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1676
+ });
1677
+ } else {
1678
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1679
+ }
1680
+ Object.keys(middleware).forEach((m) => {
1681
+ if (method === METHOD_NAME_ALL || method === m) {
1682
+ Object.keys(middleware[m]).forEach((p) => {
1683
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
1684
+ });
1685
+ }
1686
+ });
1687
+ Object.keys(routes).forEach((m) => {
1688
+ if (method === METHOD_NAME_ALL || method === m) {
1689
+ Object.keys(routes[m]).forEach(
1690
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
1691
+ );
1692
+ }
1693
+ });
1694
+ return;
1695
+ }
1696
+ const paths = checkOptionalParameter(path) || [path];
1697
+ for (let i = 0, len = paths.length; i < len; i++) {
1698
+ const path2 = paths[i];
1699
+ Object.keys(routes).forEach((m) => {
1700
+ if (method === METHOD_NAME_ALL || method === m) {
1701
+ routes[m][path2] ||= [
1702
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
1703
+ ];
1704
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
1705
+ }
1706
+ });
1707
+ }
1708
+ }
1709
+ match = match;
1710
+ buildAllMatchers() {
1711
+ const matchers = /* @__PURE__ */ Object.create(null);
1712
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1713
+ matchers[method] ||= this.#buildMatcher(method);
1714
+ });
1715
+ this.#middleware = this.#routes = void 0;
1716
+ clearWildcardRegExpCache();
1717
+ return matchers;
1718
+ }
1719
+ #buildMatcher(method) {
1720
+ const routes = [];
1721
+ let hasOwnRoute = method === METHOD_NAME_ALL;
1722
+ [this.#middleware, this.#routes].forEach((r) => {
1723
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
1724
+ if (ownRoute.length !== 0) {
1725
+ hasOwnRoute ||= true;
1726
+ routes.push(...ownRoute);
1727
+ } else if (method !== METHOD_NAME_ALL) {
1728
+ routes.push(
1729
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
1730
+ );
1731
+ }
1732
+ });
1733
+ if (!hasOwnRoute) {
1734
+ return null;
1735
+ } else {
1736
+ return buildMatcherFromPreprocessedRoutes(routes);
1737
+ }
1738
+ }
1739
+ };
1740
+ var SmartRouter = class {
1741
+ name = "SmartRouter";
1742
+ #routers = [];
1743
+ #routes = [];
1744
+ constructor(init) {
1745
+ this.#routers = init.routers;
1746
+ }
1747
+ add(method, path, handler) {
1748
+ if (!this.#routes) {
1749
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1750
+ }
1751
+ this.#routes.push([method, path, handler]);
1752
+ }
1753
+ match(method, path) {
1754
+ if (!this.#routes) {
1755
+ throw new Error("Fatal error");
1756
+ }
1757
+ const routers = this.#routers;
1758
+ const routes = this.#routes;
1759
+ const len = routers.length;
1760
+ let i = 0;
1761
+ let res;
1762
+ for (; i < len; i++) {
1763
+ const router = routers[i];
1764
+ try {
1765
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
1766
+ router.add(...routes[i2]);
1767
+ }
1768
+ res = router.match(method, path);
1769
+ } catch (e) {
1770
+ if (e instanceof UnsupportedPathError) {
1771
+ continue;
1772
+ }
1773
+ throw e;
1774
+ }
1775
+ this.match = router.match.bind(router);
1776
+ this.#routers = [router];
1777
+ this.#routes = void 0;
1778
+ break;
1779
+ }
1780
+ if (i === len) {
1781
+ throw new Error("Fatal error");
1782
+ }
1783
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
1784
+ return res;
1785
+ }
1786
+ get activeRouter() {
1787
+ if (this.#routes || this.#routers.length !== 1) {
1788
+ throw new Error("No active router has been determined yet.");
1789
+ }
1790
+ return this.#routers[0];
1791
+ }
1792
+ };
1793
+ var emptyParams = /* @__PURE__ */ Object.create(null);
1794
+ var Node = class _Node2 {
1795
+ #methods;
1796
+ #children;
1797
+ #patterns;
1798
+ #order = 0;
1799
+ #params = emptyParams;
1800
+ constructor(method, handler, children) {
1801
+ this.#children = children || /* @__PURE__ */ Object.create(null);
1802
+ this.#methods = [];
1803
+ if (method && handler) {
1804
+ const m = /* @__PURE__ */ Object.create(null);
1805
+ m[method] = { handler, possibleKeys: [], score: 0 };
1806
+ this.#methods = [m];
1807
+ }
1808
+ this.#patterns = [];
1809
+ }
1810
+ insert(method, path, handler) {
1811
+ this.#order = ++this.#order;
1812
+ let curNode = this;
1813
+ const parts = splitRoutingPath(path);
1814
+ const possibleKeys = [];
1815
+ for (let i = 0, len = parts.length; i < len; i++) {
1816
+ const p = parts[i];
1817
+ const nextP = parts[i + 1];
1818
+ const pattern = getPattern(p, nextP);
1819
+ const key = Array.isArray(pattern) ? pattern[0] : p;
1820
+ if (key in curNode.#children) {
1821
+ curNode = curNode.#children[key];
1822
+ if (pattern) {
1823
+ possibleKeys.push(pattern[1]);
1824
+ }
1825
+ continue;
1826
+ }
1827
+ curNode.#children[key] = new _Node2();
1828
+ if (pattern) {
1829
+ curNode.#patterns.push(pattern);
1830
+ possibleKeys.push(pattern[1]);
1831
+ }
1832
+ curNode = curNode.#children[key];
1833
+ }
1834
+ curNode.#methods.push({
1835
+ [method]: {
1836
+ handler,
1837
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
1838
+ score: this.#order
1839
+ }
1840
+ });
1841
+ return curNode;
1842
+ }
1843
+ #getHandlerSets(node, method, nodeParams, params) {
1844
+ const handlerSets = [];
1845
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
1846
+ const m = node.#methods[i];
1847
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
1848
+ const processedSet = {};
1849
+ if (handlerSet !== void 0) {
1850
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
1851
+ handlerSets.push(handlerSet);
1852
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
1853
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
1854
+ const key = handlerSet.possibleKeys[i2];
1855
+ const processed = processedSet[handlerSet.score];
1856
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
1857
+ processedSet[handlerSet.score] = true;
1858
+ }
1859
+ }
1860
+ }
1861
+ }
1862
+ return handlerSets;
1863
+ }
1864
+ search(method, path) {
1865
+ const handlerSets = [];
1866
+ this.#params = emptyParams;
1867
+ const curNode = this;
1868
+ let curNodes = [curNode];
1869
+ const parts = splitPath(path);
1870
+ const curNodesQueue = [];
1871
+ for (let i = 0, len = parts.length; i < len; i++) {
1872
+ const part = parts[i];
1873
+ const isLast = i === len - 1;
1874
+ const tempNodes = [];
1875
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
1876
+ const node = curNodes[j];
1877
+ const nextNode = node.#children[part];
1878
+ if (nextNode) {
1879
+ nextNode.#params = node.#params;
1880
+ if (isLast) {
1881
+ if (nextNode.#children["*"]) {
1882
+ handlerSets.push(
1883
+ ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
1884
+ );
1885
+ }
1886
+ handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
1887
+ } else {
1888
+ tempNodes.push(nextNode);
1889
+ }
1890
+ }
1891
+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
1892
+ const pattern = node.#patterns[k];
1893
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
1894
+ if (pattern === "*") {
1895
+ const astNode = node.#children["*"];
1896
+ if (astNode) {
1897
+ handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
1898
+ astNode.#params = params;
1899
+ tempNodes.push(astNode);
1900
+ }
1901
+ continue;
1902
+ }
1903
+ const [key, name, matcher] = pattern;
1904
+ if (!part && !(matcher instanceof RegExp)) {
1905
+ continue;
1906
+ }
1907
+ const child = node.#children[key];
1908
+ const restPathString = parts.slice(i).join("/");
1909
+ if (matcher instanceof RegExp) {
1910
+ const m = matcher.exec(restPathString);
1911
+ if (m) {
1912
+ params[name] = m[0];
1913
+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
1914
+ if (Object.keys(child.#children).length) {
1915
+ child.#params = params;
1916
+ const componentCount = m[0].match(/\//)?.length ?? 0;
1917
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
1918
+ targetCurNodes.push(child);
1919
+ }
1920
+ continue;
1921
+ }
1922
+ }
1923
+ if (matcher === true || matcher.test(part)) {
1924
+ params[name] = part;
1925
+ if (isLast) {
1926
+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
1927
+ if (child.#children["*"]) {
1928
+ handlerSets.push(
1929
+ ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
1930
+ );
1931
+ }
1932
+ } else {
1933
+ child.#params = params;
1934
+ tempNodes.push(child);
1935
+ }
1936
+ }
1937
+ }
1938
+ }
1939
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
1940
+ }
1941
+ if (handlerSets.length > 1) {
1942
+ handlerSets.sort((a, b) => {
1943
+ return a.score - b.score;
1944
+ });
1945
+ }
1946
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
1947
+ }
1948
+ };
1949
+ var TrieRouter = class {
1950
+ name = "TrieRouter";
1951
+ #node;
1952
+ constructor() {
1953
+ this.#node = new Node();
1954
+ }
1955
+ add(method, path, handler) {
1956
+ const results = checkOptionalParameter(path);
1957
+ if (results) {
1958
+ for (let i = 0, len = results.length; i < len; i++) {
1959
+ this.#node.insert(method, results[i], handler);
1960
+ }
1961
+ return;
1962
+ }
1963
+ this.#node.insert(method, path, handler);
1964
+ }
1965
+ match(method, path) {
1966
+ return this.#node.search(method, path);
1967
+ }
1968
+ };
1969
+ var Hono = class extends Hono$1 {
1970
+ /**
1971
+ * Creates an instance of the Hono class.
1972
+ *
1973
+ * @param options - Optional configuration options for the Hono instance.
1974
+ */
1975
+ constructor(options = {}) {
1976
+ super(options);
1977
+ this.router = options.router ?? new SmartRouter({
1978
+ routers: [new RegExpRouter(), new TrieRouter()]
1979
+ });
1980
+ }
1981
+ };
1982
+ var cors = (options) => {
1983
+ const defaults = {
1984
+ origin: "*",
1985
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
1986
+ allowHeaders: [],
1987
+ exposeHeaders: []
1988
+ };
1989
+ const opts = {
1990
+ ...defaults,
1991
+ ...options
1992
+ };
1993
+ const findAllowOrigin = ((optsOrigin) => {
1994
+ if (typeof optsOrigin === "string") {
1995
+ if (optsOrigin === "*") {
1996
+ return () => optsOrigin;
1997
+ } else {
1998
+ return (origin) => optsOrigin === origin ? origin : null;
1999
+ }
2000
+ } else if (typeof optsOrigin === "function") {
2001
+ return optsOrigin;
2002
+ } else {
2003
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
2004
+ }
2005
+ })(opts.origin);
2006
+ const findAllowMethods = ((optsAllowMethods) => {
2007
+ if (typeof optsAllowMethods === "function") {
2008
+ return optsAllowMethods;
2009
+ } else if (Array.isArray(optsAllowMethods)) {
2010
+ return () => optsAllowMethods;
2011
+ } else {
2012
+ return () => [];
2013
+ }
2014
+ })(opts.allowMethods);
2015
+ return async function cors2(c, next) {
2016
+ function set(key, value) {
2017
+ c.res.headers.set(key, value);
2018
+ }
2019
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
2020
+ if (allowOrigin) {
2021
+ set("Access-Control-Allow-Origin", allowOrigin);
2022
+ }
2023
+ if (opts.credentials) {
2024
+ set("Access-Control-Allow-Credentials", "true");
2025
+ }
2026
+ if (opts.exposeHeaders?.length) {
2027
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
2028
+ }
2029
+ if (c.req.method === "OPTIONS") {
2030
+ if (opts.origin !== "*") {
2031
+ set("Vary", "Origin");
2032
+ }
2033
+ if (opts.maxAge != null) {
2034
+ set("Access-Control-Max-Age", opts.maxAge.toString());
2035
+ }
2036
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
2037
+ if (allowMethods.length) {
2038
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
2039
+ }
2040
+ let headers = opts.allowHeaders;
2041
+ if (!headers?.length) {
2042
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
2043
+ if (requestHeaders) {
2044
+ headers = requestHeaders.split(/\s*,\s*/);
2045
+ }
2046
+ }
2047
+ if (headers?.length) {
2048
+ set("Access-Control-Allow-Headers", headers.join(","));
2049
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
2050
+ }
2051
+ c.res.headers.delete("Content-Length");
2052
+ c.res.headers.delete("Content-Type");
2053
+ return new Response(null, {
2054
+ headers: c.res.headers,
2055
+ status: 204,
2056
+ statusText: "No Content"
2057
+ });
2058
+ }
2059
+ await next();
2060
+ if (opts.origin !== "*") {
2061
+ c.header("Vary", "Origin", { append: true });
2062
+ }
2063
+ };
2064
+ };
2065
+ const setup = (app, env) => {
2066
+ const allowedOrigin = env?.ALLOWED_ORIGIN || "*";
2067
+ app.use(
2068
+ "*",
2069
+ cors({
2070
+ origin: allowedOrigin,
2071
+ allowMethods: ["GET", "POST", "OPTIONS"],
2072
+ allowHeaders: ["Content-Type", "Authorization", "Accept", "User-Agent"],
2073
+ exposeHeaders: ["Content-Length", "Content-Type"],
2074
+ maxAge: 86400,
2075
+ // 24 hours
2076
+ credentials: false
2077
+ })
2078
+ );
2079
+ app.use("*", async (c, next) => {
2080
+ await next();
2081
+ c.header("X-Content-Type-Options", "nosniff");
2082
+ c.header("X-Frame-Options", "DENY");
2083
+ c.header("X-XSS-Protection", "1; mode=block");
2084
+ c.header("Referrer-Policy", "strict-origin-when-cross-origin");
2085
+ });
2086
+ app.use("/proxy", async (c, next) => {
2087
+ await next();
2088
+ c.header("Content-Security-Policy", "default-src 'none'; connect-src 'self'");
2089
+ });
2090
+ app.get("/health", (c) => {
2091
+ return c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() });
2092
+ });
2093
+ app.get("/proxy", async (c) => {
2094
+ try {
2095
+ const url = c.req.query("url");
2096
+ if (!url) {
2097
+ return c.json(
2098
+ {
2099
+ success: false,
2100
+ error: "Missing url query parameter"
2101
+ },
2102
+ 400
2103
+ );
2104
+ }
2105
+ let urlObj;
2106
+ try {
2107
+ urlObj = new URL(url);
2108
+ } catch {
2109
+ return c.json(
2110
+ {
2111
+ success: false,
2112
+ error: "Invalid URL format"
2113
+ },
2114
+ 400
2115
+ );
2116
+ }
2117
+ if (!["http:", "https:"].includes(urlObj.protocol)) {
2118
+ return c.json(
2119
+ {
2120
+ success: false,
2121
+ error: "Invalid URL protocol. Only http and https are allowed."
2122
+ },
2123
+ 400
2124
+ );
2125
+ }
2126
+ const response = await fetch(url, {
2127
+ method: "GET",
2128
+ headers: {
2129
+ "User-Agent": "BusiCal-Proxy/1.0 (Calendar Sync App)",
2130
+ Accept: "text/calendar, text/plain, */*"
2131
+ }
2132
+ });
2133
+ const MAX_ICS_SIZE = 5 * 1024 * 1024;
2134
+ const contentLength = response.headers.get("content-length");
2135
+ if (contentLength && parseInt(contentLength) > MAX_ICS_SIZE) {
2136
+ return c.json(
2137
+ {
2138
+ success: false,
2139
+ error: "Calendar file too large (max 5MB)"
2140
+ },
2141
+ 413
2142
+ // Payload Too Large
2143
+ );
2144
+ }
2145
+ if (!response.ok) {
2146
+ return c.json(
2147
+ {
2148
+ success: false,
2149
+ error: "Failed to fetch calendar",
2150
+ upstreamStatus: response.status,
2151
+ upstreamStatusText: response.statusText
2152
+ },
2153
+ 502
2154
+ );
2155
+ }
2156
+ const icsData = await response.text();
2157
+ if (icsData.length > MAX_ICS_SIZE) {
2158
+ return c.json(
2159
+ {
2160
+ success: false,
2161
+ error: "Calendar file too large (max 5MB)"
2162
+ },
2163
+ 413
2164
+ );
2165
+ }
2166
+ if (!icsData.includes("BEGIN:VCALENDAR")) {
2167
+ return c.json(
2168
+ {
2169
+ success: false,
2170
+ error: "Response does not appear to be a valid ICS file"
2171
+ },
2172
+ 400
2173
+ );
2174
+ }
2175
+ return c.json({
2176
+ success: true,
2177
+ data: icsData,
2178
+ contentType: response.headers.get("content-type") || "text/calendar"
2179
+ });
2180
+ } catch (error) {
2181
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
2182
+ return c.json(
2183
+ {
2184
+ success: false,
2185
+ error: "Proxy request failed",
2186
+ details: errorMessage
2187
+ },
2188
+ 500
2189
+ );
2190
+ }
2191
+ });
2192
+ app.post("/proxy", async (c) => {
2193
+ try {
2194
+ const body = await c.req.json();
2195
+ const { url } = body;
2196
+ if (!url) {
2197
+ return c.json(
2198
+ {
2199
+ success: false,
2200
+ error: "Missing url parameter"
2201
+ },
2202
+ 400
2203
+ );
2204
+ }
2205
+ let urlObj;
2206
+ try {
2207
+ urlObj = new URL(url);
2208
+ } catch {
2209
+ return c.json(
2210
+ {
2211
+ success: false,
2212
+ error: "Invalid URL format"
2213
+ },
2214
+ 400
2215
+ );
2216
+ }
2217
+ if (!["http:", "https:"].includes(urlObj.protocol)) {
2218
+ return c.json(
2219
+ {
2220
+ success: false,
2221
+ error: "Invalid URL protocol"
2222
+ },
2223
+ 400
2224
+ );
2225
+ }
2226
+ const response = await fetch(url, {
2227
+ method: "GET",
2228
+ headers: {
2229
+ "User-Agent": "BusiCal-Proxy/1.0",
2230
+ Accept: "text/calendar, text/plain, */*"
2231
+ }
2232
+ });
2233
+ const MAX_ICS_SIZE = 5 * 1024 * 1024;
2234
+ const contentLength = response.headers.get("content-length");
2235
+ if (contentLength && parseInt(contentLength) > MAX_ICS_SIZE) {
2236
+ return c.json(
2237
+ {
2238
+ success: false,
2239
+ error: "Calendar file too large (max 5MB)"
2240
+ },
2241
+ 413
2242
+ // Payload Too Large
2243
+ );
2244
+ }
2245
+ if (!response.ok) {
2246
+ return c.json(
2247
+ {
2248
+ success: false,
2249
+ error: "Failed to fetch calendar",
2250
+ upstreamStatus: response.status,
2251
+ upstreamStatusText: response.statusText
2252
+ },
2253
+ 502
2254
+ );
2255
+ }
2256
+ const icsData = await response.text();
2257
+ if (icsData.length > MAX_ICS_SIZE) {
2258
+ return c.json(
2259
+ {
2260
+ success: false,
2261
+ error: "Calendar file too large (max 5MB)"
2262
+ },
2263
+ 413
2264
+ );
2265
+ }
2266
+ if (!icsData.includes("BEGIN:VCALENDAR")) {
2267
+ return c.json(
2268
+ {
2269
+ success: false,
2270
+ error: "Response does not appear to be a valid ICS file"
2271
+ },
2272
+ 400
2273
+ );
2274
+ }
2275
+ return c.json({
2276
+ success: true,
2277
+ data: icsData
2278
+ });
2279
+ } catch (error) {
2280
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
2281
+ return c.json(
2282
+ {
2283
+ success: false,
2284
+ error: "Proxy request failed",
2285
+ details: errorMessage
2286
+ },
2287
+ 500
2288
+ );
2289
+ }
2290
+ });
2291
+ app.notFound((c) => {
2292
+ return c.json(
2293
+ {
2294
+ success: false,
2295
+ error: "Not found",
2296
+ path: c.req.path
2297
+ },
2298
+ 404
2299
+ );
2300
+ });
2301
+ app.onError((err, c) => {
2302
+ return c.json(
2303
+ {
2304
+ success: false,
2305
+ error: "Internal server error",
2306
+ message: err.message
2307
+ },
2308
+ 500
2309
+ );
2310
+ });
2311
+ return app;
2312
+ };
2313
+ const index = {
2314
+ fetch: (request, env) => {
2315
+ const app = new Hono();
2316
+ return setup(app, env).fetch(request);
2317
+ }
2318
+ };
2319
+ const workerEntry = index ?? {};
2320
+ export {
2321
+ workerEntry as default
2322
+ };