emulate 0.5.0 → 0.6.0

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