@hyperspan/framework 0.1.2 → 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.
package/dist/index.js DELETED
@@ -1,2477 +0,0 @@
1
- // src/server.ts
2
- import { readdir as readdir2 } from "node:fs/promises";
3
- import { basename, extname, join } from "node:path";
4
-
5
- // ../html/dist/html.js
6
- /*!
7
- * escape-html
8
- * Copyright(c) 2012-2013 TJ Holowaychuk
9
- * Copyright(c) 2015 Andreas Lubbe
10
- * Copyright(c) 2015 Tiancheng "Timothy" Gu
11
- * MIT Licensed
12
- */
13
- var matchHtmlRegExp = /["'&<>]/;
14
- function escapeHtml(string) {
15
- const str = "" + string;
16
- const match = matchHtmlRegExp.exec(str);
17
- if (!match) {
18
- return str;
19
- }
20
- let escape;
21
- let html = "";
22
- let index = 0;
23
- let lastIndex = 0;
24
- for (index = match.index;index < str.length; index++) {
25
- switch (str.charCodeAt(index)) {
26
- case 34:
27
- escape = "&quot;";
28
- break;
29
- case 38:
30
- escape = "&amp;";
31
- break;
32
- case 39:
33
- escape = "&#39;";
34
- break;
35
- case 60:
36
- escape = "&lt;";
37
- break;
38
- case 62:
39
- escape = "&gt;";
40
- break;
41
- default:
42
- continue;
43
- }
44
- if (lastIndex !== index) {
45
- html += str.substring(lastIndex, index);
46
- }
47
- lastIndex = index + 1;
48
- html += escape;
49
- }
50
- return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
51
- }
52
-
53
- class TmplHtml {
54
- _kind = "hstmpl";
55
- content = "";
56
- asyncContent;
57
- constructor(props) {
58
- this.content = props.content;
59
- this.asyncContent = props.asyncContent;
60
- }
61
- }
62
- var htmlId = 0;
63
- function html(strings, ...values) {
64
- const asyncContent = [];
65
- let content = "";
66
- for (let i = 0;i < strings.length; i++) {
67
- const value = values[i];
68
- const kind = _typeOf(value);
69
- const renderValue = _renderValue(value, { kind, asyncContent }) || "";
70
- content += strings[i] + (renderValue ? renderValue : "");
71
- }
72
- return new TmplHtml({ content, asyncContent });
73
- }
74
- html.raw = (content) => ({ _kind: "html_safe", content });
75
- function _renderValue(value, opts = {
76
- kind: undefined,
77
- id: undefined,
78
- asyncContent: []
79
- }) {
80
- if (value === null || value === undefined || Number.isNaN(value)) {
81
- return "";
82
- }
83
- const kind = opts.kind || _typeOf(value);
84
- let id = opts.id;
85
- switch (kind) {
86
- case "array":
87
- return value.map((v) => _renderValue(v, { id, asyncContent: opts.asyncContent })).join("");
88
- case "object":
89
- id = `async_loading_${htmlId++}`;
90
- if (value instanceof TmplHtml || value.constructor.name === "TmplHtml" || value?._kind === "hstmpl") {
91
- opts.asyncContent.push(...value.asyncContent);
92
- return value.content;
93
- }
94
- if (value?._kind === "html_safe") {
95
- return value?.content || "";
96
- }
97
- if (typeof value.renderAsync === "function") {
98
- opts.asyncContent.push({
99
- id,
100
- promise: value.renderAsync().then((result) => ({
101
- id,
102
- value: result,
103
- asyncContent: opts.asyncContent
104
- }))
105
- });
106
- }
107
- if (typeof value.render === "function") {
108
- return render(_htmlPlaceholder(id, value.render()));
109
- }
110
- return JSON.stringify(value);
111
- case "promise":
112
- id = `async_loading_${htmlId++}`;
113
- opts.asyncContent.push({
114
- id,
115
- promise: value.then((result) => ({
116
- id,
117
- value: result,
118
- asyncContent: opts.asyncContent
119
- }))
120
- });
121
- return render(_htmlPlaceholder(id));
122
- case "generator":
123
- throw new Error("Generators are not supported as a template value at this time. Sorry :(");
124
- default:
125
- console.log("_renderValue kind =", kind, value);
126
- }
127
- return escapeHtml(String(value));
128
- }
129
- function _htmlPlaceholder(id, content = "Loading...") {
130
- return html`<!--hs:loading:${id}--><slot id="${id}">${content}</slot><!--/hs:loading:${id}-->`;
131
- }
132
- function render(tmpl) {
133
- return tmpl.content;
134
- }
135
- async function renderAsync(tmpl) {
136
- let { content, asyncContent } = tmpl;
137
- while (asyncContent.length !== 0) {
138
- const resolvedHtml = await Promise.all(asyncContent.map((p) => p.promise));
139
- asyncContent = [];
140
- resolvedHtml.map((obj) => {
141
- const r = new RegExp(`<!--hs:loading:${obj.id}-->(.*?)<!--/hs:loading:${obj.id}-->`);
142
- const found = content.match(r);
143
- if (found) {
144
- content = content.replace(found[0], _renderValue(obj.value, { asyncContent }));
145
- }
146
- });
147
- }
148
- return content;
149
- }
150
- async function* renderStream(tmpl) {
151
- yield render(tmpl);
152
- let asyncContent = tmpl.asyncContent;
153
- while (asyncContent.length > 0) {
154
- const nextContent = await Promise.race(asyncContent.map((p) => p.promise));
155
- asyncContent = asyncContent.filter((p) => p.id !== nextContent.id);
156
- const id = nextContent.id;
157
- const content = _renderValue(nextContent.value, {
158
- asyncContent
159
- });
160
- const script = html`<template id="${id}_content">${html.raw(content)}<!--end--></template>`;
161
- yield render(script);
162
- }
163
- }
164
- function _typeOf(obj) {
165
- if (obj instanceof Promise)
166
- return "promise";
167
- if (obj instanceof Date)
168
- return "date";
169
- if (obj instanceof String)
170
- return "string";
171
- if (obj instanceof Number)
172
- return "number";
173
- if (obj instanceof Boolean)
174
- return "boolean";
175
- if (obj instanceof Function)
176
- return "function";
177
- if (Array.isArray(obj))
178
- return "array";
179
- if (Number.isNaN(obj))
180
- return "NaN";
181
- if (obj === undefined)
182
- return "undefined";
183
- if (obj === null)
184
- return "null";
185
- if (isGenerator(obj))
186
- return "generator";
187
- return typeof obj;
188
- }
189
- function isGenerator(obj) {
190
- return obj && typeof obj.next == "function" && typeof obj.throw == "function";
191
- }
192
-
193
- // node_modules/isbot/index.mjs
194
- var fullPattern = " daum[ /]| deusu/| yadirectfetcher|(?:^|[^g])news(?!sapphire)|(?<! (?:channel/|google/))google(?!(app|/google| pixel))|(?<! cu)bots?(?:\\b|_)|(?<!(?:lib))http|(?<![hg]m)score|@[a-z][\\w-]+\\.|\\(\\)|\\.com\\b|\\btime/|\\||^<|^[\\w \\.\\-\\(?:\\):%]+(?:/v?\\d+(?:\\.\\d+)?(?:\\.\\d{1,10})*?)?(?:,|$)|^[^ ]{50,}$|^\\d+\\b|^\\w*search\\b|^\\w+/[\\w\\(\\)]*$|^active|^ad muncher|^amaya|^avsdevicesdk/|^biglotron|^bot|^bw/|^clamav[ /]|^client/|^cobweb/|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^email|^facebook|^getright/|^gozilla/|^hobbit|^hotzonu|^hwcdn/|^igetter/|^jeode/|^jetty/|^jigsaw|^microsoft bits|^movabletype|^mozilla/\\d\\.\\d\\s[\\w\\.-]+$|^mozilla/\\d\\.\\d\\s\\(compatible;?(?:\\s\\w+\\/\\d+\\.\\d+)?\\)$|^navermailapp|^netsurf|^offline|^openai/|^owler|^php|^postman|^python|^rank|^read|^reed|^rest|^rss|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor/|^track|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^wordpress|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|^{{.*}}$|adscanner/|analyzer|archive|ask jeeves/teoma|audit|bit\\.ly/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check\\b|checker|chrome-lighthouse|chromeframe|classifier|cloudflare|convertify|cookiehubscan|crawl|cypress/|dareboost|datanyze|dejaclick|detect|dmbrowser|download|evc-batch/|exaleadcloudview|feed|firephp|functionize|gomezagent|headless|httrack|hubspot marketing grader|hydra|ibisbrowser|infrawatch|insight|inspect|iplabel|ips-agent|java(?!;)|jsjcw_scanner|library|linkcheck|mail\\.ru/|manager|measure|neustar wpm|node|nutch|offbyone|onetrust|optimize|pageburst|pagespeed|parser|perl|phantomjs|pingdom|powermarks|preview|proxy|ptst[ /]\\d|retriever|rexx;|rigor|rss\\b|scanner\\.|scrape|server|sogou|sparkler/|speedcurve|spider|splash|statuscake|supercleaner|synapse|synthetic|tools|torrent|transcoder|url|validator|virtuoso|wappalyzer|webglance|webkit2png|whatcms/|zgrab";
195
- var naivePattern = /bot|crawl|http|lighthouse|scan|search|spider/i;
196
- var pattern;
197
- function getPattern() {
198
- if (pattern instanceof RegExp) {
199
- return pattern;
200
- }
201
- try {
202
- pattern = new RegExp(fullPattern, "i");
203
- } catch (error) {
204
- pattern = naivePattern;
205
- }
206
- return pattern;
207
- }
208
- function isbot(userAgent) {
209
- return Boolean(userAgent) && getPattern().test(userAgent);
210
- }
211
-
212
- // src/clientjs/md5.js
213
- var hex_chr = "0123456789abcdef".split("");
214
-
215
- // src/assets.ts
216
- import { readdir } from "node:fs/promises";
217
- import { resolve } from "node:path";
218
- var IS_PROD = false;
219
- var PWD = import.meta.dir;
220
- var clientJSFiles = new Map;
221
- async function buildClientJS() {
222
- const sourceFile = resolve(PWD, "../", "./src/clientjs/hyperspan-client.ts");
223
- const output = await Bun.build({
224
- entrypoints: [sourceFile],
225
- outdir: `./public/_hs/js`,
226
- naming: IS_PROD ? "[dir]/[name]-[hash].[ext]" : undefined,
227
- minify: IS_PROD
228
- });
229
- const jsFile = output.outputs[0].path.split("/").reverse()[0];
230
- clientJSFiles.set("_hs", { src: "/_hs/js/" + jsFile });
231
- return jsFile;
232
- }
233
- var clientCSSFiles = new Map;
234
- async function buildClientCSS() {
235
- if (clientCSSFiles.has("_hs")) {
236
- return clientCSSFiles.get("_hs");
237
- }
238
- const cssDir = "./public/_hs/css/";
239
- const cssFiles = await readdir(cssDir);
240
- let foundCSSFile = "";
241
- for (const file of cssFiles) {
242
- if (!file.endsWith(".css")) {
243
- continue;
244
- }
245
- foundCSSFile = file.replace(cssDir, "");
246
- clientCSSFiles.set("_hs", foundCSSFile);
247
- break;
248
- }
249
- if (!foundCSSFile) {
250
- console.log(`Unable to build CSS files from ${cssDir}`);
251
- }
252
- }
253
-
254
- // node_modules/hono/dist/compose.js
255
- var compose = (middleware, onError, onNotFound) => {
256
- return (context, next) => {
257
- let index = -1;
258
- return dispatch(0);
259
- async function dispatch(i) {
260
- if (i <= index) {
261
- throw new Error("next() called multiple times");
262
- }
263
- index = i;
264
- let res;
265
- let isError = false;
266
- let handler;
267
- if (middleware[i]) {
268
- handler = middleware[i][0][0];
269
- context.req.routeIndex = i;
270
- } else {
271
- handler = i === middleware.length && next || undefined;
272
- }
273
- if (handler) {
274
- try {
275
- res = await handler(context, () => dispatch(i + 1));
276
- } catch (err) {
277
- if (err instanceof Error && onError) {
278
- context.error = err;
279
- res = await onError(err, context);
280
- isError = true;
281
- } else {
282
- throw err;
283
- }
284
- }
285
- } else {
286
- if (context.finalized === false && onNotFound) {
287
- res = await onNotFound(context);
288
- }
289
- }
290
- if (res && (context.finalized === false || isError)) {
291
- context.res = res;
292
- }
293
- return context;
294
- }
295
- };
296
- };
297
-
298
- // node_modules/hono/dist/utils/body.js
299
- var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
300
- const { all = false, dot = false } = options;
301
- const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
302
- const contentType = headers.get("Content-Type");
303
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
304
- return parseFormData(request, { all, dot });
305
- }
306
- return {};
307
- };
308
- async function parseFormData(request, options) {
309
- const formData = await request.formData();
310
- if (formData) {
311
- return convertFormDataToBodyData(formData, options);
312
- }
313
- return {};
314
- }
315
- function convertFormDataToBodyData(formData, options) {
316
- const form = /* @__PURE__ */ Object.create(null);
317
- formData.forEach((value, key) => {
318
- const shouldParseAllValues = options.all || key.endsWith("[]");
319
- if (!shouldParseAllValues) {
320
- form[key] = value;
321
- } else {
322
- handleParsingAllValues(form, key, value);
323
- }
324
- });
325
- if (options.dot) {
326
- Object.entries(form).forEach(([key, value]) => {
327
- const shouldParseDotValues = key.includes(".");
328
- if (shouldParseDotValues) {
329
- handleParsingNestedValues(form, key, value);
330
- delete form[key];
331
- }
332
- });
333
- }
334
- return form;
335
- }
336
- var handleParsingAllValues = (form, key, value) => {
337
- if (form[key] !== undefined) {
338
- if (Array.isArray(form[key])) {
339
- form[key].push(value);
340
- } else {
341
- form[key] = [form[key], value];
342
- }
343
- } else {
344
- form[key] = value;
345
- }
346
- };
347
- var handleParsingNestedValues = (form, key, value) => {
348
- let nestedForm = form;
349
- const keys = key.split(".");
350
- keys.forEach((key2, index) => {
351
- if (index === keys.length - 1) {
352
- nestedForm[key2] = value;
353
- } else {
354
- if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
355
- nestedForm[key2] = /* @__PURE__ */ Object.create(null);
356
- }
357
- nestedForm = nestedForm[key2];
358
- }
359
- });
360
- };
361
-
362
- // node_modules/hono/dist/utils/url.js
363
- var splitPath = (path) => {
364
- const paths = path.split("/");
365
- if (paths[0] === "") {
366
- paths.shift();
367
- }
368
- return paths;
369
- };
370
- var splitRoutingPath = (routePath) => {
371
- const { groups, path } = extractGroupsFromPath(routePath);
372
- const paths = splitPath(path);
373
- return replaceGroupMarks(paths, groups);
374
- };
375
- var extractGroupsFromPath = (path) => {
376
- const groups = [];
377
- path = path.replace(/\{[^}]+\}/g, (match, index) => {
378
- const mark = `@${index}`;
379
- groups.push([mark, match]);
380
- return mark;
381
- });
382
- return { groups, path };
383
- };
384
- var replaceGroupMarks = (paths, groups) => {
385
- for (let i = groups.length - 1;i >= 0; i--) {
386
- const [mark] = groups[i];
387
- for (let j = paths.length - 1;j >= 0; j--) {
388
- if (paths[j].includes(mark)) {
389
- paths[j] = paths[j].replace(mark, groups[i][1]);
390
- break;
391
- }
392
- }
393
- }
394
- return paths;
395
- };
396
- var patternCache = {};
397
- var getPattern2 = (label, next) => {
398
- if (label === "*") {
399
- return "*";
400
- }
401
- const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
402
- if (match) {
403
- const cacheKey = `${label}#${next}`;
404
- if (!patternCache[cacheKey]) {
405
- if (match[2]) {
406
- patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
407
- } else {
408
- patternCache[cacheKey] = [label, match[1], true];
409
- }
410
- }
411
- return patternCache[cacheKey];
412
- }
413
- return null;
414
- };
415
- var tryDecode = (str, decoder) => {
416
- try {
417
- return decoder(str);
418
- } catch {
419
- return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
420
- try {
421
- return decoder(match);
422
- } catch {
423
- return match;
424
- }
425
- });
426
- }
427
- };
428
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
429
- var getPath = (request) => {
430
- const url = request.url;
431
- const start = url.indexOf("/", 8);
432
- let i = start;
433
- for (;i < url.length; i++) {
434
- const charCode = url.charCodeAt(i);
435
- if (charCode === 37) {
436
- const queryIndex = url.indexOf("?", i);
437
- const path = url.slice(start, queryIndex === -1 ? undefined : queryIndex);
438
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
439
- } else if (charCode === 63) {
440
- break;
441
- }
442
- }
443
- return url.slice(start, i);
444
- };
445
- var getPathNoStrict = (request) => {
446
- const result = getPath(request);
447
- return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
448
- };
449
- var mergePath = (base, sub, ...rest) => {
450
- if (rest.length) {
451
- sub = mergePath(sub, ...rest);
452
- }
453
- return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
454
- };
455
- var checkOptionalParameter = (path) => {
456
- if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
457
- return null;
458
- }
459
- const segments = path.split("/");
460
- const results = [];
461
- let basePath = "";
462
- segments.forEach((segment) => {
463
- if (segment !== "" && !/\:/.test(segment)) {
464
- basePath += "/" + segment;
465
- } else if (/\:/.test(segment)) {
466
- if (/\?/.test(segment)) {
467
- if (results.length === 0 && basePath === "") {
468
- results.push("/");
469
- } else {
470
- results.push(basePath);
471
- }
472
- const optionalSegment = segment.replace("?", "");
473
- basePath += "/" + optionalSegment;
474
- results.push(basePath);
475
- } else {
476
- basePath += "/" + segment;
477
- }
478
- }
479
- });
480
- return results.filter((v, i, a) => a.indexOf(v) === i);
481
- };
482
- var _decodeURI = (value) => {
483
- if (!/[%+]/.test(value)) {
484
- return value;
485
- }
486
- if (value.indexOf("+") !== -1) {
487
- value = value.replace(/\+/g, " ");
488
- }
489
- return value.indexOf("%") !== -1 ? decodeURIComponent_(value) : value;
490
- };
491
- var _getQueryParam = (url, key, multiple) => {
492
- let encoded;
493
- if (!multiple && key && !/[%+]/.test(key)) {
494
- let keyIndex2 = url.indexOf(`?${key}`, 8);
495
- if (keyIndex2 === -1) {
496
- keyIndex2 = url.indexOf(`&${key}`, 8);
497
- }
498
- while (keyIndex2 !== -1) {
499
- const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
500
- if (trailingKeyCode === 61) {
501
- const valueIndex = keyIndex2 + key.length + 2;
502
- const endIndex = url.indexOf("&", valueIndex);
503
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
504
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
505
- return "";
506
- }
507
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
508
- }
509
- encoded = /[%+]/.test(url);
510
- if (!encoded) {
511
- return;
512
- }
513
- }
514
- const results = {};
515
- encoded ??= /[%+]/.test(url);
516
- let keyIndex = url.indexOf("?", 8);
517
- while (keyIndex !== -1) {
518
- const nextKeyIndex = url.indexOf("&", keyIndex + 1);
519
- let valueIndex = url.indexOf("=", keyIndex);
520
- if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
521
- valueIndex = -1;
522
- }
523
- let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
524
- if (encoded) {
525
- name = _decodeURI(name);
526
- }
527
- keyIndex = nextKeyIndex;
528
- if (name === "") {
529
- continue;
530
- }
531
- let value;
532
- if (valueIndex === -1) {
533
- value = "";
534
- } else {
535
- value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
536
- if (encoded) {
537
- value = _decodeURI(value);
538
- }
539
- }
540
- if (multiple) {
541
- if (!(results[name] && Array.isArray(results[name]))) {
542
- results[name] = [];
543
- }
544
- results[name].push(value);
545
- } else {
546
- results[name] ??= value;
547
- }
548
- }
549
- return key ? results[key] : results;
550
- };
551
- var getQueryParam = _getQueryParam;
552
- var getQueryParams = (url, key) => {
553
- return _getQueryParam(url, key, true);
554
- };
555
- var decodeURIComponent_ = decodeURIComponent;
556
-
557
- // node_modules/hono/dist/request.js
558
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
559
- var HonoRequest = class {
560
- raw;
561
- #validatedData;
562
- #matchResult;
563
- routeIndex = 0;
564
- path;
565
- bodyCache = {};
566
- constructor(request, path = "/", matchResult = [[]]) {
567
- this.raw = request;
568
- this.path = path;
569
- this.#matchResult = matchResult;
570
- this.#validatedData = {};
571
- }
572
- param(key) {
573
- return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
574
- }
575
- #getDecodedParam(key) {
576
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
577
- const param = this.#getParamValue(paramKey);
578
- return param ? /\%/.test(param) ? tryDecodeURIComponent(param) : param : undefined;
579
- }
580
- #getAllDecodedParams() {
581
- const decoded = {};
582
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
583
- for (const key of keys) {
584
- const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
585
- if (value && typeof value === "string") {
586
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
587
- }
588
- }
589
- return decoded;
590
- }
591
- #getParamValue(paramKey) {
592
- return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
593
- }
594
- query(key) {
595
- return getQueryParam(this.url, key);
596
- }
597
- queries(key) {
598
- return getQueryParams(this.url, key);
599
- }
600
- header(name) {
601
- if (name) {
602
- return this.raw.headers.get(name) ?? undefined;
603
- }
604
- const headerData = {};
605
- this.raw.headers.forEach((value, key) => {
606
- headerData[key] = value;
607
- });
608
- return headerData;
609
- }
610
- async parseBody(options) {
611
- return this.bodyCache.parsedBody ??= await parseBody(this, options);
612
- }
613
- #cachedBody = (key) => {
614
- const { bodyCache, raw } = this;
615
- const cachedBody = bodyCache[key];
616
- if (cachedBody) {
617
- return cachedBody;
618
- }
619
- const anyCachedKey = Object.keys(bodyCache)[0];
620
- if (anyCachedKey) {
621
- return bodyCache[anyCachedKey].then((body) => {
622
- if (anyCachedKey === "json") {
623
- body = JSON.stringify(body);
624
- }
625
- return new Response(body)[key]();
626
- });
627
- }
628
- return bodyCache[key] = raw[key]();
629
- };
630
- json() {
631
- return this.#cachedBody("json");
632
- }
633
- text() {
634
- return this.#cachedBody("text");
635
- }
636
- arrayBuffer() {
637
- return this.#cachedBody("arrayBuffer");
638
- }
639
- blob() {
640
- return this.#cachedBody("blob");
641
- }
642
- formData() {
643
- return this.#cachedBody("formData");
644
- }
645
- addValidatedData(target, data) {
646
- this.#validatedData[target] = data;
647
- }
648
- valid(target) {
649
- return this.#validatedData[target];
650
- }
651
- get url() {
652
- return this.raw.url;
653
- }
654
- get method() {
655
- return this.raw.method;
656
- }
657
- get matchedRoutes() {
658
- return this.#matchResult[0].map(([[, route]]) => route);
659
- }
660
- get routePath() {
661
- return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
662
- }
663
- };
664
-
665
- // node_modules/hono/dist/utils/html.js
666
- var HtmlEscapedCallbackPhase = {
667
- Stringify: 1,
668
- BeforeStream: 2,
669
- Stream: 3
670
- };
671
- var raw = (value, callbacks) => {
672
- const escapedString = new String(value);
673
- escapedString.isEscaped = true;
674
- escapedString.callbacks = callbacks;
675
- return escapedString;
676
- };
677
- var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
678
- if (typeof str === "object" && !(str instanceof String)) {
679
- if (!(str instanceof Promise)) {
680
- str = str.toString();
681
- }
682
- if (str instanceof Promise) {
683
- str = await str;
684
- }
685
- }
686
- const callbacks = str.callbacks;
687
- if (!callbacks?.length) {
688
- return Promise.resolve(str);
689
- }
690
- if (buffer) {
691
- buffer[0] += str;
692
- } else {
693
- buffer = [str];
694
- }
695
- const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
696
- if (preserveCallbacks) {
697
- return raw(await resStr, callbacks);
698
- } else {
699
- return resStr;
700
- }
701
- };
702
-
703
- // node_modules/hono/dist/context.js
704
- var TEXT_PLAIN = "text/plain; charset=UTF-8";
705
- var setHeaders = (headers, map = {}) => {
706
- for (const key of Object.keys(map)) {
707
- headers.set(key, map[key]);
708
- }
709
- return headers;
710
- };
711
- var Context = class {
712
- #rawRequest;
713
- #req;
714
- env = {};
715
- #var;
716
- finalized = false;
717
- error;
718
- #status = 200;
719
- #executionCtx;
720
- #headers;
721
- #preparedHeaders;
722
- #res;
723
- #isFresh = true;
724
- #layout;
725
- #renderer;
726
- #notFoundHandler;
727
- #matchResult;
728
- #path;
729
- constructor(req, options) {
730
- this.#rawRequest = req;
731
- if (options) {
732
- this.#executionCtx = options.executionCtx;
733
- this.env = options.env;
734
- this.#notFoundHandler = options.notFoundHandler;
735
- this.#path = options.path;
736
- this.#matchResult = options.matchResult;
737
- }
738
- }
739
- get req() {
740
- this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
741
- return this.#req;
742
- }
743
- get event() {
744
- if (this.#executionCtx && "respondWith" in this.#executionCtx) {
745
- return this.#executionCtx;
746
- } else {
747
- throw Error("This context has no FetchEvent");
748
- }
749
- }
750
- get executionCtx() {
751
- if (this.#executionCtx) {
752
- return this.#executionCtx;
753
- } else {
754
- throw Error("This context has no ExecutionContext");
755
- }
756
- }
757
- get res() {
758
- this.#isFresh = false;
759
- return this.#res ||= new Response("404 Not Found", { status: 404 });
760
- }
761
- set res(_res) {
762
- this.#isFresh = false;
763
- if (this.#res && _res) {
764
- _res = new Response(_res.body, _res);
765
- for (const [k, v] of this.#res.headers.entries()) {
766
- if (k === "content-type") {
767
- continue;
768
- }
769
- if (k === "set-cookie") {
770
- const cookies = this.#res.headers.getSetCookie();
771
- _res.headers.delete("set-cookie");
772
- for (const cookie of cookies) {
773
- _res.headers.append("set-cookie", cookie);
774
- }
775
- } else {
776
- _res.headers.set(k, v);
777
- }
778
- }
779
- }
780
- this.#res = _res;
781
- this.finalized = true;
782
- }
783
- render = (...args) => {
784
- this.#renderer ??= (content) => this.html(content);
785
- return this.#renderer(...args);
786
- };
787
- setLayout = (layout) => this.#layout = layout;
788
- getLayout = () => this.#layout;
789
- setRenderer = (renderer) => {
790
- this.#renderer = renderer;
791
- };
792
- header = (name, value, options) => {
793
- if (this.finalized) {
794
- this.#res = new Response(this.#res.body, this.#res);
795
- }
796
- if (value === undefined) {
797
- if (this.#headers) {
798
- this.#headers.delete(name);
799
- } else if (this.#preparedHeaders) {
800
- delete this.#preparedHeaders[name.toLocaleLowerCase()];
801
- }
802
- if (this.finalized) {
803
- this.res.headers.delete(name);
804
- }
805
- return;
806
- }
807
- if (options?.append) {
808
- if (!this.#headers) {
809
- this.#isFresh = false;
810
- this.#headers = new Headers(this.#preparedHeaders);
811
- this.#preparedHeaders = {};
812
- }
813
- this.#headers.append(name, value);
814
- } else {
815
- if (this.#headers) {
816
- this.#headers.set(name, value);
817
- } else {
818
- this.#preparedHeaders ??= {};
819
- this.#preparedHeaders[name.toLowerCase()] = value;
820
- }
821
- }
822
- if (this.finalized) {
823
- if (options?.append) {
824
- this.res.headers.append(name, value);
825
- } else {
826
- this.res.headers.set(name, value);
827
- }
828
- }
829
- };
830
- status = (status) => {
831
- this.#isFresh = false;
832
- this.#status = status;
833
- };
834
- set = (key, value) => {
835
- this.#var ??= /* @__PURE__ */ new Map;
836
- this.#var.set(key, value);
837
- };
838
- get = (key) => {
839
- return this.#var ? this.#var.get(key) : undefined;
840
- };
841
- get var() {
842
- if (!this.#var) {
843
- return {};
844
- }
845
- return Object.fromEntries(this.#var);
846
- }
847
- #newResponse(data, arg, headers) {
848
- if (this.#isFresh && !headers && !arg && this.#status === 200) {
849
- return new Response(data, {
850
- headers: this.#preparedHeaders
851
- });
852
- }
853
- if (arg && typeof arg !== "number") {
854
- const header = new Headers(arg.headers);
855
- if (this.#headers) {
856
- this.#headers.forEach((v, k) => {
857
- if (k === "set-cookie") {
858
- header.append(k, v);
859
- } else {
860
- header.set(k, v);
861
- }
862
- });
863
- }
864
- const headers2 = setHeaders(header, this.#preparedHeaders);
865
- return new Response(data, {
866
- headers: headers2,
867
- status: arg.status ?? this.#status
868
- });
869
- }
870
- const status = typeof arg === "number" ? arg : this.#status;
871
- this.#preparedHeaders ??= {};
872
- this.#headers ??= new Headers;
873
- setHeaders(this.#headers, this.#preparedHeaders);
874
- if (this.#res) {
875
- this.#res.headers.forEach((v, k) => {
876
- if (k === "set-cookie") {
877
- this.#headers?.append(k, v);
878
- } else {
879
- this.#headers?.set(k, v);
880
- }
881
- });
882
- setHeaders(this.#headers, this.#preparedHeaders);
883
- }
884
- headers ??= {};
885
- for (const [k, v] of Object.entries(headers)) {
886
- if (typeof v === "string") {
887
- this.#headers.set(k, v);
888
- } else {
889
- this.#headers.delete(k);
890
- for (const v2 of v) {
891
- this.#headers.append(k, v2);
892
- }
893
- }
894
- }
895
- return new Response(data, {
896
- status,
897
- headers: this.#headers
898
- });
899
- }
900
- newResponse = (...args) => this.#newResponse(...args);
901
- body = (data, arg, headers) => {
902
- return typeof arg === "number" ? this.#newResponse(data, arg, headers) : this.#newResponse(data, arg);
903
- };
904
- text = (text, arg, headers) => {
905
- if (!this.#preparedHeaders) {
906
- if (this.#isFresh && !headers && !arg) {
907
- return new Response(text);
908
- }
909
- this.#preparedHeaders = {};
910
- }
911
- this.#preparedHeaders["content-type"] = TEXT_PLAIN;
912
- if (typeof arg === "number") {
913
- return this.#newResponse(text, arg, headers);
914
- }
915
- return this.#newResponse(text, arg);
916
- };
917
- json = (object, arg, headers) => {
918
- const body = JSON.stringify(object);
919
- this.#preparedHeaders ??= {};
920
- this.#preparedHeaders["content-type"] = "application/json";
921
- return typeof arg === "number" ? this.#newResponse(body, arg, headers) : this.#newResponse(body, arg);
922
- };
923
- html = (html2, arg, headers) => {
924
- this.#preparedHeaders ??= {};
925
- this.#preparedHeaders["content-type"] = "text/html; charset=UTF-8";
926
- if (typeof html2 === "object") {
927
- return resolveCallback(html2, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html22) => {
928
- return typeof arg === "number" ? this.#newResponse(html22, arg, headers) : this.#newResponse(html22, arg);
929
- });
930
- }
931
- return typeof arg === "number" ? this.#newResponse(html2, arg, headers) : this.#newResponse(html2, arg);
932
- };
933
- redirect = (location, status) => {
934
- this.#headers ??= new Headers;
935
- this.#headers.set("Location", String(location));
936
- return this.newResponse(null, status ?? 302);
937
- };
938
- notFound = () => {
939
- this.#notFoundHandler ??= () => new Response;
940
- return this.#notFoundHandler(this);
941
- };
942
- };
943
-
944
- // node_modules/hono/dist/router.js
945
- var METHOD_NAME_ALL = "ALL";
946
- var METHOD_NAME_ALL_LOWERCASE = "all";
947
- var METHODS = ["get", "post", "put", "delete", "options", "patch"];
948
- var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
949
- var UnsupportedPathError = class extends Error {
950
- };
951
-
952
- // node_modules/hono/dist/utils/constants.js
953
- var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
954
-
955
- // node_modules/hono/dist/hono-base.js
956
- var notFoundHandler = (c) => {
957
- return c.text("404 Not Found", 404);
958
- };
959
- var errorHandler = (err, c) => {
960
- if ("getResponse" in err) {
961
- return err.getResponse();
962
- }
963
- console.error(err);
964
- return c.text("Internal Server Error", 500);
965
- };
966
- var Hono = class {
967
- get;
968
- post;
969
- put;
970
- delete;
971
- options;
972
- patch;
973
- all;
974
- on;
975
- use;
976
- router;
977
- getPath;
978
- _basePath = "/";
979
- #path = "/";
980
- routes = [];
981
- constructor(options = {}) {
982
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
983
- allMethods.forEach((method) => {
984
- this[method] = (args1, ...args) => {
985
- if (typeof args1 === "string") {
986
- this.#path = args1;
987
- } else {
988
- this.#addRoute(method, this.#path, args1);
989
- }
990
- args.forEach((handler) => {
991
- this.#addRoute(method, this.#path, handler);
992
- });
993
- return this;
994
- };
995
- });
996
- this.on = (method, path, ...handlers) => {
997
- for (const p of [path].flat()) {
998
- this.#path = p;
999
- for (const m of [method].flat()) {
1000
- handlers.map((handler) => {
1001
- this.#addRoute(m.toUpperCase(), this.#path, handler);
1002
- });
1003
- }
1004
- }
1005
- return this;
1006
- };
1007
- this.use = (arg1, ...handlers) => {
1008
- if (typeof arg1 === "string") {
1009
- this.#path = arg1;
1010
- } else {
1011
- this.#path = "*";
1012
- handlers.unshift(arg1);
1013
- }
1014
- handlers.forEach((handler) => {
1015
- this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1016
- });
1017
- return this;
1018
- };
1019
- const { strict, ...optionsWithoutStrict } = options;
1020
- Object.assign(this, optionsWithoutStrict);
1021
- this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1022
- }
1023
- #clone() {
1024
- const clone = new Hono({
1025
- router: this.router,
1026
- getPath: this.getPath
1027
- });
1028
- clone.routes = this.routes;
1029
- return clone;
1030
- }
1031
- #notFoundHandler = notFoundHandler;
1032
- errorHandler = errorHandler;
1033
- route(path, app) {
1034
- const subApp = this.basePath(path);
1035
- app.routes.map((r) => {
1036
- let handler;
1037
- if (app.errorHandler === errorHandler) {
1038
- handler = r.handler;
1039
- } else {
1040
- handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
1041
- handler[COMPOSED_HANDLER] = r.handler;
1042
- }
1043
- subApp.#addRoute(r.method, r.path, handler);
1044
- });
1045
- return this;
1046
- }
1047
- basePath(path) {
1048
- const subApp = this.#clone();
1049
- subApp._basePath = mergePath(this._basePath, path);
1050
- return subApp;
1051
- }
1052
- onError = (handler) => {
1053
- this.errorHandler = handler;
1054
- return this;
1055
- };
1056
- notFound = (handler) => {
1057
- this.#notFoundHandler = handler;
1058
- return this;
1059
- };
1060
- mount(path, applicationHandler, options) {
1061
- let replaceRequest;
1062
- let optionHandler;
1063
- if (options) {
1064
- if (typeof options === "function") {
1065
- optionHandler = options;
1066
- } else {
1067
- optionHandler = options.optionHandler;
1068
- replaceRequest = options.replaceRequest;
1069
- }
1070
- }
1071
- const getOptions = optionHandler ? (c) => {
1072
- const options2 = optionHandler(c);
1073
- return Array.isArray(options2) ? options2 : [options2];
1074
- } : (c) => {
1075
- let executionContext = undefined;
1076
- try {
1077
- executionContext = c.executionCtx;
1078
- } catch {}
1079
- return [c.env, executionContext];
1080
- };
1081
- replaceRequest ||= (() => {
1082
- const mergedPath = mergePath(this._basePath, path);
1083
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1084
- return (request) => {
1085
- const url = new URL(request.url);
1086
- url.pathname = url.pathname.slice(pathPrefixLength) || "/";
1087
- return new Request(url, request);
1088
- };
1089
- })();
1090
- const handler = async (c, next) => {
1091
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1092
- if (res) {
1093
- return res;
1094
- }
1095
- await next();
1096
- };
1097
- this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
1098
- return this;
1099
- }
1100
- #addRoute(method, path, handler) {
1101
- method = method.toUpperCase();
1102
- path = mergePath(this._basePath, path);
1103
- const r = { path, method, handler };
1104
- this.router.add(method, path, [handler, r]);
1105
- this.routes.push(r);
1106
- }
1107
- #handleError(err, c) {
1108
- if (err instanceof Error) {
1109
- return this.errorHandler(err, c);
1110
- }
1111
- throw err;
1112
- }
1113
- #dispatch(request, executionCtx, env, method) {
1114
- if (method === "HEAD") {
1115
- return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1116
- }
1117
- const path = this.getPath(request, { env });
1118
- const matchResult = this.router.match(method, path);
1119
- const c = new Context(request, {
1120
- path,
1121
- matchResult,
1122
- env,
1123
- executionCtx,
1124
- notFoundHandler: this.#notFoundHandler
1125
- });
1126
- if (matchResult[0].length === 1) {
1127
- let res;
1128
- try {
1129
- res = matchResult[0][0][0][0](c, async () => {
1130
- c.res = await this.#notFoundHandler(c);
1131
- });
1132
- } catch (err) {
1133
- return this.#handleError(err, c);
1134
- }
1135
- return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
1136
- }
1137
- const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1138
- return (async () => {
1139
- try {
1140
- const context = await composed(c);
1141
- if (!context.finalized) {
1142
- throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
1143
- }
1144
- return context.res;
1145
- } catch (err) {
1146
- return this.#handleError(err, c);
1147
- }
1148
- })();
1149
- }
1150
- fetch = (request, ...rest) => {
1151
- return this.#dispatch(request, rest[1], rest[0], request.method);
1152
- };
1153
- request = (input, requestInit, Env, executionCtx) => {
1154
- if (input instanceof Request) {
1155
- return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
1156
- }
1157
- input = input.toString();
1158
- return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
1159
- };
1160
- fire = () => {
1161
- addEventListener("fetch", (event) => {
1162
- event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
1163
- });
1164
- };
1165
- };
1166
-
1167
- // node_modules/hono/dist/router/reg-exp-router/node.js
1168
- var LABEL_REG_EXP_STR = "[^/]+";
1169
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
1170
- var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1171
- var PATH_ERROR = Symbol();
1172
- var regExpMetaChars = new Set(".\\+*[^]$()");
1173
- function compareKey(a, b) {
1174
- if (a.length === 1) {
1175
- return b.length === 1 ? a < b ? -1 : 1 : -1;
1176
- }
1177
- if (b.length === 1) {
1178
- return 1;
1179
- }
1180
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
1181
- return 1;
1182
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
1183
- return -1;
1184
- }
1185
- if (a === LABEL_REG_EXP_STR) {
1186
- return 1;
1187
- } else if (b === LABEL_REG_EXP_STR) {
1188
- return -1;
1189
- }
1190
- return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
1191
- }
1192
- var Node = class {
1193
- #index;
1194
- #varIndex;
1195
- #children = /* @__PURE__ */ Object.create(null);
1196
- insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
1197
- if (tokens.length === 0) {
1198
- if (this.#index !== undefined) {
1199
- throw PATH_ERROR;
1200
- }
1201
- if (pathErrorCheckOnly) {
1202
- return;
1203
- }
1204
- this.#index = index;
1205
- return;
1206
- }
1207
- const [token, ...restTokens] = tokens;
1208
- const pattern2 = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1209
- let node;
1210
- if (pattern2) {
1211
- const name = pattern2[1];
1212
- let regexpStr = pattern2[2] || LABEL_REG_EXP_STR;
1213
- if (name && pattern2[2]) {
1214
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
1215
- if (/\((?!\?:)/.test(regexpStr)) {
1216
- throw PATH_ERROR;
1217
- }
1218
- }
1219
- node = this.#children[regexpStr];
1220
- if (!node) {
1221
- if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
1222
- throw PATH_ERROR;
1223
- }
1224
- if (pathErrorCheckOnly) {
1225
- return;
1226
- }
1227
- node = this.#children[regexpStr] = new Node;
1228
- if (name !== "") {
1229
- node.#varIndex = context.varIndex++;
1230
- }
1231
- }
1232
- if (!pathErrorCheckOnly && name !== "") {
1233
- paramMap.push([name, node.#varIndex]);
1234
- }
1235
- } else {
1236
- node = this.#children[token];
1237
- if (!node) {
1238
- if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
1239
- throw PATH_ERROR;
1240
- }
1241
- if (pathErrorCheckOnly) {
1242
- return;
1243
- }
1244
- node = this.#children[token] = new Node;
1245
- }
1246
- }
1247
- node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
1248
- }
1249
- buildRegExpStr() {
1250
- const childKeys = Object.keys(this.#children).sort(compareKey);
1251
- const strList = childKeys.map((k) => {
1252
- const c = this.#children[k];
1253
- return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
1254
- });
1255
- if (typeof this.#index === "number") {
1256
- strList.unshift(`#${this.#index}`);
1257
- }
1258
- if (strList.length === 0) {
1259
- return "";
1260
- }
1261
- if (strList.length === 1) {
1262
- return strList[0];
1263
- }
1264
- return "(?:" + strList.join("|") + ")";
1265
- }
1266
- };
1267
-
1268
- // node_modules/hono/dist/router/reg-exp-router/trie.js
1269
- var Trie = class {
1270
- #context = { varIndex: 0 };
1271
- #root = new Node;
1272
- insert(path, index, pathErrorCheckOnly) {
1273
- const paramAssoc = [];
1274
- const groups = [];
1275
- for (let i = 0;; ) {
1276
- let replaced = false;
1277
- path = path.replace(/\{[^}]+\}/g, (m) => {
1278
- const mark = `@\\${i}`;
1279
- groups[i] = [mark, m];
1280
- i++;
1281
- replaced = true;
1282
- return mark;
1283
- });
1284
- if (!replaced) {
1285
- break;
1286
- }
1287
- }
1288
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1289
- for (let i = groups.length - 1;i >= 0; i--) {
1290
- const [mark] = groups[i];
1291
- for (let j = tokens.length - 1;j >= 0; j--) {
1292
- if (tokens[j].indexOf(mark) !== -1) {
1293
- tokens[j] = tokens[j].replace(mark, groups[i][1]);
1294
- break;
1295
- }
1296
- }
1297
- }
1298
- this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
1299
- return paramAssoc;
1300
- }
1301
- buildRegExp() {
1302
- let regexp = this.#root.buildRegExpStr();
1303
- if (regexp === "") {
1304
- return [/^$/, [], []];
1305
- }
1306
- let captureIndex = 0;
1307
- const indexReplacementMap = [];
1308
- const paramReplacementMap = [];
1309
- regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1310
- if (handlerIndex !== undefined) {
1311
- indexReplacementMap[++captureIndex] = Number(handlerIndex);
1312
- return "$()";
1313
- }
1314
- if (paramIndex !== undefined) {
1315
- paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1316
- return "";
1317
- }
1318
- return "";
1319
- });
1320
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1321
- }
1322
- };
1323
-
1324
- // node_modules/hono/dist/router/reg-exp-router/router.js
1325
- var emptyParam = [];
1326
- var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1327
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1328
- function buildWildcardRegExp(path) {
1329
- return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
1330
- }
1331
- function clearWildcardRegExpCache() {
1332
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1333
- }
1334
- function buildMatcherFromPreprocessedRoutes(routes) {
1335
- const trie = new Trie;
1336
- const handlerData = [];
1337
- if (routes.length === 0) {
1338
- return nullMatcher;
1339
- }
1340
- const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
1341
- const staticMap = /* @__PURE__ */ Object.create(null);
1342
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
1343
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
1344
- if (pathErrorCheckOnly) {
1345
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1346
- } else {
1347
- j++;
1348
- }
1349
- let paramAssoc;
1350
- try {
1351
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
1352
- } catch (e) {
1353
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
1354
- }
1355
- if (pathErrorCheckOnly) {
1356
- continue;
1357
- }
1358
- handlerData[j] = handlers.map(([h, paramCount]) => {
1359
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
1360
- paramCount -= 1;
1361
- for (;paramCount >= 0; paramCount--) {
1362
- const [key, value] = paramAssoc[paramCount];
1363
- paramIndexMap[key] = value;
1364
- }
1365
- return [h, paramIndexMap];
1366
- });
1367
- }
1368
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1369
- for (let i = 0, len = handlerData.length;i < len; i++) {
1370
- for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
1371
- const map = handlerData[i][j]?.[1];
1372
- if (!map) {
1373
- continue;
1374
- }
1375
- const keys = Object.keys(map);
1376
- for (let k = 0, len3 = keys.length;k < len3; k++) {
1377
- map[keys[k]] = paramReplacementMap[map[keys[k]]];
1378
- }
1379
- }
1380
- }
1381
- const handlerMap = [];
1382
- for (const i in indexReplacementMap) {
1383
- handlerMap[i] = handlerData[indexReplacementMap[i]];
1384
- }
1385
- return [regexp, handlerMap, staticMap];
1386
- }
1387
- function findMiddleware(middleware, path) {
1388
- if (!middleware) {
1389
- return;
1390
- }
1391
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1392
- if (buildWildcardRegExp(k).test(path)) {
1393
- return [...middleware[k]];
1394
- }
1395
- }
1396
- return;
1397
- }
1398
- var RegExpRouter = class {
1399
- name = "RegExpRouter";
1400
- #middleware;
1401
- #routes;
1402
- constructor() {
1403
- this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1404
- this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1405
- }
1406
- add(method, path, handler) {
1407
- const middleware = this.#middleware;
1408
- const routes = this.#routes;
1409
- if (!middleware || !routes) {
1410
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1411
- }
1412
- if (!middleware[method]) {
1413
- [middleware, routes].forEach((handlerMap) => {
1414
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
1415
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
1416
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
1417
- });
1418
- });
1419
- }
1420
- if (path === "/*") {
1421
- path = "*";
1422
- }
1423
- const paramCount = (path.match(/\/:/g) || []).length;
1424
- if (/\*$/.test(path)) {
1425
- const re = buildWildcardRegExp(path);
1426
- if (method === METHOD_NAME_ALL) {
1427
- Object.keys(middleware).forEach((m) => {
1428
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1429
- });
1430
- } else {
1431
- middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1432
- }
1433
- Object.keys(middleware).forEach((m) => {
1434
- if (method === METHOD_NAME_ALL || method === m) {
1435
- Object.keys(middleware[m]).forEach((p) => {
1436
- re.test(p) && middleware[m][p].push([handler, paramCount]);
1437
- });
1438
- }
1439
- });
1440
- Object.keys(routes).forEach((m) => {
1441
- if (method === METHOD_NAME_ALL || method === m) {
1442
- Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
1443
- }
1444
- });
1445
- return;
1446
- }
1447
- const paths = checkOptionalParameter(path) || [path];
1448
- for (let i = 0, len = paths.length;i < len; i++) {
1449
- const path2 = paths[i];
1450
- Object.keys(routes).forEach((m) => {
1451
- if (method === METHOD_NAME_ALL || method === m) {
1452
- routes[m][path2] ||= [
1453
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
1454
- ];
1455
- routes[m][path2].push([handler, paramCount - len + i + 1]);
1456
- }
1457
- });
1458
- }
1459
- }
1460
- match(method, path) {
1461
- clearWildcardRegExpCache();
1462
- const matchers = this.#buildAllMatchers();
1463
- this.match = (method2, path2) => {
1464
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
1465
- const staticMatch = matcher[2][path2];
1466
- if (staticMatch) {
1467
- return staticMatch;
1468
- }
1469
- const match = path2.match(matcher[0]);
1470
- if (!match) {
1471
- return [[], emptyParam];
1472
- }
1473
- const index = match.indexOf("", 1);
1474
- return [matcher[1][index], match];
1475
- };
1476
- return this.match(method, path);
1477
- }
1478
- #buildAllMatchers() {
1479
- const matchers = /* @__PURE__ */ Object.create(null);
1480
- Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1481
- matchers[method] ||= this.#buildMatcher(method);
1482
- });
1483
- this.#middleware = this.#routes = undefined;
1484
- return matchers;
1485
- }
1486
- #buildMatcher(method) {
1487
- const routes = [];
1488
- let hasOwnRoute = method === METHOD_NAME_ALL;
1489
- [this.#middleware, this.#routes].forEach((r) => {
1490
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
1491
- if (ownRoute.length !== 0) {
1492
- hasOwnRoute ||= true;
1493
- routes.push(...ownRoute);
1494
- } else if (method !== METHOD_NAME_ALL) {
1495
- routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
1496
- }
1497
- });
1498
- if (!hasOwnRoute) {
1499
- return null;
1500
- } else {
1501
- return buildMatcherFromPreprocessedRoutes(routes);
1502
- }
1503
- }
1504
- };
1505
-
1506
- // node_modules/hono/dist/router/smart-router/router.js
1507
- var SmartRouter = class {
1508
- name = "SmartRouter";
1509
- #routers = [];
1510
- #routes = [];
1511
- constructor(init) {
1512
- this.#routers = init.routers;
1513
- }
1514
- add(method, path, handler) {
1515
- if (!this.#routes) {
1516
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1517
- }
1518
- this.#routes.push([method, path, handler]);
1519
- }
1520
- match(method, path) {
1521
- if (!this.#routes) {
1522
- throw new Error("Fatal error");
1523
- }
1524
- const routers = this.#routers;
1525
- const routes = this.#routes;
1526
- const len = routers.length;
1527
- let i = 0;
1528
- let res;
1529
- for (;i < len; i++) {
1530
- const router = routers[i];
1531
- try {
1532
- for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
1533
- router.add(...routes[i2]);
1534
- }
1535
- res = router.match(method, path);
1536
- } catch (e) {
1537
- if (e instanceof UnsupportedPathError) {
1538
- continue;
1539
- }
1540
- throw e;
1541
- }
1542
- this.match = router.match.bind(router);
1543
- this.#routers = [router];
1544
- this.#routes = undefined;
1545
- break;
1546
- }
1547
- if (i === len) {
1548
- throw new Error("Fatal error");
1549
- }
1550
- this.name = `SmartRouter + ${this.activeRouter.name}`;
1551
- return res;
1552
- }
1553
- get activeRouter() {
1554
- if (this.#routes || this.#routers.length !== 1) {
1555
- throw new Error("No active router has been determined yet.");
1556
- }
1557
- return this.#routers[0];
1558
- }
1559
- };
1560
-
1561
- // node_modules/hono/dist/router/trie-router/node.js
1562
- var emptyParams = /* @__PURE__ */ Object.create(null);
1563
- var Node2 = class {
1564
- #methods;
1565
- #children;
1566
- #patterns;
1567
- #order = 0;
1568
- #params = emptyParams;
1569
- constructor(method, handler, children) {
1570
- this.#children = children || /* @__PURE__ */ Object.create(null);
1571
- this.#methods = [];
1572
- if (method && handler) {
1573
- const m = /* @__PURE__ */ Object.create(null);
1574
- m[method] = { handler, possibleKeys: [], score: 0 };
1575
- this.#methods = [m];
1576
- }
1577
- this.#patterns = [];
1578
- }
1579
- insert(method, path, handler) {
1580
- this.#order = ++this.#order;
1581
- let curNode = this;
1582
- const parts = splitRoutingPath(path);
1583
- const possibleKeys = [];
1584
- for (let i = 0, len = parts.length;i < len; i++) {
1585
- const p = parts[i];
1586
- const nextP = parts[i + 1];
1587
- const pattern2 = getPattern2(p, nextP);
1588
- const key = Array.isArray(pattern2) ? pattern2[0] : p;
1589
- if (Object.keys(curNode.#children).includes(key)) {
1590
- curNode = curNode.#children[key];
1591
- const pattern22 = getPattern2(p, nextP);
1592
- if (pattern22) {
1593
- possibleKeys.push(pattern22[1]);
1594
- }
1595
- continue;
1596
- }
1597
- curNode.#children[key] = new Node2;
1598
- if (pattern2) {
1599
- curNode.#patterns.push(pattern2);
1600
- possibleKeys.push(pattern2[1]);
1601
- }
1602
- curNode = curNode.#children[key];
1603
- }
1604
- const m = /* @__PURE__ */ Object.create(null);
1605
- const handlerSet = {
1606
- handler,
1607
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
1608
- score: this.#order
1609
- };
1610
- m[method] = handlerSet;
1611
- curNode.#methods.push(m);
1612
- return curNode;
1613
- }
1614
- #getHandlerSets(node, method, nodeParams, params) {
1615
- const handlerSets = [];
1616
- for (let i = 0, len = node.#methods.length;i < len; i++) {
1617
- const m = node.#methods[i];
1618
- const handlerSet = m[method] || m[METHOD_NAME_ALL];
1619
- const processedSet = {};
1620
- if (handlerSet !== undefined) {
1621
- handlerSet.params = /* @__PURE__ */ Object.create(null);
1622
- handlerSets.push(handlerSet);
1623
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
1624
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
1625
- const key = handlerSet.possibleKeys[i2];
1626
- const processed = processedSet[handlerSet.score];
1627
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
1628
- processedSet[handlerSet.score] = true;
1629
- }
1630
- }
1631
- }
1632
- }
1633
- return handlerSets;
1634
- }
1635
- search(method, path) {
1636
- const handlerSets = [];
1637
- this.#params = emptyParams;
1638
- const curNode = this;
1639
- let curNodes = [curNode];
1640
- const parts = splitPath(path);
1641
- const curNodesQueue = [];
1642
- for (let i = 0, len = parts.length;i < len; i++) {
1643
- const part = parts[i];
1644
- const isLast = i === len - 1;
1645
- const tempNodes = [];
1646
- for (let j = 0, len2 = curNodes.length;j < len2; j++) {
1647
- const node = curNodes[j];
1648
- const nextNode = node.#children[part];
1649
- if (nextNode) {
1650
- nextNode.#params = node.#params;
1651
- if (isLast) {
1652
- if (nextNode.#children["*"]) {
1653
- handlerSets.push(...this.#getHandlerSets(nextNode.#children["*"], method, node.#params));
1654
- }
1655
- handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
1656
- } else {
1657
- tempNodes.push(nextNode);
1658
- }
1659
- }
1660
- for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
1661
- const pattern2 = node.#patterns[k];
1662
- const params = node.#params === emptyParams ? {} : { ...node.#params };
1663
- if (pattern2 === "*") {
1664
- const astNode = node.#children["*"];
1665
- if (astNode) {
1666
- handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
1667
- astNode.#params = params;
1668
- tempNodes.push(astNode);
1669
- }
1670
- continue;
1671
- }
1672
- if (part === "") {
1673
- continue;
1674
- }
1675
- const [key, name, matcher] = pattern2;
1676
- const child = node.#children[key];
1677
- const restPathString = parts.slice(i).join("/");
1678
- if (matcher instanceof RegExp) {
1679
- const m = matcher.exec(restPathString);
1680
- if (m) {
1681
- params[name] = m[0];
1682
- handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
1683
- if (Object.keys(child.#children).length) {
1684
- child.#params = params;
1685
- const componentCount = m[0].match(/\//)?.length ?? 0;
1686
- const targetCurNodes = curNodesQueue[componentCount] ||= [];
1687
- targetCurNodes.push(child);
1688
- }
1689
- continue;
1690
- }
1691
- }
1692
- if (matcher === true || matcher.test(part)) {
1693
- params[name] = part;
1694
- if (isLast) {
1695
- handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
1696
- if (child.#children["*"]) {
1697
- handlerSets.push(...this.#getHandlerSets(child.#children["*"], method, params, node.#params));
1698
- }
1699
- } else {
1700
- child.#params = params;
1701
- tempNodes.push(child);
1702
- }
1703
- }
1704
- }
1705
- }
1706
- curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
1707
- }
1708
- if (handlerSets.length > 1) {
1709
- handlerSets.sort((a, b) => {
1710
- return a.score - b.score;
1711
- });
1712
- }
1713
- return [handlerSets.map(({ handler, params }) => [handler, params])];
1714
- }
1715
- };
1716
-
1717
- // node_modules/hono/dist/router/trie-router/router.js
1718
- var TrieRouter = class {
1719
- name = "TrieRouter";
1720
- #node;
1721
- constructor() {
1722
- this.#node = new Node2;
1723
- }
1724
- add(method, path, handler) {
1725
- const results = checkOptionalParameter(path);
1726
- if (results) {
1727
- for (let i = 0, len = results.length;i < len; i++) {
1728
- this.#node.insert(method, results[i], handler);
1729
- }
1730
- return;
1731
- }
1732
- this.#node.insert(method, path, handler);
1733
- }
1734
- match(method, path) {
1735
- return this.#node.search(method, path);
1736
- }
1737
- };
1738
-
1739
- // node_modules/hono/dist/hono.js
1740
- var Hono2 = class extends Hono {
1741
- constructor(options = {}) {
1742
- super(options);
1743
- this.router = options.router ?? new SmartRouter({
1744
- routers: [new RegExpRouter, new TrieRouter]
1745
- });
1746
- }
1747
- };
1748
-
1749
- // node_modules/hono/dist/adapter/bun/serve-static.js
1750
- import { stat } from "node:fs/promises";
1751
-
1752
- // node_modules/hono/dist/utils/compress.js
1753
- var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
1754
-
1755
- // node_modules/hono/dist/utils/filepath.js
1756
- var getFilePath = (options) => {
1757
- let filename = options.filename;
1758
- const defaultDocument = options.defaultDocument || "index.html";
1759
- if (filename.endsWith("/")) {
1760
- filename = filename.concat(defaultDocument);
1761
- } else if (!filename.match(/\.[a-zA-Z0-9_-]+$/)) {
1762
- filename = filename.concat("/" + defaultDocument);
1763
- }
1764
- const path = getFilePathWithoutDefaultDocument({
1765
- root: options.root,
1766
- filename
1767
- });
1768
- return path;
1769
- };
1770
- var getFilePathWithoutDefaultDocument = (options) => {
1771
- let root = options.root || "";
1772
- let filename = options.filename;
1773
- if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {
1774
- return;
1775
- }
1776
- filename = filename.replace(/^\.?[\/\\]/, "");
1777
- filename = filename.replace(/\\/, "/");
1778
- root = root.replace(/\/$/, "");
1779
- let path = root ? root + "/" + filename : filename;
1780
- path = path.replace(/^\.?\//, "");
1781
- if (root[0] !== "/" && path[0] === "/") {
1782
- return;
1783
- }
1784
- return path;
1785
- };
1786
-
1787
- // node_modules/hono/dist/utils/mime.js
1788
- var getMimeType = (filename, mimes = baseMimes) => {
1789
- const regexp = /\.([a-zA-Z0-9]+?)$/;
1790
- const match = filename.match(regexp);
1791
- if (!match) {
1792
- return;
1793
- }
1794
- let mimeType = mimes[match[1]];
1795
- if (mimeType && mimeType.startsWith("text")) {
1796
- mimeType += "; charset=utf-8";
1797
- }
1798
- return mimeType;
1799
- };
1800
- var _baseMimes = {
1801
- aac: "audio/aac",
1802
- avi: "video/x-msvideo",
1803
- avif: "image/avif",
1804
- av1: "video/av1",
1805
- bin: "application/octet-stream",
1806
- bmp: "image/bmp",
1807
- css: "text/css",
1808
- csv: "text/csv",
1809
- eot: "application/vnd.ms-fontobject",
1810
- epub: "application/epub+zip",
1811
- gif: "image/gif",
1812
- gz: "application/gzip",
1813
- htm: "text/html",
1814
- html: "text/html",
1815
- ico: "image/x-icon",
1816
- ics: "text/calendar",
1817
- jpeg: "image/jpeg",
1818
- jpg: "image/jpeg",
1819
- js: "text/javascript",
1820
- json: "application/json",
1821
- jsonld: "application/ld+json",
1822
- map: "application/json",
1823
- mid: "audio/x-midi",
1824
- midi: "audio/x-midi",
1825
- mjs: "text/javascript",
1826
- mp3: "audio/mpeg",
1827
- mp4: "video/mp4",
1828
- mpeg: "video/mpeg",
1829
- oga: "audio/ogg",
1830
- ogv: "video/ogg",
1831
- ogx: "application/ogg",
1832
- opus: "audio/opus",
1833
- otf: "font/otf",
1834
- pdf: "application/pdf",
1835
- png: "image/png",
1836
- rtf: "application/rtf",
1837
- svg: "image/svg+xml",
1838
- tif: "image/tiff",
1839
- tiff: "image/tiff",
1840
- ts: "video/mp2t",
1841
- ttf: "font/ttf",
1842
- txt: "text/plain",
1843
- wasm: "application/wasm",
1844
- webm: "video/webm",
1845
- weba: "audio/webm",
1846
- webp: "image/webp",
1847
- woff: "font/woff",
1848
- woff2: "font/woff2",
1849
- xhtml: "application/xhtml+xml",
1850
- xml: "application/xml",
1851
- zip: "application/zip",
1852
- "3gp": "video/3gpp",
1853
- "3g2": "video/3gpp2",
1854
- gltf: "model/gltf+json",
1855
- glb: "model/gltf-binary"
1856
- };
1857
- var baseMimes = _baseMimes;
1858
-
1859
- // node_modules/hono/dist/middleware/serve-static/index.js
1860
- var ENCODINGS = {
1861
- br: ".br",
1862
- zstd: ".zst",
1863
- gzip: ".gz"
1864
- };
1865
- var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
1866
- var DEFAULT_DOCUMENT = "index.html";
1867
- var defaultPathResolve = (path) => path;
1868
- var serveStatic = (options) => {
1869
- let isAbsoluteRoot = false;
1870
- let root;
1871
- if (options.root) {
1872
- if (options.root.startsWith("/")) {
1873
- isAbsoluteRoot = true;
1874
- root = new URL(`file://${options.root}`).pathname;
1875
- } else {
1876
- root = options.root;
1877
- }
1878
- }
1879
- return async (c, next) => {
1880
- if (c.finalized) {
1881
- await next();
1882
- return;
1883
- }
1884
- let filename = options.path ?? decodeURI(c.req.path);
1885
- filename = options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename;
1886
- if (!filename.endsWith("/") && options.isDir) {
1887
- const path2 = getFilePathWithoutDefaultDocument({
1888
- filename,
1889
- root
1890
- });
1891
- if (path2 && await options.isDir(path2)) {
1892
- filename += "/";
1893
- }
1894
- }
1895
- let path = getFilePath({
1896
- filename,
1897
- root,
1898
- defaultDocument: DEFAULT_DOCUMENT
1899
- });
1900
- if (!path) {
1901
- return await next();
1902
- }
1903
- if (isAbsoluteRoot) {
1904
- path = "/" + path;
1905
- }
1906
- const getContent = options.getContent;
1907
- const pathResolve = options.pathResolve ?? defaultPathResolve;
1908
- path = pathResolve(path);
1909
- let content = await getContent(path, c);
1910
- if (!content) {
1911
- let pathWithoutDefaultDocument = getFilePathWithoutDefaultDocument({
1912
- filename,
1913
- root
1914
- });
1915
- if (!pathWithoutDefaultDocument) {
1916
- return await next();
1917
- }
1918
- pathWithoutDefaultDocument = pathResolve(pathWithoutDefaultDocument);
1919
- if (pathWithoutDefaultDocument !== path) {
1920
- content = await getContent(pathWithoutDefaultDocument, c);
1921
- if (content) {
1922
- path = pathWithoutDefaultDocument;
1923
- }
1924
- }
1925
- }
1926
- if (content instanceof Response) {
1927
- return c.newResponse(content.body, content);
1928
- }
1929
- if (content) {
1930
- const mimeType = options.mimes && getMimeType(path, options.mimes) || getMimeType(path);
1931
- c.header("Content-Type", mimeType || "application/octet-stream");
1932
- if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
1933
- const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
1934
- for (const encoding of ENCODINGS_ORDERED_KEYS) {
1935
- if (!acceptEncodingSet.has(encoding)) {
1936
- continue;
1937
- }
1938
- const compressedContent = await getContent(path + ENCODINGS[encoding], c);
1939
- if (compressedContent) {
1940
- content = compressedContent;
1941
- c.header("Content-Encoding", encoding);
1942
- c.header("Vary", "Accept-Encoding", { append: true });
1943
- break;
1944
- }
1945
- }
1946
- }
1947
- await options.onFound?.(path, c);
1948
- return c.body(content);
1949
- }
1950
- await options.onNotFound?.(path, c);
1951
- await next();
1952
- return;
1953
- };
1954
- };
1955
-
1956
- // node_modules/hono/dist/adapter/bun/serve-static.js
1957
- var serveStatic2 = (options) => {
1958
- return async function serveStatic2(c, next) {
1959
- const getContent = async (path) => {
1960
- path = path.startsWith("/") ? path : `./${path}`;
1961
- const file = Bun.file(path);
1962
- return await file.exists() ? file : null;
1963
- };
1964
- const pathResolve = (path) => {
1965
- return path.startsWith("/") ? path : `./${path}`;
1966
- };
1967
- const isDir = async (path) => {
1968
- let isDir2;
1969
- try {
1970
- const stats = await stat(path);
1971
- isDir2 = stats.isDirectory();
1972
- } catch {}
1973
- return isDir2;
1974
- };
1975
- return serveStatic({
1976
- ...options,
1977
- getContent,
1978
- pathResolve,
1979
- isDir
1980
- })(c, next);
1981
- };
1982
- };
1983
-
1984
- // node_modules/hono/dist/helper/ssg/middleware.js
1985
- var X_HONO_DISABLE_SSG_HEADER_KEY = "x-hono-disable-ssg";
1986
- var SSG_DISABLED_RESPONSE = (() => {
1987
- try {
1988
- return new Response("SSG is disabled", {
1989
- status: 404,
1990
- headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: "true" }
1991
- });
1992
- } catch {
1993
- return null;
1994
- }
1995
- })();
1996
- // node_modules/hono/dist/adapter/bun/ssg.js
1997
- var { write } = Bun;
1998
-
1999
- // node_modules/hono/dist/helper/websocket/index.js
2000
- var WSContext = class {
2001
- #init;
2002
- constructor(init) {
2003
- this.#init = init;
2004
- this.raw = init.raw;
2005
- this.url = init.url ? new URL(init.url) : null;
2006
- this.protocol = init.protocol ?? null;
2007
- }
2008
- send(source, options) {
2009
- this.#init.send(source, options ?? {});
2010
- }
2011
- raw;
2012
- binaryType = "arraybuffer";
2013
- get readyState() {
2014
- return this.#init.readyState;
2015
- }
2016
- url;
2017
- protocol;
2018
- close(code, reason) {
2019
- this.#init.close(code, reason);
2020
- }
2021
- };
2022
-
2023
- // node_modules/@zod/core/dist/esm/core.js
2024
- var $brand = Symbol("zod_brand");
2025
-
2026
- class $ZodAsyncError extends Error {
2027
- constructor() {
2028
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
2029
- }
2030
- }
2031
- var globalConfig = {};
2032
- function config(config2) {
2033
- if (config2)
2034
- Object.assign(globalConfig, config2);
2035
- return globalConfig;
2036
- }
2037
-
2038
- // node_modules/@zod/core/dist/esm/util.js
2039
- function jsonStringifyReplacer(_, value) {
2040
- if (typeof value === "bigint")
2041
- return value.toString();
2042
- return value;
2043
- }
2044
- function cached(getter) {
2045
- const set = false;
2046
- return {
2047
- get value() {
2048
- if (!set) {
2049
- const value = getter();
2050
- Object.defineProperty(this, "value", { value });
2051
- return value;
2052
- }
2053
- throw new Error("cached value already set");
2054
- }
2055
- };
2056
- }
2057
- var allowsEval = cached(() => {
2058
- try {
2059
- new Function("");
2060
- return true;
2061
- } catch (_) {
2062
- return false;
2063
- }
2064
- });
2065
- var propertyKeyTypes = new Set(["string", "number", "symbol"]);
2066
- var primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
2067
- var NUMBER_FORMAT_RANGES = {
2068
- safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
2069
- int32: [-2147483648, 2147483647],
2070
- uint32: [0, 4294967295],
2071
- float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
2072
- float64: [-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000]
2073
- };
2074
- function unwrapMessage(message) {
2075
- return typeof message === "string" ? message : message?.message;
2076
- }
2077
- function finalizeIssue(iss, ctx, config2) {
2078
- const full = { ...iss, path: iss.path ?? [] };
2079
- if (!iss.message) {
2080
- const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
2081
- full.message = message;
2082
- }
2083
- delete full.inst;
2084
- delete full.continue;
2085
- if (!ctx?.reportInput) {
2086
- delete full.input;
2087
- }
2088
- return full;
2089
- }
2090
-
2091
- // node_modules/@zod/core/dist/esm/errors.js
2092
- var ZOD_ERROR = Symbol.for("{{zod.error}}");
2093
-
2094
- class $ZodError {
2095
- get message() {
2096
- return JSON.stringify(this.issues, jsonStringifyReplacer, 2);
2097
- }
2098
- constructor(issues) {
2099
- Object.defineProperty(this, "_tag", { value: ZOD_ERROR, enumerable: false });
2100
- Object.defineProperty(this, "name", { value: "$ZodError", enumerable: false });
2101
- this.issues = issues;
2102
- }
2103
- static [Symbol.hasInstance](inst) {
2104
- return inst?._tag === ZOD_ERROR;
2105
- }
2106
- }
2107
- function flattenError(error, mapper = (issue) => issue.message) {
2108
- const fieldErrors = {};
2109
- const formErrors = [];
2110
- for (const sub of error.issues) {
2111
- if (sub.path.length > 0) {
2112
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
2113
- fieldErrors[sub.path[0]].push(mapper(sub));
2114
- } else {
2115
- formErrors.push(mapper(sub));
2116
- }
2117
- }
2118
- return { formErrors, fieldErrors };
2119
- }
2120
- function formatError(error, _mapper) {
2121
- const mapper = _mapper || function(issue) {
2122
- return issue.message;
2123
- };
2124
- const fieldErrors = { _errors: [] };
2125
- const processError = (error2) => {
2126
- for (const issue of error2.issues) {
2127
- if (issue.code === "invalid_union") {
2128
- issue.errors.map((issues) => processError({ issues }));
2129
- } else if (issue.code === "invalid_key") {
2130
- processError({ issues: issue.issues });
2131
- } else if (issue.code === "invalid_element") {
2132
- processError({ issues: issue.issues });
2133
- } else if (issue.path.length === 0) {
2134
- fieldErrors._errors.push(mapper(issue));
2135
- } else {
2136
- let curr = fieldErrors;
2137
- let i = 0;
2138
- while (i < issue.path.length) {
2139
- const el = issue.path[i];
2140
- const terminal = i === issue.path.length - 1;
2141
- if (!terminal) {
2142
- curr[el] = curr[el] || { _errors: [] };
2143
- } else {
2144
- curr[el] = curr[el] || { _errors: [] };
2145
- curr[el]._errors.push(mapper(issue));
2146
- }
2147
- curr = curr[el];
2148
- i++;
2149
- }
2150
- }
2151
- }
2152
- };
2153
- processError(error);
2154
- return fieldErrors;
2155
- }
2156
-
2157
- // node_modules/@zod/core/dist/esm/parse.js
2158
- function _parse(schema, value, _ctx) {
2159
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
2160
- const result = schema._zod.run({ value, issues: [] }, ctx);
2161
- if (result instanceof Promise) {
2162
- throw new $ZodAsyncError;
2163
- }
2164
- if (result.issues.length) {
2165
- throw new (this?.Error ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
2166
- }
2167
- return result.value;
2168
- }
2169
-
2170
- // node_modules/zod/dist/esm/errors.js
2171
- class ZodError extends $ZodError {
2172
- format(mapper) {
2173
- return formatError(this, mapper);
2174
- }
2175
- flatten(mapper) {
2176
- return flattenError(this, mapper);
2177
- }
2178
- addIssue(issue) {
2179
- this.issues.push(issue);
2180
- }
2181
- addIssues(issues) {
2182
- this.issues.push(...issues);
2183
- }
2184
- get isEmpty() {
2185
- return this.issues.length === 0;
2186
- }
2187
- }
2188
-
2189
- // node_modules/zod/dist/esm/parse.js
2190
- var parse = /* @__PURE__ */ _parse.bind({ Error: ZodError });
2191
-
2192
- // src/server.ts
2193
- var IS_PROD2 = false;
2194
- var CWD = process.cwd();
2195
- function createRoute(handler) {
2196
- return new HSRoute(handler);
2197
- }
2198
- function createComponent(render2) {
2199
- return new HSComponent(render2);
2200
- }
2201
- function createForm(renderForm, schema) {
2202
- return new HSFormRoute(renderForm, schema);
2203
- }
2204
- var HS_DEFAULT_LOADING = () => html`<div>Loading...</div>`;
2205
-
2206
- class HSComponent {
2207
- _kind = "hsComponent";
2208
- _handlers = {};
2209
- _loading;
2210
- render;
2211
- constructor(render2) {
2212
- this.render = render2;
2213
- }
2214
- loading(fn) {
2215
- this._loading = fn;
2216
- return this;
2217
- }
2218
- }
2219
-
2220
- class HSRoute {
2221
- _kind = "hsRoute";
2222
- _handlers = {};
2223
- _methods = null;
2224
- constructor(handler) {
2225
- this._handlers.GET = handler;
2226
- }
2227
- }
2228
-
2229
- class HSFormRoute {
2230
- _kind = "hsFormRoute";
2231
- _handlers = {};
2232
- _form;
2233
- _methods = null;
2234
- _schema = null;
2235
- constructor(renderForm, schema = null) {
2236
- if (schema) {
2237
- this._form = renderForm;
2238
- this._schema = schema;
2239
- } else {
2240
- this._form = renderForm;
2241
- }
2242
- this._handlers.GET = () => renderForm(this.getDefaultData());
2243
- }
2244
- getDefaultData() {
2245
- if (!this._schema) {
2246
- return {};
2247
- }
2248
- const data = parse(this._schema, {});
2249
- return data;
2250
- }
2251
- renderForm(data) {
2252
- return this._form(data || this.getDefaultData());
2253
- }
2254
- get(handler) {
2255
- this._handlers.GET = handler;
2256
- return this;
2257
- }
2258
- patch(handler) {
2259
- this._handlers.PATCH = handler;
2260
- return this;
2261
- }
2262
- post(handler) {
2263
- this._handlers.POST = handler;
2264
- return this;
2265
- }
2266
- put(handler) {
2267
- this._handlers.PUT = handler;
2268
- return this;
2269
- }
2270
- delete(handler) {
2271
- this._handlers.DELETE = handler;
2272
- return this;
2273
- }
2274
- }
2275
- async function runFileRoute(RouteModule, context) {
2276
- const req = context.req;
2277
- const url = new URL(req.url);
2278
- const qs = url.searchParams;
2279
- const userIsBot = isbot(context.req.header("User-Agent"));
2280
- const streamOpt = qs.get("__nostream") ? !Boolean(qs.get("__nostream")) : undefined;
2281
- const streamingEnabled = !userIsBot && (streamOpt !== undefined ? streamOpt : true);
2282
- const RouteComponent = RouteModule.default;
2283
- const reqMethod = req.method.toUpperCase();
2284
- try {
2285
- if (RouteModule[reqMethod] !== undefined) {
2286
- return await runAPIRoute(RouteModule[reqMethod], context);
2287
- }
2288
- let routeContent;
2289
- if (!RouteComponent) {
2290
- throw new Error("No route was exported by default in matched route file.");
2291
- }
2292
- if (typeof RouteComponent._handlers !== "undefined") {
2293
- const routeMethodHandler = RouteComponent._handlers[reqMethod];
2294
- if (!routeMethodHandler) {
2295
- return new Response("Method Not Allowed", {
2296
- status: 405,
2297
- headers: { "content-type": "text/plain" }
2298
- });
2299
- }
2300
- routeContent = await routeMethodHandler(context);
2301
- } else {
2302
- routeContent = await RouteComponent(context);
2303
- }
2304
- if (routeContent instanceof Response) {
2305
- return routeContent;
2306
- }
2307
- let routeKind = typeof routeContent;
2308
- if (routeKind === "object" && (routeContent instanceof TmplHtml || routeContent.constructor.name === "TmplHtml" || routeContent?._kind === "TmplHtml")) {
2309
- if (streamingEnabled) {
2310
- return new StreamResponse(renderStream(routeContent));
2311
- } else {
2312
- const output = await renderAsync(routeContent);
2313
- return context.html(output);
2314
- }
2315
- }
2316
- console.log("Returning unknown type... ", routeContent);
2317
- return routeContent;
2318
- } catch (e) {
2319
- console.error(e);
2320
- return await showErrorReponse(context, e);
2321
- }
2322
- }
2323
- async function runAPIRoute(routeFn, context, middlewareResult) {
2324
- try {
2325
- return await routeFn(context, middlewareResult);
2326
- } catch (err) {
2327
- const e = err;
2328
- console.error(e);
2329
- return context.json({
2330
- meta: { success: false },
2331
- data: {
2332
- message: e.message,
2333
- stack: IS_PROD2 ? undefined : e.stack?.split(`
2334
- `)
2335
- }
2336
- }, { status: 500 });
2337
- }
2338
- }
2339
- async function showErrorReponse(context, err) {
2340
- const output = render(html`
2341
- <main>
2342
- <h1>Error</h1>
2343
- <pre>${err.message}</pre>
2344
- <pre>${!IS_PROD2 && err.stack ? err.stack.split(`
2345
- `).slice(1).join(`
2346
- `) : ""}</pre>
2347
- </main>
2348
- `);
2349
- return context.html(output, {
2350
- status: 500
2351
- });
2352
- }
2353
- var ROUTE_SEGMENT = /(\[[a-zA-Z_\.]+\])/g;
2354
- async function buildRoutes(config2) {
2355
- const routesDir = join(config2.appDir, "routes");
2356
- console.log(routesDir);
2357
- const files = await readdir2(routesDir, { recursive: true });
2358
- const routes = [];
2359
- for (const file of files) {
2360
- if (!file.includes(".") || basename(file).startsWith(".")) {
2361
- continue;
2362
- }
2363
- let route = "/" + file.replace(extname(file), "");
2364
- if (route.endsWith("index")) {
2365
- route = route === "index" ? "/" : route.substring(0, route.length - 6);
2366
- }
2367
- let params = [];
2368
- const dynamicPaths = ROUTE_SEGMENT.test(route);
2369
- if (dynamicPaths) {
2370
- params = [];
2371
- route = route.replace(ROUTE_SEGMENT, (match) => {
2372
- const paramName = match.replace(/[^a-zA-Z_\.]+/g, "");
2373
- if (match.includes("...")) {
2374
- params.push(paramName.replace("...", ""));
2375
- return "*";
2376
- } else {
2377
- params.push(paramName);
2378
- return ":" + paramName;
2379
- }
2380
- });
2381
- }
2382
- routes.push({
2383
- file: join("./", routesDir, file),
2384
- route: route || "/",
2385
- params
2386
- });
2387
- }
2388
- return routes;
2389
- }
2390
- async function createServer(config2) {
2391
- await Promise.all([buildClientJS(), buildClientCSS()]);
2392
- const app = new Hono2;
2393
- config2.beforeRoutesAdded && config2.beforeRoutesAdded(app);
2394
- const fileRoutes = await buildRoutes(config2);
2395
- const routeMap = [];
2396
- for (let i = 0;i < fileRoutes.length; i++) {
2397
- let route = fileRoutes[i];
2398
- const fullRouteFile = join(CWD, route.file);
2399
- const routePattern = normalizePath(route.route);
2400
- routeMap.push({ route: routePattern, file: route.file });
2401
- const routeModule = await import(fullRouteFile);
2402
- app.all(routePattern, async (context) => {
2403
- const matchedRoute = await runFileRoute(routeModule, context);
2404
- if (matchedRoute) {
2405
- return matchedRoute;
2406
- }
2407
- return context.notFound();
2408
- });
2409
- }
2410
- if (routeMap.length === 0) {
2411
- app.get("/", (context) => {
2412
- return context.text("No routes found. Add routes to app/routes. Example: `app/routes/index.ts`", { status: 404 });
2413
- });
2414
- }
2415
- if (!IS_PROD2) {
2416
- console.log("[Hyperspan] File system routes (in app/routes):");
2417
- console.table(routeMap);
2418
- }
2419
- config2.afterRoutesAdded && config2.afterRoutesAdded(app);
2420
- app.use("*", serveStatic2({
2421
- root: config2.staticFileRoot
2422
- }));
2423
- app.notFound((context) => {
2424
- return context.text("Not... found?", { status: 404 });
2425
- });
2426
- return app;
2427
- }
2428
-
2429
- class StreamResponse extends Response {
2430
- constructor(iterator, options = {}) {
2431
- super();
2432
- const stream = createReadableStreamFromAsyncGenerator(iterator);
2433
- return new Response(stream, {
2434
- status: 200,
2435
- headers: {
2436
- "Content-Type": "text/html",
2437
- "Transfer-Encoding": "chunked",
2438
- ...options?.headers ?? {}
2439
- },
2440
- ...options
2441
- });
2442
- }
2443
- }
2444
- function createReadableStreamFromAsyncGenerator(output) {
2445
- const encoder = new TextEncoder;
2446
- return new ReadableStream({
2447
- async start(controller) {
2448
- while (true) {
2449
- const { done, value } = await output.next();
2450
- if (done) {
2451
- controller.close();
2452
- break;
2453
- }
2454
- controller.enqueue(encoder.encode(value));
2455
- }
2456
- }
2457
- });
2458
- }
2459
- function normalizePath(urlPath) {
2460
- return (urlPath.endsWith("/") ? urlPath.substring(0, urlPath.length - 1) : urlPath).toLowerCase() || "/";
2461
- }
2462
- export {
2463
- runFileRoute,
2464
- normalizePath,
2465
- createServer,
2466
- createRoute,
2467
- createReadableStreamFromAsyncGenerator,
2468
- createForm,
2469
- createComponent,
2470
- buildRoutes,
2471
- StreamResponse,
2472
- IS_PROD2 as IS_PROD,
2473
- HS_DEFAULT_LOADING,
2474
- HSRoute,
2475
- HSFormRoute,
2476
- HSComponent
2477
- };