workers-sentinel 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +341 -0
  3. package/dist/README.md +1 -0
  4. package/dist/dashboard/assets/EventDetail-DgqYLyiF.js +1 -0
  5. package/dist/dashboard/assets/IssueDetail-CjG-J6cD.js +1 -0
  6. package/dist/dashboard/assets/Issues-Cfnqb_a0.js +33 -0
  7. package/dist/dashboard/assets/Layout-Edli6x7p.js +1 -0
  8. package/dist/dashboard/assets/Login-DHYJjZXJ.js +1 -0
  9. package/dist/dashboard/assets/ProjectCreate-D5GeKxHe.js +33 -0
  10. package/dist/dashboard/assets/ProjectSettings-6OwGPcir.js +1 -0
  11. package/dist/dashboard/assets/Projects-Bth0OyBs.js +1 -0
  12. package/dist/dashboard/assets/Register-C3zVYtDV.js +1 -0
  13. package/dist/dashboard/assets/index-7dRN2NZv.js +30 -0
  14. package/dist/dashboard/assets/index-JMAa_1Q2.css +1 -0
  15. package/dist/dashboard/assets/projects-BUj8O17i.js +1 -0
  16. package/dist/dashboard/index.html +14 -0
  17. package/dist/durable-objects/auth-state.d.ts +28 -0
  18. package/dist/durable-objects/auth-state.d.ts.map +1 -0
  19. package/dist/durable-objects/project-state.d.ts +23 -0
  20. package/dist/durable-objects/project-state.d.ts.map +1 -0
  21. package/dist/index.d.ts +13 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +4774 -0
  24. package/dist/index.js.map +8 -0
  25. package/dist/lib/envelope-parser.d.ts +38 -0
  26. package/dist/lib/envelope-parser.d.ts.map +1 -0
  27. package/dist/lib/fingerprint.d.ts +23 -0
  28. package/dist/lib/fingerprint.d.ts.map +1 -0
  29. package/dist/middleware/auth.d.ts +10 -0
  30. package/dist/middleware/auth.d.ts.map +1 -0
  31. package/dist/routes/auth.d.ts +6 -0
  32. package/dist/routes/auth.d.ts.map +1 -0
  33. package/dist/routes/events.d.ts +11 -0
  34. package/dist/routes/events.d.ts.map +1 -0
  35. package/dist/routes/ingestion.d.ts +6 -0
  36. package/dist/routes/ingestion.d.ts.map +1 -0
  37. package/dist/routes/issues.d.ts +11 -0
  38. package/dist/routes/issues.d.ts.map +1 -0
  39. package/dist/routes/projects.d.ts +11 -0
  40. package/dist/routes/projects.d.ts.map +1 -0
  41. package/dist/rpc.d.ts +59 -0
  42. package/dist/rpc.d.ts.map +1 -0
  43. package/dist/types.d.ts +166 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/package.json +60 -0
