@hasna/logs 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1862 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ import {
4
+ startScheduler
5
+ } from "../index-dh02dp7n.js";
6
+ import {
7
+ createPage,
8
+ createProject,
9
+ getDb,
10
+ getLatestSnapshot,
11
+ getLogContext,
12
+ getPerfTrend,
13
+ getProject,
14
+ ingestBatch,
15
+ ingestLog,
16
+ listPages,
17
+ listProjects,
18
+ searchLogs,
19
+ summarizeLogs,
20
+ tailLogs,
21
+ updateProject
22
+ } from "../index-zj6ymcv7.js";
23
+ import {
24
+ createJob,
25
+ deleteJob,
26
+ listJobs,
27
+ updateJob
28
+ } from "../index-4mnved04.js";
29
+
30
+ // node_modules/hono/dist/compose.js
31
+ var compose = (middleware, onError, onNotFound) => {
32
+ return (context, next) => {
33
+ let index = -1;
34
+ return dispatch(0);
35
+ async function dispatch(i) {
36
+ if (i <= index) {
37
+ throw new Error("next() called multiple times");
38
+ }
39
+ index = i;
40
+ let res;
41
+ let isError = false;
42
+ let handler;
43
+ if (middleware[i]) {
44
+ handler = middleware[i][0][0];
45
+ context.req.routeIndex = i;
46
+ } else {
47
+ handler = i === middleware.length && next || undefined;
48
+ }
49
+ if (handler) {
50
+ try {
51
+ res = await handler(context, () => dispatch(i + 1));
52
+ } catch (err) {
53
+ if (err instanceof Error && onError) {
54
+ context.error = err;
55
+ res = await onError(err, context);
56
+ isError = true;
57
+ } else {
58
+ throw err;
59
+ }
60
+ }
61
+ } else {
62
+ if (context.finalized === false && onNotFound) {
63
+ res = await onNotFound(context);
64
+ }
65
+ }
66
+ if (res && (context.finalized === false || isError)) {
67
+ context.res = res;
68
+ }
69
+ return context;
70
+ }
71
+ };
72
+ };
73
+
74
+ // node_modules/hono/dist/request/constants.js
75
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
76
+
77
+ // node_modules/hono/dist/utils/body.js
78
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
79
+ const { all = false, dot = false } = options;
80
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
81
+ const contentType = headers.get("Content-Type");
82
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
83
+ return parseFormData(request, { all, dot });
84
+ }
85
+ return {};
86
+ };
87
+ async function parseFormData(request, options) {
88
+ const formData = await request.formData();
89
+ if (formData) {
90
+ return convertFormDataToBodyData(formData, options);
91
+ }
92
+ return {};
93
+ }
94
+ function convertFormDataToBodyData(formData, options) {
95
+ const form = /* @__PURE__ */ Object.create(null);
96
+ formData.forEach((value, key) => {
97
+ const shouldParseAllValues = options.all || key.endsWith("[]");
98
+ if (!shouldParseAllValues) {
99
+ form[key] = value;
100
+ } else {
101
+ handleParsingAllValues(form, key, value);
102
+ }
103
+ });
104
+ if (options.dot) {
105
+ Object.entries(form).forEach(([key, value]) => {
106
+ const shouldParseDotValues = key.includes(".");
107
+ if (shouldParseDotValues) {
108
+ handleParsingNestedValues(form, key, value);
109
+ delete form[key];
110
+ }
111
+ });
112
+ }
113
+ return form;
114
+ }
115
+ var handleParsingAllValues = (form, key, value) => {
116
+ if (form[key] !== undefined) {
117
+ if (Array.isArray(form[key])) {
118
+ form[key].push(value);
119
+ } else {
120
+ form[key] = [form[key], value];
121
+ }
122
+ } else {
123
+ if (!key.endsWith("[]")) {
124
+ form[key] = value;
125
+ } else {
126
+ form[key] = [value];
127
+ }
128
+ }
129
+ };
130
+ var handleParsingNestedValues = (form, key, value) => {
131
+ if (/(?:^|\.)__proto__\./.test(key)) {
132
+ return;
133
+ }
134
+ let nestedForm = form;
135
+ const keys = key.split(".");
136
+ keys.forEach((key2, index) => {
137
+ if (index === keys.length - 1) {
138
+ nestedForm[key2] = value;
139
+ } else {
140
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
141
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
142
+ }
143
+ nestedForm = nestedForm[key2];
144
+ }
145
+ });
146
+ };
147
+
148
+ // node_modules/hono/dist/utils/url.js
149
+ var splitPath = (path) => {
150
+ const paths = path.split("/");
151
+ if (paths[0] === "") {
152
+ paths.shift();
153
+ }
154
+ return paths;
155
+ };
156
+ var splitRoutingPath = (routePath) => {
157
+ const { groups, path } = extractGroupsFromPath(routePath);
158
+ const paths = splitPath(path);
159
+ return replaceGroupMarks(paths, groups);
160
+ };
161
+ var extractGroupsFromPath = (path) => {
162
+ const groups = [];
163
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
164
+ const mark = `@${index}`;
165
+ groups.push([mark, match]);
166
+ return mark;
167
+ });
168
+ return { groups, path };
169
+ };
170
+ var replaceGroupMarks = (paths, groups) => {
171
+ for (let i = groups.length - 1;i >= 0; i--) {
172
+ const [mark] = groups[i];
173
+ for (let j = paths.length - 1;j >= 0; j--) {
174
+ if (paths[j].includes(mark)) {
175
+ paths[j] = paths[j].replace(mark, groups[i][1]);
176
+ break;
177
+ }
178
+ }
179
+ }
180
+ return paths;
181
+ };
182
+ var patternCache = {};
183
+ var getPattern = (label, next) => {
184
+ if (label === "*") {
185
+ return "*";
186
+ }
187
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
188
+ if (match) {
189
+ const cacheKey = `${label}#${next}`;
190
+ if (!patternCache[cacheKey]) {
191
+ if (match[2]) {
192
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
193
+ } else {
194
+ patternCache[cacheKey] = [label, match[1], true];
195
+ }
196
+ }
197
+ return patternCache[cacheKey];
198
+ }
199
+ return null;
200
+ };
201
+ var tryDecode = (str, decoder) => {
202
+ try {
203
+ return decoder(str);
204
+ } catch {
205
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
206
+ try {
207
+ return decoder(match);
208
+ } catch {
209
+ return match;
210
+ }
211
+ });
212
+ }
213
+ };
214
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
215
+ var getPath = (request) => {
216
+ const url = request.url;
217
+ const start = url.indexOf("/", url.indexOf(":") + 4);
218
+ let i = start;
219
+ for (;i < url.length; i++) {
220
+ const charCode = url.charCodeAt(i);
221
+ if (charCode === 37) {
222
+ const queryIndex = url.indexOf("?", i);
223
+ const hashIndex = url.indexOf("#", i);
224
+ const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
225
+ const path = url.slice(start, end);
226
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
227
+ } else if (charCode === 63 || charCode === 35) {
228
+ break;
229
+ }
230
+ }
231
+ return url.slice(start, i);
232
+ };
233
+ var getPathNoStrict = (request) => {
234
+ const result = getPath(request);
235
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
236
+ };
237
+ var mergePath = (base, sub, ...rest) => {
238
+ if (rest.length) {
239
+ sub = mergePath(sub, ...rest);
240
+ }
241
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
242
+ };
243
+ var checkOptionalParameter = (path) => {
244
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
245
+ return null;
246
+ }
247
+ const segments = path.split("/");
248
+ const results = [];
249
+ let basePath = "";
250
+ segments.forEach((segment) => {
251
+ if (segment !== "" && !/\:/.test(segment)) {
252
+ basePath += "/" + segment;
253
+ } else if (/\:/.test(segment)) {
254
+ if (/\?/.test(segment)) {
255
+ if (results.length === 0 && basePath === "") {
256
+ results.push("/");
257
+ } else {
258
+ results.push(basePath);
259
+ }
260
+ const optionalSegment = segment.replace("?", "");
261
+ basePath += "/" + optionalSegment;
262
+ results.push(basePath);
263
+ } else {
264
+ basePath += "/" + segment;
265
+ }
266
+ }
267
+ });
268
+ return results.filter((v, i, a) => a.indexOf(v) === i);
269
+ };
270
+ var _decodeURI = (value) => {
271
+ if (!/[%+]/.test(value)) {
272
+ return value;
273
+ }
274
+ if (value.indexOf("+") !== -1) {
275
+ value = value.replace(/\+/g, " ");
276
+ }
277
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
278
+ };
279
+ var _getQueryParam = (url, key, multiple) => {
280
+ let encoded;
281
+ if (!multiple && key && !/[%+]/.test(key)) {
282
+ let keyIndex2 = url.indexOf("?", 8);
283
+ if (keyIndex2 === -1) {
284
+ return;
285
+ }
286
+ if (!url.startsWith(key, keyIndex2 + 1)) {
287
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
288
+ }
289
+ while (keyIndex2 !== -1) {
290
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
291
+ if (trailingKeyCode === 61) {
292
+ const valueIndex = keyIndex2 + key.length + 2;
293
+ const endIndex = url.indexOf("&", valueIndex);
294
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
295
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
296
+ return "";
297
+ }
298
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
299
+ }
300
+ encoded = /[%+]/.test(url);
301
+ if (!encoded) {
302
+ return;
303
+ }
304
+ }
305
+ const results = {};
306
+ encoded ??= /[%+]/.test(url);
307
+ let keyIndex = url.indexOf("?", 8);
308
+ while (keyIndex !== -1) {
309
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
310
+ let valueIndex = url.indexOf("=", keyIndex);
311
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
312
+ valueIndex = -1;
313
+ }
314
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
315
+ if (encoded) {
316
+ name = _decodeURI(name);
317
+ }
318
+ keyIndex = nextKeyIndex;
319
+ if (name === "") {
320
+ continue;
321
+ }
322
+ let value;
323
+ if (valueIndex === -1) {
324
+ value = "";
325
+ } else {
326
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
327
+ if (encoded) {
328
+ value = _decodeURI(value);
329
+ }
330
+ }
331
+ if (multiple) {
332
+ if (!(results[name] && Array.isArray(results[name]))) {
333
+ results[name] = [];
334
+ }
335
+ results[name].push(value);
336
+ } else {
337
+ results[name] ??= value;
338
+ }
339
+ }
340
+ return key ? results[key] : results;
341
+ };
342
+ var getQueryParam = _getQueryParam;
343
+ var getQueryParams = (url, key) => {
344
+ return _getQueryParam(url, key, true);
345
+ };
346
+ var decodeURIComponent_ = decodeURIComponent;
347
+
348
+ // node_modules/hono/dist/request.js
349
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
350
+ var HonoRequest = class {
351
+ raw;
352
+ #validatedData;
353
+ #matchResult;
354
+ routeIndex = 0;
355
+ path;
356
+ bodyCache = {};
357
+ constructor(request, path = "/", matchResult = [[]]) {
358
+ this.raw = request;
359
+ this.path = path;
360
+ this.#matchResult = matchResult;
361
+ this.#validatedData = {};
362
+ }
363
+ param(key) {
364
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
365
+ }
366
+ #getDecodedParam(key) {
367
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
368
+ const param = this.#getParamValue(paramKey);
369
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
370
+ }
371
+ #getAllDecodedParams() {
372
+ const decoded = {};
373
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
374
+ for (const key of keys) {
375
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
376
+ if (value !== undefined) {
377
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
378
+ }
379
+ }
380
+ return decoded;
381
+ }
382
+ #getParamValue(paramKey) {
383
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
384
+ }
385
+ query(key) {
386
+ return getQueryParam(this.url, key);
387
+ }
388
+ queries(key) {
389
+ return getQueryParams(this.url, key);
390
+ }
391
+ header(name) {
392
+ if (name) {
393
+ return this.raw.headers.get(name) ?? undefined;
394
+ }
395
+ const headerData = {};
396
+ this.raw.headers.forEach((value, key) => {
397
+ headerData[key] = value;
398
+ });
399
+ return headerData;
400
+ }
401
+ async parseBody(options) {
402
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
403
+ }
404
+ #cachedBody = (key) => {
405
+ const { bodyCache, raw } = this;
406
+ const cachedBody = bodyCache[key];
407
+ if (cachedBody) {
408
+ return cachedBody;
409
+ }
410
+ const anyCachedKey = Object.keys(bodyCache)[0];
411
+ if (anyCachedKey) {
412
+ return bodyCache[anyCachedKey].then((body) => {
413
+ if (anyCachedKey === "json") {
414
+ body = JSON.stringify(body);
415
+ }
416
+ return new Response(body)[key]();
417
+ });
418
+ }
419
+ return bodyCache[key] = raw[key]();
420
+ };
421
+ json() {
422
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
423
+ }
424
+ text() {
425
+ return this.#cachedBody("text");
426
+ }
427
+ arrayBuffer() {
428
+ return this.#cachedBody("arrayBuffer");
429
+ }
430
+ blob() {
431
+ return this.#cachedBody("blob");
432
+ }
433
+ formData() {
434
+ return this.#cachedBody("formData");
435
+ }
436
+ addValidatedData(target, data) {
437
+ this.#validatedData[target] = data;
438
+ }
439
+ valid(target) {
440
+ return this.#validatedData[target];
441
+ }
442
+ get url() {
443
+ return this.raw.url;
444
+ }
445
+ get method() {
446
+ return this.raw.method;
447
+ }
448
+ get [GET_MATCH_RESULT]() {
449
+ return this.#matchResult;
450
+ }
451
+ get matchedRoutes() {
452
+ return this.#matchResult[0].map(([[, route]]) => route);
453
+ }
454
+ get routePath() {
455
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
456
+ }
457
+ };
458
+
459
+ // node_modules/hono/dist/utils/html.js
460
+ var HtmlEscapedCallbackPhase = {
461
+ Stringify: 1,
462
+ BeforeStream: 2,
463
+ Stream: 3
464
+ };
465
+ var raw = (value, callbacks) => {
466
+ const escapedString = new String(value);
467
+ escapedString.isEscaped = true;
468
+ escapedString.callbacks = callbacks;
469
+ return escapedString;
470
+ };
471
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
472
+ if (typeof str === "object" && !(str instanceof String)) {
473
+ if (!(str instanceof Promise)) {
474
+ str = str.toString();
475
+ }
476
+ if (str instanceof Promise) {
477
+ str = await str;
478
+ }
479
+ }
480
+ const callbacks = str.callbacks;
481
+ if (!callbacks?.length) {
482
+ return Promise.resolve(str);
483
+ }
484
+ if (buffer) {
485
+ buffer[0] += str;
486
+ } else {
487
+ buffer = [str];
488
+ }
489
+ 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]));
490
+ if (preserveCallbacks) {
491
+ return raw(await resStr, callbacks);
492
+ } else {
493
+ return resStr;
494
+ }
495
+ };
496
+
497
+ // node_modules/hono/dist/context.js
498
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
499
+ var setDefaultContentType = (contentType, headers) => {
500
+ return {
501
+ "Content-Type": contentType,
502
+ ...headers
503
+ };
504
+ };
505
+ var createResponseInstance = (body, init) => new Response(body, init);
506
+ var Context = class {
507
+ #rawRequest;
508
+ #req;
509
+ env = {};
510
+ #var;
511
+ finalized = false;
512
+ error;
513
+ #status;
514
+ #executionCtx;
515
+ #res;
516
+ #layout;
517
+ #renderer;
518
+ #notFoundHandler;
519
+ #preparedHeaders;
520
+ #matchResult;
521
+ #path;
522
+ constructor(req, options) {
523
+ this.#rawRequest = req;
524
+ if (options) {
525
+ this.#executionCtx = options.executionCtx;
526
+ this.env = options.env;
527
+ this.#notFoundHandler = options.notFoundHandler;
528
+ this.#path = options.path;
529
+ this.#matchResult = options.matchResult;
530
+ }
531
+ }
532
+ get req() {
533
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
534
+ return this.#req;
535
+ }
536
+ get event() {
537
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
538
+ return this.#executionCtx;
539
+ } else {
540
+ throw Error("This context has no FetchEvent");
541
+ }
542
+ }
543
+ get executionCtx() {
544
+ if (this.#executionCtx) {
545
+ return this.#executionCtx;
546
+ } else {
547
+ throw Error("This context has no ExecutionContext");
548
+ }
549
+ }
550
+ get res() {
551
+ return this.#res ||= createResponseInstance(null, {
552
+ headers: this.#preparedHeaders ??= new Headers
553
+ });
554
+ }
555
+ set res(_res) {
556
+ if (this.#res && _res) {
557
+ _res = createResponseInstance(_res.body, _res);
558
+ for (const [k, v] of this.#res.headers.entries()) {
559
+ if (k === "content-type") {
560
+ continue;
561
+ }
562
+ if (k === "set-cookie") {
563
+ const cookies = this.#res.headers.getSetCookie();
564
+ _res.headers.delete("set-cookie");
565
+ for (const cookie of cookies) {
566
+ _res.headers.append("set-cookie", cookie);
567
+ }
568
+ } else {
569
+ _res.headers.set(k, v);
570
+ }
571
+ }
572
+ }
573
+ this.#res = _res;
574
+ this.finalized = true;
575
+ }
576
+ render = (...args) => {
577
+ this.#renderer ??= (content) => this.html(content);
578
+ return this.#renderer(...args);
579
+ };
580
+ setLayout = (layout) => this.#layout = layout;
581
+ getLayout = () => this.#layout;
582
+ setRenderer = (renderer) => {
583
+ this.#renderer = renderer;
584
+ };
585
+ header = (name, value, options) => {
586
+ if (this.finalized) {
587
+ this.#res = createResponseInstance(this.#res.body, this.#res);
588
+ }
589
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
590
+ if (value === undefined) {
591
+ headers.delete(name);
592
+ } else if (options?.append) {
593
+ headers.append(name, value);
594
+ } else {
595
+ headers.set(name, value);
596
+ }
597
+ };
598
+ status = (status) => {
599
+ this.#status = status;
600
+ };
601
+ set = (key, value) => {
602
+ this.#var ??= /* @__PURE__ */ new Map;
603
+ this.#var.set(key, value);
604
+ };
605
+ get = (key) => {
606
+ return this.#var ? this.#var.get(key) : undefined;
607
+ };
608
+ get var() {
609
+ if (!this.#var) {
610
+ return {};
611
+ }
612
+ return Object.fromEntries(this.#var);
613
+ }
614
+ #newResponse(data, arg, headers) {
615
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
616
+ if (typeof arg === "object" && "headers" in arg) {
617
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
618
+ for (const [key, value] of argHeaders) {
619
+ if (key.toLowerCase() === "set-cookie") {
620
+ responseHeaders.append(key, value);
621
+ } else {
622
+ responseHeaders.set(key, value);
623
+ }
624
+ }
625
+ }
626
+ if (headers) {
627
+ for (const [k, v] of Object.entries(headers)) {
628
+ if (typeof v === "string") {
629
+ responseHeaders.set(k, v);
630
+ } else {
631
+ responseHeaders.delete(k);
632
+ for (const v2 of v) {
633
+ responseHeaders.append(k, v2);
634
+ }
635
+ }
636
+ }
637
+ }
638
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
639
+ return createResponseInstance(data, { status, headers: responseHeaders });
640
+ }
641
+ newResponse = (...args) => this.#newResponse(...args);
642
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
643
+ text = (text, arg, headers) => {
644
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
645
+ };
646
+ json = (object, arg, headers) => {
647
+ return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
648
+ };
649
+ html = (html, arg, headers) => {
650
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
651
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
652
+ };
653
+ redirect = (location, status) => {
654
+ const locationString = String(location);
655
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
656
+ return this.newResponse(null, status ?? 302);
657
+ };
658
+ notFound = () => {
659
+ this.#notFoundHandler ??= () => createResponseInstance();
660
+ return this.#notFoundHandler(this);
661
+ };
662
+ };
663
+
664
+ // node_modules/hono/dist/router.js
665
+ var METHOD_NAME_ALL = "ALL";
666
+ var METHOD_NAME_ALL_LOWERCASE = "all";
667
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
668
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
669
+ var UnsupportedPathError = class extends Error {
670
+ };
671
+
672
+ // node_modules/hono/dist/utils/constants.js
673
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
674
+
675
+ // node_modules/hono/dist/hono-base.js
676
+ var notFoundHandler = (c) => {
677
+ return c.text("404 Not Found", 404);
678
+ };
679
+ var errorHandler = (err, c) => {
680
+ if ("getResponse" in err) {
681
+ const res = err.getResponse();
682
+ return c.newResponse(res.body, res);
683
+ }
684
+ console.error(err);
685
+ return c.text("Internal Server Error", 500);
686
+ };
687
+ var Hono = class _Hono {
688
+ get;
689
+ post;
690
+ put;
691
+ delete;
692
+ options;
693
+ patch;
694
+ all;
695
+ on;
696
+ use;
697
+ router;
698
+ getPath;
699
+ _basePath = "/";
700
+ #path = "/";
701
+ routes = [];
702
+ constructor(options = {}) {
703
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
704
+ allMethods.forEach((method) => {
705
+ this[method] = (args1, ...args) => {
706
+ if (typeof args1 === "string") {
707
+ this.#path = args1;
708
+ } else {
709
+ this.#addRoute(method, this.#path, args1);
710
+ }
711
+ args.forEach((handler) => {
712
+ this.#addRoute(method, this.#path, handler);
713
+ });
714
+ return this;
715
+ };
716
+ });
717
+ this.on = (method, path, ...handlers) => {
718
+ for (const p of [path].flat()) {
719
+ this.#path = p;
720
+ for (const m of [method].flat()) {
721
+ handlers.map((handler) => {
722
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
723
+ });
724
+ }
725
+ }
726
+ return this;
727
+ };
728
+ this.use = (arg1, ...handlers) => {
729
+ if (typeof arg1 === "string") {
730
+ this.#path = arg1;
731
+ } else {
732
+ this.#path = "*";
733
+ handlers.unshift(arg1);
734
+ }
735
+ handlers.forEach((handler) => {
736
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
737
+ });
738
+ return this;
739
+ };
740
+ const { strict, ...optionsWithoutStrict } = options;
741
+ Object.assign(this, optionsWithoutStrict);
742
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
743
+ }
744
+ #clone() {
745
+ const clone = new _Hono({
746
+ router: this.router,
747
+ getPath: this.getPath
748
+ });
749
+ clone.errorHandler = this.errorHandler;
750
+ clone.#notFoundHandler = this.#notFoundHandler;
751
+ clone.routes = this.routes;
752
+ return clone;
753
+ }
754
+ #notFoundHandler = notFoundHandler;
755
+ errorHandler = errorHandler;
756
+ route(path, app) {
757
+ const subApp = this.basePath(path);
758
+ app.routes.map((r) => {
759
+ let handler;
760
+ if (app.errorHandler === errorHandler) {
761
+ handler = r.handler;
762
+ } else {
763
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
764
+ handler[COMPOSED_HANDLER] = r.handler;
765
+ }
766
+ subApp.#addRoute(r.method, r.path, handler);
767
+ });
768
+ return this;
769
+ }
770
+ basePath(path) {
771
+ const subApp = this.#clone();
772
+ subApp._basePath = mergePath(this._basePath, path);
773
+ return subApp;
774
+ }
775
+ onError = (handler) => {
776
+ this.errorHandler = handler;
777
+ return this;
778
+ };
779
+ notFound = (handler) => {
780
+ this.#notFoundHandler = handler;
781
+ return this;
782
+ };
783
+ mount(path, applicationHandler, options) {
784
+ let replaceRequest;
785
+ let optionHandler;
786
+ if (options) {
787
+ if (typeof options === "function") {
788
+ optionHandler = options;
789
+ } else {
790
+ optionHandler = options.optionHandler;
791
+ if (options.replaceRequest === false) {
792
+ replaceRequest = (request) => request;
793
+ } else {
794
+ replaceRequest = options.replaceRequest;
795
+ }
796
+ }
797
+ }
798
+ const getOptions = optionHandler ? (c) => {
799
+ const options2 = optionHandler(c);
800
+ return Array.isArray(options2) ? options2 : [options2];
801
+ } : (c) => {
802
+ let executionContext = undefined;
803
+ try {
804
+ executionContext = c.executionCtx;
805
+ } catch {}
806
+ return [c.env, executionContext];
807
+ };
808
+ replaceRequest ||= (() => {
809
+ const mergedPath = mergePath(this._basePath, path);
810
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
811
+ return (request) => {
812
+ const url = new URL(request.url);
813
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
814
+ return new Request(url, request);
815
+ };
816
+ })();
817
+ const handler = async (c, next) => {
818
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
819
+ if (res) {
820
+ return res;
821
+ }
822
+ await next();
823
+ };
824
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
825
+ return this;
826
+ }
827
+ #addRoute(method, path, handler) {
828
+ method = method.toUpperCase();
829
+ path = mergePath(this._basePath, path);
830
+ const r = { basePath: this._basePath, path, method, handler };
831
+ this.router.add(method, path, [handler, r]);
832
+ this.routes.push(r);
833
+ }
834
+ #handleError(err, c) {
835
+ if (err instanceof Error) {
836
+ return this.errorHandler(err, c);
837
+ }
838
+ throw err;
839
+ }
840
+ #dispatch(request, executionCtx, env, method) {
841
+ if (method === "HEAD") {
842
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
843
+ }
844
+ const path = this.getPath(request, { env });
845
+ const matchResult = this.router.match(method, path);
846
+ const c = new Context(request, {
847
+ path,
848
+ matchResult,
849
+ env,
850
+ executionCtx,
851
+ notFoundHandler: this.#notFoundHandler
852
+ });
853
+ if (matchResult[0].length === 1) {
854
+ let res;
855
+ try {
856
+ res = matchResult[0][0][0][0](c, async () => {
857
+ c.res = await this.#notFoundHandler(c);
858
+ });
859
+ } catch (err) {
860
+ return this.#handleError(err, c);
861
+ }
862
+ 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);
863
+ }
864
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
865
+ return (async () => {
866
+ try {
867
+ const context = await composed(c);
868
+ if (!context.finalized) {
869
+ throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
870
+ }
871
+ return context.res;
872
+ } catch (err) {
873
+ return this.#handleError(err, c);
874
+ }
875
+ })();
876
+ }
877
+ fetch = (request, ...rest) => {
878
+ return this.#dispatch(request, rest[1], rest[0], request.method);
879
+ };
880
+ request = (input, requestInit, Env, executionCtx) => {
881
+ if (input instanceof Request) {
882
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
883
+ }
884
+ input = input.toString();
885
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
886
+ };
887
+ fire = () => {
888
+ addEventListener("fetch", (event) => {
889
+ event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
890
+ });
891
+ };
892
+ };
893
+
894
+ // node_modules/hono/dist/router/reg-exp-router/matcher.js
895
+ var emptyParam = [];
896
+ function match(method, path) {
897
+ const matchers = this.buildAllMatchers();
898
+ const match2 = (method2, path2) => {
899
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
900
+ const staticMatch = matcher[2][path2];
901
+ if (staticMatch) {
902
+ return staticMatch;
903
+ }
904
+ const match3 = path2.match(matcher[0]);
905
+ if (!match3) {
906
+ return [[], emptyParam];
907
+ }
908
+ const index = match3.indexOf("", 1);
909
+ return [matcher[1][index], match3];
910
+ };
911
+ this.match = match2;
912
+ return match2(method, path);
913
+ }
914
+
915
+ // node_modules/hono/dist/router/reg-exp-router/node.js
916
+ var LABEL_REG_EXP_STR = "[^/]+";
917
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
918
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
919
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
920
+ var regExpMetaChars = new Set(".\\+*[^]$()");
921
+ function compareKey(a, b) {
922
+ if (a.length === 1) {
923
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
924
+ }
925
+ if (b.length === 1) {
926
+ return 1;
927
+ }
928
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
929
+ return 1;
930
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
931
+ return -1;
932
+ }
933
+ if (a === LABEL_REG_EXP_STR) {
934
+ return 1;
935
+ } else if (b === LABEL_REG_EXP_STR) {
936
+ return -1;
937
+ }
938
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
939
+ }
940
+ var Node = class _Node {
941
+ #index;
942
+ #varIndex;
943
+ #children = /* @__PURE__ */ Object.create(null);
944
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
945
+ if (tokens.length === 0) {
946
+ if (this.#index !== undefined) {
947
+ throw PATH_ERROR;
948
+ }
949
+ if (pathErrorCheckOnly) {
950
+ return;
951
+ }
952
+ this.#index = index;
953
+ return;
954
+ }
955
+ const [token, ...restTokens] = tokens;
956
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
957
+ let node;
958
+ if (pattern) {
959
+ const name = pattern[1];
960
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
961
+ if (name && pattern[2]) {
962
+ if (regexpStr === ".*") {
963
+ throw PATH_ERROR;
964
+ }
965
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
966
+ if (/\((?!\?:)/.test(regexpStr)) {
967
+ throw PATH_ERROR;
968
+ }
969
+ }
970
+ node = this.#children[regexpStr];
971
+ if (!node) {
972
+ if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
973
+ throw PATH_ERROR;
974
+ }
975
+ if (pathErrorCheckOnly) {
976
+ return;
977
+ }
978
+ node = this.#children[regexpStr] = new _Node;
979
+ if (name !== "") {
980
+ node.#varIndex = context.varIndex++;
981
+ }
982
+ }
983
+ if (!pathErrorCheckOnly && name !== "") {
984
+ paramMap.push([name, node.#varIndex]);
985
+ }
986
+ } else {
987
+ node = this.#children[token];
988
+ if (!node) {
989
+ if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
990
+ throw PATH_ERROR;
991
+ }
992
+ if (pathErrorCheckOnly) {
993
+ return;
994
+ }
995
+ node = this.#children[token] = new _Node;
996
+ }
997
+ }
998
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
999
+ }
1000
+ buildRegExpStr() {
1001
+ const childKeys = Object.keys(this.#children).sort(compareKey);
1002
+ const strList = childKeys.map((k) => {
1003
+ const c = this.#children[k];
1004
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
1005
+ });
1006
+ if (typeof this.#index === "number") {
1007
+ strList.unshift(`#${this.#index}`);
1008
+ }
1009
+ if (strList.length === 0) {
1010
+ return "";
1011
+ }
1012
+ if (strList.length === 1) {
1013
+ return strList[0];
1014
+ }
1015
+ return "(?:" + strList.join("|") + ")";
1016
+ }
1017
+ };
1018
+
1019
+ // node_modules/hono/dist/router/reg-exp-router/trie.js
1020
+ var Trie = class {
1021
+ #context = { varIndex: 0 };
1022
+ #root = new Node;
1023
+ insert(path, index, pathErrorCheckOnly) {
1024
+ const paramAssoc = [];
1025
+ const groups = [];
1026
+ for (let i = 0;; ) {
1027
+ let replaced = false;
1028
+ path = path.replace(/\{[^}]+\}/g, (m) => {
1029
+ const mark = `@\\${i}`;
1030
+ groups[i] = [mark, m];
1031
+ i++;
1032
+ replaced = true;
1033
+ return mark;
1034
+ });
1035
+ if (!replaced) {
1036
+ break;
1037
+ }
1038
+ }
1039
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1040
+ for (let i = groups.length - 1;i >= 0; i--) {
1041
+ const [mark] = groups[i];
1042
+ for (let j = tokens.length - 1;j >= 0; j--) {
1043
+ if (tokens[j].indexOf(mark) !== -1) {
1044
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1045
+ break;
1046
+ }
1047
+ }
1048
+ }
1049
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
1050
+ return paramAssoc;
1051
+ }
1052
+ buildRegExp() {
1053
+ let regexp = this.#root.buildRegExpStr();
1054
+ if (regexp === "") {
1055
+ return [/^$/, [], []];
1056
+ }
1057
+ let captureIndex = 0;
1058
+ const indexReplacementMap = [];
1059
+ const paramReplacementMap = [];
1060
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1061
+ if (handlerIndex !== undefined) {
1062
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1063
+ return "$()";
1064
+ }
1065
+ if (paramIndex !== undefined) {
1066
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1067
+ return "";
1068
+ }
1069
+ return "";
1070
+ });
1071
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1072
+ }
1073
+ };
1074
+
1075
+ // node_modules/hono/dist/router/reg-exp-router/router.js
1076
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1077
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1078
+ function buildWildcardRegExp(path) {
1079
+ return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
1080
+ }
1081
+ function clearWildcardRegExpCache() {
1082
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1083
+ }
1084
+ function buildMatcherFromPreprocessedRoutes(routes) {
1085
+ const trie = new Trie;
1086
+ const handlerData = [];
1087
+ if (routes.length === 0) {
1088
+ return nullMatcher;
1089
+ }
1090
+ const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
1091
+ const staticMap = /* @__PURE__ */ Object.create(null);
1092
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
1093
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
1094
+ if (pathErrorCheckOnly) {
1095
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1096
+ } else {
1097
+ j++;
1098
+ }
1099
+ let paramAssoc;
1100
+ try {
1101
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
1102
+ } catch (e) {
1103
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
1104
+ }
1105
+ if (pathErrorCheckOnly) {
1106
+ continue;
1107
+ }
1108
+ handlerData[j] = handlers.map(([h, paramCount]) => {
1109
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
1110
+ paramCount -= 1;
1111
+ for (;paramCount >= 0; paramCount--) {
1112
+ const [key, value] = paramAssoc[paramCount];
1113
+ paramIndexMap[key] = value;
1114
+ }
1115
+ return [h, paramIndexMap];
1116
+ });
1117
+ }
1118
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1119
+ for (let i = 0, len = handlerData.length;i < len; i++) {
1120
+ for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
1121
+ const map = handlerData[i][j]?.[1];
1122
+ if (!map) {
1123
+ continue;
1124
+ }
1125
+ const keys = Object.keys(map);
1126
+ for (let k = 0, len3 = keys.length;k < len3; k++) {
1127
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
1128
+ }
1129
+ }
1130
+ }
1131
+ const handlerMap = [];
1132
+ for (const i in indexReplacementMap) {
1133
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1134
+ }
1135
+ return [regexp, handlerMap, staticMap];
1136
+ }
1137
+ function findMiddleware(middleware, path) {
1138
+ if (!middleware) {
1139
+ return;
1140
+ }
1141
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1142
+ if (buildWildcardRegExp(k).test(path)) {
1143
+ return [...middleware[k]];
1144
+ }
1145
+ }
1146
+ return;
1147
+ }
1148
+ var RegExpRouter = class {
1149
+ name = "RegExpRouter";
1150
+ #middleware;
1151
+ #routes;
1152
+ constructor() {
1153
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1154
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1155
+ }
1156
+ add(method, path, handler) {
1157
+ const middleware = this.#middleware;
1158
+ const routes = this.#routes;
1159
+ if (!middleware || !routes) {
1160
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1161
+ }
1162
+ if (!middleware[method]) {
1163
+ [middleware, routes].forEach((handlerMap) => {
1164
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
1165
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
1166
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
1167
+ });
1168
+ });
1169
+ }
1170
+ if (path === "/*") {
1171
+ path = "*";
1172
+ }
1173
+ const paramCount = (path.match(/\/:/g) || []).length;
1174
+ if (/\*$/.test(path)) {
1175
+ const re = buildWildcardRegExp(path);
1176
+ if (method === METHOD_NAME_ALL) {
1177
+ Object.keys(middleware).forEach((m) => {
1178
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1179
+ });
1180
+ } else {
1181
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1182
+ }
1183
+ Object.keys(middleware).forEach((m) => {
1184
+ if (method === METHOD_NAME_ALL || method === m) {
1185
+ Object.keys(middleware[m]).forEach((p) => {
1186
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
1187
+ });
1188
+ }
1189
+ });
1190
+ Object.keys(routes).forEach((m) => {
1191
+ if (method === METHOD_NAME_ALL || method === m) {
1192
+ Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
1193
+ }
1194
+ });
1195
+ return;
1196
+ }
1197
+ const paths = checkOptionalParameter(path) || [path];
1198
+ for (let i = 0, len = paths.length;i < len; i++) {
1199
+ const path2 = paths[i];
1200
+ Object.keys(routes).forEach((m) => {
1201
+ if (method === METHOD_NAME_ALL || method === m) {
1202
+ routes[m][path2] ||= [
1203
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
1204
+ ];
1205
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
1206
+ }
1207
+ });
1208
+ }
1209
+ }
1210
+ match = match;
1211
+ buildAllMatchers() {
1212
+ const matchers = /* @__PURE__ */ Object.create(null);
1213
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1214
+ matchers[method] ||= this.#buildMatcher(method);
1215
+ });
1216
+ this.#middleware = this.#routes = undefined;
1217
+ clearWildcardRegExpCache();
1218
+ return matchers;
1219
+ }
1220
+ #buildMatcher(method) {
1221
+ const routes = [];
1222
+ let hasOwnRoute = method === METHOD_NAME_ALL;
1223
+ [this.#middleware, this.#routes].forEach((r) => {
1224
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
1225
+ if (ownRoute.length !== 0) {
1226
+ hasOwnRoute ||= true;
1227
+ routes.push(...ownRoute);
1228
+ } else if (method !== METHOD_NAME_ALL) {
1229
+ routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
1230
+ }
1231
+ });
1232
+ if (!hasOwnRoute) {
1233
+ return null;
1234
+ } else {
1235
+ return buildMatcherFromPreprocessedRoutes(routes);
1236
+ }
1237
+ }
1238
+ };
1239
+
1240
+ // node_modules/hono/dist/router/reg-exp-router/prepared-router.js
1241
+ var PreparedRegExpRouter = class {
1242
+ name = "PreparedRegExpRouter";
1243
+ #matchers;
1244
+ #relocateMap;
1245
+ constructor(matchers, relocateMap) {
1246
+ this.#matchers = matchers;
1247
+ this.#relocateMap = relocateMap;
1248
+ }
1249
+ #addWildcard(method, handlerData) {
1250
+ const matcher = this.#matchers[method];
1251
+ matcher[1].forEach((list) => list && list.push(handlerData));
1252
+ Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
1253
+ }
1254
+ #addPath(method, path, handler, indexes, map) {
1255
+ const matcher = this.#matchers[method];
1256
+ if (!map) {
1257
+ matcher[2][path][0].push([handler, {}]);
1258
+ } else {
1259
+ indexes.forEach((index) => {
1260
+ if (typeof index === "number") {
1261
+ matcher[1][index].push([handler, map]);
1262
+ } else {
1263
+ matcher[2][index || path][0].push([handler, map]);
1264
+ }
1265
+ });
1266
+ }
1267
+ }
1268
+ add(method, path, handler) {
1269
+ if (!this.#matchers[method]) {
1270
+ const all = this.#matchers[METHOD_NAME_ALL];
1271
+ const staticMap = {};
1272
+ for (const key in all[2]) {
1273
+ staticMap[key] = [all[2][key][0].slice(), emptyParam];
1274
+ }
1275
+ this.#matchers[method] = [
1276
+ all[0],
1277
+ all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
1278
+ staticMap
1279
+ ];
1280
+ }
1281
+ if (path === "/*" || path === "*") {
1282
+ const handlerData = [handler, {}];
1283
+ if (method === METHOD_NAME_ALL) {
1284
+ for (const m in this.#matchers) {
1285
+ this.#addWildcard(m, handlerData);
1286
+ }
1287
+ } else {
1288
+ this.#addWildcard(method, handlerData);
1289
+ }
1290
+ return;
1291
+ }
1292
+ const data = this.#relocateMap[path];
1293
+ if (!data) {
1294
+ throw new Error(`Path ${path} is not registered`);
1295
+ }
1296
+ for (const [indexes, map] of data) {
1297
+ if (method === METHOD_NAME_ALL) {
1298
+ for (const m in this.#matchers) {
1299
+ this.#addPath(m, path, handler, indexes, map);
1300
+ }
1301
+ } else {
1302
+ this.#addPath(method, path, handler, indexes, map);
1303
+ }
1304
+ }
1305
+ }
1306
+ buildAllMatchers() {
1307
+ return this.#matchers;
1308
+ }
1309
+ match = match;
1310
+ };
1311
+
1312
+ // node_modules/hono/dist/router/smart-router/router.js
1313
+ var SmartRouter = class {
1314
+ name = "SmartRouter";
1315
+ #routers = [];
1316
+ #routes = [];
1317
+ constructor(init) {
1318
+ this.#routers = init.routers;
1319
+ }
1320
+ add(method, path, handler) {
1321
+ if (!this.#routes) {
1322
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1323
+ }
1324
+ this.#routes.push([method, path, handler]);
1325
+ }
1326
+ match(method, path) {
1327
+ if (!this.#routes) {
1328
+ throw new Error("Fatal error");
1329
+ }
1330
+ const routers = this.#routers;
1331
+ const routes = this.#routes;
1332
+ const len = routers.length;
1333
+ let i = 0;
1334
+ let res;
1335
+ for (;i < len; i++) {
1336
+ const router = routers[i];
1337
+ try {
1338
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
1339
+ router.add(...routes[i2]);
1340
+ }
1341
+ res = router.match(method, path);
1342
+ } catch (e) {
1343
+ if (e instanceof UnsupportedPathError) {
1344
+ continue;
1345
+ }
1346
+ throw e;
1347
+ }
1348
+ this.match = router.match.bind(router);
1349
+ this.#routers = [router];
1350
+ this.#routes = undefined;
1351
+ break;
1352
+ }
1353
+ if (i === len) {
1354
+ throw new Error("Fatal error");
1355
+ }
1356
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
1357
+ return res;
1358
+ }
1359
+ get activeRouter() {
1360
+ if (this.#routes || this.#routers.length !== 1) {
1361
+ throw new Error("No active router has been determined yet.");
1362
+ }
1363
+ return this.#routers[0];
1364
+ }
1365
+ };
1366
+
1367
+ // node_modules/hono/dist/router/trie-router/node.js
1368
+ var emptyParams = /* @__PURE__ */ Object.create(null);
1369
+ var hasChildren = (children) => {
1370
+ for (const _ in children) {
1371
+ return true;
1372
+ }
1373
+ return false;
1374
+ };
1375
+ var Node2 = class _Node2 {
1376
+ #methods;
1377
+ #children;
1378
+ #patterns;
1379
+ #order = 0;
1380
+ #params = emptyParams;
1381
+ constructor(method, handler, children) {
1382
+ this.#children = children || /* @__PURE__ */ Object.create(null);
1383
+ this.#methods = [];
1384
+ if (method && handler) {
1385
+ const m = /* @__PURE__ */ Object.create(null);
1386
+ m[method] = { handler, possibleKeys: [], score: 0 };
1387
+ this.#methods = [m];
1388
+ }
1389
+ this.#patterns = [];
1390
+ }
1391
+ insert(method, path, handler) {
1392
+ this.#order = ++this.#order;
1393
+ let curNode = this;
1394
+ const parts = splitRoutingPath(path);
1395
+ const possibleKeys = [];
1396
+ for (let i = 0, len = parts.length;i < len; i++) {
1397
+ const p = parts[i];
1398
+ const nextP = parts[i + 1];
1399
+ const pattern = getPattern(p, nextP);
1400
+ const key = Array.isArray(pattern) ? pattern[0] : p;
1401
+ if (key in curNode.#children) {
1402
+ curNode = curNode.#children[key];
1403
+ if (pattern) {
1404
+ possibleKeys.push(pattern[1]);
1405
+ }
1406
+ continue;
1407
+ }
1408
+ curNode.#children[key] = new _Node2;
1409
+ if (pattern) {
1410
+ curNode.#patterns.push(pattern);
1411
+ possibleKeys.push(pattern[1]);
1412
+ }
1413
+ curNode = curNode.#children[key];
1414
+ }
1415
+ curNode.#methods.push({
1416
+ [method]: {
1417
+ handler,
1418
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
1419
+ score: this.#order
1420
+ }
1421
+ });
1422
+ return curNode;
1423
+ }
1424
+ #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
1425
+ for (let i = 0, len = node.#methods.length;i < len; i++) {
1426
+ const m = node.#methods[i];
1427
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
1428
+ const processedSet = {};
1429
+ if (handlerSet !== undefined) {
1430
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
1431
+ handlerSets.push(handlerSet);
1432
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
1433
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
1434
+ const key = handlerSet.possibleKeys[i2];
1435
+ const processed = processedSet[handlerSet.score];
1436
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
1437
+ processedSet[handlerSet.score] = true;
1438
+ }
1439
+ }
1440
+ }
1441
+ }
1442
+ }
1443
+ search(method, path) {
1444
+ const handlerSets = [];
1445
+ this.#params = emptyParams;
1446
+ const curNode = this;
1447
+ let curNodes = [curNode];
1448
+ const parts = splitPath(path);
1449
+ const curNodesQueue = [];
1450
+ const len = parts.length;
1451
+ let partOffsets = null;
1452
+ for (let i = 0;i < len; i++) {
1453
+ const part = parts[i];
1454
+ const isLast = i === len - 1;
1455
+ const tempNodes = [];
1456
+ for (let j = 0, len2 = curNodes.length;j < len2; j++) {
1457
+ const node = curNodes[j];
1458
+ const nextNode = node.#children[part];
1459
+ if (nextNode) {
1460
+ nextNode.#params = node.#params;
1461
+ if (isLast) {
1462
+ if (nextNode.#children["*"]) {
1463
+ this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
1464
+ }
1465
+ this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
1466
+ } else {
1467
+ tempNodes.push(nextNode);
1468
+ }
1469
+ }
1470
+ for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
1471
+ const pattern = node.#patterns[k];
1472
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
1473
+ if (pattern === "*") {
1474
+ const astNode = node.#children["*"];
1475
+ if (astNode) {
1476
+ this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
1477
+ astNode.#params = params;
1478
+ tempNodes.push(astNode);
1479
+ }
1480
+ continue;
1481
+ }
1482
+ const [key, name, matcher] = pattern;
1483
+ if (!part && !(matcher instanceof RegExp)) {
1484
+ continue;
1485
+ }
1486
+ const child = node.#children[key];
1487
+ if (matcher instanceof RegExp) {
1488
+ if (partOffsets === null) {
1489
+ partOffsets = new Array(len);
1490
+ let offset = path[0] === "/" ? 1 : 0;
1491
+ for (let p = 0;p < len; p++) {
1492
+ partOffsets[p] = offset;
1493
+ offset += parts[p].length + 1;
1494
+ }
1495
+ }
1496
+ const restPathString = path.substring(partOffsets[i]);
1497
+ const m = matcher.exec(restPathString);
1498
+ if (m) {
1499
+ params[name] = m[0];
1500
+ this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
1501
+ if (hasChildren(child.#children)) {
1502
+ child.#params = params;
1503
+ const componentCount = m[0].match(/\//)?.length ?? 0;
1504
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
1505
+ targetCurNodes.push(child);
1506
+ }
1507
+ continue;
1508
+ }
1509
+ }
1510
+ if (matcher === true || matcher.test(part)) {
1511
+ params[name] = part;
1512
+ if (isLast) {
1513
+ this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
1514
+ if (child.#children["*"]) {
1515
+ this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
1516
+ }
1517
+ } else {
1518
+ child.#params = params;
1519
+ tempNodes.push(child);
1520
+ }
1521
+ }
1522
+ }
1523
+ }
1524
+ const shifted = curNodesQueue.shift();
1525
+ curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
1526
+ }
1527
+ if (handlerSets.length > 1) {
1528
+ handlerSets.sort((a, b) => {
1529
+ return a.score - b.score;
1530
+ });
1531
+ }
1532
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
1533
+ }
1534
+ };
1535
+
1536
+ // node_modules/hono/dist/router/trie-router/router.js
1537
+ var TrieRouter = class {
1538
+ name = "TrieRouter";
1539
+ #node;
1540
+ constructor() {
1541
+ this.#node = new Node2;
1542
+ }
1543
+ add(method, path, handler) {
1544
+ const results = checkOptionalParameter(path);
1545
+ if (results) {
1546
+ for (let i = 0, len = results.length;i < len; i++) {
1547
+ this.#node.insert(method, results[i], handler);
1548
+ }
1549
+ return;
1550
+ }
1551
+ this.#node.insert(method, path, handler);
1552
+ }
1553
+ match(method, path) {
1554
+ return this.#node.search(method, path);
1555
+ }
1556
+ };
1557
+
1558
+ // node_modules/hono/dist/hono.js
1559
+ var Hono2 = class extends Hono {
1560
+ constructor(options = {}) {
1561
+ super(options);
1562
+ this.router = options.router ?? new SmartRouter({
1563
+ routers: [new RegExpRouter, new TrieRouter]
1564
+ });
1565
+ }
1566
+ };
1567
+
1568
+ // node_modules/hono/dist/middleware/cors/index.js
1569
+ var cors = (options) => {
1570
+ const defaults = {
1571
+ origin: "*",
1572
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
1573
+ allowHeaders: [],
1574
+ exposeHeaders: []
1575
+ };
1576
+ const opts = {
1577
+ ...defaults,
1578
+ ...options
1579
+ };
1580
+ const findAllowOrigin = ((optsOrigin) => {
1581
+ if (typeof optsOrigin === "string") {
1582
+ if (optsOrigin === "*") {
1583
+ return () => optsOrigin;
1584
+ } else {
1585
+ return (origin) => optsOrigin === origin ? origin : null;
1586
+ }
1587
+ } else if (typeof optsOrigin === "function") {
1588
+ return optsOrigin;
1589
+ } else {
1590
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
1591
+ }
1592
+ })(opts.origin);
1593
+ const findAllowMethods = ((optsAllowMethods) => {
1594
+ if (typeof optsAllowMethods === "function") {
1595
+ return optsAllowMethods;
1596
+ } else if (Array.isArray(optsAllowMethods)) {
1597
+ return () => optsAllowMethods;
1598
+ } else {
1599
+ return () => [];
1600
+ }
1601
+ })(opts.allowMethods);
1602
+ return async function cors2(c, next) {
1603
+ function set(key, value) {
1604
+ c.res.headers.set(key, value);
1605
+ }
1606
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
1607
+ if (allowOrigin) {
1608
+ set("Access-Control-Allow-Origin", allowOrigin);
1609
+ }
1610
+ if (opts.credentials) {
1611
+ set("Access-Control-Allow-Credentials", "true");
1612
+ }
1613
+ if (opts.exposeHeaders?.length) {
1614
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
1615
+ }
1616
+ if (c.req.method === "OPTIONS") {
1617
+ if (opts.origin !== "*") {
1618
+ set("Vary", "Origin");
1619
+ }
1620
+ if (opts.maxAge != null) {
1621
+ set("Access-Control-Max-Age", opts.maxAge.toString());
1622
+ }
1623
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
1624
+ if (allowMethods.length) {
1625
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
1626
+ }
1627
+ let headers = opts.allowHeaders;
1628
+ if (!headers?.length) {
1629
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
1630
+ if (requestHeaders) {
1631
+ headers = requestHeaders.split(/\s*,\s*/);
1632
+ }
1633
+ }
1634
+ if (headers?.length) {
1635
+ set("Access-Control-Allow-Headers", headers.join(","));
1636
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
1637
+ }
1638
+ c.res.headers.delete("Content-Length");
1639
+ c.res.headers.delete("Content-Type");
1640
+ return new Response(null, {
1641
+ headers: c.res.headers,
1642
+ status: 204,
1643
+ statusText: "No Content"
1644
+ });
1645
+ }
1646
+ await next();
1647
+ if (opts.origin !== "*") {
1648
+ c.header("Vary", "Origin", { append: true });
1649
+ }
1650
+ };
1651
+ };
1652
+
1653
+ // src/lib/browser-script.ts
1654
+ function getBrowserScript(serverUrl) {
1655
+ return `(function(){
1656
+ var cfg={url:'${serverUrl}',projectId:null};
1657
+ var el=document.currentScript;
1658
+ if(el){cfg.projectId=el.getAttribute('data-project')||null;}
1659
+ var q=[];
1660
+ function flush(){if(!q.length)return;var b=q.splice(0);fetch(cfg.url+'/api/logs',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(b),keepalive:true}).catch(function(){});}
1661
+ setInterval(flush,2000);
1662
+ function push(level,msg,extra){
1663
+ q.push(Object.assign({level:level,message:String(msg),source:'script',url:location.href,timestamp:new Date().toISOString()},cfg.projectId?{project_id:cfg.projectId}:{},extra||{}));
1664
+ if(q.length>=10)flush();
1665
+ }
1666
+ var _ce=console.error.bind(console);
1667
+ console.error=function(){_ce.apply(console,arguments);push('error',Array.from(arguments).join(' '));};
1668
+ var _cw=console.warn.bind(console);
1669
+ console.warn=function(){_cw.apply(console,arguments);push('warn',Array.from(arguments).join(' '));};
1670
+ window.addEventListener('error',function(e){push('error',e.message,{stack_trace:e.error?e.error.stack:null,url:e.filename});});
1671
+ window.addEventListener('unhandledrejection',function(e){push('error','Unhandled promise rejection: '+(e.reason&&e.reason.message||String(e.reason)),{stack_trace:e.reason&&e.reason.stack||null});});
1672
+ window.addEventListener('beforeunload',flush);
1673
+ window.__logs={push:push,flush:flush,config:cfg};
1674
+ })();`;
1675
+ }
1676
+
1677
+ // src/server/routes/jobs.ts
1678
+ function jobsRoutes(db) {
1679
+ const app = new Hono2;
1680
+ app.post("/", async (c) => {
1681
+ const body = await c.req.json();
1682
+ if (!body.project_id || !body.schedule)
1683
+ return c.json({ error: "project_id and schedule are required" }, 422);
1684
+ return c.json(createJob(db, body), 201);
1685
+ });
1686
+ app.get("/", (c) => {
1687
+ const { project_id } = c.req.query();
1688
+ return c.json(listJobs(db, project_id || undefined));
1689
+ });
1690
+ app.put("/:id", async (c) => {
1691
+ const body = await c.req.json();
1692
+ const updated = updateJob(db, c.req.param("id"), body);
1693
+ if (!updated)
1694
+ return c.json({ error: "not found" }, 404);
1695
+ return c.json(updated);
1696
+ });
1697
+ app.delete("/:id", (c) => {
1698
+ deleteJob(db, c.req.param("id"));
1699
+ return c.json({ deleted: true });
1700
+ });
1701
+ return app;
1702
+ }
1703
+
1704
+ // src/server/routes/logs.ts
1705
+ function logsRoutes(db) {
1706
+ const app = new Hono2;
1707
+ app.post("/", async (c) => {
1708
+ const body = await c.req.json();
1709
+ if (Array.isArray(body)) {
1710
+ const rows = ingestBatch(db, body);
1711
+ return c.json({ inserted: rows.length }, 201);
1712
+ }
1713
+ const row = ingestLog(db, body);
1714
+ return c.json(row, 201);
1715
+ });
1716
+ app.get("/", (c) => {
1717
+ const { project_id, page_id, level, service, since, until, text, trace_id, limit, offset, fields } = c.req.query();
1718
+ const rows = searchLogs(db, {
1719
+ project_id: project_id || undefined,
1720
+ page_id: page_id || undefined,
1721
+ level: level ? level.split(",") : undefined,
1722
+ service: service || undefined,
1723
+ since: since || undefined,
1724
+ until: until || undefined,
1725
+ text: text || undefined,
1726
+ trace_id: trace_id || undefined,
1727
+ limit: limit ? Number(limit) : 100,
1728
+ offset: offset ? Number(offset) : 0
1729
+ });
1730
+ if (fields) {
1731
+ const keys = fields.split(",");
1732
+ return c.json(rows.map((r) => Object.fromEntries(keys.map((k) => [k, r[k]]))));
1733
+ }
1734
+ return c.json(rows);
1735
+ });
1736
+ app.get("/tail", (c) => {
1737
+ const { project_id, n } = c.req.query();
1738
+ const rows = tailLogs(db, project_id || undefined, n ? Number(n) : 50);
1739
+ return c.json(rows);
1740
+ });
1741
+ app.get("/summary", (c) => {
1742
+ const { project_id, since } = c.req.query();
1743
+ const summary = summarizeLogs(db, project_id || undefined, since || undefined);
1744
+ return c.json(summary);
1745
+ });
1746
+ app.get("/:trace_id/context", (c) => {
1747
+ const rows = getLogContext(db, c.req.param("trace_id"));
1748
+ return c.json(rows);
1749
+ });
1750
+ return app;
1751
+ }
1752
+
1753
+ // src/server/routes/perf.ts
1754
+ function perfRoutes(db) {
1755
+ const app = new Hono2;
1756
+ app.get("/", (c) => {
1757
+ const { project_id, page_id, since } = c.req.query();
1758
+ if (!project_id)
1759
+ return c.json({ error: "project_id is required" }, 422);
1760
+ const snap = getLatestSnapshot(db, project_id, page_id || undefined);
1761
+ return c.json(snap);
1762
+ });
1763
+ app.get("/trend", (c) => {
1764
+ const { project_id, page_id, since, limit } = c.req.query();
1765
+ if (!project_id)
1766
+ return c.json({ error: "project_id is required" }, 422);
1767
+ const trend = getPerfTrend(db, project_id, page_id || undefined, since || undefined, limit ? Number(limit) : 50);
1768
+ return c.json(trend);
1769
+ });
1770
+ return app;
1771
+ }
1772
+
1773
+ // src/lib/github.ts
1774
+ async function syncGithubRepo(db, project) {
1775
+ if (!project.github_repo)
1776
+ return project;
1777
+ const repo = project.github_repo.replace(/^https?:\/\/github\.com\//, "");
1778
+ const headers = { Accept: "application/vnd.github.v3+json" };
1779
+ if (process.env.GITHUB_TOKEN)
1780
+ headers["Authorization"] = `Bearer ${process.env.GITHUB_TOKEN}`;
1781
+ try {
1782
+ const [repoRes, commitRes] = await Promise.all([
1783
+ fetch(`https://api.github.com/repos/${repo}`, { headers }),
1784
+ fetch(`https://api.github.com/repos/${repo}/commits?per_page=1`, { headers })
1785
+ ]);
1786
+ if (!repoRes.ok)
1787
+ return project;
1788
+ const repoData = await repoRes.json();
1789
+ const commits = commitRes.ok ? await commitRes.json() : [];
1790
+ return updateProject(db, project.id, {
1791
+ github_description: repoData.description,
1792
+ github_branch: repoData.default_branch,
1793
+ github_sha: commits[0]?.sha ?? null,
1794
+ last_synced_at: new Date().toISOString()
1795
+ });
1796
+ } catch {
1797
+ return project;
1798
+ }
1799
+ }
1800
+
1801
+ // src/server/routes/projects.ts
1802
+ function projectsRoutes(db) {
1803
+ const app = new Hono2;
1804
+ app.post("/", async (c) => {
1805
+ const body = await c.req.json();
1806
+ if (!body.name)
1807
+ return c.json({ error: "name is required" }, 422);
1808
+ const project = createProject(db, body);
1809
+ return c.json(project, 201);
1810
+ });
1811
+ app.get("/", (c) => c.json(listProjects(db)));
1812
+ app.get("/:id", (c) => {
1813
+ const project = getProject(db, c.req.param("id"));
1814
+ if (!project)
1815
+ return c.json({ error: "not found" }, 404);
1816
+ return c.json(project);
1817
+ });
1818
+ app.post("/:id/pages", async (c) => {
1819
+ const body = await c.req.json();
1820
+ if (!body.url)
1821
+ return c.json({ error: "url is required" }, 422);
1822
+ const page = createPage(db, { ...body, project_id: c.req.param("id") });
1823
+ return c.json(page, 201);
1824
+ });
1825
+ app.get("/:id/pages", (c) => c.json(listPages(db, c.req.param("id"))));
1826
+ app.post("/:id/sync-repo", async (c) => {
1827
+ const project = getProject(db, c.req.param("id"));
1828
+ if (!project)
1829
+ return c.json({ error: "not found" }, 404);
1830
+ if (!project.github_repo)
1831
+ return c.json({ error: "no github_repo set" }, 422);
1832
+ const updated = await syncGithubRepo(db, project);
1833
+ return c.json(updated);
1834
+ });
1835
+ return app;
1836
+ }
1837
+
1838
+ // src/server/index.ts
1839
+ var PORT = Number(process.env.LOGS_PORT ?? 3460);
1840
+ var db = getDb();
1841
+ var app = new Hono2;
1842
+ app.use("*", cors());
1843
+ app.get("/script.js", (c) => {
1844
+ const host = `${c.req.header("x-forwarded-proto") ?? "http"}://${c.req.header("host") ?? `localhost:${PORT}`}`;
1845
+ c.header("Content-Type", "application/javascript");
1846
+ c.header("Cache-Control", "public, max-age=300");
1847
+ return c.text(getBrowserScript(host));
1848
+ });
1849
+ app.route("/api/logs", logsRoutes(db));
1850
+ app.route("/api/projects", projectsRoutes(db));
1851
+ app.route("/api/jobs", jobsRoutes(db));
1852
+ app.route("/api/perf", perfRoutes(db));
1853
+ app.get("/", (c) => c.json({ service: "@hasna/logs", port: PORT, status: "ok" }));
1854
+ startScheduler(db);
1855
+ console.log(`@hasna/logs server running on http://localhost:${PORT}`);
1856
+ var server_default = {
1857
+ port: PORT,
1858
+ fetch: app.fetch
1859
+ };
1860
+ export {
1861
+ server_default as default
1862
+ };