package/dist/index.js ADDED
@@ -0,0 +1,4774 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // ../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/_internal/utils.mjs
5
+ // @__NO_SIDE_EFFECTS__
6
+ function createNotImplementedError(name) {
7
+ return new Error(`[unenv] ${name} is not implemented yet!`);
8
+ }
9
+ __name(createNotImplementedError, "createNotImplementedError");
10
+ // @__NO_SIDE_EFFECTS__
11
+ function notImplemented(name) {
12
+ const fn = /* @__PURE__ */ __name(() => {
13
+ throw /* @__PURE__ */ createNotImplementedError(name);
14
+ }, "fn");
15
+ return Object.assign(fn, { __unenv__: true });
16
+ }
17
+ __name(notImplemented, "notImplemented");
18
+
19
+ // ../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/perf_hooks/performance.mjs
20
+ var _timeOrigin = globalThis.performance?.timeOrigin ?? Date.now();
21
+ var _performanceNow = globalThis.performance?.now ? globalThis.performance.now.bind(globalThis.performance) : () => Date.now() - _timeOrigin;
22
+ var nodeTiming = {
23
+ name: "node",
24
+ entryType: "node",
25
+ startTime: 0,
26
+ duration: 0,
27
+ nodeStart: 0,
28
+ v8Start: 0,
29
+ bootstrapComplete: 0,
30
+ environment: 0,
31
+ loopStart: 0,
32
+ loopExit: 0,
33
+ idleTime: 0,
34
+ uvMetricsInfo: {
35
+ loopCount: 0,
36
+ events: 0,
37
+ eventsWaiting: 0
38
+ },
39
+ detail: void 0,
40
+ toJSON() {
41
+ return this;
42
+ }
43
+ };
44
+ var PerformanceEntry = class {
45
+ static {
46
+ __name(this, "PerformanceEntry");
47
+ }
48
+ __unenv__ = true;
49
+ detail;
50
+ entryType = "event";
51
+ name;
52
+ startTime;
53
+ constructor(name, options) {
54
+ this.name = name;
55
+ this.startTime = options?.startTime || _performanceNow();
56
+ this.detail = options?.detail;
57
+ }
58
+ get duration() {
59
+ return _performanceNow() - this.startTime;
60
+ }
61
+ toJSON() {
62
+ return {
63
+ name: this.name,
64
+ entryType: this.entryType,
65
+ startTime: this.startTime,
66
+ duration: this.duration,
67
+ detail: this.detail
68
+ };
69
+ }
70
+ };
71
+ var PerformanceMark = class PerformanceMark2 extends PerformanceEntry {
72
+ static {
73
+ __name(this, "PerformanceMark");
74
+ }
75
+ entryType = "mark";
76
+ constructor() {
77
+ super(...arguments);
78
+ }
79
+ get duration() {
80
+ return 0;
81
+ }
82
+ };
83
+ var PerformanceMeasure = class extends PerformanceEntry {
84
+ static {
85
+ __name(this, "PerformanceMeasure");
86
+ }
87
+ entryType = "measure";
88
+ };
89
+ var PerformanceResourceTiming = class extends PerformanceEntry {
90
+ static {
91
+ __name(this, "PerformanceResourceTiming");
92
+ }
93
+ entryType = "resource";
94
+ serverTiming = [];
95
+ connectEnd = 0;
96
+ connectStart = 0;
97
+ decodedBodySize = 0;
98
+ domainLookupEnd = 0;
99
+ domainLookupStart = 0;
100
+ encodedBodySize = 0;
101
+ fetchStart = 0;
102
+ initiatorType = "";
103
+ name = "";
104
+ nextHopProtocol = "";
105
+ redirectEnd = 0;
106
+ redirectStart = 0;
107
+ requestStart = 0;
108
+ responseEnd = 0;
109
+ responseStart = 0;
110
+ secureConnectionStart = 0;
111
+ startTime = 0;
112
+ transferSize = 0;
113
+ workerStart = 0;
114
+ responseStatus = 0;
115
+ };
116
+ var PerformanceObserverEntryList = class {
117
+ static {
118
+ __name(this, "PerformanceObserverEntryList");
119
+ }
120
+ __unenv__ = true;
121
+ getEntries() {
122
+ return [];
123
+ }
124
+ getEntriesByName(_name, _type) {
125
+ return [];
126
+ }
127
+ getEntriesByType(type) {
128
+ return [];
129
+ }
130
+ };
131
+ var Performance = class {
132
+ static {
133
+ __name(this, "Performance");
134
+ }
135
+ __unenv__ = true;
136
+ timeOrigin = _timeOrigin;
137
+ eventCounts = /* @__PURE__ */ new Map();
138
+ _entries = [];
139
+ _resourceTimingBufferSize = 0;
140
+ navigation = void 0;
141
+ timing = void 0;
142
+ timerify(_fn, _options) {
143
+ throw createNotImplementedError("Performance.timerify");
144
+ }
145
+ get nodeTiming() {
146
+ return nodeTiming;
147
+ }
148
+ eventLoopUtilization() {
149
+ return {};
150
+ }
151
+ markResourceTiming() {
152
+ return new PerformanceResourceTiming("");
153
+ }
154
+ onresourcetimingbufferfull = null;
155
+ now() {
156
+ if (this.timeOrigin === _timeOrigin) {
157
+ return _performanceNow();
158
+ }
159
+ return Date.now() - this.timeOrigin;
160
+ }
161
+ clearMarks(markName) {
162
+ this._entries = markName ? this._entries.filter((e) => e.name !== markName) : this._entries.filter((e) => e.entryType !== "mark");
163
+ }
164
+ clearMeasures(measureName) {
165
+ this._entries = measureName ? this._entries.filter((e) => e.name !== measureName) : this._entries.filter((e) => e.entryType !== "measure");
166
+ }
167
+ clearResourceTimings() {
168
+ this._entries = this._entries.filter((e) => e.entryType !== "resource" || e.entryType !== "navigation");
169
+ }
170
+ getEntries() {
171
+ return this._entries;
172
+ }
173
+ getEntriesByName(name, type) {
174
+ return this._entries.filter((e) => e.name === name && (!type || e.entryType === type));
175
+ }
176
+ getEntriesByType(type) {
177
+ return this._entries.filter((e) => e.entryType === type);
178
+ }
179
+ mark(name, options) {
180
+ const entry = new PerformanceMark(name, options);
181
+ this._entries.push(entry);
182
+ return entry;
183
+ }
184
+ measure(measureName, startOrMeasureOptions, endMark) {
185
+ let start;
186
+ let end;
187
+ if (typeof startOrMeasureOptions === "string") {
188
+ start = this.getEntriesByName(startOrMeasureOptions, "mark")[0]?.startTime;
189
+ end = this.getEntriesByName(endMark, "mark")[0]?.startTime;
190
+ } else {
191
+ start = Number.parseFloat(startOrMeasureOptions?.start) || this.now();
192
+ end = Number.parseFloat(startOrMeasureOptions?.end) || this.now();
193
+ }
194
+ const entry = new PerformanceMeasure(measureName, {
195
+ startTime: start,
196
+ detail: {
197
+ start,
198
+ end
199
+ }
200
+ });
201
+ this._entries.push(entry);
202
+ return entry;
203
+ }
204
+ setResourceTimingBufferSize(maxSize) {
205
+ this._resourceTimingBufferSize = maxSize;
206
+ }
207
+ addEventListener(type, listener, options) {
208
+ throw createNotImplementedError("Performance.addEventListener");
209
+ }
210
+ removeEventListener(type, listener, options) {
211
+ throw createNotImplementedError("Performance.removeEventListener");
212
+ }
213
+ dispatchEvent(event) {
214
+ throw createNotImplementedError("Performance.dispatchEvent");
215
+ }
216
+ toJSON() {
217
+ return this;
218
+ }
219
+ };
220
+ var PerformanceObserver = class {
221
+ static {
222
+ __name(this, "PerformanceObserver");
223
+ }
224
+ __unenv__ = true;
225
+ static supportedEntryTypes = [];
226
+ _callback = null;
227
+ constructor(callback) {
228
+ this._callback = callback;
229
+ }
230
+ takeRecords() {
231
+ return [];
232
+ }
233
+ disconnect() {
234
+ throw createNotImplementedError("PerformanceObserver.disconnect");
235
+ }
236
+ observe(options) {
237
+ throw createNotImplementedError("PerformanceObserver.observe");
238
+ }
239
+ bind(fn) {
240
+ return fn;
241
+ }
242
+ runInAsyncScope(fn, thisArg, ...args) {
243
+ return fn.call(thisArg, ...args);
244
+ }
245
+ asyncId() {
246
+ return 0;
247
+ }
248
+ triggerAsyncId() {
249
+ return 0;
250
+ }
251
+ emitDestroy() {
252
+ return this;
253
+ }
254
+ };
255
+ var performance = globalThis.performance && "addEventListener" in globalThis.performance ? globalThis.performance : new Performance();
256
+
257
+ // ../../node_modules/.pnpm/@cloudflare+unenv-preset@2.10.0_unenv@2.0.0-rc.24_workerd@1.20260114.0/node_modules/@cloudflare/unenv-preset/dist/runtime/polyfill/performance.mjs
258
+ globalThis.performance = performance;
259
+ globalThis.Performance = Performance;
260
+ globalThis.PerformanceEntry = PerformanceEntry;
261
+ globalThis.PerformanceMark = PerformanceMark;
262
+ globalThis.PerformanceMeasure = PerformanceMeasure;
263
+ globalThis.PerformanceObserver = PerformanceObserver;
264
+ globalThis.PerformanceObserverEntryList = PerformanceObserverEntryList;
265
+ globalThis.PerformanceResourceTiming = PerformanceResourceTiming;
266
+
267
+ // ../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/process/hrtime.mjs
268
+ var hrtime = /* @__PURE__ */ Object.assign(/* @__PURE__ */ __name(function hrtime2(startTime) {
269
+ const now = Date.now();
270
+ const seconds = Math.trunc(now / 1e3);
271
+ const nanos = now % 1e3 * 1e6;
272
+ if (startTime) {
273
+ let diffSeconds = seconds - startTime[0];
274
+ let diffNanos = nanos - startTime[0];
275
+ if (diffNanos < 0) {
276
+ diffSeconds = diffSeconds - 1;
277
+ diffNanos = 1e9 + diffNanos;
278
+ }
279
+ return [diffSeconds, diffNanos];
280
+ }
281
+ return [seconds, nanos];
282
+ }, "hrtime"), { bigint: /* @__PURE__ */ __name(function bigint() {
283
+ return BigInt(Date.now() * 1e6);
284
+ }, "bigint") });
285
+
286
+ // ../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/process/process.mjs
287
+ import { EventEmitter } from "node:events";
288
+
289
+ // ../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/tty/read-stream.mjs
290
+ var ReadStream = class {
291
+ static {
292
+ __name(this, "ReadStream");
293
+ }
294
+ fd;
295
+ isRaw = false;
296
+ isTTY = false;
297
+ constructor(fd) {
298
+ this.fd = fd;
299
+ }
300
+ setRawMode(mode) {
301
+ this.isRaw = mode;
302
+ return this;
303
+ }
304
+ };
305
+
306
+ // ../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/tty/write-stream.mjs
307
+ var WriteStream = class {
308
+ static {
309
+ __name(this, "WriteStream");
310
+ }
311
+ fd;
312
+ columns = 80;
313
+ rows = 24;
314
+ isTTY = false;
315
+ constructor(fd) {
316
+ this.fd = fd;
317
+ }
318
+ clearLine(dir, callback) {
319
+ callback && callback();
320
+ return false;
321
+ }
322
+ clearScreenDown(callback) {
323
+ callback && callback();
324
+ return false;
325
+ }
326
+ cursorTo(x, y, callback) {
327
+ callback && typeof callback === "function" && callback();
328
+ return false;
329
+ }
330
+ moveCursor(dx, dy, callback) {
331
+ callback && callback();
332
+ return false;
333
+ }
334
+ getColorDepth(env2) {
335
+ return 1;
336
+ }
337
+ hasColors(count, env2) {
338
+ return false;
339
+ }
340
+ getWindowSize() {
341
+ return [this.columns, this.rows];
342
+ }
343
+ write(str, encoding, cb) {
344
+ if (str instanceof Uint8Array) {
345
+ str = new TextDecoder().decode(str);
346
+ }
347
+ try {
348
+ console.log(str);
349
+ } catch {
350
+ }
351
+ cb && typeof cb === "function" && cb();
352
+ return false;
353
+ }
354
+ };
355
+
356
+ // ../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/process/node-version.mjs
357
+ var NODE_VERSION = "22.14.0";
358
+
359
+ // ../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/process/process.mjs
360
+ var Process = class _Process extends EventEmitter {
361
+ static {
362
+ __name(this, "Process");
363
+ }
364
+ env;
365
+ hrtime;
366
+ nextTick;
367
+ constructor(impl) {
368
+ super();
369
+ this.env = impl.env;
370
+ this.hrtime = impl.hrtime;
371
+ this.nextTick = impl.nextTick;
372
+ for (const prop of [...Object.getOwnPropertyNames(_Process.prototype), ...Object.getOwnPropertyNames(EventEmitter.prototype)]) {
373
+ const value = this[prop];
374
+ if (typeof value === "function") {
375
+ this[prop] = value.bind(this);
376
+ }
377
+ }
378
+ }
379
+ // --- event emitter ---
380
+ emitWarning(warning, type, code) {
381
+ console.warn(`${code ? `[${code}] ` : ""}${type ? `${type}: ` : ""}${warning}`);
382
+ }
383
+ emit(...args) {
384
+ return super.emit(...args);
385
+ }
386
+ listeners(eventName) {
387
+ return super.listeners(eventName);
388
+ }
389
+ // --- stdio (lazy initializers) ---
390
+ #stdin;
391
+ #stdout;
392
+ #stderr;
393
+ get stdin() {
394
+ return this.#stdin ??= new ReadStream(0);
395
+ }
396
+ get stdout() {
397
+ return this.#stdout ??= new WriteStream(1);
398
+ }
399
+ get stderr() {
400
+ return this.#stderr ??= new WriteStream(2);
401
+ }
402
+ // --- cwd ---
403
+ #cwd = "/";
404
+ chdir(cwd2) {
405
+ this.#cwd = cwd2;
406
+ }
407
+ cwd() {
408
+ return this.#cwd;
409
+ }
410
+ // --- dummy props and getters ---
411
+ arch = "";
412
+ platform = "";
413
+ argv = [];
414
+ argv0 = "";
415
+ execArgv = [];
416
+ execPath = "";
417
+ title = "";
418
+ pid = 200;
419
+ ppid = 100;
420
+ get version() {
421
+ return `v${NODE_VERSION}`;
422
+ }
423
+ get versions() {
424
+ return { node: NODE_VERSION };
425
+ }
426
+ get allowedNodeEnvironmentFlags() {
427
+ return /* @__PURE__ */ new Set();
428
+ }
429
+ get sourceMapsEnabled() {
430
+ return false;
431
+ }
432
+ get debugPort() {
433
+ return 0;
434
+ }
435
+ get throwDeprecation() {
436
+ return false;
437
+ }
438
+ get traceDeprecation() {
439
+ return false;
440
+ }
441
+ get features() {
442
+ return {};
443
+ }
444
+ get release() {
445
+ return {};
446
+ }
447
+ get connected() {
448
+ return false;
449
+ }
450
+ get config() {
451
+ return {};
452
+ }
453
+ get moduleLoadList() {
454
+ return [];
455
+ }
456
+ constrainedMemory() {
457
+ return 0;
458
+ }
459
+ availableMemory() {
460
+ return 0;
461
+ }
462
+ uptime() {
463
+ return 0;
464
+ }
465
+ resourceUsage() {
466
+ return {};
467
+ }
468
+ // --- noop methods ---
469
+ ref() {
470
+ }
471
+ unref() {
472
+ }
473
+ // --- unimplemented methods ---
474
+ umask() {
475
+ throw createNotImplementedError("process.umask");
476
+ }
477
+ getBuiltinModule() {
478
+ return void 0;
479
+ }
480
+ getActiveResourcesInfo() {
481
+ throw createNotImplementedError("process.getActiveResourcesInfo");
482
+ }
483
+ exit() {
484
+ throw createNotImplementedError("process.exit");
485
+ }
486
+ reallyExit() {
487
+ throw createNotImplementedError("process.reallyExit");
488
+ }
489
+ kill() {
490
+ throw createNotImplementedError("process.kill");
491
+ }
492
+ abort() {
493
+ throw createNotImplementedError("process.abort");
494
+ }
495
+ dlopen() {
496
+ throw createNotImplementedError("process.dlopen");
497
+ }
498
+ setSourceMapsEnabled() {
499
+ throw createNotImplementedError("process.setSourceMapsEnabled");
500
+ }
501
+ loadEnvFile() {
502
+ throw createNotImplementedError("process.loadEnvFile");
503
+ }
504
+ disconnect() {
505
+ throw createNotImplementedError("process.disconnect");
506
+ }
507
+ cpuUsage() {
508
+ throw createNotImplementedError("process.cpuUsage");
509
+ }
510
+ setUncaughtExceptionCaptureCallback() {
511
+ throw createNotImplementedError("process.setUncaughtExceptionCaptureCallback");
512
+ }
513
+ hasUncaughtExceptionCaptureCallback() {
514
+ throw createNotImplementedError("process.hasUncaughtExceptionCaptureCallback");
515
+ }
516
+ initgroups() {
517
+ throw createNotImplementedError("process.initgroups");
518
+ }
519
+ openStdin() {
520
+ throw createNotImplementedError("process.openStdin");
521
+ }
522
+ assert() {
523
+ throw createNotImplementedError("process.assert");
524
+ }
525
+ binding() {
526
+ throw createNotImplementedError("process.binding");
527
+ }
528
+ // --- attached interfaces ---
529
+ permission = { has: /* @__PURE__ */ notImplemented("process.permission.has") };
530
+ report = {
531
+ directory: "",
532
+ filename: "",
533
+ signal: "SIGUSR2",
534
+ compact: false,
535
+ reportOnFatalError: false,
536
+ reportOnSignal: false,
537
+ reportOnUncaughtException: false,
538
+ getReport: /* @__PURE__ */ notImplemented("process.report.getReport"),
539
+ writeReport: /* @__PURE__ */ notImplemented("process.report.writeReport")
540
+ };
541
+ finalization = {
542
+ register: /* @__PURE__ */ notImplemented("process.finalization.register"),
543
+ unregister: /* @__PURE__ */ notImplemented("process.finalization.unregister"),
544
+ registerBeforeExit: /* @__PURE__ */ notImplemented("process.finalization.registerBeforeExit")
545
+ };
546
+ memoryUsage = Object.assign(() => ({
547
+ arrayBuffers: 0,
548
+ rss: 0,
549
+ external: 0,
550
+ heapTotal: 0,
551
+ heapUsed: 0
552
+ }), { rss: /* @__PURE__ */ __name(() => 0, "rss") });
553
+ // --- undefined props ---
554
+ mainModule = void 0;
555
+ domain = void 0;
556
+ // optional
557
+ send = void 0;
558
+ exitCode = void 0;
559
+ channel = void 0;
560
+ getegid = void 0;
561
+ geteuid = void 0;
562
+ getgid = void 0;
563
+ getgroups = void 0;
564
+ getuid = void 0;
565
+ setegid = void 0;
566
+ seteuid = void 0;
567
+ setgid = void 0;
568
+ setgroups = void 0;
569
+ setuid = void 0;
570
+ // internals
571
+ _events = void 0;
572
+ _eventsCount = void 0;
573
+ _exiting = void 0;
574
+ _maxListeners = void 0;
575
+ _debugEnd = void 0;
576
+ _debugProcess = void 0;
577
+ _fatalException = void 0;
578
+ _getActiveHandles = void 0;
579
+ _getActiveRequests = void 0;
580
+ _kill = void 0;
581
+ _preload_modules = void 0;
582
+ _rawDebug = void 0;
583
+ _startProfilerIdleNotifier = void 0;
584
+ _stopProfilerIdleNotifier = void 0;
585
+ _tickCallback = void 0;
586
+ _disconnect = void 0;
587
+ _handleQueue = void 0;
588
+ _pendingMessage = void 0;
589
+ _channel = void 0;
590
+ _send = void 0;
591
+ _linkedBinding = void 0;
592
+ };
593
+
594
+ // ../../node_modules/.pnpm/@cloudflare+unenv-preset@2.10.0_unenv@2.0.0-rc.24_workerd@1.20260114.0/node_modules/@cloudflare/unenv-preset/dist/runtime/node/process.mjs
595
+ var globalProcess = globalThis["process"];
596
+ var getBuiltinModule = globalProcess.getBuiltinModule;
597
+ var workerdProcess = getBuiltinModule("node:process");
598
+ var isWorkerdProcessV2 = globalThis.Cloudflare.compatibilityFlags.enable_nodejs_process_v2;
599
+ var unenvProcess = new Process({
600
+ env: globalProcess.env,
601
+ // `hrtime` is only available from workerd process v2
602
+ hrtime: isWorkerdProcessV2 ? workerdProcess.hrtime : hrtime,
603
+ // `nextTick` is available from workerd process v1
604
+ nextTick: workerdProcess.nextTick
605
+ });
606
+ var { exit, features, platform } = workerdProcess;
607
+ var {
608
+ // Always implemented by workerd
609
+ env,
610
+ // Only implemented in workerd v2
611
+ hrtime: hrtime3,
612
+ // Always implemented by workerd
613
+ nextTick
614
+ } = unenvProcess;
615
+ var {
616
+ _channel,
617
+ _disconnect,
618
+ _events,
619
+ _eventsCount,
620
+ _handleQueue,
621
+ _maxListeners,
622
+ _pendingMessage,
623
+ _send,
624
+ assert,
625
+ disconnect,
626
+ mainModule
627
+ } = unenvProcess;
628
+ var {
629
+ // @ts-expect-error `_debugEnd` is missing typings
630
+ _debugEnd,
631
+ // @ts-expect-error `_debugProcess` is missing typings
632
+ _debugProcess,
633
+ // @ts-expect-error `_exiting` is missing typings
634
+ _exiting,
635
+ // @ts-expect-error `_fatalException` is missing typings
636
+ _fatalException,
637
+ // @ts-expect-error `_getActiveHandles` is missing typings
638
+ _getActiveHandles,
639
+ // @ts-expect-error `_getActiveRequests` is missing typings
640
+ _getActiveRequests,
641
+ // @ts-expect-error `_kill` is missing typings
642
+ _kill,
643
+ // @ts-expect-error `_linkedBinding` is missing typings
644
+ _linkedBinding,
645
+ // @ts-expect-error `_preload_modules` is missing typings
646
+ _preload_modules,
647
+ // @ts-expect-error `_rawDebug` is missing typings
648
+ _rawDebug,
649
+ // @ts-expect-error `_startProfilerIdleNotifier` is missing typings
650
+ _startProfilerIdleNotifier,
651
+ // @ts-expect-error `_stopProfilerIdleNotifier` is missing typings
652
+ _stopProfilerIdleNotifier,
653
+ // @ts-expect-error `_tickCallback` is missing typings
654
+ _tickCallback,
655
+ abort,
656
+ addListener,
657
+ allowedNodeEnvironmentFlags,
658
+ arch,
659
+ argv,
660
+ argv0,
661
+ availableMemory,
662
+ // @ts-expect-error `binding` is missing typings
663
+ binding,
664
+ channel,
665
+ chdir,
666
+ config,
667
+ connected,
668
+ constrainedMemory,
669
+ cpuUsage,
670
+ cwd,
671
+ debugPort,
672
+ dlopen,
673
+ // @ts-expect-error `domain` is missing typings
674
+ domain,
675
+ emit,
676
+ emitWarning,
677
+ eventNames,
678
+ execArgv,
679
+ execPath,
680
+ exitCode,
681
+ finalization,
682
+ getActiveResourcesInfo,
683
+ getegid,
684
+ geteuid,
685
+ getgid,
686
+ getgroups,
687
+ getMaxListeners,
688
+ getuid,
689
+ hasUncaughtExceptionCaptureCallback,
690
+ // @ts-expect-error `initgroups` is missing typings
691
+ initgroups,
692
+ kill,
693
+ listenerCount,
694
+ listeners,
695
+ loadEnvFile,
696
+ memoryUsage,
697
+ // @ts-expect-error `moduleLoadList` is missing typings
698
+ moduleLoadList,
699
+ off,
700
+ on,
701
+ once,
702
+ // @ts-expect-error `openStdin` is missing typings
703
+ openStdin,
704
+ permission,
705
+ pid,
706
+ ppid,
707
+ prependListener,
708
+ prependOnceListener,
709
+ rawListeners,
710
+ // @ts-expect-error `reallyExit` is missing typings
711
+ reallyExit,
712
+ ref,
713
+ release,
714
+ removeAllListeners,
715
+ removeListener,
716
+ report,
717
+ resourceUsage,
718
+ send,
719
+ setegid,
720
+ seteuid,
721
+ setgid,
722
+ setgroups,
723
+ setMaxListeners,
724
+ setSourceMapsEnabled,
725
+ setuid,
726
+ setUncaughtExceptionCaptureCallback,
727
+ sourceMapsEnabled,
728
+ stderr,
729
+ stdin,
730
+ stdout,
731
+ throwDeprecation,
732
+ title,
733
+ traceDeprecation,
734
+ umask,
735
+ unref,
736
+ uptime,
737
+ version,
738
+ versions
739
+ } = isWorkerdProcessV2 ? workerdProcess : unenvProcess;
740
+ var _process = {
741
+ abort,
742
+ addListener,
743
+ allowedNodeEnvironmentFlags,
744
+ hasUncaughtExceptionCaptureCallback,
745
+ setUncaughtExceptionCaptureCallback,
746
+ loadEnvFile,
747
+ sourceMapsEnabled,
748
+ arch,
749
+ argv,
750
+ argv0,
751
+ chdir,
752
+ config,
753
+ connected,
754
+ constrainedMemory,
755
+ availableMemory,
756
+ cpuUsage,
757
+ cwd,
758
+ debugPort,
759
+ dlopen,
760
+ disconnect,
761
+ emit,
762
+ emitWarning,
763
+ env,
764
+ eventNames,
765
+ execArgv,
766
+ execPath,
767
+ exit,
768
+ finalization,
769
+ features,
770
+ getBuiltinModule,
771
+ getActiveResourcesInfo,
772
+ getMaxListeners,
773
+ hrtime: hrtime3,
774
+ kill,
775
+ listeners,
776
+ listenerCount,
777
+ memoryUsage,
778
+ nextTick,
779
+ on,
780
+ off,
781
+ once,
782
+ pid,
783
+ platform,
784
+ ppid,
785
+ prependListener,
786
+ prependOnceListener,
787
+ rawListeners,
788
+ release,
789
+ removeAllListeners,
790
+ removeListener,
791
+ report,
792
+ resourceUsage,
793
+ setMaxListeners,
794
+ setSourceMapsEnabled,
795
+ stderr,
796
+ stdin,
797
+ stdout,
798
+ title,
799
+ throwDeprecation,
800
+ traceDeprecation,
801
+ umask,
802
+ uptime,
803
+ version,
804
+ versions,
805
+ // @ts-expect-error old API
806
+ domain,
807
+ initgroups,
808
+ moduleLoadList,
809
+ reallyExit,
810
+ openStdin,
811
+ assert,
812
+ binding,
813
+ send,
814
+ exitCode,
815
+ channel,
816
+ getegid,
817
+ geteuid,
818
+ getgid,
819
+ getgroups,
820
+ getuid,
821
+ setegid,
822
+ seteuid,
823
+ setgid,
824
+ setgroups,
825
+ setuid,
826
+ permission,
827
+ mainModule,
828
+ _events,
829
+ _eventsCount,
830
+ _exiting,
831
+ _maxListeners,
832
+ _debugEnd,
833
+ _debugProcess,
834
+ _fatalException,
835
+ _getActiveHandles,
836
+ _getActiveRequests,
837
+ _kill,
838
+ _preload_modules,
839
+ _rawDebug,
840
+ _startProfilerIdleNotifier,
841
+ _stopProfilerIdleNotifier,
842
+ _tickCallback,
843
+ _disconnect,
844
+ _handleQueue,
845
+ _pendingMessage,
846
+ _channel,
847
+ _send,
848
+ _linkedBinding
849
+ };
850
+ var process_default = _process;
851
+
852
+ // ../../node_modules/.pnpm/wrangler@4.59.2_@cloudflare+workers-types@4.20260118.0/node_modules/wrangler/_virtual_unenv_global_polyfill-@cloudflare-unenv-preset-node-process
853
+ globalThis.process = process_default;
854
+
855
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/compose.js
856
+ var compose = /* @__PURE__ */ __name((middleware, onError, onNotFound) => {
857
+ return (context, next) => {
858
+ let index = -1;
859
+ return dispatch(0);
860
+ async function dispatch(i) {
861
+ if (i <= index) {
862
+ throw new Error("next() called multiple times");
863
+ }
864
+ index = i;
865
+ let res;
866
+ let isError = false;
867
+ let handler;
868
+ if (middleware[i]) {
869
+ handler = middleware[i][0][0];
870
+ context.req.routeIndex = i;
871
+ } else {
872
+ handler = i === middleware.length && next || void 0;
873
+ }
874
+ if (handler) {
875
+ try {
876
+ res = await handler(context, () => dispatch(i + 1));
877
+ } catch (err) {
878
+ if (err instanceof Error && onError) {
879
+ context.error = err;
880
+ res = await onError(err, context);
881
+ isError = true;
882
+ } else {
883
+ throw err;
884
+ }
885
+ }
886
+ } else {
887
+ if (context.finalized === false && onNotFound) {
888
+ res = await onNotFound(context);
889
+ }
890
+ }
891
+ if (res && (context.finalized === false || isError)) {
892
+ context.res = res;
893
+ }
894
+ return context;
895
+ }
896
+ __name(dispatch, "dispatch");
897
+ };
898
+ }, "compose");
899
+
900
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/request/constants.js
901
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
902
+
903
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/body.js
904
+ var parseBody = /* @__PURE__ */ __name(async (request, options = /* @__PURE__ */ Object.create(null)) => {
905
+ const { all = false, dot = false } = options;
906
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
907
+ const contentType = headers.get("Content-Type");
908
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
909
+ return parseFormData(request, { all, dot });
910
+ }
911
+ return {};
912
+ }, "parseBody");
913
+ async function parseFormData(request, options) {
914
+ const formData = await request.formData();
915
+ if (formData) {
916
+ return convertFormDataToBodyData(formData, options);
917
+ }
918
+ return {};
919
+ }
920
+ __name(parseFormData, "parseFormData");
921
+ function convertFormDataToBodyData(formData, options) {
922
+ const form = /* @__PURE__ */ Object.create(null);
923
+ formData.forEach((value, key) => {
924
+ const shouldParseAllValues = options.all || key.endsWith("[]");
925
+ if (!shouldParseAllValues) {
926
+ form[key] = value;
927
+ } else {
928
+ handleParsingAllValues(form, key, value);
929
+ }
930
+ });
931
+ if (options.dot) {
932
+ Object.entries(form).forEach(([key, value]) => {
933
+ const shouldParseDotValues = key.includes(".");
934
+ if (shouldParseDotValues) {
935
+ handleParsingNestedValues(form, key, value);
936
+ delete form[key];
937
+ }
938
+ });
939
+ }
940
+ return form;
941
+ }
942
+ __name(convertFormDataToBodyData, "convertFormDataToBodyData");
943
+ var handleParsingAllValues = /* @__PURE__ */ __name((form, key, value) => {
944
+ if (form[key] !== void 0) {
945
+ if (Array.isArray(form[key])) {
946
+ ;
947
+ form[key].push(value);
948
+ } else {
949
+ form[key] = [form[key], value];
950
+ }
951
+ } else {
952
+ if (!key.endsWith("[]")) {
953
+ form[key] = value;
954
+ } else {
955
+ form[key] = [value];
956
+ }
957
+ }
958
+ }, "handleParsingAllValues");
959
+ var handleParsingNestedValues = /* @__PURE__ */ __name((form, key, value) => {
960
+ let nestedForm = form;
961
+ const keys = key.split(".");
962
+ keys.forEach((key2, index) => {
963
+ if (index === keys.length - 1) {
964
+ nestedForm[key2] = value;
965
+ } else {
966
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
967
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
968
+ }
969
+ nestedForm = nestedForm[key2];
970
+ }
971
+ });
972
+ }, "handleParsingNestedValues");
973
+
974
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/url.js
975
+ var splitPath = /* @__PURE__ */ __name((path) => {
976
+ const paths = path.split("/");
977
+ if (paths[0] === "") {
978
+ paths.shift();
979
+ }
980
+ return paths;
981
+ }, "splitPath");
982
+ var splitRoutingPath = /* @__PURE__ */ __name((routePath) => {
983
+ const { groups, path } = extractGroupsFromPath(routePath);
984
+ const paths = splitPath(path);
985
+ return replaceGroupMarks(paths, groups);
986
+ }, "splitRoutingPath");
987
+ var extractGroupsFromPath = /* @__PURE__ */ __name((path) => {
988
+ const groups = [];
989
+ path = path.replace(/\{[^}]+\}/g, (match2, index) => {
990
+ const mark = `@${index}`;
991
+ groups.push([mark, match2]);
992
+ return mark;
993
+ });
994
+ return { groups, path };
995
+ }, "extractGroupsFromPath");
996
+ var replaceGroupMarks = /* @__PURE__ */ __name((paths, groups) => {
997
+ for (let i = groups.length - 1; i >= 0; i--) {
998
+ const [mark] = groups[i];
999
+ for (let j = paths.length - 1; j >= 0; j--) {
1000
+ if (paths[j].includes(mark)) {
1001
+ paths[j] = paths[j].replace(mark, groups[i][1]);
1002
+ break;
1003
+ }
1004
+ }
1005
+ }
1006
+ return paths;
1007
+ }, "replaceGroupMarks");
1008
+ var patternCache = {};
1009
+ var getPattern = /* @__PURE__ */ __name((label, next) => {
1010
+ if (label === "*") {
1011
+ return "*";
1012
+ }
1013
+ const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1014
+ if (match2) {
1015
+ const cacheKey = `${label}#${next}`;
1016
+ if (!patternCache[cacheKey]) {
1017
+ if (match2[2]) {
1018
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
1019
+ } else {
1020
+ patternCache[cacheKey] = [label, match2[1], true];
1021
+ }
1022
+ }
1023
+ return patternCache[cacheKey];
1024
+ }
1025
+ return null;
1026
+ }, "getPattern");
1027
+ var tryDecode = /* @__PURE__ */ __name((str, decoder) => {
1028
+ try {
1029
+ return decoder(str);
1030
+ } catch {
1031
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
1032
+ try {
1033
+ return decoder(match2);
1034
+ } catch {
1035
+ return match2;
1036
+ }
1037
+ });
1038
+ }
1039
+ }, "tryDecode");
1040
+ var tryDecodeURI = /* @__PURE__ */ __name((str) => tryDecode(str, decodeURI), "tryDecodeURI");
1041
+ var getPath = /* @__PURE__ */ __name((request) => {
1042
+ const url = request.url;
1043
+ const start = url.indexOf("/", url.indexOf(":") + 4);
1044
+ let i = start;
1045
+ for (; i < url.length; i++) {
1046
+ const charCode = url.charCodeAt(i);
1047
+ if (charCode === 37) {
1048
+ const queryIndex = url.indexOf("?", i);
1049
+ const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
1050
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
1051
+ } else if (charCode === 63) {
1052
+ break;
1053
+ }
1054
+ }
1055
+ return url.slice(start, i);
1056
+ }, "getPath");
1057
+ var getPathNoStrict = /* @__PURE__ */ __name((request) => {
1058
+ const result = getPath(request);
1059
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
1060
+ }, "getPathNoStrict");
1061
+ var mergePath = /* @__PURE__ */ __name((base, sub, ...rest) => {
1062
+ if (rest.length) {
1063
+ sub = mergePath(sub, ...rest);
1064
+ }
1065
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
1066
+ }, "mergePath");
1067
+ var checkOptionalParameter = /* @__PURE__ */ __name((path) => {
1068
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
1069
+ return null;
1070
+ }
1071
+ const segments = path.split("/");
1072
+ const results = [];
1073
+ let basePath = "";
1074
+ segments.forEach((segment) => {
1075
+ if (segment !== "" && !/\:/.test(segment)) {
1076
+ basePath += "/" + segment;
1077
+ } else if (/\:/.test(segment)) {
1078
+ if (/\?/.test(segment)) {
1079
+ if (results.length === 0 && basePath === "") {
1080
+ results.push("/");
1081
+ } else {
1082
+ results.push(basePath);
1083
+ }
1084
+ const optionalSegment = segment.replace("?", "");
1085
+ basePath += "/" + optionalSegment;
1086
+ results.push(basePath);
1087
+ } else {
1088
+ basePath += "/" + segment;
1089
+ }
1090
+ }
1091
+ });
1092
+ return results.filter((v, i, a) => a.indexOf(v) === i);
1093
+ }, "checkOptionalParameter");
1094
+ var _decodeURI = /* @__PURE__ */ __name((value) => {
1095
+ if (!/[%+]/.test(value)) {
1096
+ return value;
1097
+ }
1098
+ if (value.indexOf("+") !== -1) {
1099
+ value = value.replace(/\+/g, " ");
1100
+ }
1101
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
1102
+ }, "_decodeURI");
1103
+ var _getQueryParam = /* @__PURE__ */ __name((url, key, multiple) => {
1104
+ let encoded;
1105
+ if (!multiple && key && !/[%+]/.test(key)) {
1106
+ let keyIndex2 = url.indexOf("?", 8);
1107
+ if (keyIndex2 === -1) {
1108
+ return void 0;
1109
+ }
1110
+ if (!url.startsWith(key, keyIndex2 + 1)) {
1111
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1112
+ }
1113
+ while (keyIndex2 !== -1) {
1114
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
1115
+ if (trailingKeyCode === 61) {
1116
+ const valueIndex = keyIndex2 + key.length + 2;
1117
+ const endIndex = url.indexOf("&", valueIndex);
1118
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
1119
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
1120
+ return "";
1121
+ }
1122
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1123
+ }
1124
+ encoded = /[%+]/.test(url);
1125
+ if (!encoded) {
1126
+ return void 0;
1127
+ }
1128
+ }
1129
+ const results = {};
1130
+ encoded ??= /[%+]/.test(url);
1131
+ let keyIndex = url.indexOf("?", 8);
1132
+ while (keyIndex !== -1) {
1133
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
1134
+ let valueIndex = url.indexOf("=", keyIndex);
1135
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
1136
+ valueIndex = -1;
1137
+ }
1138
+ let name = url.slice(
1139
+ keyIndex + 1,
1140
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
1141
+ );
1142
+ if (encoded) {
1143
+ name = _decodeURI(name);
1144
+ }
1145
+ keyIndex = nextKeyIndex;
1146
+ if (name === "") {
1147
+ continue;
1148
+ }
1149
+ let value;
1150
+ if (valueIndex === -1) {
1151
+ value = "";
1152
+ } else {
1153
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
1154
+ if (encoded) {
1155
+ value = _decodeURI(value);
1156
+ }
1157
+ }
1158
+ if (multiple) {
1159
+ if (!(results[name] && Array.isArray(results[name]))) {
1160
+ results[name] = [];
1161
+ }
1162
+ ;
1163
+ results[name].push(value);
1164
+ } else {
1165
+ results[name] ??= value;
1166
+ }
1167
+ }
1168
+ return key ? results[key] : results;
1169
+ }, "_getQueryParam");
1170
+ var getQueryParam = _getQueryParam;
1171
+ var getQueryParams = /* @__PURE__ */ __name((url, key) => {
1172
+ return _getQueryParam(url, key, true);
1173
+ }, "getQueryParams");
1174
+ var decodeURIComponent_ = decodeURIComponent;
1175
+
1176
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/request.js
1177
+ var tryDecodeURIComponent = /* @__PURE__ */ __name((str) => tryDecode(str, decodeURIComponent_), "tryDecodeURIComponent");
1178
+ var HonoRequest = class {
1179
+ static {
1180
+ __name(this, "HonoRequest");
1181
+ }
1182
+ /**
1183
+ * `.raw` can get the raw Request object.
1184
+ *
1185
+ * @see {@link https://hono.dev/docs/api/request#raw}
1186
+ *
1187
+ * @example
1188
+ * ```ts
1189
+ * // For Cloudflare Workers
1190
+ * app.post('/', async (c) => {
1191
+ * const metadata = c.req.raw.cf?.hostMetadata?
1192
+ * ...
1193
+ * })
1194
+ * ```
1195
+ */
1196
+ raw;
1197
+ #validatedData;
1198
+ // Short name of validatedData
1199
+ #matchResult;
1200
+ routeIndex = 0;
1201
+ /**
1202
+ * `.path` can get the pathname of the request.
1203
+ *
1204
+ * @see {@link https://hono.dev/docs/api/request#path}
1205
+ *
1206
+ * @example
1207
+ * ```ts
1208
+ * app.get('/about/me', (c) => {
1209
+ * const pathname = c.req.path // `/about/me`
1210
+ * })
1211
+ * ```
1212
+ */
1213
+ path;
1214
+ bodyCache = {};
1215
+ constructor(request, path = "/", matchResult = [[]]) {
1216
+ this.raw = request;
1217
+ this.path = path;
1218
+ this.#matchResult = matchResult;
1219
+ this.#validatedData = {};
1220
+ }
1221
+ param(key) {
1222
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
1223
+ }
1224
+ #getDecodedParam(key) {
1225
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
1226
+ const param = this.#getParamValue(paramKey);
1227
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
1228
+ }
1229
+ #getAllDecodedParams() {
1230
+ const decoded = {};
1231
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
1232
+ for (const key of keys) {
1233
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
1234
+ if (value !== void 0) {
1235
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
1236
+ }
1237
+ }
1238
+ return decoded;
1239
+ }
1240
+ #getParamValue(paramKey) {
1241
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
1242
+ }
1243
+ query(key) {
1244
+ return getQueryParam(this.url, key);
1245
+ }
1246
+ queries(key) {
1247
+ return getQueryParams(this.url, key);
1248
+ }
1249
+ header(name) {
1250
+ if (name) {
1251
+ return this.raw.headers.get(name) ?? void 0;
1252
+ }
1253
+ const headerData = {};
1254
+ this.raw.headers.forEach((value, key) => {
1255
+ headerData[key] = value;
1256
+ });
1257
+ return headerData;
1258
+ }
1259
+ async parseBody(options) {
1260
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
1261
+ }
1262
+ #cachedBody = /* @__PURE__ */ __name((key) => {
1263
+ const { bodyCache, raw: raw2 } = this;
1264
+ const cachedBody = bodyCache[key];
1265
+ if (cachedBody) {
1266
+ return cachedBody;
1267
+ }
1268
+ const anyCachedKey = Object.keys(bodyCache)[0];
1269
+ if (anyCachedKey) {
1270
+ return bodyCache[anyCachedKey].then((body) => {
1271
+ if (anyCachedKey === "json") {
1272
+ body = JSON.stringify(body);
1273
+ }
1274
+ return new Response(body)[key]();
1275
+ });
1276
+ }
1277
+ return bodyCache[key] = raw2[key]();
1278
+ }, "#cachedBody");
1279
+ /**
1280
+ * `.json()` can parse Request body of type `application/json`
1281
+ *
1282
+ * @see {@link https://hono.dev/docs/api/request#json}
1283
+ *
1284
+ * @example
1285
+ * ```ts
1286
+ * app.post('/entry', async (c) => {
1287
+ * const body = await c.req.json()
1288
+ * })
1289
+ * ```
1290
+ */
1291
+ json() {
1292
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
1293
+ }
1294
+ /**
1295
+ * `.text()` can parse Request body of type `text/plain`
1296
+ *
1297
+ * @see {@link https://hono.dev/docs/api/request#text}
1298
+ *
1299
+ * @example
1300
+ * ```ts
1301
+ * app.post('/entry', async (c) => {
1302
+ * const body = await c.req.text()
1303
+ * })
1304
+ * ```
1305
+ */
1306
+ text() {
1307
+ return this.#cachedBody("text");
1308
+ }
1309
+ /**
1310
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
1311
+ *
1312
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
1313
+ *
1314
+ * @example
1315
+ * ```ts
1316
+ * app.post('/entry', async (c) => {
1317
+ * const body = await c.req.arrayBuffer()
1318
+ * })
1319
+ * ```
1320
+ */
1321
+ arrayBuffer() {
1322
+ return this.#cachedBody("arrayBuffer");
1323
+ }
1324
+ /**
1325
+ * Parses the request body as a `Blob`.
1326
+ * @example
1327
+ * ```ts
1328
+ * app.post('/entry', async (c) => {
1329
+ * const body = await c.req.blob();
1330
+ * });
1331
+ * ```
1332
+ * @see https://hono.dev/docs/api/request#blob
1333
+ */
1334
+ blob() {
1335
+ return this.#cachedBody("blob");
1336
+ }
1337
+ /**
1338
+ * Parses the request body as `FormData`.
1339
+ * @example
1340
+ * ```ts
1341
+ * app.post('/entry', async (c) => {
1342
+ * const body = await c.req.formData();
1343
+ * });
1344
+ * ```
1345
+ * @see https://hono.dev/docs/api/request#formdata
1346
+ */
1347
+ formData() {
1348
+ return this.#cachedBody("formData");
1349
+ }
1350
+ /**
1351
+ * Adds validated data to the request.
1352
+ *
1353
+ * @param target - The target of the validation.
1354
+ * @param data - The validated data to add.
1355
+ */
1356
+ addValidatedData(target, data) {
1357
+ this.#validatedData[target] = data;
1358
+ }
1359
+ valid(target) {
1360
+ return this.#validatedData[target];
1361
+ }
1362
+ /**
1363
+ * `.url()` can get the request url strings.
1364
+ *
1365
+ * @see {@link https://hono.dev/docs/api/request#url}
1366
+ *
1367
+ * @example
1368
+ * ```ts
1369
+ * app.get('/about/me', (c) => {
1370
+ * const url = c.req.url // `http://localhost:8787/about/me`
1371
+ * ...
1372
+ * })
1373
+ * ```
1374
+ */
1375
+ get url() {
1376
+ return this.raw.url;
1377
+ }
1378
+ /**
1379
+ * `.method()` can get the method name of the request.
1380
+ *
1381
+ * @see {@link https://hono.dev/docs/api/request#method}
1382
+ *
1383
+ * @example
1384
+ * ```ts
1385
+ * app.get('/about/me', (c) => {
1386
+ * const method = c.req.method // `GET`
1387
+ * })
1388
+ * ```
1389
+ */
1390
+ get method() {
1391
+ return this.raw.method;
1392
+ }
1393
+ get [GET_MATCH_RESULT]() {
1394
+ return this.#matchResult;
1395
+ }
1396
+ /**
1397
+ * `.matchedRoutes()` can return a matched route in the handler
1398
+ *
1399
+ * @deprecated
1400
+ *
1401
+ * Use matchedRoutes helper defined in "hono/route" instead.
1402
+ *
1403
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
1404
+ *
1405
+ * @example
1406
+ * ```ts
1407
+ * app.use('*', async function logger(c, next) {
1408
+ * await next()
1409
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
1410
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
1411
+ * console.log(
1412
+ * method,
1413
+ * ' ',
1414
+ * path,
1415
+ * ' '.repeat(Math.max(10 - path.length, 0)),
1416
+ * name,
1417
+ * i === c.req.routeIndex ? '<- respond from here' : ''
1418
+ * )
1419
+ * })
1420
+ * })
1421
+ * ```
1422
+ */
1423
+ get matchedRoutes() {
1424
+ return this.#matchResult[0].map(([[, route]]) => route);
1425
+ }
1426
+ /**
1427
+ * `routePath()` can retrieve the path registered within the handler
1428
+ *
1429
+ * @deprecated
1430
+ *
1431
+ * Use routePath helper defined in "hono/route" instead.
1432
+ *
1433
+ * @see {@link https://hono.dev/docs/api/request#routepath}
1434
+ *
1435
+ * @example
1436
+ * ```ts
1437
+ * app.get('/posts/:id', (c) => {
1438
+ * return c.json({ path: c.req.routePath })
1439
+ * })
1440
+ * ```
1441
+ */
1442
+ get routePath() {
1443
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
1444
+ }
1445
+ };
1446
+
1447
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/html.js
1448
+ var HtmlEscapedCallbackPhase = {
1449
+ Stringify: 1,
1450
+ BeforeStream: 2,
1451
+ Stream: 3
1452
+ };
1453
+ var raw = /* @__PURE__ */ __name((value, callbacks) => {
1454
+ const escapedString = new String(value);
1455
+ escapedString.isEscaped = true;
1456
+ escapedString.callbacks = callbacks;
1457
+ return escapedString;
1458
+ }, "raw");
1459
+ var resolveCallback = /* @__PURE__ */ __name(async (str, phase, preserveCallbacks, context, buffer) => {
1460
+ if (typeof str === "object" && !(str instanceof String)) {
1461
+ if (!(str instanceof Promise)) {
1462
+ str = str.toString();
1463
+ }
1464
+ if (str instanceof Promise) {
1465
+ str = await str;
1466
+ }
1467
+ }
1468
+ const callbacks = str.callbacks;
1469
+ if (!callbacks?.length) {
1470
+ return Promise.resolve(str);
1471
+ }
1472
+ if (buffer) {
1473
+ buffer[0] += str;
1474
+ } else {
1475
+ buffer = [str];
1476
+ }
1477
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
1478
+ (res) => Promise.all(
1479
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
1480
+ ).then(() => buffer[0])
1481
+ );
1482
+ if (preserveCallbacks) {
1483
+ return raw(await resStr, callbacks);
1484
+ } else {
1485
+ return resStr;
1486
+ }
1487
+ }, "resolveCallback");
1488
+
1489
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/context.js
1490
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
1491
+ var setDefaultContentType = /* @__PURE__ */ __name((contentType, headers) => {
1492
+ return {
1493
+ "Content-Type": contentType,
1494
+ ...headers
1495
+ };
1496
+ }, "setDefaultContentType");
1497
+ var Context = class {
1498
+ static {
1499
+ __name(this, "Context");
1500
+ }
1501
+ #rawRequest;
1502
+ #req;
1503
+ /**
1504
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
1505
+ *
1506
+ * @see {@link https://hono.dev/docs/api/context#env}
1507
+ *
1508
+ * @example
1509
+ * ```ts
1510
+ * // Environment object for Cloudflare Workers
1511
+ * app.get('*', async c => {
1512
+ * const counter = c.env.COUNTER
1513
+ * })
1514
+ * ```
1515
+ */
1516
+ env = {};
1517
+ #var;
1518
+ finalized = false;
1519
+ /**
1520
+ * `.error` can get the error object from the middleware if the Handler throws an error.
1521
+ *
1522
+ * @see {@link https://hono.dev/docs/api/context#error}
1523
+ *
1524
+ * @example
1525
+ * ```ts
1526
+ * app.use('*', async (c, next) => {
1527
+ * await next()
1528
+ * if (c.error) {
1529
+ * // do something...
1530
+ * }
1531
+ * })
1532
+ * ```
1533
+ */
1534
+ error;
1535
+ #status;
1536
+ #executionCtx;
1537
+ #res;
1538
+ #layout;
1539
+ #renderer;
1540
+ #notFoundHandler;
1541
+ #preparedHeaders;
1542
+ #matchResult;
1543
+ #path;
1544
+ /**
1545
+ * Creates an instance of the Context class.
1546
+ *
1547
+ * @param req - The Request object.
1548
+ * @param options - Optional configuration options for the context.
1549
+ */
1550
+ constructor(req, options) {
1551
+ this.#rawRequest = req;
1552
+ if (options) {
1553
+ this.#executionCtx = options.executionCtx;
1554
+ this.env = options.env;
1555
+ this.#notFoundHandler = options.notFoundHandler;
1556
+ this.#path = options.path;
1557
+ this.#matchResult = options.matchResult;
1558
+ }
1559
+ }
1560
+ /**
1561
+ * `.req` is the instance of {@link HonoRequest}.
1562
+ */
1563
+ get req() {
1564
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
1565
+ return this.#req;
1566
+ }
1567
+ /**
1568
+ * @see {@link https://hono.dev/docs/api/context#event}
1569
+ * The FetchEvent associated with the current request.
1570
+ *
1571
+ * @throws Will throw an error if the context does not have a FetchEvent.
1572
+ */
1573
+ get event() {
1574
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
1575
+ return this.#executionCtx;
1576
+ } else {
1577
+ throw Error("This context has no FetchEvent");
1578
+ }
1579
+ }
1580
+ /**
1581
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
1582
+ * The ExecutionContext associated with the current request.
1583
+ *
1584
+ * @throws Will throw an error if the context does not have an ExecutionContext.
1585
+ */
1586
+ get executionCtx() {
1587
+ if (this.#executionCtx) {
1588
+ return this.#executionCtx;
1589
+ } else {
1590
+ throw Error("This context has no ExecutionContext");
1591
+ }
1592
+ }
1593
+ /**
1594
+ * @see {@link https://hono.dev/docs/api/context#res}
1595
+ * The Response object for the current request.
1596
+ */
1597
+ get res() {
1598
+ return this.#res ||= new Response(null, {
1599
+ headers: this.#preparedHeaders ??= new Headers()
1600
+ });
1601
+ }
1602
+ /**
1603
+ * Sets the Response object for the current request.
1604
+ *
1605
+ * @param _res - The Response object to set.
1606
+ */
1607
+ set res(_res) {
1608
+ if (this.#res && _res) {
1609
+ _res = new Response(_res.body, _res);
1610
+ for (const [k, v] of this.#res.headers.entries()) {
1611
+ if (k === "content-type") {
1612
+ continue;
1613
+ }
1614
+ if (k === "set-cookie") {
1615
+ const cookies = this.#res.headers.getSetCookie();
1616
+ _res.headers.delete("set-cookie");
1617
+ for (const cookie of cookies) {
1618
+ _res.headers.append("set-cookie", cookie);
1619
+ }
1620
+ } else {
1621
+ _res.headers.set(k, v);
1622
+ }
1623
+ }
1624
+ }
1625
+ this.#res = _res;
1626
+ this.finalized = true;
1627
+ }
1628
+ /**
1629
+ * `.render()` can create a response within a layout.
1630
+ *
1631
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1632
+ *
1633
+ * @example
1634
+ * ```ts
1635
+ * app.get('/', (c) => {
1636
+ * return c.render('Hello!')
1637
+ * })
1638
+ * ```
1639
+ */
1640
+ render = /* @__PURE__ */ __name((...args) => {
1641
+ this.#renderer ??= (content) => this.html(content);
1642
+ return this.#renderer(...args);
1643
+ }, "render");
1644
+ /**
1645
+ * Sets the layout for the response.
1646
+ *
1647
+ * @param layout - The layout to set.
1648
+ * @returns The layout function.
1649
+ */
1650
+ setLayout = /* @__PURE__ */ __name((layout) => this.#layout = layout, "setLayout");
1651
+ /**
1652
+ * Gets the current layout for the response.
1653
+ *
1654
+ * @returns The current layout function.
1655
+ */
1656
+ getLayout = /* @__PURE__ */ __name(() => this.#layout, "getLayout");
1657
+ /**
1658
+ * `.setRenderer()` can set the layout in the custom middleware.
1659
+ *
1660
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1661
+ *
1662
+ * @example
1663
+ * ```tsx
1664
+ * app.use('*', async (c, next) => {
1665
+ * c.setRenderer((content) => {
1666
+ * return c.html(
1667
+ * <html>
1668
+ * <body>
1669
+ * <p>{content}</p>
1670
+ * </body>
1671
+ * </html>
1672
+ * )
1673
+ * })
1674
+ * await next()
1675
+ * })
1676
+ * ```
1677
+ */
1678
+ setRenderer = /* @__PURE__ */ __name((renderer) => {
1679
+ this.#renderer = renderer;
1680
+ }, "setRenderer");
1681
+ /**
1682
+ * `.header()` can set headers.
1683
+ *
1684
+ * @see {@link https://hono.dev/docs/api/context#header}
1685
+ *
1686
+ * @example
1687
+ * ```ts
1688
+ * app.get('/welcome', (c) => {
1689
+ * // Set headers
1690
+ * c.header('X-Message', 'Hello!')
1691
+ * c.header('Content-Type', 'text/plain')
1692
+ *
1693
+ * return c.body('Thank you for coming')
1694
+ * })
1695
+ * ```
1696
+ */
1697
+ header = /* @__PURE__ */ __name((name, value, options) => {
1698
+ if (this.finalized) {
1699
+ this.#res = new Response(this.#res.body, this.#res);
1700
+ }
1701
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
1702
+ if (value === void 0) {
1703
+ headers.delete(name);
1704
+ } else if (options?.append) {
1705
+ headers.append(name, value);
1706
+ } else {
1707
+ headers.set(name, value);
1708
+ }
1709
+ }, "header");
1710
+ status = /* @__PURE__ */ __name((status) => {
1711
+ this.#status = status;
1712
+ }, "status");
1713
+ /**
1714
+ * `.set()` can set the value specified by the key.
1715
+ *
1716
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1717
+ *
1718
+ * @example
1719
+ * ```ts
1720
+ * app.use('*', async (c, next) => {
1721
+ * c.set('message', 'Hono is hot!!')
1722
+ * await next()
1723
+ * })
1724
+ * ```
1725
+ */
1726
+ set = /* @__PURE__ */ __name((key, value) => {
1727
+ this.#var ??= /* @__PURE__ */ new Map();
1728
+ this.#var.set(key, value);
1729
+ }, "set");
1730
+ /**
1731
+ * `.get()` can use the value specified by the key.
1732
+ *
1733
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1734
+ *
1735
+ * @example
1736
+ * ```ts
1737
+ * app.get('/', (c) => {
1738
+ * const message = c.get('message')
1739
+ * return c.text(`The message is "${message}"`)
1740
+ * })
1741
+ * ```
1742
+ */
1743
+ get = /* @__PURE__ */ __name((key) => {
1744
+ return this.#var ? this.#var.get(key) : void 0;
1745
+ }, "get");
1746
+ /**
1747
+ * `.var` can access the value of a variable.
1748
+ *
1749
+ * @see {@link https://hono.dev/docs/api/context#var}
1750
+ *
1751
+ * @example
1752
+ * ```ts
1753
+ * const result = c.var.client.oneMethod()
1754
+ * ```
1755
+ */
1756
+ // c.var.propName is a read-only
1757
+ get var() {
1758
+ if (!this.#var) {
1759
+ return {};
1760
+ }
1761
+ return Object.fromEntries(this.#var);
1762
+ }
1763
+ #newResponse(data, arg, headers) {
1764
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
1765
+ if (typeof arg === "object" && "headers" in arg) {
1766
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
1767
+ for (const [key, value] of argHeaders) {
1768
+ if (key.toLowerCase() === "set-cookie") {
1769
+ responseHeaders.append(key, value);
1770
+ } else {
1771
+ responseHeaders.set(key, value);
1772
+ }
1773
+ }
1774
+ }
1775
+ if (headers) {
1776
+ for (const [k, v] of Object.entries(headers)) {
1777
+ if (typeof v === "string") {
1778
+ responseHeaders.set(k, v);
1779
+ } else {
1780
+ responseHeaders.delete(k);
1781
+ for (const v2 of v) {
1782
+ responseHeaders.append(k, v2);
1783
+ }
1784
+ }
1785
+ }
1786
+ }
1787
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
1788
+ return new Response(data, { status, headers: responseHeaders });
1789
+ }
1790
+ newResponse = /* @__PURE__ */ __name((...args) => this.#newResponse(...args), "newResponse");
1791
+ /**
1792
+ * `.body()` can return the HTTP response.
1793
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
1794
+ * This can also be set in `.text()`, `.json()` and so on.
1795
+ *
1796
+ * @see {@link https://hono.dev/docs/api/context#body}
1797
+ *
1798
+ * @example
1799
+ * ```ts
1800
+ * app.get('/welcome', (c) => {
1801
+ * // Set headers
1802
+ * c.header('X-Message', 'Hello!')
1803
+ * c.header('Content-Type', 'text/plain')
1804
+ * // Set HTTP status code
1805
+ * c.status(201)
1806
+ *
1807
+ * // Return the response body
1808
+ * return c.body('Thank you for coming')
1809
+ * })
1810
+ * ```
1811
+ */
1812
+ body = /* @__PURE__ */ __name((data, arg, headers) => this.#newResponse(data, arg, headers), "body");
1813
+ /**
1814
+ * `.text()` can render text as `Content-Type:text/plain`.
1815
+ *
1816
+ * @see {@link https://hono.dev/docs/api/context#text}
1817
+ *
1818
+ * @example
1819
+ * ```ts
1820
+ * app.get('/say', (c) => {
1821
+ * return c.text('Hello!')
1822
+ * })
1823
+ * ```
1824
+ */
1825
+ text = /* @__PURE__ */ __name((text, arg, headers) => {
1826
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
1827
+ text,
1828
+ arg,
1829
+ setDefaultContentType(TEXT_PLAIN, headers)
1830
+ );
1831
+ }, "text");
1832
+ /**
1833
+ * `.json()` can render JSON as `Content-Type:application/json`.
1834
+ *
1835
+ * @see {@link https://hono.dev/docs/api/context#json}
1836
+ *
1837
+ * @example
1838
+ * ```ts
1839
+ * app.get('/api', (c) => {
1840
+ * return c.json({ message: 'Hello!' })
1841
+ * })
1842
+ * ```
1843
+ */
1844
+ json = /* @__PURE__ */ __name((object, arg, headers) => {
1845
+ return this.#newResponse(
1846
+ JSON.stringify(object),
1847
+ arg,
1848
+ setDefaultContentType("application/json", headers)
1849
+ );
1850
+ }, "json");
1851
+ html = /* @__PURE__ */ __name((html, arg, headers) => {
1852
+ const res = /* @__PURE__ */ __name((html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers)), "res");
1853
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
1854
+ }, "html");
1855
+ /**
1856
+ * `.redirect()` can Redirect, default status code is 302.
1857
+ *
1858
+ * @see {@link https://hono.dev/docs/api/context#redirect}
1859
+ *
1860
+ * @example
1861
+ * ```ts
1862
+ * app.get('/redirect', (c) => {
1863
+ * return c.redirect('/')
1864
+ * })
1865
+ * app.get('/redirect-permanently', (c) => {
1866
+ * return c.redirect('/', 301)
1867
+ * })
1868
+ * ```
1869
+ */
1870
+ redirect = /* @__PURE__ */ __name((location, status) => {
1871
+ const locationString = String(location);
1872
+ this.header(
1873
+ "Location",
1874
+ // Multibyes should be encoded
1875
+ // eslint-disable-next-line no-control-regex
1876
+ !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
1877
+ );
1878
+ return this.newResponse(null, status ?? 302);
1879
+ }, "redirect");
1880
+ /**
1881
+ * `.notFound()` can return the Not Found Response.
1882
+ *
1883
+ * @see {@link https://hono.dev/docs/api/context#notfound}
1884
+ *
1885
+ * @example
1886
+ * ```ts
1887
+ * app.get('/notfound', (c) => {
1888
+ * return c.notFound()
1889
+ * })
1890
+ * ```
1891
+ */
1892
+ notFound = /* @__PURE__ */ __name(() => {
1893
+ this.#notFoundHandler ??= () => new Response();
1894
+ return this.#notFoundHandler(this);
1895
+ }, "notFound");
1896
+ };
1897
+
1898
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router.js
1899
+ var METHOD_NAME_ALL = "ALL";
1900
+ var METHOD_NAME_ALL_LOWERCASE = "all";
1901
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1902
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1903
+ var UnsupportedPathError = class extends Error {
1904
+ static {
1905
+ __name(this, "UnsupportedPathError");
1906
+ }
1907
+ };
1908
+
1909
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/constants.js
1910
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1911
+
1912
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/hono-base.js
1913
+ var notFoundHandler = /* @__PURE__ */ __name((c) => {
1914
+ return c.text("404 Not Found", 404);
1915
+ }, "notFoundHandler");
1916
+ var errorHandler = /* @__PURE__ */ __name((err, c) => {
1917
+ if ("getResponse" in err) {
1918
+ const res = err.getResponse();
1919
+ return c.newResponse(res.body, res);
1920
+ }
1921
+ console.error(err);
1922
+ return c.text("Internal Server Error", 500);
1923
+ }, "errorHandler");
1924
+ var Hono = class _Hono {
1925
+ static {
1926
+ __name(this, "_Hono");
1927
+ }
1928
+ get;
1929
+ post;
1930
+ put;
1931
+ delete;
1932
+ options;
1933
+ patch;
1934
+ all;
1935
+ on;
1936
+ use;
1937
+ /*
1938
+ This class is like an abstract class and does not have a router.
1939
+ To use it, inherit the class and implement router in the constructor.
1940
+ */
1941
+ router;
1942
+ getPath;
1943
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1944
+ _basePath = "/";
1945
+ #path = "/";
1946
+ routes = [];
1947
+ constructor(options = {}) {
1948
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1949
+ allMethods.forEach((method) => {
1950
+ this[method] = (args1, ...args) => {
1951
+ if (typeof args1 === "string") {
1952
+ this.#path = args1;
1953
+ } else {
1954
+ this.#addRoute(method, this.#path, args1);
1955
+ }
1956
+ args.forEach((handler) => {
1957
+ this.#addRoute(method, this.#path, handler);
1958
+ });
1959
+ return this;
1960
+ };
1961
+ });
1962
+ this.on = (method, path, ...handlers) => {
1963
+ for (const p of [path].flat()) {
1964
+ this.#path = p;
1965
+ for (const m of [method].flat()) {
1966
+ handlers.map((handler) => {
1967
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1968
+ });
1969
+ }
1970
+ }
1971
+ return this;
1972
+ };
1973
+ this.use = (arg1, ...handlers) => {
1974
+ if (typeof arg1 === "string") {
1975
+ this.#path = arg1;
1976
+ } else {
1977
+ this.#path = "*";
1978
+ handlers.unshift(arg1);
1979
+ }
1980
+ handlers.forEach((handler) => {
1981
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1982
+ });
1983
+ return this;
1984
+ };
1985
+ const { strict, ...optionsWithoutStrict } = options;
1986
+ Object.assign(this, optionsWithoutStrict);
1987
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1988
+ }
1989
+ #clone() {
1990
+ const clone = new _Hono({
1991
+ router: this.router,
1992
+ getPath: this.getPath
1993
+ });
1994
+ clone.errorHandler = this.errorHandler;
1995
+ clone.#notFoundHandler = this.#notFoundHandler;
1996
+ clone.routes = this.routes;
1997
+ return clone;
1998
+ }
1999
+ #notFoundHandler = notFoundHandler;
2000
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
2001
+ errorHandler = errorHandler;
2002
+ /**
2003
+ * `.route()` allows grouping other Hono instance in routes.
2004
+ *
2005
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
2006
+ *
2007
+ * @param {string} path - base Path
2008
+ * @param {Hono} app - other Hono instance
2009
+ * @returns {Hono} routed Hono instance
2010
+ *
2011
+ * @example
2012
+ * ```ts
2013
+ * const app = new Hono()
2014
+ * const app2 = new Hono()
2015
+ *
2016
+ * app2.get("/user", (c) => c.text("user"))
2017
+ * app.route("/api", app2) // GET /api/user
2018
+ * ```
2019
+ */
2020
+ route(path, app2) {
2021
+ const subApp = this.basePath(path);
2022
+ app2.routes.map((r) => {
2023
+ let handler;
2024
+ if (app2.errorHandler === errorHandler) {
2025
+ handler = r.handler;
2026
+ } else {
2027
+ handler = /* @__PURE__ */ __name(async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res, "handler");
2028
+ handler[COMPOSED_HANDLER] = r.handler;
2029
+ }
2030
+ subApp.#addRoute(r.method, r.path, handler);
2031
+ });
2032
+ return this;
2033
+ }
2034
+ /**
2035
+ * `.basePath()` allows base paths to be specified.
2036
+ *
2037
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
2038
+ *
2039
+ * @param {string} path - base Path
2040
+ * @returns {Hono} changed Hono instance
2041
+ *
2042
+ * @example
2043
+ * ```ts
2044
+ * const api = new Hono().basePath('/api')
2045
+ * ```
2046
+ */
2047
+ basePath(path) {
2048
+ const subApp = this.#clone();
2049
+ subApp._basePath = mergePath(this._basePath, path);
2050
+ return subApp;
2051
+ }
2052
+ /**
2053
+ * `.onError()` handles an error and returns a customized Response.
2054
+ *
2055
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
2056
+ *
2057
+ * @param {ErrorHandler} handler - request Handler for error
2058
+ * @returns {Hono} changed Hono instance
2059
+ *
2060
+ * @example
2061
+ * ```ts
2062
+ * app.onError((err, c) => {
2063
+ * console.error(`${err}`)
2064
+ * return c.text('Custom Error Message', 500)
2065
+ * })
2066
+ * ```
2067
+ */
2068
+ onError = /* @__PURE__ */ __name((handler) => {
2069
+ this.errorHandler = handler;
2070
+ return this;
2071
+ }, "onError");
2072
+ /**
2073
+ * `.notFound()` allows you to customize a Not Found Response.
2074
+ *
2075
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
2076
+ *
2077
+ * @param {NotFoundHandler} handler - request handler for not-found
2078
+ * @returns {Hono} changed Hono instance
2079
+ *
2080
+ * @example
2081
+ * ```ts
2082
+ * app.notFound((c) => {
2083
+ * return c.text('Custom 404 Message', 404)
2084
+ * })
2085
+ * ```
2086
+ */
2087
+ notFound = /* @__PURE__ */ __name((handler) => {
2088
+ this.#notFoundHandler = handler;
2089
+ return this;
2090
+ }, "notFound");
2091
+ /**
2092
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
2093
+ *
2094
+ * @see {@link https://hono.dev/docs/api/hono#mount}
2095
+ *
2096
+ * @param {string} path - base Path
2097
+ * @param {Function} applicationHandler - other Request Handler
2098
+ * @param {MountOptions} [options] - options of `.mount()`
2099
+ * @returns {Hono} mounted Hono instance
2100
+ *
2101
+ * @example
2102
+ * ```ts
2103
+ * import { Router as IttyRouter } from 'itty-router'
2104
+ * import { Hono } from 'hono'
2105
+ * // Create itty-router application
2106
+ * const ittyRouter = IttyRouter()
2107
+ * // GET /itty-router/hello
2108
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
2109
+ *
2110
+ * const app = new Hono()
2111
+ * app.mount('/itty-router', ittyRouter.handle)
2112
+ * ```
2113
+ *
2114
+ * @example
2115
+ * ```ts
2116
+ * const app = new Hono()
2117
+ * // Send the request to another application without modification.
2118
+ * app.mount('/app', anotherApp, {
2119
+ * replaceRequest: (req) => req,
2120
+ * })
2121
+ * ```
2122
+ */
2123
+ mount(path, applicationHandler, options) {
2124
+ let replaceRequest;
2125
+ let optionHandler;
2126
+ if (options) {
2127
+ if (typeof options === "function") {
2128
+ optionHandler = options;
2129
+ } else {
2130
+ optionHandler = options.optionHandler;
2131
+ if (options.replaceRequest === false) {
2132
+ replaceRequest = /* @__PURE__ */ __name((request) => request, "replaceRequest");
2133
+ } else {
2134
+ replaceRequest = options.replaceRequest;
2135
+ }
2136
+ }
2137
+ }
2138
+ const getOptions = optionHandler ? (c) => {
2139
+ const options2 = optionHandler(c);
2140
+ return Array.isArray(options2) ? options2 : [options2];
2141
+ } : (c) => {
2142
+ let executionContext = void 0;
2143
+ try {
2144
+ executionContext = c.executionCtx;
2145
+ } catch {
2146
+ }
2147
+ return [c.env, executionContext];
2148
+ };
2149
+ replaceRequest ||= (() => {
2150
+ const mergedPath = mergePath(this._basePath, path);
2151
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
2152
+ return (request) => {
2153
+ const url = new URL(request.url);
2154
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
2155
+ return new Request(url, request);
2156
+ };
2157
+ })();
2158
+ const handler = /* @__PURE__ */ __name(async (c, next) => {
2159
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
2160
+ if (res) {
2161
+ return res;
2162
+ }
2163
+ await next();
2164
+ }, "handler");
2165
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
2166
+ return this;
2167
+ }
2168
+ #addRoute(method, path, handler) {
2169
+ method = method.toUpperCase();
2170
+ path = mergePath(this._basePath, path);
2171
+ const r = { basePath: this._basePath, path, method, handler };
2172
+ this.router.add(method, path, [handler, r]);
2173
+ this.routes.push(r);
2174
+ }
2175
+ #handleError(err, c) {
2176
+ if (err instanceof Error) {
2177
+ return this.errorHandler(err, c);
2178
+ }
2179
+ throw err;
2180
+ }
2181
+ #dispatch(request, executionCtx, env2, method) {
2182
+ if (method === "HEAD") {
2183
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env2, "GET")))();
2184
+ }
2185
+ const path = this.getPath(request, { env: env2 });
2186
+ const matchResult = this.router.match(method, path);
2187
+ const c = new Context(request, {
2188
+ path,
2189
+ matchResult,
2190
+ env: env2,
2191
+ executionCtx,
2192
+ notFoundHandler: this.#notFoundHandler
2193
+ });
2194
+ if (matchResult[0].length === 1) {
2195
+ let res;
2196
+ try {
2197
+ res = matchResult[0][0][0][0](c, async () => {
2198
+ c.res = await this.#notFoundHandler(c);
2199
+ });
2200
+ } catch (err) {
2201
+ return this.#handleError(err, c);
2202
+ }
2203
+ return res instanceof Promise ? res.then(
2204
+ (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
2205
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
2206
+ }
2207
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
2208
+ return (async () => {
2209
+ try {
2210
+ const context = await composed(c);
2211
+ if (!context.finalized) {
2212
+ throw new Error(
2213
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
2214
+ );
2215
+ }
2216
+ return context.res;
2217
+ } catch (err) {
2218
+ return this.#handleError(err, c);
2219
+ }
2220
+ })();
2221
+ }
2222
+ /**
2223
+ * `.fetch()` will be entry point of your app.
2224
+ *
2225
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
2226
+ *
2227
+ * @param {Request} request - request Object of request
2228
+ * @param {Env} Env - env Object
2229
+ * @param {ExecutionContext} - context of execution
2230
+ * @returns {Response | Promise<Response>} response of request
2231
+ *
2232
+ */
2233
+ fetch = /* @__PURE__ */ __name((request, ...rest) => {
2234
+ return this.#dispatch(request, rest[1], rest[0], request.method);
2235
+ }, "fetch");
2236
+ /**
2237
+ * `.request()` is a useful method for testing.
2238
+ * You can pass a URL or pathname to send a GET request.
2239
+ * app will return a Response object.
2240
+ * ```ts
2241
+ * test('GET /hello is ok', async () => {
2242
+ * const res = await app.request('/hello')
2243
+ * expect(res.status).toBe(200)
2244
+ * })
2245
+ * ```
2246
+ * @see https://hono.dev/docs/api/hono#request
2247
+ */
2248
+ request = /* @__PURE__ */ __name((input, requestInit, Env, executionCtx) => {
2249
+ if (input instanceof Request) {
2250
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
2251
+ }
2252
+ input = input.toString();
2253
+ return this.fetch(
2254
+ new Request(
2255
+ /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
2256
+ requestInit
2257
+ ),
2258
+ Env,
2259
+ executionCtx
2260
+ );
2261
+ }, "request");
2262
+ /**
2263
+ * `.fire()` automatically adds a global fetch event listener.
2264
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
2265
+ * @deprecated
2266
+ * Use `fire` from `hono/service-worker` instead.
2267
+ * ```ts
2268
+ * import { Hono } from 'hono'
2269
+ * import { fire } from 'hono/service-worker'
2270
+ *
2271
+ * const app = new Hono()
2272
+ * // ...
2273
+ * fire(app)
2274
+ * ```
2275
+ * @see https://hono.dev/docs/api/hono#fire
2276
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
2277
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
2278
+ */
2279
+ fire = /* @__PURE__ */ __name(() => {
2280
+ addEventListener("fetch", (event) => {
2281
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
2282
+ });
2283
+ }, "fire");
2284
+ };
2285
+
2286
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/matcher.js
2287
+ var emptyParam = [];
2288
+ function match(method, path) {
2289
+ const matchers = this.buildAllMatchers();
2290
+ const match2 = /* @__PURE__ */ __name(((method2, path2) => {
2291
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
2292
+ const staticMatch = matcher[2][path2];
2293
+ if (staticMatch) {
2294
+ return staticMatch;
2295
+ }
2296
+ const match3 = path2.match(matcher[0]);
2297
+ if (!match3) {
2298
+ return [[], emptyParam];
2299
+ }
2300
+ const index = match3.indexOf("", 1);
2301
+ return [matcher[1][index], match3];
2302
+ }), "match2");
2303
+ this.match = match2;
2304
+ return match2(method, path);
2305
+ }
2306
+ __name(match, "match");
2307
+
2308
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/node.js
2309
+ var LABEL_REG_EXP_STR = "[^/]+";
2310
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
2311
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
2312
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
2313
+ var regExpMetaChars = new Set(".\\+*[^]$()");
2314
+ function compareKey(a, b) {
2315
+ if (a.length === 1) {
2316
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
2317
+ }
2318
+ if (b.length === 1) {
2319
+ return 1;
2320
+ }
2321
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2322
+ return 1;
2323
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2324
+ return -1;
2325
+ }
2326
+ if (a === LABEL_REG_EXP_STR) {
2327
+ return 1;
2328
+ } else if (b === LABEL_REG_EXP_STR) {
2329
+ return -1;
2330
+ }
2331
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2332
+ }
2333
+ __name(compareKey, "compareKey");
2334
+ var Node = class _Node {
2335
+ static {
2336
+ __name(this, "_Node");
2337
+ }
2338
+ #index;
2339
+ #varIndex;
2340
+ #children = /* @__PURE__ */ Object.create(null);
2341
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2342
+ if (tokens.length === 0) {
2343
+ if (this.#index !== void 0) {
2344
+ throw PATH_ERROR;
2345
+ }
2346
+ if (pathErrorCheckOnly) {
2347
+ return;
2348
+ }
2349
+ this.#index = index;
2350
+ return;
2351
+ }
2352
+ const [token, ...restTokens] = tokens;
2353
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2354
+ let node;
2355
+ if (pattern) {
2356
+ const name = pattern[1];
2357
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2358
+ if (name && pattern[2]) {
2359
+ if (regexpStr === ".*") {
2360
+ throw PATH_ERROR;
2361
+ }
2362
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2363
+ if (/\((?!\?:)/.test(regexpStr)) {
2364
+ throw PATH_ERROR;
2365
+ }
2366
+ }
2367
+ node = this.#children[regexpStr];
2368
+ if (!node) {
2369
+ if (Object.keys(this.#children).some(
2370
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2371
+ )) {
2372
+ throw PATH_ERROR;
2373
+ }
2374
+ if (pathErrorCheckOnly) {
2375
+ return;
2376
+ }
2377
+ node = this.#children[regexpStr] = new _Node();
2378
+ if (name !== "") {
2379
+ node.#varIndex = context.varIndex++;
2380
+ }
2381
+ }
2382
+ if (!pathErrorCheckOnly && name !== "") {
2383
+ paramMap.push([name, node.#varIndex]);
2384
+ }
2385
+ } else {
2386
+ node = this.#children[token];
2387
+ if (!node) {
2388
+ if (Object.keys(this.#children).some(
2389
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2390
+ )) {
2391
+ throw PATH_ERROR;
2392
+ }
2393
+ if (pathErrorCheckOnly) {
2394
+ return;
2395
+ }
2396
+ node = this.#children[token] = new _Node();
2397
+ }
2398
+ }
2399
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
2400
+ }
2401
+ buildRegExpStr() {
2402
+ const childKeys = Object.keys(this.#children).sort(compareKey);
2403
+ const strList = childKeys.map((k) => {
2404
+ const c = this.#children[k];
2405
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
2406
+ });
2407
+ if (typeof this.#index === "number") {
2408
+ strList.unshift(`#${this.#index}`);
2409
+ }
2410
+ if (strList.length === 0) {
2411
+ return "";
2412
+ }
2413
+ if (strList.length === 1) {
2414
+ return strList[0];
2415
+ }
2416
+ return "(?:" + strList.join("|") + ")";
2417
+ }
2418
+ };
2419
+
2420
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/trie.js
2421
+ var Trie = class {
2422
+ static {
2423
+ __name(this, "Trie");
2424
+ }
2425
+ #context = { varIndex: 0 };
2426
+ #root = new Node();
2427
+ insert(path, index, pathErrorCheckOnly) {
2428
+ const paramAssoc = [];
2429
+ const groups = [];
2430
+ for (let i = 0; ; ) {
2431
+ let replaced = false;
2432
+ path = path.replace(/\{[^}]+\}/g, (m) => {
2433
+ const mark = `@\\${i}`;
2434
+ groups[i] = [mark, m];
2435
+ i++;
2436
+ replaced = true;
2437
+ return mark;
2438
+ });
2439
+ if (!replaced) {
2440
+ break;
2441
+ }
2442
+ }
2443
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2444
+ for (let i = groups.length - 1; i >= 0; i--) {
2445
+ const [mark] = groups[i];
2446
+ for (let j = tokens.length - 1; j >= 0; j--) {
2447
+ if (tokens[j].indexOf(mark) !== -1) {
2448
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
2449
+ break;
2450
+ }
2451
+ }
2452
+ }
2453
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
2454
+ return paramAssoc;
2455
+ }
2456
+ buildRegExp() {
2457
+ let regexp = this.#root.buildRegExpStr();
2458
+ if (regexp === "") {
2459
+ return [/^$/, [], []];
2460
+ }
2461
+ let captureIndex = 0;
2462
+ const indexReplacementMap = [];
2463
+ const paramReplacementMap = [];
2464
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
2465
+ if (handlerIndex !== void 0) {
2466
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
2467
+ return "$()";
2468
+ }
2469
+ if (paramIndex !== void 0) {
2470
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
2471
+ return "";
2472
+ }
2473
+ return "";
2474
+ });
2475
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
2476
+ }
2477
+ };
2478
+
2479
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/router.js
2480
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2481
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2482
+ function buildWildcardRegExp(path) {
2483
+ return wildcardRegExpCache[path] ??= new RegExp(
2484
+ path === "*" ? "" : `^${path.replace(
2485
+ /\/\*$|([.\\+*[^\]$()])/g,
2486
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
2487
+ )}$`
2488
+ );
2489
+ }
2490
+ __name(buildWildcardRegExp, "buildWildcardRegExp");
2491
+ function clearWildcardRegExpCache() {
2492
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2493
+ }
2494
+ __name(clearWildcardRegExpCache, "clearWildcardRegExpCache");
2495
+ function buildMatcherFromPreprocessedRoutes(routes) {
2496
+ const trie = new Trie();
2497
+ const handlerData = [];
2498
+ if (routes.length === 0) {
2499
+ return nullMatcher;
2500
+ }
2501
+ const routesWithStaticPathFlag = routes.map(
2502
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
2503
+ ).sort(
2504
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
2505
+ );
2506
+ const staticMap = /* @__PURE__ */ Object.create(null);
2507
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
2508
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
2509
+ if (pathErrorCheckOnly) {
2510
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
2511
+ } else {
2512
+ j++;
2513
+ }
2514
+ let paramAssoc;
2515
+ try {
2516
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
2517
+ } catch (e) {
2518
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
2519
+ }
2520
+ if (pathErrorCheckOnly) {
2521
+ continue;
2522
+ }
2523
+ handlerData[j] = handlers.map(([h, paramCount]) => {
2524
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
2525
+ paramCount -= 1;
2526
+ for (; paramCount >= 0; paramCount--) {
2527
+ const [key, value] = paramAssoc[paramCount];
2528
+ paramIndexMap[key] = value;
2529
+ }
2530
+ return [h, paramIndexMap];
2531
+ });
2532
+ }
2533
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
2534
+ for (let i = 0, len = handlerData.length; i < len; i++) {
2535
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
2536
+ const map = handlerData[i][j]?.[1];
2537
+ if (!map) {
2538
+ continue;
2539
+ }
2540
+ const keys = Object.keys(map);
2541
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
2542
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
2543
+ }
2544
+ }
2545
+ }
2546
+ const handlerMap = [];
2547
+ for (const i in indexReplacementMap) {
2548
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
2549
+ }
2550
+ return [regexp, handlerMap, staticMap];
2551
+ }
2552
+ __name(buildMatcherFromPreprocessedRoutes, "buildMatcherFromPreprocessedRoutes");
2553
+ function findMiddleware(middleware, path) {
2554
+ if (!middleware) {
2555
+ return void 0;
2556
+ }
2557
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
2558
+ if (buildWildcardRegExp(k).test(path)) {
2559
+ return [...middleware[k]];
2560
+ }
2561
+ }
2562
+ return void 0;
2563
+ }
2564
+ __name(findMiddleware, "findMiddleware");
2565
+ var RegExpRouter = class {
2566
+ static {
2567
+ __name(this, "RegExpRouter");
2568
+ }
2569
+ name = "RegExpRouter";
2570
+ #middleware;
2571
+ #routes;
2572
+ constructor() {
2573
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2574
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2575
+ }
2576
+ add(method, path, handler) {
2577
+ const middleware = this.#middleware;
2578
+ const routes = this.#routes;
2579
+ if (!middleware || !routes) {
2580
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2581
+ }
2582
+ if (!middleware[method]) {
2583
+ ;
2584
+ [middleware, routes].forEach((handlerMap) => {
2585
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
2586
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
2587
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
2588
+ });
2589
+ });
2590
+ }
2591
+ if (path === "/*") {
2592
+ path = "*";
2593
+ }
2594
+ const paramCount = (path.match(/\/:/g) || []).length;
2595
+ if (/\*$/.test(path)) {
2596
+ const re = buildWildcardRegExp(path);
2597
+ if (method === METHOD_NAME_ALL) {
2598
+ Object.keys(middleware).forEach((m) => {
2599
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2600
+ });
2601
+ } else {
2602
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2603
+ }
2604
+ Object.keys(middleware).forEach((m) => {
2605
+ if (method === METHOD_NAME_ALL || method === m) {
2606
+ Object.keys(middleware[m]).forEach((p) => {
2607
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
2608
+ });
2609
+ }
2610
+ });
2611
+ Object.keys(routes).forEach((m) => {
2612
+ if (method === METHOD_NAME_ALL || method === m) {
2613
+ Object.keys(routes[m]).forEach(
2614
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
2615
+ );
2616
+ }
2617
+ });
2618
+ return;
2619
+ }
2620
+ const paths = checkOptionalParameter(path) || [path];
2621
+ for (let i = 0, len = paths.length; i < len; i++) {
2622
+ const path2 = paths[i];
2623
+ Object.keys(routes).forEach((m) => {
2624
+ if (method === METHOD_NAME_ALL || method === m) {
2625
+ routes[m][path2] ||= [
2626
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
2627
+ ];
2628
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
2629
+ }
2630
+ });
2631
+ }
2632
+ }
2633
+ match = match;
2634
+ buildAllMatchers() {
2635
+ const matchers = /* @__PURE__ */ Object.create(null);
2636
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
2637
+ matchers[method] ||= this.#buildMatcher(method);
2638
+ });
2639
+ this.#middleware = this.#routes = void 0;
2640
+ clearWildcardRegExpCache();
2641
+ return matchers;
2642
+ }
2643
+ #buildMatcher(method) {
2644
+ const routes = [];
2645
+ let hasOwnRoute = method === METHOD_NAME_ALL;
2646
+ [this.#middleware, this.#routes].forEach((r) => {
2647
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
2648
+ if (ownRoute.length !== 0) {
2649
+ hasOwnRoute ||= true;
2650
+ routes.push(...ownRoute);
2651
+ } else if (method !== METHOD_NAME_ALL) {
2652
+ routes.push(
2653
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
2654
+ );
2655
+ }
2656
+ });
2657
+ if (!hasOwnRoute) {
2658
+ return null;
2659
+ } else {
2660
+ return buildMatcherFromPreprocessedRoutes(routes);
2661
+ }
2662
+ }
2663
+ };
2664
+
2665
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/smart-router/router.js
2666
+ var SmartRouter = class {
2667
+ static {
2668
+ __name(this, "SmartRouter");
2669
+ }
2670
+ name = "SmartRouter";
2671
+ #routers = [];
2672
+ #routes = [];
2673
+ constructor(init) {
2674
+ this.#routers = init.routers;
2675
+ }
2676
+ add(method, path, handler) {
2677
+ if (!this.#routes) {
2678
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2679
+ }
2680
+ this.#routes.push([method, path, handler]);
2681
+ }
2682
+ match(method, path) {
2683
+ if (!this.#routes) {
2684
+ throw new Error("Fatal error");
2685
+ }
2686
+ const routers = this.#routers;
2687
+ const routes = this.#routes;
2688
+ const len = routers.length;
2689
+ let i = 0;
2690
+ let res;
2691
+ for (; i < len; i++) {
2692
+ const router = routers[i];
2693
+ try {
2694
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
2695
+ router.add(...routes[i2]);
2696
+ }
2697
+ res = router.match(method, path);
2698
+ } catch (e) {
2699
+ if (e instanceof UnsupportedPathError) {
2700
+ continue;
2701
+ }
2702
+ throw e;
2703
+ }
2704
+ this.match = router.match.bind(router);
2705
+ this.#routers = [router];
2706
+ this.#routes = void 0;
2707
+ break;
2708
+ }
2709
+ if (i === len) {
2710
+ throw new Error("Fatal error");
2711
+ }
2712
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
2713
+ return res;
2714
+ }
2715
+ get activeRouter() {
2716
+ if (this.#routes || this.#routers.length !== 1) {
2717
+ throw new Error("No active router has been determined yet.");
2718
+ }
2719
+ return this.#routers[0];
2720
+ }
2721
+ };
2722
+
2723
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/trie-router/node.js
2724
+ var emptyParams = /* @__PURE__ */ Object.create(null);
2725
+ var Node2 = class _Node2 {
2726
+ static {
2727
+ __name(this, "_Node");
2728
+ }
2729
+ #methods;
2730
+ #children;
2731
+ #patterns;
2732
+ #order = 0;
2733
+ #params = emptyParams;
2734
+ constructor(method, handler, children) {
2735
+ this.#children = children || /* @__PURE__ */ Object.create(null);
2736
+ this.#methods = [];
2737
+ if (method && handler) {
2738
+ const m = /* @__PURE__ */ Object.create(null);
2739
+ m[method] = { handler, possibleKeys: [], score: 0 };
2740
+ this.#methods = [m];
2741
+ }
2742
+ this.#patterns = [];
2743
+ }
2744
+ insert(method, path, handler) {
2745
+ this.#order = ++this.#order;
2746
+ let curNode = this;
2747
+ const parts = splitRoutingPath(path);
2748
+ const possibleKeys = [];
2749
+ for (let i = 0, len = parts.length; i < len; i++) {
2750
+ const p = parts[i];
2751
+ const nextP = parts[i + 1];
2752
+ const pattern = getPattern(p, nextP);
2753
+ const key = Array.isArray(pattern) ? pattern[0] : p;
2754
+ if (key in curNode.#children) {
2755
+ curNode = curNode.#children[key];
2756
+ if (pattern) {
2757
+ possibleKeys.push(pattern[1]);
2758
+ }
2759
+ continue;
2760
+ }
2761
+ curNode.#children[key] = new _Node2();
2762
+ if (pattern) {
2763
+ curNode.#patterns.push(pattern);
2764
+ possibleKeys.push(pattern[1]);
2765
+ }
2766
+ curNode = curNode.#children[key];
2767
+ }
2768
+ curNode.#methods.push({
2769
+ [method]: {
2770
+ handler,
2771
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
2772
+ score: this.#order
2773
+ }
2774
+ });
2775
+ return curNode;
2776
+ }
2777
+ #getHandlerSets(node, method, nodeParams, params) {
2778
+ const handlerSets = [];
2779
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
2780
+ const m = node.#methods[i];
2781
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
2782
+ const processedSet = {};
2783
+ if (handlerSet !== void 0) {
2784
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
2785
+ handlerSets.push(handlerSet);
2786
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
2787
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
2788
+ const key = handlerSet.possibleKeys[i2];
2789
+ const processed = processedSet[handlerSet.score];
2790
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
2791
+ processedSet[handlerSet.score] = true;
2792
+ }
2793
+ }
2794
+ }
2795
+ }
2796
+ return handlerSets;
2797
+ }
2798
+ search(method, path) {
2799
+ const handlerSets = [];
2800
+ this.#params = emptyParams;
2801
+ const curNode = this;
2802
+ let curNodes = [curNode];
2803
+ const parts = splitPath(path);
2804
+ const curNodesQueue = [];
2805
+ for (let i = 0, len = parts.length; i < len; i++) {
2806
+ const part = parts[i];
2807
+ const isLast = i === len - 1;
2808
+ const tempNodes = [];
2809
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
2810
+ const node = curNodes[j];
2811
+ const nextNode = node.#children[part];
2812
+ if (nextNode) {
2813
+ nextNode.#params = node.#params;
2814
+ if (isLast) {
2815
+ if (nextNode.#children["*"]) {
2816
+ handlerSets.push(
2817
+ ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
2818
+ );
2819
+ }
2820
+ handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
2821
+ } else {
2822
+ tempNodes.push(nextNode);
2823
+ }
2824
+ }
2825
+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
2826
+ const pattern = node.#patterns[k];
2827
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
2828
+ if (pattern === "*") {
2829
+ const astNode = node.#children["*"];
2830
+ if (astNode) {
2831
+ handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
2832
+ astNode.#params = params;
2833
+ tempNodes.push(astNode);
2834
+ }
2835
+ continue;
2836
+ }
2837
+ const [key, name, matcher] = pattern;
2838
+ if (!part && !(matcher instanceof RegExp)) {
2839
+ continue;
2840
+ }
2841
+ const child = node.#children[key];
2842
+ const restPathString = parts.slice(i).join("/");
2843
+ if (matcher instanceof RegExp) {
2844
+ const m = matcher.exec(restPathString);
2845
+ if (m) {
2846
+ params[name] = m[0];
2847
+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
2848
+ if (Object.keys(child.#children).length) {
2849
+ child.#params = params;
2850
+ const componentCount = m[0].match(/\//)?.length ?? 0;
2851
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
2852
+ targetCurNodes.push(child);
2853
+ }
2854
+ continue;
2855
+ }
2856
+ }
2857
+ if (matcher === true || matcher.test(part)) {
2858
+ params[name] = part;
2859
+ if (isLast) {
2860
+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
2861
+ if (child.#children["*"]) {
2862
+ handlerSets.push(
2863
+ ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
2864
+ );
2865
+ }
2866
+ } else {
2867
+ child.#params = params;
2868
+ tempNodes.push(child);
2869
+ }
2870
+ }
2871
+ }
2872
+ }
2873
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
2874
+ }
2875
+ if (handlerSets.length > 1) {
2876
+ handlerSets.sort((a, b) => {
2877
+ return a.score - b.score;
2878
+ });
2879
+ }
2880
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
2881
+ }
2882
+ };
2883
+
2884
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/trie-router/router.js
2885
+ var TrieRouter = class {
2886
+ static {
2887
+ __name(this, "TrieRouter");
2888
+ }
2889
+ name = "TrieRouter";
2890
+ #node;
2891
+ constructor() {
2892
+ this.#node = new Node2();
2893
+ }
2894
+ add(method, path, handler) {
2895
+ const results = checkOptionalParameter(path);
2896
+ if (results) {
2897
+ for (let i = 0, len = results.length; i < len; i++) {
2898
+ this.#node.insert(method, results[i], handler);
2899
+ }
2900
+ return;
2901
+ }
2902
+ this.#node.insert(method, path, handler);
2903
+ }
2904
+ match(method, path) {
2905
+ return this.#node.search(method, path);
2906
+ }
2907
+ };
2908
+
2909
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/hono.js
2910
+ var Hono2 = class extends Hono {
2911
+ static {
2912
+ __name(this, "Hono");
2913
+ }
2914
+ /**
2915
+ * Creates an instance of the Hono class.
2916
+ *
2917
+ * @param options - Optional configuration options for the Hono instance.
2918
+ */
2919
+ constructor(options = {}) {
2920
+ super(options);
2921
+ this.router = options.router ?? new SmartRouter({
2922
+ routers: [new RegExpRouter(), new TrieRouter()]
2923
+ });
2924
+ }
2925
+ };
2926
+
2927
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/middleware/cors/index.js
2928
+ var cors = /* @__PURE__ */ __name((options) => {
2929
+ const defaults = {
2930
+ origin: "*",
2931
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
2932
+ allowHeaders: [],
2933
+ exposeHeaders: []
2934
+ };
2935
+ const opts = {
2936
+ ...defaults,
2937
+ ...options
2938
+ };
2939
+ const findAllowOrigin = ((optsOrigin) => {
2940
+ if (typeof optsOrigin === "string") {
2941
+ if (optsOrigin === "*") {
2942
+ return () => optsOrigin;
2943
+ } else {
2944
+ return (origin) => optsOrigin === origin ? origin : null;
2945
+ }
2946
+ } else if (typeof optsOrigin === "function") {
2947
+ return optsOrigin;
2948
+ } else {
2949
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
2950
+ }
2951
+ })(opts.origin);
2952
+ const findAllowMethods = ((optsAllowMethods) => {
2953
+ if (typeof optsAllowMethods === "function") {
2954
+ return optsAllowMethods;
2955
+ } else if (Array.isArray(optsAllowMethods)) {
2956
+ return () => optsAllowMethods;
2957
+ } else {
2958
+ return () => [];
2959
+ }
2960
+ })(opts.allowMethods);
2961
+ return /* @__PURE__ */ __name(async function cors2(c, next) {
2962
+ function set(key, value) {
2963
+ c.res.headers.set(key, value);
2964
+ }
2965
+ __name(set, "set");
2966
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
2967
+ if (allowOrigin) {
2968
+ set("Access-Control-Allow-Origin", allowOrigin);
2969
+ }
2970
+ if (opts.credentials) {
2971
+ set("Access-Control-Allow-Credentials", "true");
2972
+ }
2973
+ if (opts.exposeHeaders?.length) {
2974
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
2975
+ }
2976
+ if (c.req.method === "OPTIONS") {
2977
+ if (opts.origin !== "*") {
2978
+ set("Vary", "Origin");
2979
+ }
2980
+ if (opts.maxAge != null) {
2981
+ set("Access-Control-Max-Age", opts.maxAge.toString());
2982
+ }
2983
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
2984
+ if (allowMethods.length) {
2985
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
2986
+ }
2987
+ let headers = opts.allowHeaders;
2988
+ if (!headers?.length) {
2989
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
2990
+ if (requestHeaders) {
2991
+ headers = requestHeaders.split(/\s*,\s*/);
2992
+ }
2993
+ }
2994
+ if (headers?.length) {
2995
+ set("Access-Control-Allow-Headers", headers.join(","));
2996
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
2997
+ }
2998
+ c.res.headers.delete("Content-Length");
2999
+ c.res.headers.delete("Content-Type");
3000
+ return new Response(null, {
3001
+ headers: c.res.headers,
3002
+ status: 204,
3003
+ statusText: "No Content"
3004
+ });
3005
+ }
3006
+ await next();
3007
+ if (opts.origin !== "*") {
3008
+ c.header("Vary", "Origin", { append: true });
3009
+ }
3010
+ }, "cors2");
3011
+ }, "cors");
3012
+
3013
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/helper/factory/index.js
3014
+ var createMiddleware = /* @__PURE__ */ __name((middleware) => middleware, "createMiddleware");
3015
+
3016
+ // src/middleware/auth.ts
3017
+ var authMiddleware = createMiddleware(async (c, next) => {
3018
+ const authHeader = c.req.header("Authorization");
3019
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
3020
+ return c.json(
3021
+ { error: "unauthorized", message: "Missing or invalid authorization header" },
3022
+ 401
3023
+ );
3024
+ }
3025
+ const token = authHeader.substring(7);
3026
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3027
+ const authState = c.env.AUTH_STATE.get(authStateId);
3028
+ const response = await authState.fetch(
3029
+ new Request("http://internal/validate-session", {
3030
+ method: "POST",
3031
+ headers: { "Content-Type": "application/json" },
3032
+ body: JSON.stringify({ token })
3033
+ })
3034
+ );
3035
+ if (!response.ok) {
3036
+ return c.json({ error: "unauthorized", message: "Invalid or expired session" }, 401);
3037
+ }
3038
+ const auth = await response.json();
3039
+ c.set("auth", auth);
3040
+ return next();
3041
+ });
3042
+
3043
+ // src/routes/auth.ts
3044
+ var authRoutes = new Hono2();
3045
+ authRoutes.post("/register", async (c) => {
3046
+ const body = await c.req.json();
3047
+ if (!body.email || !body.password || !body.name) {
3048
+ return c.json(
3049
+ { error: "missing_fields", message: "Email, password, and name are required" },
3050
+ 400
3051
+ );
3052
+ }
3053
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3054
+ const authState = c.env.AUTH_STATE.get(authStateId);
3055
+ const response = await authState.fetch(
3056
+ new Request("http://internal/register", {
3057
+ method: "POST",
3058
+ headers: { "Content-Type": "application/json" },
3059
+ body: JSON.stringify(body)
3060
+ })
3061
+ );
3062
+ const data = await response.json();
3063
+ return c.json(data, response.status);
3064
+ });
3065
+ authRoutes.post("/login", async (c) => {
3066
+ const body = await c.req.json();
3067
+ if (!body.email || !body.password) {
3068
+ return c.json({ error: "missing_fields", message: "Email and password are required" }, 400);
3069
+ }
3070
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3071
+ const authState = c.env.AUTH_STATE.get(authStateId);
3072
+ const response = await authState.fetch(
3073
+ new Request("http://internal/login", {
3074
+ method: "POST",
3075
+ headers: { "Content-Type": "application/json" },
3076
+ body: JSON.stringify(body)
3077
+ })
3078
+ );
3079
+ const data = await response.json();
3080
+ return c.json(data, response.status);
3081
+ });
3082
+ authRoutes.post("/logout", async (c) => {
3083
+ const authHeader = c.req.header("Authorization");
3084
+ const token = authHeader?.startsWith("Bearer ") ? authHeader.substring(7) : null;
3085
+ if (!token) {
3086
+ return c.json({ success: true });
3087
+ }
3088
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3089
+ const authState = c.env.AUTH_STATE.get(authStateId);
3090
+ await authState.fetch(
3091
+ new Request("http://internal/logout", {
3092
+ method: "POST",
3093
+ headers: { "Content-Type": "application/json" },
3094
+ body: JSON.stringify({ token })
3095
+ })
3096
+ );
3097
+ return c.json({ success: true });
3098
+ });
3099
+ authRoutes.get("/me", async (c) => {
3100
+ const authHeader = c.req.header("Authorization");
3101
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
3102
+ return c.json({ error: "unauthorized", message: "Missing authorization header" }, 401);
3103
+ }
3104
+ const token = authHeader.substring(7);
3105
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3106
+ const authState = c.env.AUTH_STATE.get(authStateId);
3107
+ const response = await authState.fetch(
3108
+ new Request("http://internal/validate-session", {
3109
+ method: "POST",
3110
+ headers: { "Content-Type": "application/json" },
3111
+ body: JSON.stringify({ token })
3112
+ })
3113
+ );
3114
+ if (!response.ok) {
3115
+ return c.json({ error: "unauthorized", message: "Invalid or expired session" }, 401);
3116
+ }
3117
+ const data = await response.json();
3118
+ return c.json(data);
3119
+ });
3120
+
3121
+ // src/routes/events.ts
3122
+ var eventRoutes = new Hono2();
3123
+ async function getProjectWithAccess(c, slug) {
3124
+ const auth = c.get("auth");
3125
+ if (!auth) {
3126
+ return c.json({ error: "unauthorized" }, 401);
3127
+ }
3128
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3129
+ const authState = c.env.AUTH_STATE.get(authStateId);
3130
+ const response = await authState.fetch(
3131
+ new Request("http://internal/get-project", {
3132
+ method: "POST",
3133
+ headers: { "Content-Type": "application/json" },
3134
+ body: JSON.stringify({ slug, userId: auth.user.id })
3135
+ })
3136
+ );
3137
+ if (!response.ok) {
3138
+ return c.json({ error: "project_not_found" }, 404);
3139
+ }
3140
+ return response.json();
3141
+ }
3142
+ __name(getProjectWithAccess, "getProjectWithAccess");
3143
+ eventRoutes.get("/:slug/issues/:issueId/events", async (c) => {
3144
+ const slug = c.req.param("slug");
3145
+ const issueId = c.req.param("issueId");
3146
+ const projectResult = await getProjectWithAccess(c, slug);
3147
+ if (projectResult instanceof Response) {
3148
+ return projectResult;
3149
+ }
3150
+ const { project } = projectResult;
3151
+ const cursor = c.req.query("cursor");
3152
+ const limit = c.req.query("limit");
3153
+ const projectStateId = c.env.PROJECT_STATE.idFromName(project.id);
3154
+ const projectState = c.env.PROJECT_STATE.get(projectStateId);
3155
+ const response = await projectState.fetch(
3156
+ new Request("http://internal/issue/events", {
3157
+ method: "POST",
3158
+ headers: { "Content-Type": "application/json" },
3159
+ body: JSON.stringify({
3160
+ issueId,
3161
+ cursor,
3162
+ limit: limit ? parseInt(limit, 10) : void 0
3163
+ })
3164
+ })
3165
+ );
3166
+ const data = await response.json();
3167
+ return c.json(data);
3168
+ });
3169
+ eventRoutes.get("/:slug/events/:eventId", async (c) => {
3170
+ const slug = c.req.param("slug");
3171
+ const eventId = c.req.param("eventId");
3172
+ const projectResult = await getProjectWithAccess(c, slug);
3173
+ if (projectResult instanceof Response) {
3174
+ return projectResult;
3175
+ }
3176
+ const { project } = projectResult;
3177
+ const projectStateId = c.env.PROJECT_STATE.idFromName(project.id);
3178
+ const projectState = c.env.PROJECT_STATE.get(projectStateId);
3179
+ const response = await projectState.fetch(
3180
+ new Request("http://internal/event", {
3181
+ method: "POST",
3182
+ headers: { "Content-Type": "application/json" },
3183
+ body: JSON.stringify({ eventId })
3184
+ })
3185
+ );
3186
+ if (!response.ok) {
3187
+ const error = await response.json();
3188
+ return c.json(error, response.status);
3189
+ }
3190
+ const data = await response.json();
3191
+ return c.json(data);
3192
+ });
3193
+ eventRoutes.get("/:slug/events/latest", async (c) => {
3194
+ const slug = c.req.param("slug");
3195
+ const projectResult = await getProjectWithAccess(c, slug);
3196
+ if (projectResult instanceof Response) {
3197
+ return projectResult;
3198
+ }
3199
+ const { project } = projectResult;
3200
+ const limit = c.req.query("limit");
3201
+ const projectStateId = c.env.PROJECT_STATE.idFromName(project.id);
3202
+ const projectState = c.env.PROJECT_STATE.get(projectStateId);
3203
+ const response = await projectState.fetch(
3204
+ new Request("http://internal/events/latest", {
3205
+ method: "POST",
3206
+ headers: { "Content-Type": "application/json" },
3207
+ body: JSON.stringify({
3208
+ limit: limit ? parseInt(limit, 10) : void 0
3209
+ })
3210
+ })
3211
+ );
3212
+ const data = await response.json();
3213
+ return c.json(data);
3214
+ });
3215
+
3216
+ // src/lib/envelope-parser.ts
3217
+ function parseEnvelope(body) {
3218
+ const lines = body.split("\n");
3219
+ if (lines.length < 1) {
3220
+ throw new Error("Invalid envelope: empty body");
3221
+ }
3222
+ let header;
3223
+ try {
3224
+ header = JSON.parse(lines[0]);
3225
+ } catch {
3226
+ throw new Error("Invalid envelope: failed to parse header");
3227
+ }
3228
+ const items = [];
3229
+ let i = 1;
3230
+ while (i < lines.length) {
3231
+ if (!lines[i] || lines[i].trim() === "") {
3232
+ i++;
3233
+ continue;
3234
+ }
3235
+ let itemHeader;
3236
+ try {
3237
+ itemHeader = JSON.parse(lines[i]);
3238
+ } catch {
3239
+ i++;
3240
+ continue;
3241
+ }
3242
+ i++;
3243
+ if (i >= lines.length) {
3244
+ break;
3245
+ }
3246
+ let payload;
3247
+ if (itemHeader.length !== void 0) {
3248
+ const payloadStr = lines[i].substring(0, itemHeader.length);
3249
+ try {
3250
+ payload = JSON.parse(payloadStr);
3251
+ } catch {
3252
+ payload = payloadStr;
3253
+ }
3254
+ } else {
3255
+ try {
3256
+ payload = JSON.parse(lines[i]);
3257
+ } catch {
3258
+ payload = lines[i];
3259
+ }
3260
+ }
3261
+ items.push({
3262
+ type: itemHeader.type,
3263
+ payload
3264
+ });
3265
+ i++;
3266
+ }
3267
+ return { header, items };
3268
+ }
3269
+ __name(parseEnvelope, "parseEnvelope");
3270
+ function extractKeyFromAuthHeader(header) {
3271
+ if (!header.startsWith("Sentry ")) {
3272
+ return null;
3273
+ }
3274
+ const parts = header.substring(7).split(",");
3275
+ for (const part of parts) {
3276
+ const [key, value] = part.trim().split("=");
3277
+ if (key === "sentry_key") {
3278
+ return value;
3279
+ }
3280
+ }
3281
+ return null;
3282
+ }
3283
+ __name(extractKeyFromAuthHeader, "extractKeyFromAuthHeader");
3284
+ function extractEvents(envelope) {
3285
+ const events = [];
3286
+ for (const item of envelope.items) {
3287
+ if (item.type === "event" || item.type === "transaction") {
3288
+ const event = item.payload;
3289
+ if (!event.event_id) {
3290
+ event.event_id = crypto.randomUUID().replace(/-/g, "");
3291
+ }
3292
+ if (!event.timestamp) {
3293
+ event.timestamp = (/* @__PURE__ */ new Date()).toISOString();
3294
+ }
3295
+ events.push(event);
3296
+ }
3297
+ }
3298
+ return events;
3299
+ }
3300
+ __name(extractEvents, "extractEvents");
3301
+ async function maybeDecompress(body, contentEncoding) {
3302
+ if (contentEncoding === "gzip") {
3303
+ const ds = new DecompressionStream("gzip");
3304
+ const decompressed = new Response(body).body.pipeThrough(ds);
3305
+ return await new Response(decompressed).text();
3306
+ }
3307
+ return new TextDecoder().decode(body);
3308
+ }
3309
+ __name(maybeDecompress, "maybeDecompress");
3310
+
3311
+ // src/routes/ingestion.ts
3312
+ var ingestionRoutes = new Hono2();
3313
+ ingestionRoutes.post("/:projectId/envelope", handleIngestion);
3314
+ ingestionRoutes.post("/:projectId/envelope/", handleIngestion);
3315
+ ingestionRoutes.post("/:projectId/store", handleIngestion);
3316
+ ingestionRoutes.post("/:projectId/store/", handleIngestion);
3317
+ async function handleIngestion(c) {
3318
+ const projectId = c.req.param("projectId");
3319
+ let publicKey = null;
3320
+ const sentryKeyParam = c.req.query("sentry_key");
3321
+ if (sentryKeyParam) {
3322
+ publicKey = sentryKeyParam;
3323
+ }
3324
+ if (!publicKey) {
3325
+ const authHeader = c.req.header("X-Sentry-Auth");
3326
+ if (authHeader) {
3327
+ publicKey = extractKeyFromAuthHeader(authHeader);
3328
+ }
3329
+ }
3330
+ if (!publicKey) {
3331
+ const authHeader = c.req.header("Authorization");
3332
+ if (authHeader?.startsWith("Basic ")) {
3333
+ try {
3334
+ const decoded = atob(authHeader.substring(6));
3335
+ publicKey = decoded.split(":")[0];
3336
+ } catch {
3337
+ }
3338
+ }
3339
+ }
3340
+ if (!publicKey) {
3341
+ return c.json({ error: "missing_auth", message: "No authentication provided" }, 401);
3342
+ }
3343
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3344
+ const authState = c.env.AUTH_STATE.get(authStateId);
3345
+ const projectResponse = await authState.fetch(
3346
+ new Request("http://internal/get-project-by-key", {
3347
+ method: "POST",
3348
+ headers: { "Content-Type": "application/json" },
3349
+ body: JSON.stringify({ publicKey })
3350
+ })
3351
+ );
3352
+ if (!projectResponse.ok) {
3353
+ return c.json({ error: "invalid_auth", message: "Invalid DSN" }, 401);
3354
+ }
3355
+ const projectData = await projectResponse.json();
3356
+ const project = projectData.project;
3357
+ if (projectId && projectId !== project.id) {
3358
+ return c.json({ error: "project_mismatch", message: "Project ID does not match DSN" }, 400);
3359
+ }
3360
+ const contentEncoding = c.req.header("Content-Encoding") ?? null;
3361
+ const contentType = c.req.header("Content-Type") || "";
3362
+ const bodyBuffer = await c.req.arrayBuffer();
3363
+ let bodyText;
3364
+ try {
3365
+ bodyText = await maybeDecompress(bodyBuffer, contentEncoding);
3366
+ } catch {
3367
+ return c.json({ error: "decompression_failed", message: "Failed to decompress body" }, 400);
3368
+ }
3369
+ let events;
3370
+ try {
3371
+ if (contentType.includes("application/json") && !bodyText.includes("\n{")) {
3372
+ const event = JSON.parse(bodyText);
3373
+ events = [event];
3374
+ } else {
3375
+ const envelope = parseEnvelope(bodyText);
3376
+ events = extractEvents(envelope);
3377
+ }
3378
+ } catch (error) {
3379
+ console.error("Parse error:", error);
3380
+ return c.json({ error: "parse_failed", message: "Failed to parse envelope" }, 400);
3381
+ }
3382
+ if (events.length === 0) {
3383
+ return c.json({ id: null, message: "No events in envelope" });
3384
+ }
3385
+ const projectStateId = c.env.PROJECT_STATE.idFromName(project.id);
3386
+ const projectState = c.env.PROJECT_STATE.get(projectStateId);
3387
+ const results = [];
3388
+ for (const event of events) {
3389
+ try {
3390
+ const response = await projectState.fetch(
3391
+ new Request("http://internal/ingest", {
3392
+ method: "POST",
3393
+ headers: { "Content-Type": "application/json" },
3394
+ body: JSON.stringify(event)
3395
+ })
3396
+ );
3397
+ if (response.ok) {
3398
+ const result = await response.json();
3399
+ results.push(result);
3400
+ } else {
3401
+ console.error("Ingest error:", await response.text());
3402
+ }
3403
+ } catch (error) {
3404
+ console.error("Ingest error:", error);
3405
+ }
3406
+ }
3407
+ const firstResult = results[0];
3408
+ return c.json({ id: firstResult?.eventId || events[0]?.event_id || null });
3409
+ }
3410
+ __name(handleIngestion, "handleIngestion");
3411
+ ingestionRoutes.get("/:projectId/security", async (c) => {
3412
+ return c.json({
3413
+ allowedDomains: ["*"],
3414
+ scrubData: true
3415
+ });
3416
+ });
3417
+
3418
+ // src/routes/issues.ts
3419
+ var issueRoutes = new Hono2();
3420
+ async function getProjectWithAccess2(c, slug) {
3421
+ const auth = c.get("auth");
3422
+ if (!auth) {
3423
+ return c.json({ error: "unauthorized" }, 401);
3424
+ }
3425
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3426
+ const authState = c.env.AUTH_STATE.get(authStateId);
3427
+ const response = await authState.fetch(
3428
+ new Request("http://internal/get-project", {
3429
+ method: "POST",
3430
+ headers: { "Content-Type": "application/json" },
3431
+ body: JSON.stringify({ slug, userId: auth.user.id })
3432
+ })
3433
+ );
3434
+ if (!response.ok) {
3435
+ return c.json({ error: "project_not_found" }, 404);
3436
+ }
3437
+ return response.json();
3438
+ }
3439
+ __name(getProjectWithAccess2, "getProjectWithAccess");
3440
+ issueRoutes.get("/:slug/issues", async (c) => {
3441
+ const slug = c.req.param("slug");
3442
+ const projectResult = await getProjectWithAccess2(c, slug);
3443
+ if (projectResult instanceof Response) {
3444
+ return projectResult;
3445
+ }
3446
+ const { project } = projectResult;
3447
+ const status = c.req.query("status");
3448
+ const level = c.req.query("level");
3449
+ const environment = c.req.query("environment");
3450
+ const query = c.req.query("query");
3451
+ const sort = c.req.query("sort");
3452
+ const cursor = c.req.query("cursor");
3453
+ const limit = c.req.query("limit");
3454
+ const projectStateId = c.env.PROJECT_STATE.idFromName(project.id);
3455
+ const projectState = c.env.PROJECT_STATE.get(projectStateId);
3456
+ const response = await projectState.fetch(
3457
+ new Request("http://internal/issues", {
3458
+ method: "POST",
3459
+ headers: { "Content-Type": "application/json" },
3460
+ body: JSON.stringify({
3461
+ status,
3462
+ level,
3463
+ environment,
3464
+ query,
3465
+ sort,
3466
+ cursor,
3467
+ limit: limit ? parseInt(limit, 10) : void 0
3468
+ })
3469
+ })
3470
+ );
3471
+ const data = await response.json();
3472
+ return c.json(data);
3473
+ });
3474
+ issueRoutes.get("/:slug/issues/:issueId", async (c) => {
3475
+ const slug = c.req.param("slug");
3476
+ const issueId = c.req.param("issueId");
3477
+ const projectResult = await getProjectWithAccess2(c, slug);
3478
+ if (projectResult instanceof Response) {
3479
+ return projectResult;
3480
+ }
3481
+ const { project } = projectResult;
3482
+ const projectStateId = c.env.PROJECT_STATE.idFromName(project.id);
3483
+ const projectState = c.env.PROJECT_STATE.get(projectStateId);
3484
+ const response = await projectState.fetch(
3485
+ new Request("http://internal/issue", {
3486
+ method: "POST",
3487
+ headers: { "Content-Type": "application/json" },
3488
+ body: JSON.stringify({ issueId })
3489
+ })
3490
+ );
3491
+ if (!response.ok) {
3492
+ const error = await response.json();
3493
+ return c.json(error, response.status);
3494
+ }
3495
+ const data = await response.json();
3496
+ return c.json(data);
3497
+ });
3498
+ var updateIssueHandler = /* @__PURE__ */ __name(async (c) => {
3499
+ const slug = c.req.param("slug");
3500
+ const issueId = c.req.param("issueId");
3501
+ const projectResult = await getProjectWithAccess2(c, slug);
3502
+ if (projectResult instanceof Response) {
3503
+ return projectResult;
3504
+ }
3505
+ const { project } = projectResult;
3506
+ const body = await c.req.json();
3507
+ const projectStateId = c.env.PROJECT_STATE.idFromName(project.id);
3508
+ const projectState = c.env.PROJECT_STATE.get(projectStateId);
3509
+ const response = await projectState.fetch(
3510
+ new Request("http://internal/issue/update", {
3511
+ method: "POST",
3512
+ headers: { "Content-Type": "application/json" },
3513
+ body: JSON.stringify({
3514
+ issueId,
3515
+ status: body.status,
3516
+ assignee: body.assignee
3517
+ })
3518
+ })
3519
+ );
3520
+ const data = await response.json();
3521
+ return c.json(data, response.status);
3522
+ }, "updateIssueHandler");
3523
+ issueRoutes.patch("/:slug/issues/:issueId", updateIssueHandler);
3524
+ issueRoutes.put("/:slug/issues/:issueId", updateIssueHandler);
3525
+ issueRoutes.delete("/:slug/issues/:issueId", async (c) => {
3526
+ const slug = c.req.param("slug");
3527
+ const issueId = c.req.param("issueId");
3528
+ const projectResult = await getProjectWithAccess2(c, slug);
3529
+ if (projectResult instanceof Response) {
3530
+ return projectResult;
3531
+ }
3532
+ const { project } = projectResult;
3533
+ const projectStateId = c.env.PROJECT_STATE.idFromName(project.id);
3534
+ const projectState = c.env.PROJECT_STATE.get(projectStateId);
3535
+ const response = await projectState.fetch(
3536
+ new Request("http://internal/issue/delete", {
3537
+ method: "POST",
3538
+ headers: { "Content-Type": "application/json" },
3539
+ body: JSON.stringify({ issueId })
3540
+ })
3541
+ );
3542
+ const data = await response.json();
3543
+ return c.json(data);
3544
+ });
3545
+ issueRoutes.get("/:slug/stats", async (c) => {
3546
+ const slug = c.req.param("slug");
3547
+ const projectResult = await getProjectWithAccess2(c, slug);
3548
+ if (projectResult instanceof Response) {
3549
+ return projectResult;
3550
+ }
3551
+ const { project } = projectResult;
3552
+ const interval = c.req.query("interval");
3553
+ const start = c.req.query("start");
3554
+ const end = c.req.query("end");
3555
+ const projectStateId = c.env.PROJECT_STATE.idFromName(project.id);
3556
+ const projectState = c.env.PROJECT_STATE.get(projectStateId);
3557
+ const response = await projectState.fetch(
3558
+ new Request("http://internal/stats", {
3559
+ method: "POST",
3560
+ headers: { "Content-Type": "application/json" },
3561
+ body: JSON.stringify({ interval, start, end })
3562
+ })
3563
+ );
3564
+ const data = await response.json();
3565
+ return c.json(data);
3566
+ });
3567
+
3568
+ // src/routes/projects.ts
3569
+ var projectRoutes = new Hono2();
3570
+ projectRoutes.get("/", async (c) => {
3571
+ const auth = c.get("auth");
3572
+ if (!auth) {
3573
+ return c.json({ error: "unauthorized" }, 401);
3574
+ }
3575
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3576
+ const authState = c.env.AUTH_STATE.get(authStateId);
3577
+ const response = await authState.fetch(
3578
+ new Request("http://internal/list-projects", {
3579
+ method: "POST",
3580
+ headers: { "Content-Type": "application/json" },
3581
+ body: JSON.stringify({ userId: auth.user.id })
3582
+ })
3583
+ );
3584
+ const data = await response.json();
3585
+ return c.json(data);
3586
+ });
3587
+ projectRoutes.post("/", async (c) => {
3588
+ const auth = c.get("auth");
3589
+ if (!auth) {
3590
+ return c.json({ error: "unauthorized" }, 401);
3591
+ }
3592
+ const body = await c.req.json();
3593
+ if (!body.name) {
3594
+ return c.json({ error: "missing_fields", message: "Name is required" }, 400);
3595
+ }
3596
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3597
+ const authState = c.env.AUTH_STATE.get(authStateId);
3598
+ const response = await authState.fetch(
3599
+ new Request("http://internal/create-project", {
3600
+ method: "POST",
3601
+ headers: { "Content-Type": "application/json" },
3602
+ body: JSON.stringify({
3603
+ name: body.name,
3604
+ platform: body.platform,
3605
+ userId: auth.user.id
3606
+ })
3607
+ })
3608
+ );
3609
+ const data = await response.json();
3610
+ const host = new URL(c.req.url).host;
3611
+ const dsn = `https://${data.project.publicKey}@${host}/${data.project.id}`;
3612
+ return c.json({ ...data, dsn }, response.status);
3613
+ });
3614
+ projectRoutes.get("/:slug", async (c) => {
3615
+ const auth = c.get("auth");
3616
+ if (!auth) {
3617
+ return c.json({ error: "unauthorized" }, 401);
3618
+ }
3619
+ const slug = c.req.param("slug");
3620
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3621
+ const authState = c.env.AUTH_STATE.get(authStateId);
3622
+ const response = await authState.fetch(
3623
+ new Request("http://internal/get-project", {
3624
+ method: "POST",
3625
+ headers: { "Content-Type": "application/json" },
3626
+ body: JSON.stringify({ slug, userId: auth.user.id })
3627
+ })
3628
+ );
3629
+ if (!response.ok) {
3630
+ const error = await response.json();
3631
+ return c.json(error, response.status);
3632
+ }
3633
+ const data = await response.json();
3634
+ const host = new URL(c.req.url).host;
3635
+ const dsn = `https://${data.project.publicKey}@${host}/${data.project.id}`;
3636
+ return c.json({ ...data, dsn });
3637
+ });
3638
+ projectRoutes.patch("/:slug", async (c) => {
3639
+ const auth = c.get("auth");
3640
+ if (!auth) {
3641
+ return c.json({ error: "unauthorized" }, 401);
3642
+ }
3643
+ return c.json({ error: "not_implemented" }, 501);
3644
+ });
3645
+ projectRoutes.delete("/:slug", async (c) => {
3646
+ const auth = c.get("auth");
3647
+ if (!auth) {
3648
+ return c.json({ error: "unauthorized" }, 401);
3649
+ }
3650
+ const slug = c.req.param("slug");
3651
+ const authStateId = c.env.AUTH_STATE.idFromName("global");
3652
+ const authState = c.env.AUTH_STATE.get(authStateId);
3653
+ const getResponse = await authState.fetch(
3654
+ new Request("http://internal/get-project", {
3655
+ method: "POST",
3656
+ headers: { "Content-Type": "application/json" },
3657
+ body: JSON.stringify({ slug, userId: auth.user.id })
3658
+ })
3659
+ );
3660
+ if (!getResponse.ok) {
3661
+ const error = await getResponse.json();
3662
+ return c.json(error, getResponse.status);
3663
+ }
3664
+ const projectData = await getResponse.json();
3665
+ const deleteResponse = await authState.fetch(
3666
+ new Request("http://internal/delete-project", {
3667
+ method: "POST",
3668
+ headers: { "Content-Type": "application/json" },
3669
+ body: JSON.stringify({
3670
+ projectId: projectData.project.id,
3671
+ userId: auth.user.id
3672
+ })
3673
+ })
3674
+ );
3675
+ const data = await deleteResponse.json();
3676
+ return c.json(data, deleteResponse.status);
3677
+ });
3678
+
3679
+ // src/durable-objects/auth-state.ts
3680
+ import { DurableObject } from "cloudflare:workers";
3681
+ var SCHEMA = `
3682
+ CREATE TABLE IF NOT EXISTS users (
3683
+ id TEXT PRIMARY KEY,
3684
+ email TEXT UNIQUE NOT NULL,
3685
+ password_hash TEXT NOT NULL,
3686
+ name TEXT NOT NULL,
3687
+ role TEXT NOT NULL DEFAULT 'member',
3688
+ created_at TEXT NOT NULL,
3689
+ updated_at TEXT NOT NULL
3690
+ );
3691
+
3692
+ CREATE TABLE IF NOT EXISTS sessions (
3693
+ id TEXT PRIMARY KEY,
3694
+ user_id TEXT NOT NULL,
3695
+ expires_at TEXT NOT NULL,
3696
+ created_at TEXT NOT NULL,
3697
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
3698
+ );
3699
+ CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
3700
+ CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
3701
+
3702
+ CREATE TABLE IF NOT EXISTS projects (
3703
+ id TEXT PRIMARY KEY,
3704
+ name TEXT NOT NULL,
3705
+ slug TEXT UNIQUE NOT NULL,
3706
+ platform TEXT NOT NULL DEFAULT 'javascript',
3707
+ public_key TEXT UNIQUE NOT NULL,
3708
+ created_at TEXT NOT NULL,
3709
+ created_by TEXT NOT NULL,
3710
+ FOREIGN KEY (created_by) REFERENCES users(id)
3711
+ );
3712
+ CREATE INDEX IF NOT EXISTS idx_projects_slug ON projects(slug);
3713
+ CREATE INDEX IF NOT EXISTS idx_projects_public_key ON projects(public_key);
3714
+
3715
+ CREATE TABLE IF NOT EXISTS project_members (
3716
+ project_id TEXT NOT NULL,
3717
+ user_id TEXT NOT NULL,
3718
+ role TEXT NOT NULL DEFAULT 'member',
3719
+ created_at TEXT NOT NULL,
3720
+ PRIMARY KEY (project_id, user_id),
3721
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
3722
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
3723
+ );
3724
+ `;
3725
+ var AuthState = class extends DurableObject {
3726
+ static {
3727
+ __name(this, "AuthState");
3728
+ }
3729
+ sql;
3730
+ initialized = false;
3731
+ constructor(ctx, env2) {
3732
+ super(ctx, env2);
3733
+ this.sql = ctx.storage.sql;
3734
+ }
3735
+ async ensureSchema() {
3736
+ if (this.initialized) return;
3737
+ this.sql.exec(SCHEMA);
3738
+ this.initialized = true;
3739
+ }
3740
+ async fetch(request) {
3741
+ await this.ensureSchema();
3742
+ const url = new URL(request.url);
3743
+ const path = url.pathname;
3744
+ try {
3745
+ switch (path) {
3746
+ case "/register":
3747
+ return this.handleRegister(request);
3748
+ case "/login":
3749
+ return this.handleLogin(request);
3750
+ case "/logout":
3751
+ return this.handleLogout(request);
3752
+ case "/validate-session":
3753
+ return this.handleValidateSession(request);
3754
+ case "/me":
3755
+ return this.handleGetMe(request);
3756
+ case "/create-project":
3757
+ return this.handleCreateProject(request);
3758
+ case "/list-projects":
3759
+ return this.handleListProjects(request);
3760
+ case "/get-project":
3761
+ return this.handleGetProject(request);
3762
+ case "/get-project-by-key":
3763
+ return this.handleGetProjectByKey(request);
3764
+ case "/delete-project":
3765
+ return this.handleDeleteProject(request);
3766
+ case "/check-access":
3767
+ return this.handleCheckAccess(request);
3768
+ default:
3769
+ return new Response(JSON.stringify({ error: "not_found" }), {
3770
+ status: 404,
3771
+ headers: { "Content-Type": "application/json" }
3772
+ });
3773
+ }
3774
+ } catch (error) {
3775
+ console.error("AuthState error:", error);
3776
+ return new Response(
3777
+ JSON.stringify({
3778
+ error: "internal_error",
3779
+ message: error instanceof Error ? error.message : "Unknown error"
3780
+ }),
3781
+ { status: 500, headers: { "Content-Type": "application/json" } }
3782
+ );
3783
+ }
3784
+ }
3785
+ async handleRegister(request) {
3786
+ const { email, password, name } = await request.json();
3787
+ if (!email || !password || !name) {
3788
+ return this.jsonResponse(
3789
+ { error: "missing_fields", message: "Email, password, and name are required" },
3790
+ 400
3791
+ );
3792
+ }
3793
+ const existing = this.sql.exec("SELECT id FROM users WHERE email = ?", email).toArray();
3794
+ if (existing.length > 0) {
3795
+ return this.jsonResponse(
3796
+ { error: "user_exists", message: "User with this email already exists" },
3797
+ 409
3798
+ );
3799
+ }
3800
+ const userCount = this.sql.exec("SELECT COUNT(*) as count FROM users").one();
3801
+ const isFirstUser = userCount?.count === 0;
3802
+ const passwordHash = await this.hashPassword(password);
3803
+ const userId = crypto.randomUUID();
3804
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3805
+ const role = isFirstUser ? "admin" : "member";
3806
+ this.sql.exec(
3807
+ "INSERT INTO users (id, email, password_hash, name, role, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
3808
+ userId,
3809
+ email.toLowerCase(),
3810
+ passwordHash,
3811
+ name,
3812
+ role,
3813
+ now,
3814
+ now
3815
+ );
3816
+ const session = await this.createSession(userId);
3817
+ const user = {
3818
+ id: userId,
3819
+ email: email.toLowerCase(),
3820
+ name,
3821
+ role,
3822
+ createdAt: now,
3823
+ updatedAt: now
3824
+ };
3825
+ return this.jsonResponse({ user, token: session.id });
3826
+ }
3827
+ async handleLogin(request) {
3828
+ const { email, password } = await request.json();
3829
+ if (!email || !password) {
3830
+ return this.jsonResponse(
3831
+ { error: "missing_fields", message: "Email and password are required" },
3832
+ 400
3833
+ );
3834
+ }
3835
+ const userRows = this.sql.exec(
3836
+ "SELECT id, email, password_hash, name, role, created_at, updated_at FROM users WHERE email = ?",
3837
+ email.toLowerCase()
3838
+ ).toArray();
3839
+ if (userRows.length === 0) {
3840
+ return this.jsonResponse(
3841
+ { error: "invalid_credentials", message: "Invalid email or password" },
3842
+ 401
3843
+ );
3844
+ }
3845
+ const userRow = userRows[0];
3846
+ const valid = await this.verifyPassword(password, userRow.password_hash);
3847
+ if (!valid) {
3848
+ return this.jsonResponse(
3849
+ { error: "invalid_credentials", message: "Invalid email or password" },
3850
+ 401
3851
+ );
3852
+ }
3853
+ const session = await this.createSession(userRow.id);
3854
+ const user = {
3855
+ id: userRow.id,
3856
+ email: userRow.email,
3857
+ name: userRow.name,
3858
+ role: userRow.role,
3859
+ createdAt: userRow.created_at,
3860
+ updatedAt: userRow.updated_at
3861
+ };
3862
+ return this.jsonResponse({ user, token: session.id });
3863
+ }
3864
+ async handleLogout(request) {
3865
+ const { token } = await request.json();
3866
+ if (token) {
3867
+ this.sql.exec("DELETE FROM sessions WHERE id = ?", token);
3868
+ }
3869
+ return this.jsonResponse({ success: true });
3870
+ }
3871
+ async handleValidateSession(request) {
3872
+ const { token } = await request.json();
3873
+ if (!token) {
3874
+ return this.jsonResponse({ error: "missing_token" }, 400);
3875
+ }
3876
+ await this.cleanExpiredSessions();
3877
+ const rows = this.sql.exec(
3878
+ `SELECT s.id as session_id, s.expires_at, s.created_at as session_created,
3879
+ u.id as user_id, u.email, u.name, u.role, u.created_at, u.updated_at
3880
+ FROM sessions s
3881
+ JOIN users u ON s.user_id = u.id
3882
+ WHERE s.id = ? AND s.expires_at > ?`,
3883
+ token,
3884
+ (/* @__PURE__ */ new Date()).toISOString()
3885
+ ).toArray();
3886
+ if (rows.length === 0) {
3887
+ return this.jsonResponse({ error: "invalid_session" }, 401);
3888
+ }
3889
+ const row = rows[0];
3890
+ const user = {
3891
+ id: row.user_id,
3892
+ email: row.email,
3893
+ name: row.name,
3894
+ role: row.role,
3895
+ createdAt: row.created_at,
3896
+ updatedAt: row.updated_at
3897
+ };
3898
+ const session = {
3899
+ id: row.session_id,
3900
+ userId: row.user_id,
3901
+ expiresAt: row.expires_at,
3902
+ createdAt: row.session_created
3903
+ };
3904
+ return this.jsonResponse({ user, session });
3905
+ }
3906
+ async handleGetMe(request) {
3907
+ const { token } = await request.json();
3908
+ return this.handleValidateSession(
3909
+ new Request(request.url, {
3910
+ method: "POST",
3911
+ body: JSON.stringify({ token })
3912
+ })
3913
+ );
3914
+ }
3915
+ async handleCreateProject(request) {
3916
+ const { name, platform: platform2, userId } = await request.json();
3917
+ if (!name || !userId) {
3918
+ return this.jsonResponse(
3919
+ { error: "missing_fields", message: "Name and userId are required" },
3920
+ 400
3921
+ );
3922
+ }
3923
+ const baseSlug = this.slugify(name);
3924
+ let slug = baseSlug;
3925
+ let counter = 1;
3926
+ while (this.sql.exec("SELECT id FROM projects WHERE slug = ?", slug).toArray().length > 0) {
3927
+ slug = `${baseSlug}-${counter}`;
3928
+ counter++;
3929
+ }
3930
+ const publicKey = this.generateKey(32);
3931
+ const projectId = crypto.randomUUID();
3932
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3933
+ this.sql.exec(
3934
+ "INSERT INTO projects (id, name, slug, platform, public_key, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)",
3935
+ projectId,
3936
+ name,
3937
+ slug,
3938
+ platform2 || "javascript",
3939
+ publicKey,
3940
+ now,
3941
+ userId
3942
+ );
3943
+ this.sql.exec(
3944
+ "INSERT INTO project_members (project_id, user_id, role, created_at) VALUES (?, ?, ?, ?)",
3945
+ projectId,
3946
+ userId,
3947
+ "owner",
3948
+ now
3949
+ );
3950
+ const project = {
3951
+ id: projectId,
3952
+ name,
3953
+ slug,
3954
+ platform: platform2 || "javascript",
3955
+ publicKey,
3956
+ createdAt: now,
3957
+ createdBy: userId
3958
+ };
3959
+ return this.jsonResponse({ project });
3960
+ }
3961
+ async handleListProjects(request) {
3962
+ const { userId } = await request.json();
3963
+ if (!userId) {
3964
+ return this.jsonResponse({ error: "missing_user_id" }, 400);
3965
+ }
3966
+ const rows = this.sql.exec(
3967
+ `SELECT p.id, p.name, p.slug, p.platform, p.public_key, p.created_at, p.created_by, pm.role as member_role
3968
+ FROM projects p
3969
+ JOIN project_members pm ON p.id = pm.project_id
3970
+ WHERE pm.user_id = ?
3971
+ ORDER BY p.created_at DESC`,
3972
+ userId
3973
+ ).toArray();
3974
+ const projects = rows.map((row) => ({
3975
+ id: row.id,
3976
+ name: row.name,
3977
+ slug: row.slug,
3978
+ platform: row.platform,
3979
+ publicKey: row.public_key,
3980
+ createdAt: row.created_at,
3981
+ createdBy: row.created_by,
3982
+ memberRole: row.member_role
3983
+ }));
3984
+ return this.jsonResponse({ projects });
3985
+ }
3986
+ async handleGetProject(request) {
3987
+ const { slug, userId } = await request.json();
3988
+ if (!slug) {
3989
+ return this.jsonResponse({ error: "missing_slug" }, 400);
3990
+ }
3991
+ let rows;
3992
+ if (userId) {
3993
+ rows = this.sql.exec(
3994
+ `SELECT p.id, p.name, p.slug, p.platform, p.public_key, p.created_at, p.created_by
3995
+ FROM projects p
3996
+ JOIN project_members pm ON p.id = pm.project_id AND pm.user_id = ?
3997
+ WHERE p.slug = ?`,
3998
+ userId,
3999
+ slug
4000
+ ).toArray();
4001
+ } else {
4002
+ rows = this.sql.exec(
4003
+ `SELECT p.id, p.name, p.slug, p.platform, p.public_key, p.created_at, p.created_by
4004
+ FROM projects p
4005
+ WHERE p.slug = ?`,
4006
+ slug
4007
+ ).toArray();
4008
+ }
4009
+ if (rows.length === 0) {
4010
+ return this.jsonResponse({ error: "project_not_found" }, 404);
4011
+ }
4012
+ const row = rows[0];
4013
+ const project = {
4014
+ id: row.id,
4015
+ name: row.name,
4016
+ slug: row.slug,
4017
+ platform: row.platform,
4018
+ publicKey: row.public_key,
4019
+ createdAt: row.created_at,
4020
+ createdBy: row.created_by
4021
+ };
4022
+ return this.jsonResponse({ project });
4023
+ }
4024
+ async handleGetProjectByKey(request) {
4025
+ const { publicKey } = await request.json();
4026
+ if (!publicKey) {
4027
+ return this.jsonResponse({ error: "missing_key" }, 400);
4028
+ }
4029
+ const rows = this.sql.exec(
4030
+ "SELECT id, name, slug, platform, public_key, created_at, created_by FROM projects WHERE public_key = ?",
4031
+ publicKey
4032
+ ).toArray();
4033
+ if (rows.length === 0) {
4034
+ return this.jsonResponse({ error: "project_not_found" }, 404);
4035
+ }
4036
+ const row = rows[0];
4037
+ const project = {
4038
+ id: row.id,
4039
+ name: row.name,
4040
+ slug: row.slug,
4041
+ platform: row.platform,
4042
+ publicKey: row.public_key,
4043
+ createdAt: row.created_at,
4044
+ createdBy: row.created_by
4045
+ };
4046
+ return this.jsonResponse({ project });
4047
+ }
4048
+ async handleDeleteProject(request) {
4049
+ const { projectId, userId } = await request.json();
4050
+ if (!projectId || !userId) {
4051
+ return this.jsonResponse({ error: "missing_fields" }, 400);
4052
+ }
4053
+ const memberRows = this.sql.exec(
4054
+ "SELECT role FROM project_members WHERE project_id = ? AND user_id = ?",
4055
+ projectId,
4056
+ userId
4057
+ ).toArray();
4058
+ if (memberRows.length === 0 || memberRows[0].role !== "owner") {
4059
+ return this.jsonResponse(
4060
+ { error: "forbidden", message: "Only project owner can delete" },
4061
+ 403
4062
+ );
4063
+ }
4064
+ this.sql.exec("DELETE FROM projects WHERE id = ?", projectId);
4065
+ return this.jsonResponse({ success: true });
4066
+ }
4067
+ async handleCheckAccess(request) {
4068
+ const { projectId, userId } = await request.json();
4069
+ if (!projectId || !userId) {
4070
+ return this.jsonResponse({ error: "missing_fields" }, 400);
4071
+ }
4072
+ const memberRows = this.sql.exec(
4073
+ "SELECT role FROM project_members WHERE project_id = ? AND user_id = ?",
4074
+ projectId,
4075
+ userId
4076
+ ).toArray();
4077
+ const member = memberRows.length > 0 ? memberRows[0] : null;
4078
+ return this.jsonResponse({
4079
+ hasAccess: !!member,
4080
+ role: member?.role || null
4081
+ });
4082
+ }
4083
+ async createSession(userId) {
4084
+ const sessionId = this.generateKey(64);
4085
+ const now = /* @__PURE__ */ new Date();
4086
+ const expiresAt = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1e3);
4087
+ this.sql.exec(
4088
+ "INSERT INTO sessions (id, user_id, expires_at, created_at) VALUES (?, ?, ?, ?)",
4089
+ sessionId,
4090
+ userId,
4091
+ expiresAt.toISOString(),
4092
+ now.toISOString()
4093
+ );
4094
+ return {
4095
+ id: sessionId,
4096
+ userId,
4097
+ expiresAt: expiresAt.toISOString(),
4098
+ createdAt: now.toISOString()
4099
+ };
4100
+ }
4101
+ async cleanExpiredSessions() {
4102
+ this.sql.exec("DELETE FROM sessions WHERE expires_at < ?", (/* @__PURE__ */ new Date()).toISOString());
4103
+ }
4104
+ async hashPassword(password) {
4105
+ const encoder = new TextEncoder();
4106
+ const data = encoder.encode(password);
4107
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
4108
+ const hashArray2 = Array.from(new Uint8Array(hashBuffer));
4109
+ return hashArray2.map((b) => b.toString(16).padStart(2, "0")).join("");
4110
+ }
4111
+ async verifyPassword(password, hash) {
4112
+ const passwordHash = await this.hashPassword(password);
4113
+ return passwordHash === hash;
4114
+ }
4115
+ generateKey(length) {
4116
+ const array = new Uint8Array(length);
4117
+ crypto.getRandomValues(array);
4118
+ return Array.from(array).map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, length);
4119
+ }
4120
+ slugify(text) {
4121
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
4122
+ }
4123
+ jsonResponse(data, status = 200) {
4124
+ return new Response(JSON.stringify(data), {
4125
+ status,
4126
+ headers: { "Content-Type": "application/json" }
4127
+ });
4128
+ }
4129
+ };
4130
+
4131
+ // src/durable-objects/project-state.ts
4132
+ import { DurableObject as DurableObject2 } from "cloudflare:workers";
4133
+
4134
+ // src/lib/fingerprint.ts
4135
+ function generateFingerprint(event) {
4136
+ if (event.fingerprint && event.fingerprint.length > 0) {
4137
+ const nonDefault = event.fingerprint.filter((f) => f !== "{{ default }}");
4138
+ if (nonDefault.length > 0) {
4139
+ return hashArray(nonDefault);
4140
+ }
4141
+ }
4142
+ if (event.exception?.values && event.exception.values.length > 0) {
4143
+ const exc = event.exception.values[0];
4144
+ const parts = [];
4145
+ parts.push(exc.type || "Error");
4146
+ const normalizedMessage = normalizeMessage(exc.value || "");
4147
+ parts.push(normalizedMessage);
4148
+ const topFrames = getTopFrames(exc.stacktrace, 3);
4149
+ for (const frame of topFrames) {
4150
+ parts.push(formatFrame(frame));
4151
+ }
4152
+ return hashArray(parts);
4153
+ }
4154
+ if (event.message) {
4155
+ const normalizedMessage = normalizeMessage(event.message);
4156
+ return hashArray([event.level || "error", normalizedMessage]);
4157
+ }
4158
+ return hashArray([event.event_id]);
4159
+ }
4160
+ __name(generateFingerprint, "generateFingerprint");
4161
+ function extractTitle(event) {
4162
+ if (event.exception?.values && event.exception.values.length > 0) {
4163
+ const exc = event.exception.values[0];
4164
+ const type = exc.type || "Error";
4165
+ const value = exc.value || "";
4166
+ const truncatedValue = value.length > 100 ? value.slice(0, 97) + "..." : value;
4167
+ return `${type}: ${truncatedValue}`;
4168
+ }
4169
+ if (event.message) {
4170
+ return event.message.length > 128 ? event.message.slice(0, 125) + "..." : event.message;
4171
+ }
4172
+ return "Unknown Error";
4173
+ }
4174
+ __name(extractTitle, "extractTitle");
4175
+ function extractCulprit(event) {
4176
+ if (event.transaction) {
4177
+ return event.transaction;
4178
+ }
4179
+ if (event.exception?.values && event.exception.values.length > 0) {
4180
+ const exc = event.exception.values[0];
4181
+ const frame = getTopFrame(exc.stacktrace);
4182
+ if (frame) {
4183
+ const parts = [];
4184
+ if (frame.filename) {
4185
+ parts.push(frame.filename);
4186
+ }
4187
+ if (frame.function && frame.function !== "<anonymous>") {
4188
+ parts.push(`in ${frame.function}`);
4189
+ }
4190
+ if (frame.lineno) {
4191
+ parts.push(`at line ${frame.lineno}`);
4192
+ }
4193
+ if (parts.length > 0) {
4194
+ return parts.join(" ");
4195
+ }
4196
+ }
4197
+ }
4198
+ return null;
4199
+ }
4200
+ __name(extractCulprit, "extractCulprit");
4201
+ function extractMetadata(event) {
4202
+ const metadata = {
4203
+ type: "Error",
4204
+ value: ""
4205
+ };
4206
+ if (event.exception?.values && event.exception.values.length > 0) {
4207
+ const exc = event.exception.values[0];
4208
+ metadata.type = exc.type || "Error";
4209
+ metadata.value = (exc.value || "").slice(0, 200);
4210
+ const frame = getTopFrame(exc.stacktrace);
4211
+ if (frame) {
4212
+ metadata.filename = frame.filename;
4213
+ metadata.function = frame.function;
4214
+ }
4215
+ } else if (event.message) {
4216
+ metadata.type = "Message";
4217
+ metadata.value = event.message.slice(0, 200);
4218
+ }
4219
+ return metadata;
4220
+ }
4221
+ __name(extractMetadata, "extractMetadata");
4222
+ function getTopFrames(stacktrace, count) {
4223
+ if (!stacktrace?.frames || stacktrace.frames.length === 0) {
4224
+ return [];
4225
+ }
4226
+ const frames = [...stacktrace.frames].reverse();
4227
+ const inAppFrames = frames.filter((f) => f.in_app !== false);
4228
+ if (inAppFrames.length > 0) {
4229
+ return inAppFrames.slice(0, count);
4230
+ }
4231
+ return frames.slice(0, count);
4232
+ }
4233
+ __name(getTopFrames, "getTopFrames");
4234
+ function getTopFrame(stacktrace) {
4235
+ const frames = getTopFrames(stacktrace, 1);
4236
+ return frames.length > 0 ? frames[0] : null;
4237
+ }
4238
+ __name(getTopFrame, "getTopFrame");
4239
+ function formatFrame(frame) {
4240
+ const parts = [];
4241
+ if (frame.filename) {
4242
+ const filename = frame.filename.split("?")[0].split("#")[0];
4243
+ parts.push(filename);
4244
+ }
4245
+ if (frame.function) {
4246
+ parts.push(frame.function);
4247
+ }
4248
+ if (frame.lineno) {
4249
+ parts.push(String(frame.lineno));
4250
+ }
4251
+ return parts.join(":");
4252
+ }
4253
+ __name(formatFrame, "formatFrame");
4254
+ function normalizeMessage(message) {
4255
+ return message.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, "<uuid>").replace(/\b[0-9a-f]{24,}\b/gi, "<id>").replace(/\b\d{6,}\b/g, "<num>").replace(/\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/g, "<timestamp>").replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, "<ip>").replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, "<email>").replace(/\s+/g, " ").trim().slice(0, 500);
4256
+ }
4257
+ __name(normalizeMessage, "normalizeMessage");
4258
+ function hashArray(parts) {
4259
+ const str = parts.join("||");
4260
+ return simpleHash(str);
4261
+ }
4262
+ __name(hashArray, "hashArray");
4263
+ function simpleHash(str) {
4264
+ let hash = 5381;
4265
+ for (let i = 0; i < str.length; i++) {
4266
+ hash = hash * 33 ^ str.charCodeAt(i);
4267
+ }
4268
+ return (hash >>> 0).toString(16).padStart(8, "0");
4269
+ }
4270
+ __name(simpleHash, "simpleHash");
4271
+
4272
+ // src/durable-objects/project-state.ts
4273
+ var SCHEMA2 = `
4274
+ CREATE TABLE IF NOT EXISTS issues (
4275
+ id TEXT PRIMARY KEY,
4276
+ fingerprint TEXT UNIQUE NOT NULL,
4277
+ title TEXT NOT NULL,
4278
+ culprit TEXT,
4279
+ level TEXT NOT NULL DEFAULT 'error',
4280
+ platform TEXT NOT NULL DEFAULT 'javascript',
4281
+ first_seen TEXT NOT NULL,
4282
+ last_seen TEXT NOT NULL,
4283
+ count INTEGER NOT NULL DEFAULT 1,
4284
+ user_count INTEGER NOT NULL DEFAULT 0,
4285
+ status TEXT NOT NULL DEFAULT 'unresolved',
4286
+ metadata TEXT NOT NULL DEFAULT '{}'
4287
+ );
4288
+ CREATE INDEX IF NOT EXISTS idx_issues_fingerprint ON issues(fingerprint);
4289
+ CREATE INDEX IF NOT EXISTS idx_issues_last_seen ON issues(last_seen DESC);
4290
+ CREATE INDEX IF NOT EXISTS idx_issues_status ON issues(status);
4291
+
4292
+ CREATE TABLE IF NOT EXISTS events (
4293
+ id TEXT PRIMARY KEY,
4294
+ issue_id TEXT NOT NULL,
4295
+ timestamp TEXT NOT NULL,
4296
+ received_at TEXT NOT NULL,
4297
+ level TEXT NOT NULL DEFAULT 'error',
4298
+ platform TEXT,
4299
+ environment TEXT,
4300
+ release TEXT,
4301
+ transaction_name TEXT,
4302
+ user_id TEXT,
4303
+ user_email TEXT,
4304
+ user_ip TEXT,
4305
+ tags TEXT,
4306
+ data TEXT NOT NULL,
4307
+ FOREIGN KEY (issue_id) REFERENCES issues(id) ON DELETE CASCADE
4308
+ );
4309
+ CREATE INDEX IF NOT EXISTS idx_events_issue ON events(issue_id);
4310
+ CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp DESC);
4311
+ CREATE INDEX IF NOT EXISTS idx_events_environment ON events(environment);
4312
+ CREATE INDEX IF NOT EXISTS idx_events_release ON events(release);
4313
+
4314
+ CREATE TABLE IF NOT EXISTS issue_stats (
4315
+ issue_id TEXT NOT NULL,
4316
+ bucket TEXT NOT NULL,
4317
+ count INTEGER NOT NULL DEFAULT 0,
4318
+ PRIMARY KEY (issue_id, bucket),
4319
+ FOREIGN KEY (issue_id) REFERENCES issues(id) ON DELETE CASCADE
4320
+ );
4321
+
4322
+ CREATE TABLE IF NOT EXISTS issue_users (
4323
+ issue_id TEXT NOT NULL,
4324
+ user_hash TEXT NOT NULL,
4325
+ first_seen TEXT NOT NULL,
4326
+ last_seen TEXT NOT NULL,
4327
+ PRIMARY KEY (issue_id, user_hash),
4328
+ FOREIGN KEY (issue_id) REFERENCES issues(id) ON DELETE CASCADE
4329
+ );
4330
+ `;
4331
+ var ProjectState = class extends DurableObject2 {
4332
+ static {
4333
+ __name(this, "ProjectState");
4334
+ }
4335
+ sql;
4336
+ initialized = false;
4337
+ constructor(ctx, env2) {
4338
+ super(ctx, env2);
4339
+ this.sql = ctx.storage.sql;
4340
+ }
4341
+ async ensureSchema() {
4342
+ if (this.initialized) return;
4343
+ this.sql.exec(SCHEMA2);
4344
+ this.initialized = true;
4345
+ }
4346
+ async fetch(request) {
4347
+ await this.ensureSchema();
4348
+ const url = new URL(request.url);
4349
+ const path = url.pathname;
4350
+ try {
4351
+ switch (path) {
4352
+ case "/ingest":
4353
+ return this.handleIngest(request);
4354
+ case "/issues":
4355
+ return this.handleGetIssues(request);
4356
+ case "/issue":
4357
+ return this.handleGetIssue(request);
4358
+ case "/issue/update":
4359
+ return this.handleUpdateIssue(request);
4360
+ case "/issue/delete":
4361
+ return this.handleDeleteIssue(request);
4362
+ case "/issue/events":
4363
+ return this.handleGetIssueEvents(request);
4364
+ case "/event":
4365
+ return this.handleGetEvent(request);
4366
+ case "/events/latest":
4367
+ return this.handleGetLatestEvents(request);
4368
+ case "/stats":
4369
+ return this.handleGetStats(request);
4370
+ default:
4371
+ return new Response(JSON.stringify({ error: "not_found" }), {
4372
+ status: 404,
4373
+ headers: { "Content-Type": "application/json" }
4374
+ });
4375
+ }
4376
+ } catch (error) {
4377
+ console.error("ProjectState error:", error);
4378
+ return new Response(
4379
+ JSON.stringify({
4380
+ error: "internal_error",
4381
+ message: error instanceof Error ? error.message : "Unknown error"
4382
+ }),
4383
+ { status: 500, headers: { "Content-Type": "application/json" } }
4384
+ );
4385
+ }
4386
+ }
4387
+ async handleIngest(request) {
4388
+ const event = await request.json();
4389
+ const eventId = event.event_id || crypto.randomUUID();
4390
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4391
+ const timestamp = event.timestamp || now;
4392
+ const fingerprint = generateFingerprint(event);
4393
+ const existingRows = this.sql.exec("SELECT id, count FROM issues WHERE fingerprint = ?", fingerprint).toArray();
4394
+ const existingIssue = existingRows.length > 0 ? existingRows[0] : null;
4395
+ let issueId;
4396
+ if (existingIssue) {
4397
+ issueId = existingIssue.id;
4398
+ this.sql.exec(
4399
+ "UPDATE issues SET last_seen = ?, count = count + 1 WHERE id = ?",
4400
+ now,
4401
+ issueId
4402
+ );
4403
+ } else {
4404
+ issueId = crypto.randomUUID();
4405
+ const title2 = extractTitle(event);
4406
+ const culprit = extractCulprit(event);
4407
+ const metadata = extractMetadata(event);
4408
+ this.sql.exec(
4409
+ `INSERT INTO issues (id, fingerprint, title, culprit, level, platform, first_seen, last_seen, count, status, metadata)
4410
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 'unresolved', ?)`,
4411
+ issueId,
4412
+ fingerprint,
4413
+ title2,
4414
+ culprit,
4415
+ event.level || "error",
4416
+ event.platform || "javascript",
4417
+ now,
4418
+ now,
4419
+ JSON.stringify(metadata)
4420
+ );
4421
+ }
4422
+ this.sql.exec(
4423
+ `INSERT INTO events (id, issue_id, timestamp, received_at, level, platform, environment, release, transaction_name, user_id, user_email, user_ip, tags, data)
4424
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
4425
+ eventId,
4426
+ issueId,
4427
+ timestamp,
4428
+ now,
4429
+ event.level || "error",
4430
+ event.platform || null,
4431
+ event.environment || null,
4432
+ event.release || null,
4433
+ event.transaction || null,
4434
+ event.user?.id || null,
4435
+ event.user?.email || null,
4436
+ event.user?.ip_address || null,
4437
+ event.tags ? JSON.stringify(event.tags) : null,
4438
+ JSON.stringify(event)
4439
+ );
4440
+ const bucket = this.getHourBucket(timestamp);
4441
+ this.sql.exec(
4442
+ `INSERT INTO issue_stats (issue_id, bucket, count)
4443
+ VALUES (?, ?, 1)
4444
+ ON CONFLICT (issue_id, bucket) DO UPDATE SET count = count + 1`,
4445
+ issueId,
4446
+ bucket
4447
+ );
4448
+ if (event.user) {
4449
+ const userHash = await this.hashUserIdentifier(event.user);
4450
+ if (userHash) {
4451
+ const existingUser = this.sql.exec(
4452
+ "SELECT issue_id FROM issue_users WHERE issue_id = ? AND user_hash = ?",
4453
+ issueId,
4454
+ userHash
4455
+ ).one();
4456
+ if (existingUser) {
4457
+ this.sql.exec(
4458
+ "UPDATE issue_users SET last_seen = ? WHERE issue_id = ? AND user_hash = ?",
4459
+ now,
4460
+ issueId,
4461
+ userHash
4462
+ );
4463
+ } else {
4464
+ this.sql.exec(
4465
+ "INSERT INTO issue_users (issue_id, user_hash, first_seen, last_seen) VALUES (?, ?, ?, ?)",
4466
+ issueId,
4467
+ userHash,
4468
+ now,
4469
+ now
4470
+ );
4471
+ this.sql.exec("UPDATE issues SET user_count = user_count + 1 WHERE id = ?", issueId);
4472
+ }
4473
+ }
4474
+ }
4475
+ return this.jsonResponse({ eventId, issueId });
4476
+ }
4477
+ async handleGetIssues(request) {
4478
+ const { status, level, query, sort, cursor, limit } = await request.json();
4479
+ const pageLimit = Math.min(limit || 25, 100);
4480
+ const sortField = sort || "last_seen";
4481
+ const sortOrder = "DESC";
4482
+ let sql = "SELECT * FROM issues WHERE 1=1";
4483
+ const params = [];
4484
+ if (status) {
4485
+ sql += " AND status = ?";
4486
+ params.push(status);
4487
+ }
4488
+ if (level) {
4489
+ sql += " AND level = ?";
4490
+ params.push(level);
4491
+ }
4492
+ if (query) {
4493
+ sql += " AND (title LIKE ? OR culprit LIKE ?)";
4494
+ params.push(`%${query}%`, `%${query}%`);
4495
+ }
4496
+ if (cursor) {
4497
+ sql += ` AND ${sortField} < ?`;
4498
+ params.push(cursor);
4499
+ }
4500
+ sql += ` ORDER BY ${sortField} ${sortOrder} LIMIT ?`;
4501
+ params.push(pageLimit + 1);
4502
+ const rows = this.sql.exec(sql, ...params).toArray();
4503
+ const hasMore = rows.length > pageLimit;
4504
+ const issues = rows.slice(0, pageLimit).map((row) => this.rowToIssue(row));
4505
+ const nextCursor = hasMore && issues.length > 0 ? issues[issues.length - 1][sortField] : void 0;
4506
+ return this.jsonResponse({
4507
+ issues,
4508
+ nextCursor,
4509
+ hasMore
4510
+ });
4511
+ }
4512
+ async handleGetIssue(request) {
4513
+ const { issueId } = await request.json();
4514
+ const rows = this.sql.exec("SELECT * FROM issues WHERE id = ?", issueId).toArray();
4515
+ if (rows.length === 0) {
4516
+ return this.jsonResponse({ error: "issue_not_found" }, 404);
4517
+ }
4518
+ const row = rows[0];
4519
+ const statsRows = this.sql.exec(
4520
+ "SELECT bucket, count FROM issue_stats WHERE issue_id = ? ORDER BY bucket DESC LIMIT 168",
4521
+ issueId
4522
+ ).toArray();
4523
+ const stats = statsRows.map((s) => ({
4524
+ bucket: s.bucket,
4525
+ count: s.count
4526
+ }));
4527
+ return this.jsonResponse({
4528
+ issue: this.rowToIssue(row),
4529
+ stats
4530
+ });
4531
+ }
4532
+ async handleUpdateIssue(request) {
4533
+ const { issueId, status } = await request.json();
4534
+ if (!issueId) {
4535
+ return this.jsonResponse({ error: "missing_issue_id" }, 400);
4536
+ }
4537
+ const updates = [];
4538
+ const params = [];
4539
+ if (status) {
4540
+ updates.push("status = ?");
4541
+ params.push(status);
4542
+ }
4543
+ if (updates.length === 0) {
4544
+ return this.jsonResponse({ error: "no_updates" }, 400);
4545
+ }
4546
+ params.push(issueId);
4547
+ this.sql.exec(`UPDATE issues SET ${updates.join(", ")} WHERE id = ?`, ...params);
4548
+ const row = this.sql.exec("SELECT * FROM issues WHERE id = ?", issueId).one();
4549
+ return this.jsonResponse({ issue: row ? this.rowToIssue(row) : null });
4550
+ }
4551
+ async handleDeleteIssue(request) {
4552
+ const { issueId } = await request.json();
4553
+ if (!issueId) {
4554
+ return this.jsonResponse({ error: "missing_issue_id" }, 400);
4555
+ }
4556
+ this.sql.exec("DELETE FROM issues WHERE id = ?", issueId);
4557
+ return this.jsonResponse({ success: true });
4558
+ }
4559
+ async handleGetIssueEvents(request) {
4560
+ const { issueId, cursor, limit } = await request.json();
4561
+ const pageLimit = Math.min(limit || 25, 100);
4562
+ let sql = "SELECT * FROM events WHERE issue_id = ?";
4563
+ const params = [issueId];
4564
+ if (cursor) {
4565
+ sql += " AND timestamp < ?";
4566
+ params.push(cursor);
4567
+ }
4568
+ sql += " ORDER BY timestamp DESC LIMIT ?";
4569
+ params.push(pageLimit + 1);
4570
+ const rows = this.sql.exec(sql, ...params).toArray();
4571
+ const hasMore = rows.length > pageLimit;
4572
+ const events = rows.slice(0, pageLimit).map((row) => JSON.parse(row.data));
4573
+ const nextCursor = hasMore && events.length > 0 ? events[events.length - 1].timestamp : void 0;
4574
+ return this.jsonResponse({
4575
+ events,
4576
+ nextCursor,
4577
+ hasMore
4578
+ });
4579
+ }
4580
+ async handleGetEvent(request) {
4581
+ const { eventId } = await request.json();
4582
+ const rows = this.sql.exec("SELECT * FROM events WHERE id = ?", eventId).toArray();
4583
+ if (rows.length === 0) {
4584
+ return this.jsonResponse({ error: "event_not_found" }, 404);
4585
+ }
4586
+ const row = rows[0];
4587
+ return this.jsonResponse({
4588
+ event: JSON.parse(row.data),
4589
+ issueId: row.issue_id
4590
+ });
4591
+ }
4592
+ async handleGetLatestEvents(request) {
4593
+ const { limit } = await request.json();
4594
+ const pageLimit = Math.min(limit || 25, 100);
4595
+ const rows = this.sql.exec("SELECT * FROM events ORDER BY timestamp DESC LIMIT ?", pageLimit).toArray();
4596
+ const events = rows.map((row) => ({
4597
+ ...JSON.parse(row.data),
4598
+ issueId: row.issue_id
4599
+ }));
4600
+ return this.jsonResponse({ events });
4601
+ }
4602
+ async handleGetStats(request) {
4603
+ const { interval, start, end } = await request.json();
4604
+ const endDate = end ? new Date(end) : /* @__PURE__ */ new Date();
4605
+ const startDate = start ? new Date(start) : new Date(
4606
+ endDate.getTime() - (interval === "1w" ? 7 : interval === "1d" ? 1 : 1) * 24 * 60 * 60 * 1e3
4607
+ );
4608
+ const rows = this.sql.exec(
4609
+ `SELECT bucket, SUM(count) as count
4610
+ FROM issue_stats
4611
+ WHERE bucket >= ? AND bucket <= ?
4612
+ GROUP BY bucket
4613
+ ORDER BY bucket ASC`,
4614
+ startDate.toISOString(),
4615
+ endDate.toISOString()
4616
+ ).toArray();
4617
+ const series = rows.map((row) => ({
4618
+ bucket: row.bucket,
4619
+ count: row.count
4620
+ }));
4621
+ const total = series.reduce((sum, s) => sum + s.count, 0);
4622
+ return this.jsonResponse({ total, series });
4623
+ }
4624
+ getHourBucket(timestamp) {
4625
+ const date = new Date(timestamp);
4626
+ date.setMinutes(0, 0, 0);
4627
+ return date.toISOString();
4628
+ }
4629
+ async hashUserIdentifier(user) {
4630
+ if (!user) return null;
4631
+ const identifier = user.id || user.email || user.ip_address || user.username;
4632
+ if (!identifier) return null;
4633
+ const encoder = new TextEncoder();
4634
+ const data = encoder.encode(identifier);
4635
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
4636
+ const hashArray2 = Array.from(new Uint8Array(hashBuffer));
4637
+ return hashArray2.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 32);
4638
+ }
4639
+ rowToIssue(row) {
4640
+ return {
4641
+ id: row.id,
4642
+ fingerprint: row.fingerprint,
4643
+ title: row.title,
4644
+ culprit: row.culprit,
4645
+ level: row.level,
4646
+ platform: row.platform,
4647
+ firstSeen: row.first_seen,
4648
+ lastSeen: row.last_seen,
4649
+ count: row.count,
4650
+ userCount: row.user_count,
4651
+ status: row.status,
4652
+ metadata: JSON.parse(row.metadata || "{}")
4653
+ };
4654
+ }
4655
+ jsonResponse(data, status = 200) {
4656
+ return new Response(JSON.stringify(data), {
4657
+ status,
4658
+ headers: { "Content-Type": "application/json" }
4659
+ });
4660
+ }
4661
+ };
4662
+
4663
+ // src/rpc.ts
4664
+ import { WorkerEntrypoint } from "cloudflare:workers";
4665
+ var SentinelRpc = class extends WorkerEntrypoint {
4666
+ static {
4667
+ __name(this, "SentinelRpc");
4668
+ }
4669
+ /**
4670
+ * Capture a Sentry envelope.
4671
+ *
4672
+ * @param dsn - The full DSN string (e.g., "https://publicKey@host/projectId")
4673
+ * @param envelope - The Sentry envelope object (not serialized)
4674
+ * @returns Object with status code and optional event ID
4675
+ */
4676
+ async captureEnvelope(dsn, envelope) {
4677
+ let publicKey;
4678
+ let projectId;
4679
+ try {
4680
+ const url = new URL(dsn);
4681
+ publicKey = url.username;
4682
+ projectId = url.pathname.split("/").filter(Boolean).pop() || "";
4683
+ if (!publicKey || !projectId) {
4684
+ return { status: 400 };
4685
+ }
4686
+ } catch {
4687
+ return { status: 400 };
4688
+ }
4689
+ const parsed = {
4690
+ header: envelope[0],
4691
+ items: (envelope[1] || []).map(([header, payload]) => ({
4692
+ type: header.type,
4693
+ payload
4694
+ }))
4695
+ };
4696
+ const authStateId = this.env.AUTH_STATE.idFromName("global");
4697
+ const authState = this.env.AUTH_STATE.get(authStateId);
4698
+ const projectResponse = await authState.fetch(
4699
+ new Request("http://internal/get-project-by-key", {
4700
+ method: "POST",
4701
+ headers: { "Content-Type": "application/json" },
4702
+ body: JSON.stringify({ publicKey })
4703
+ })
4704
+ );
4705
+ if (!projectResponse.ok) {
4706
+ return { status: 401 };
4707
+ }
4708
+ const projectData = await projectResponse.json();
4709
+ const project = projectData.project;
4710
+ if (projectId !== project.id) {
4711
+ return { status: 400 };
4712
+ }
4713
+ const events = extractEvents(parsed);
4714
+ if (events.length === 0) {
4715
+ return { status: 200 };
4716
+ }
4717
+ const projectStateId = this.env.PROJECT_STATE.idFromName(project.id);
4718
+ const projectState = this.env.PROJECT_STATE.get(projectStateId);
4719
+ let firstEventId;
4720
+ for (const event of events) {
4721
+ try {
4722
+ const response = await projectState.fetch(
4723
+ new Request("http://internal/ingest", {
4724
+ method: "POST",
4725
+ headers: { "Content-Type": "application/json" },
4726
+ body: JSON.stringify(event)
4727
+ })
4728
+ );
4729
+ if (response.ok && !firstEventId) {
4730
+ const result = await response.json();
4731
+ firstEventId = result.eventId;
4732
+ }
4733
+ } catch {
4734
+ }
4735
+ }
4736
+ return { status: 200, eventId: firstEventId };
4737
+ }
4738
+ /**
4739
+ * Handle fetch requests (fallback for non-RPC calls)
4740
+ */
4741
+ async fetch() {
4742
+ return new Response("SentinelRpc: Use captureEnvelope() RPC method", { status: 400 });
4743
+ }
4744
+ };
4745
+
4746
+ // src/index.ts
4747
+ var app = new Hono2();
4748
+ app.use(
4749
+ "/api/*",
4750
+ cors({
4751
+ origin: "*",
4752
+ allowHeaders: ["Content-Type", "Authorization"],
4753
+ allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
4754
+ credentials: true
4755
+ })
4756
+ );
4757
+ app.get("/api/health", (c) => c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
4758
+ app.route("/api/auth", authRoutes);
4759
+ app.route("/api", ingestionRoutes);
4760
+ app.use("/api/projects/*", authMiddleware);
4761
+ app.route("/api/projects", projectRoutes);
4762
+ app.route("/api/projects", issueRoutes);
4763
+ app.route("/api/projects", eventRoutes);
4764
+ app.get("*", (c) => {
4765
+ return c.env.ASSETS?.fetch(c.req.raw) ?? c.text("Dashboard not found", 404);
4766
+ });
4767
+ var index_default = app;
4768
+ export {
4769
+ AuthState,
4770
+ ProjectState,
4771
+ SentinelRpc,
4772
+ index_default as default
4773
+ };
4774
+ //# sourceMappingURL=index.js.map