@rotorsoft/act-http 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +12 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/@types/api/actor.d.ts +20 -0
  4. package/dist/@types/api/actor.d.ts.map +1 -0
  5. package/dist/@types/api/errors.d.ts +73 -0
  6. package/dist/@types/api/errors.d.ts.map +1 -0
  7. package/dist/@types/api/idempotency.d.ts +36 -0
  8. package/dist/@types/api/idempotency.d.ts.map +1 -0
  9. package/dist/@types/api/index.d.ts +39 -0
  10. package/dist/@types/api/index.d.ts.map +1 -0
  11. package/dist/@types/receiver/start.d.ts +1 -1
  12. package/dist/@types/sse/apply-patch.d.ts +3 -3
  13. package/dist/@types/sse/broadcast.d.ts +6 -6
  14. package/dist/@types/sse/broadcast.d.ts.map +1 -1
  15. package/dist/@types/sse/presence.d.ts +7 -7
  16. package/dist/@types/sse/presence.d.ts.map +1 -1
  17. package/dist/@types/webhook/classify.d.ts +6 -6
  18. package/dist/@types/webhook/classify.d.ts.map +1 -1
  19. package/dist/@types/webhook/index.d.ts +1 -1
  20. package/dist/@types/webhook/index.d.ts.map +1 -1
  21. package/dist/@types/webhook/sign.d.ts +1 -1
  22. package/dist/@types/webhook/sign.d.ts.map +1 -1
  23. package/dist/api/index.cjs +85 -0
  24. package/dist/api/index.cjs.map +1 -0
  25. package/dist/api/index.js +62 -0
  26. package/dist/api/index.js.map +1 -0
  27. package/dist/{chunk-NOIXOF2I.js → chunk-4CGAUB5H.js} +13 -13
  28. package/dist/chunk-4CGAUB5H.js.map +1 -0
  29. package/dist/{chunk-F7VWYZ37.js → chunk-K4HAOBRF.js} +4 -4
  30. package/dist/{chunk-F7VWYZ37.js.map → chunk-K4HAOBRF.js.map} +1 -1
  31. package/dist/receiver/express/index.cjs +14 -14
  32. package/dist/receiver/express/index.cjs.map +1 -1
  33. package/dist/receiver/express/index.js +3 -3
  34. package/dist/receiver/express/index.js.map +1 -1
  35. package/dist/receiver/fastify/index.cjs +12 -12
  36. package/dist/receiver/fastify/index.cjs.map +1 -1
  37. package/dist/receiver/fastify/index.js +1 -1
  38. package/dist/receiver/hono/index.cjs +14 -14
  39. package/dist/receiver/hono/index.cjs.map +1 -1
  40. package/dist/receiver/hono/index.js +2 -2
  41. package/dist/receiver/index.cjs +19 -2746
  42. package/dist/receiver/index.cjs.map +1 -1
  43. package/dist/receiver/index.js +5 -2077
  44. package/dist/receiver/index.js.map +1 -1
  45. package/dist/receiver/trpc/index.cjs +12 -12
  46. package/dist/receiver/trpc/index.cjs.map +1 -1
  47. package/dist/receiver/trpc/index.js +1 -1
  48. package/dist/sse/index.cjs +21 -21
  49. package/dist/sse/index.cjs.map +1 -1
  50. package/dist/sse/index.js +24 -24
  51. package/dist/sse/index.js.map +1 -1
  52. package/dist/webhook/index.cjs +14 -34
  53. package/dist/webhook/index.cjs.map +1 -1
  54. package/dist/webhook/index.js +14 -32
  55. package/dist/webhook/index.js.map +1 -1
  56. package/package.json +34 -12
  57. package/dist/chunk-NOIXOF2I.js.map +0 -1
  58. package/dist/dist-NWMJQI4E.js +0 -647
  59. package/dist/dist-NWMJQI4E.js.map +0 -1
@@ -5,9 +5,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
8
  var __export = (target, all) => {
12
9
  for (var name in all)
13
10
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -30,660 +27,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
27
  ));
31
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
29
 
33
- // ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.23/node_modules/@hono/node-server/dist/index.mjs
34
- var dist_exports = {};
35
- __export(dist_exports, {
36
- RequestError: () => RequestError,
37
- createAdaptorServer: () => createAdaptorServer,
38
- getRequestListener: () => getRequestListener,
39
- serve: () => serve
40
- });
41
- async function readWithoutBlocking(readPromise) {
42
- return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
43
- }
44
- function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
45
- const cancel = (error) => {
46
- reader.cancel(error).catch(() => {
47
- });
48
- };
49
- writable.on("close", cancel);
50
- writable.on("error", cancel);
51
- (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
52
- return reader.closed.finally(() => {
53
- writable.off("close", cancel);
54
- writable.off("error", cancel);
55
- });
56
- function handleStreamError(error) {
57
- if (error) {
58
- writable.destroy(error);
59
- }
60
- }
61
- function onDrain() {
62
- reader.read().then(flow, handleStreamError);
63
- }
64
- function flow({ done, value }) {
65
- try {
66
- if (done) {
67
- writable.end();
68
- } else if (!writable.write(value)) {
69
- writable.once("drain", onDrain);
70
- } else {
71
- return reader.read().then(flow, handleStreamError);
72
- }
73
- } catch (e) {
74
- handleStreamError(e);
75
- }
76
- }
77
- }
78
- function writeFromReadableStream(stream, writable) {
79
- if (stream.locked) {
80
- throw new TypeError("ReadableStream is locked.");
81
- } else if (writable.destroyed) {
82
- return;
83
- }
84
- return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
85
- }
86
- var import_http, import_http2, import_http22, import_stream, import_crypto, RequestError, toRequestError, GlobalRequest, Request2, newHeadersFromIncoming, wrapBodyStream, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, headersKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, outgoingEnded, incomingDraining, DRAIN_TIMEOUT_MS, MAX_DRAIN_BYTES, drainIncoming, handleRequestError, handleFetchError, handleResponseError, flushHeaders, responseViaCache, isPromise, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
87
- var init_dist = __esm({
88
- "../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.23/node_modules/@hono/node-server/dist/index.mjs"() {
89
- "use strict";
90
- import_http = require("http");
91
- import_http2 = require("http2");
92
- import_http22 = require("http2");
93
- import_stream = require("stream");
94
- import_crypto = __toESM(require("crypto"), 1);
95
- RequestError = class extends Error {
96
- constructor(message, options) {
97
- super(message, options);
98
- this.name = "RequestError";
99
- }
100
- };
101
- toRequestError = (e) => {
102
- if (e instanceof RequestError) {
103
- return e;
104
- }
105
- return new RequestError(e.message, { cause: e });
106
- };
107
- GlobalRequest = global.Request;
108
- Request2 = class extends GlobalRequest {
109
- constructor(input, options) {
110
- if (typeof input === "object" && getRequestCache in input) {
111
- input = input[getRequestCache]();
112
- }
113
- if (typeof options?.body?.getReader !== "undefined") {
114
- ;
115
- options.duplex ??= "half";
116
- }
117
- super(input, options);
118
- }
119
- };
120
- newHeadersFromIncoming = (incoming) => {
121
- const headerRecord = [];
122
- const rawHeaders = incoming.rawHeaders;
123
- for (let i = 0; i < rawHeaders.length; i += 2) {
124
- const { [i]: key, [i + 1]: value } = rawHeaders;
125
- if (key.charCodeAt(0) !== /*:*/
126
- 58) {
127
- headerRecord.push([key, value]);
128
- }
129
- }
130
- return new Headers(headerRecord);
131
- };
132
- wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream");
133
- newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
134
- const init = {
135
- method,
136
- headers,
137
- signal: abortController.signal
138
- };
139
- if (method === "TRACE") {
140
- init.method = "GET";
141
- const req = new Request2(url, init);
142
- Object.defineProperty(req, "method", {
143
- get() {
144
- return "TRACE";
145
- }
146
- });
147
- return req;
148
- }
149
- if (!(method === "GET" || method === "HEAD")) {
150
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
151
- init.body = new ReadableStream({
152
- start(controller) {
153
- controller.enqueue(incoming.rawBody);
154
- controller.close();
155
- }
156
- });
157
- } else if (incoming[wrapBodyStream]) {
158
- let reader;
159
- init.body = new ReadableStream({
160
- async pull(controller) {
161
- try {
162
- reader ||= import_stream.Readable.toWeb(incoming).getReader();
163
- const { done, value } = await reader.read();
164
- if (done) {
165
- controller.close();
166
- } else {
167
- controller.enqueue(value);
168
- }
169
- } catch (error) {
170
- controller.error(error);
171
- }
172
- }
173
- });
174
- } else {
175
- init.body = import_stream.Readable.toWeb(incoming);
176
- }
177
- }
178
- return new Request2(url, init);
179
- };
180
- getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
181
- requestCache = /* @__PURE__ */ Symbol("requestCache");
182
- incomingKey = /* @__PURE__ */ Symbol("incomingKey");
183
- urlKey = /* @__PURE__ */ Symbol("urlKey");
184
- headersKey = /* @__PURE__ */ Symbol("headersKey");
185
- abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
186
- getAbortController = /* @__PURE__ */ Symbol("getAbortController");
187
- requestPrototype = {
188
- get method() {
189
- return this[incomingKey].method || "GET";
190
- },
191
- get url() {
192
- return this[urlKey];
193
- },
194
- get headers() {
195
- return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
196
- },
197
- [getAbortController]() {
198
- this[getRequestCache]();
199
- return this[abortControllerKey];
200
- },
201
- [getRequestCache]() {
202
- this[abortControllerKey] ||= new AbortController();
203
- return this[requestCache] ||= newRequestFromIncoming(
204
- this.method,
205
- this[urlKey],
206
- this.headers,
207
- this[incomingKey],
208
- this[abortControllerKey]
209
- );
210
- }
211
- };
212
- [
213
- "body",
214
- "bodyUsed",
215
- "cache",
216
- "credentials",
217
- "destination",
218
- "integrity",
219
- "mode",
220
- "redirect",
221
- "referrer",
222
- "referrerPolicy",
223
- "signal",
224
- "keepalive"
225
- ].forEach((k) => {
226
- Object.defineProperty(requestPrototype, k, {
227
- get() {
228
- return this[getRequestCache]()[k];
229
- }
230
- });
231
- });
232
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
233
- Object.defineProperty(requestPrototype, k, {
234
- value: function() {
235
- return this[getRequestCache]()[k]();
236
- }
237
- });
238
- });
239
- Object.defineProperty(requestPrototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
240
- value: function(depth, options, inspectFn) {
241
- const props = {
242
- method: this.method,
243
- url: this.url,
244
- headers: this.headers,
245
- nativeRequest: this[requestCache]
246
- };
247
- return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
248
- }
249
- });
250
- Object.setPrototypeOf(requestPrototype, Request2.prototype);
251
- newRequest = (incoming, defaultHostname) => {
252
- const req = Object.create(requestPrototype);
253
- req[incomingKey] = incoming;
254
- const incomingUrl = incoming.url || "";
255
- if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
256
- (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
257
- if (incoming instanceof import_http22.Http2ServerRequest) {
258
- throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
259
- }
260
- try {
261
- const url2 = new URL(incomingUrl);
262
- req[urlKey] = url2.href;
263
- } catch (e) {
264
- throw new RequestError("Invalid absolute URL", { cause: e });
265
- }
266
- return req;
267
- }
268
- const host = (incoming instanceof import_http22.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
269
- if (!host) {
270
- throw new RequestError("Missing host header");
271
- }
272
- let scheme;
273
- if (incoming instanceof import_http22.Http2ServerRequest) {
274
- scheme = incoming.scheme;
275
- if (!(scheme === "http" || scheme === "https")) {
276
- throw new RequestError("Unsupported scheme");
277
- }
278
- } else {
279
- scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
280
- }
281
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
282
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
283
- throw new RequestError("Invalid host header");
284
- }
285
- req[urlKey] = url.href;
286
- return req;
287
- };
288
- responseCache = /* @__PURE__ */ Symbol("responseCache");
289
- getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
290
- cacheKey = /* @__PURE__ */ Symbol("cache");
291
- GlobalResponse = global.Response;
292
- Response2 = class _Response {
293
- #body;
294
- #init;
295
- [getResponseCache]() {
296
- delete this[cacheKey];
297
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
298
- }
299
- constructor(body, init) {
300
- let headers;
301
- this.#body = body;
302
- if (init instanceof _Response) {
303
- const cachedGlobalResponse = init[responseCache];
304
- if (cachedGlobalResponse) {
305
- this.#init = cachedGlobalResponse;
306
- this[getResponseCache]();
307
- return;
308
- } else {
309
- this.#init = init.#init;
310
- headers = new Headers(init.#init.headers);
311
- }
312
- } else {
313
- this.#init = init;
314
- }
315
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
316
- ;
317
- this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
318
- }
319
- }
320
- get headers() {
321
- const cache = this[cacheKey];
322
- if (cache) {
323
- if (!(cache[2] instanceof Headers)) {
324
- cache[2] = new Headers(
325
- cache[2] || { "content-type": "text/plain; charset=UTF-8" }
326
- );
327
- }
328
- return cache[2];
329
- }
330
- return this[getResponseCache]().headers;
331
- }
332
- get status() {
333
- return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
334
- }
335
- get ok() {
336
- const status = this.status;
337
- return status >= 200 && status < 300;
338
- }
339
- };
340
- ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
341
- Object.defineProperty(Response2.prototype, k, {
342
- get() {
343
- return this[getResponseCache]()[k];
344
- }
345
- });
346
- });
347
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
348
- Object.defineProperty(Response2.prototype, k, {
349
- value: function() {
350
- return this[getResponseCache]()[k]();
351
- }
352
- });
353
- });
354
- Object.defineProperty(Response2.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
355
- value: function(depth, options, inspectFn) {
356
- const props = {
357
- status: this.status,
358
- headers: this.headers,
359
- ok: this.ok,
360
- nativeResponse: this[responseCache]
361
- };
362
- return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
363
- }
364
- });
365
- Object.setPrototypeOf(Response2, GlobalResponse);
366
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
367
- buildOutgoingHttpHeaders = (headers) => {
368
- const res = {};
369
- if (!(headers instanceof Headers)) {
370
- headers = new Headers(headers ?? void 0);
371
- }
372
- const cookies = [];
373
- for (const [k, v] of headers) {
374
- if (k === "set-cookie") {
375
- cookies.push(v);
376
- } else {
377
- res[k] = v;
378
- }
379
- }
380
- if (cookies.length > 0) {
381
- res["set-cookie"] = cookies;
382
- }
383
- res["content-type"] ??= "text/plain; charset=UTF-8";
384
- return res;
385
- };
386
- X_ALREADY_SENT = "x-hono-already-sent";
387
- if (typeof global.crypto === "undefined") {
388
- global.crypto = import_crypto.default;
389
- }
390
- outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
391
- incomingDraining = /* @__PURE__ */ Symbol("incomingDraining");
392
- DRAIN_TIMEOUT_MS = 500;
393
- MAX_DRAIN_BYTES = 64 * 1024 * 1024;
394
- drainIncoming = (incoming) => {
395
- const incomingWithDrainState = incoming;
396
- if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
397
- return;
398
- }
399
- incomingWithDrainState[incomingDraining] = true;
400
- if (incoming instanceof import_http2.Http2ServerRequest) {
401
- try {
402
- ;
403
- incoming.stream?.close?.(import_http2.constants.NGHTTP2_NO_ERROR);
404
- } catch {
405
- }
406
- return;
407
- }
408
- let bytesRead = 0;
409
- const cleanup = () => {
410
- clearTimeout(timer);
411
- incoming.off("data", onData);
412
- incoming.off("end", cleanup);
413
- incoming.off("error", cleanup);
414
- };
415
- const forceClose = () => {
416
- cleanup();
417
- const socket = incoming.socket;
418
- if (socket && !socket.destroyed) {
419
- socket.destroySoon();
420
- }
421
- };
422
- const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
423
- timer.unref?.();
424
- const onData = (chunk) => {
425
- bytesRead += chunk.length;
426
- if (bytesRead > MAX_DRAIN_BYTES) {
427
- forceClose();
428
- }
429
- };
430
- incoming.on("data", onData);
431
- incoming.on("end", cleanup);
432
- incoming.on("error", cleanup);
433
- incoming.resume();
434
- };
435
- handleRequestError = () => new Response(null, {
436
- status: 400
437
- });
438
- handleFetchError = (e) => new Response(null, {
439
- status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
440
- });
441
- handleResponseError = (e, outgoing) => {
442
- const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
443
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
444
- console.info("The user aborted a request.");
445
- } else {
446
- console.error(e);
447
- if (!outgoing.headersSent) {
448
- outgoing.writeHead(500, { "Content-Type": "text/plain" });
449
- }
450
- outgoing.end(`Error: ${err.message}`);
451
- outgoing.destroy(err);
452
- }
453
- };
454
- flushHeaders = (outgoing) => {
455
- if ("flushHeaders" in outgoing && outgoing.writable) {
456
- outgoing.flushHeaders();
457
- }
458
- };
459
- responseViaCache = async (res, outgoing) => {
460
- let [status, body, header] = res[cacheKey];
461
- let hasContentLength = false;
462
- if (!header) {
463
- header = { "content-type": "text/plain; charset=UTF-8" };
464
- } else if (header instanceof Headers) {
465
- hasContentLength = header.has("content-length");
466
- header = buildOutgoingHttpHeaders(header);
467
- } else if (Array.isArray(header)) {
468
- const headerObj = new Headers(header);
469
- hasContentLength = headerObj.has("content-length");
470
- header = buildOutgoingHttpHeaders(headerObj);
471
- } else {
472
- for (const key in header) {
473
- if (key.length === 14 && key.toLowerCase() === "content-length") {
474
- hasContentLength = true;
475
- break;
476
- }
477
- }
478
- }
479
- if (!hasContentLength) {
480
- if (typeof body === "string") {
481
- header["Content-Length"] = Buffer.byteLength(body);
482
- } else if (body instanceof Uint8Array) {
483
- header["Content-Length"] = body.byteLength;
484
- } else if (body instanceof Blob) {
485
- header["Content-Length"] = body.size;
486
- }
487
- }
488
- outgoing.writeHead(status, header);
489
- if (typeof body === "string" || body instanceof Uint8Array) {
490
- outgoing.end(body);
491
- } else if (body instanceof Blob) {
492
- outgoing.end(new Uint8Array(await body.arrayBuffer()));
493
- } else {
494
- flushHeaders(outgoing);
495
- await writeFromReadableStream(body, outgoing)?.catch(
496
- (e) => handleResponseError(e, outgoing)
497
- );
498
- }
499
- ;
500
- outgoing[outgoingEnded]?.();
501
- };
502
- isPromise = (res) => typeof res.then === "function";
503
- responseViaResponseObject = async (res, outgoing, options = {}) => {
504
- if (isPromise(res)) {
505
- if (options.errorHandler) {
506
- try {
507
- res = await res;
508
- } catch (err) {
509
- const errRes = await options.errorHandler(err);
510
- if (!errRes) {
511
- return;
512
- }
513
- res = errRes;
514
- }
515
- } else {
516
- res = await res.catch(handleFetchError);
517
- }
518
- }
519
- if (cacheKey in res) {
520
- return responseViaCache(res, outgoing);
521
- }
522
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
523
- if (res.body) {
524
- const reader = res.body.getReader();
525
- const values = [];
526
- let done = false;
527
- let currentReadPromise = void 0;
528
- if (resHeaderRecord["transfer-encoding"] !== "chunked") {
529
- let maxReadCount = 2;
530
- for (let i = 0; i < maxReadCount; i++) {
531
- currentReadPromise ||= reader.read();
532
- const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
533
- console.error(e);
534
- done = true;
535
- });
536
- if (!chunk) {
537
- if (i === 1) {
538
- await new Promise((resolve) => setTimeout(resolve));
539
- maxReadCount = 3;
540
- continue;
541
- }
542
- break;
543
- }
544
- currentReadPromise = void 0;
545
- if (chunk.value) {
546
- values.push(chunk.value);
547
- }
548
- if (chunk.done) {
549
- done = true;
550
- break;
551
- }
552
- }
553
- if (done && !("content-length" in resHeaderRecord)) {
554
- resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
555
- }
556
- }
557
- outgoing.writeHead(res.status, resHeaderRecord);
558
- values.forEach((value) => {
559
- ;
560
- outgoing.write(value);
561
- });
562
- if (done) {
563
- outgoing.end();
564
- } else {
565
- if (values.length === 0) {
566
- flushHeaders(outgoing);
567
- }
568
- await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
569
- }
570
- } else if (resHeaderRecord[X_ALREADY_SENT]) {
571
- } else {
572
- outgoing.writeHead(res.status, resHeaderRecord);
573
- outgoing.end();
574
- }
575
- ;
576
- outgoing[outgoingEnded]?.();
577
- };
578
- getRequestListener = (fetchCallback, options = {}) => {
579
- const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
580
- if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
581
- Object.defineProperty(global, "Request", {
582
- value: Request2
583
- });
584
- Object.defineProperty(global, "Response", {
585
- value: Response2
586
- });
587
- }
588
- return async (incoming, outgoing) => {
589
- let res, req;
590
- try {
591
- req = newRequest(incoming, options.hostname);
592
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
593
- if (!incomingEnded) {
594
- ;
595
- incoming[wrapBodyStream] = true;
596
- incoming.on("end", () => {
597
- incomingEnded = true;
598
- });
599
- if (incoming instanceof import_http2.Http2ServerRequest) {
600
- ;
601
- outgoing[outgoingEnded] = () => {
602
- if (!incomingEnded) {
603
- setTimeout(() => {
604
- if (!incomingEnded) {
605
- setTimeout(() => {
606
- drainIncoming(incoming);
607
- });
608
- }
609
- });
610
- }
611
- };
612
- }
613
- outgoing.on("finish", () => {
614
- if (!incomingEnded) {
615
- drainIncoming(incoming);
616
- }
617
- });
618
- }
619
- outgoing.on("close", () => {
620
- const abortController = req[abortControllerKey];
621
- if (abortController) {
622
- if (incoming.errored) {
623
- req[abortControllerKey].abort(incoming.errored.toString());
624
- } else if (!outgoing.writableFinished) {
625
- req[abortControllerKey].abort("Client connection prematurely closed.");
626
- }
627
- }
628
- if (!incomingEnded) {
629
- setTimeout(() => {
630
- if (!incomingEnded) {
631
- setTimeout(() => {
632
- drainIncoming(incoming);
633
- });
634
- }
635
- });
636
- }
637
- });
638
- res = fetchCallback(req, { incoming, outgoing });
639
- if (cacheKey in res) {
640
- return responseViaCache(res, outgoing);
641
- }
642
- } catch (e) {
643
- if (!res) {
644
- if (options.errorHandler) {
645
- res = await options.errorHandler(req ? e : toRequestError(e));
646
- if (!res) {
647
- return;
648
- }
649
- } else if (!req) {
650
- res = handleRequestError();
651
- } else {
652
- res = handleFetchError(e);
653
- }
654
- } else {
655
- return handleResponseError(e, outgoing);
656
- }
657
- }
658
- try {
659
- return await responseViaResponseObject(res, outgoing, options);
660
- } catch (e) {
661
- return handleResponseError(e, outgoing);
662
- }
663
- };
664
- };
665
- createAdaptorServer = (options) => {
666
- const fetchCallback = options.fetch;
667
- const requestListener = getRequestListener(fetchCallback, {
668
- hostname: options.hostname,
669
- overrideGlobalObjects: options.overrideGlobalObjects,
670
- autoCleanupIncoming: options.autoCleanupIncoming
671
- });
672
- const createServer = options.createServer || import_http.createServer;
673
- const server = createServer(options.serverOptions || {}, requestListener);
674
- return server;
675
- };
676
- serve = (options, listeningListener) => {
677
- const server = createAdaptorServer(options);
678
- server.listen(options?.port ?? 3e3, options.hostname, () => {
679
- const serverInfo = server.address();
680
- listeningListener && listeningListener(serverInfo);
681
- });
682
- return server;
683
- };
684
- }
685
- });
686
-
687
30
  // src/receiver/index.ts
688
31
  var receiver_exports = {};
689
32
  __export(receiver_exports, {
@@ -710,12 +53,12 @@ var import_node_crypto = require("crypto");
710
53
  function verifyWebhook(headers, body, secret, options) {
711
54
  const maxAgeSeconds = options?.maxAgeSeconds ?? 300;
712
55
  const now = options?.now ?? Math.floor(Date.now() / 1e3);
713
- const signature = pickHeader(headers, "x-webhook-signature");
56
+ const signature = pick_header(headers, "x-webhook-signature");
714
57
  if (!signature) return { ok: false, reason: "missing-signature" };
715
- const timestampStr = pickHeader(headers, "x-webhook-timestamp");
716
- if (!timestampStr) return { ok: false, reason: "missing-timestamp" };
717
- const timestamp = Number.parseInt(timestampStr, 10);
718
- if (Number.isNaN(timestamp) || String(timestamp) !== timestampStr) {
58
+ const timestamp_str = pick_header(headers, "x-webhook-timestamp");
59
+ if (!timestamp_str) return { ok: false, reason: "missing-timestamp" };
60
+ const timestamp = Number.parseInt(timestamp_str, 10);
61
+ if (Number.isNaN(timestamp) || String(timestamp) !== timestamp_str) {
719
62
  return { ok: false, reason: "missing-timestamp" };
720
63
  }
721
64
  const delta = now - timestamp;
@@ -724,21 +67,21 @@ function verifyWebhook(headers, body, secret, options) {
724
67
  if (!signature.startsWith("sha256=")) {
725
68
  return { ok: false, reason: "bad-signature" };
726
69
  }
727
- const providedHex = signature.slice("sha256=".length);
728
- if (!/^[0-9a-fA-F]{64}$/.test(providedHex)) {
70
+ const provided_hex = signature.slice("sha256=".length);
71
+ if (!/^[0-9a-fA-F]{64}$/.test(provided_hex)) {
729
72
  return { ok: false, reason: "bad-signature" };
730
73
  }
731
- const expectedHex = (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestampStr}.${body}`).digest("hex");
732
- const a = Buffer.from(providedHex, "hex");
733
- const b = Buffer.from(expectedHex, "hex");
74
+ const expected_hex = (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestamp_str}.${body}`).digest("hex");
75
+ const a = Buffer.from(provided_hex, "hex");
76
+ const b = Buffer.from(expected_hex, "hex");
734
77
  if (!(0, import_node_crypto.timingSafeEqual)(a, b)) {
735
78
  return { ok: false, reason: "bad-signature" };
736
79
  }
737
80
  return { ok: true };
738
81
  }
739
- function pickHeader(headers, lowerName) {
82
+ function pick_header(headers, lower_name) {
740
83
  for (const [name, value] of Object.entries(headers)) {
741
- if (name.toLowerCase() !== lowerName) continue;
84
+ if (name.toLowerCase() !== lower_name) continue;
742
85
  if (Array.isArray(value) || value === void 0 || value === "") {
743
86
  return void 0;
744
87
  }
@@ -766,2083 +109,13 @@ async function checkWebhook(headers, body, options) {
766
109
  return { ok: true, key, deduped: !claimed };
767
110
  }
768
111
 
769
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/compose.js
770
- var compose = (middleware, onError, onNotFound) => {
771
- return (context, next) => {
772
- let index = -1;
773
- return dispatch(0);
774
- async function dispatch(i) {
775
- if (i <= index) {
776
- throw new Error("next() called multiple times");
777
- }
778
- index = i;
779
- let res;
780
- let isError = false;
781
- let handler;
782
- if (middleware[i]) {
783
- handler = middleware[i][0][0];
784
- context.req.routeIndex = i;
785
- } else {
786
- handler = i === middleware.length && next || void 0;
787
- }
788
- if (handler) {
789
- try {
790
- res = await handler(context, () => dispatch(i + 1));
791
- } catch (err) {
792
- if (err instanceof Error && onError) {
793
- context.error = err;
794
- res = await onError(err, context);
795
- isError = true;
796
- } else {
797
- throw err;
798
- }
799
- }
800
- } else {
801
- if (context.finalized === false && onNotFound) {
802
- res = await onNotFound(context);
803
- }
804
- }
805
- if (res && (context.finalized === false || isError)) {
806
- context.res = res;
807
- }
808
- return context;
809
- }
810
- };
811
- };
812
-
813
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request/constants.js
814
- var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
815
-
816
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/body.js
817
- var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
818
- const { all = false, dot = false } = options;
819
- const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
820
- const contentType = headers.get("Content-Type");
821
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
822
- return parseFormData(request, { all, dot });
823
- }
824
- return {};
825
- };
826
- async function parseFormData(request, options) {
827
- const formData = await request.formData();
828
- if (formData) {
829
- return convertFormDataToBodyData(formData, options);
830
- }
831
- return {};
832
- }
833
- function convertFormDataToBodyData(formData, options) {
834
- const form = /* @__PURE__ */ Object.create(null);
835
- formData.forEach((value, key) => {
836
- const shouldParseAllValues = options.all || key.endsWith("[]");
837
- if (!shouldParseAllValues) {
838
- form[key] = value;
839
- } else {
840
- handleParsingAllValues(form, key, value);
841
- }
842
- });
843
- if (options.dot) {
844
- Object.entries(form).forEach(([key, value]) => {
845
- const shouldParseDotValues = key.includes(".");
846
- if (shouldParseDotValues) {
847
- handleParsingNestedValues(form, key, value);
848
- delete form[key];
849
- }
850
- });
851
- }
852
- return form;
853
- }
854
- var handleParsingAllValues = (form, key, value) => {
855
- if (form[key] !== void 0) {
856
- if (Array.isArray(form[key])) {
857
- ;
858
- form[key].push(value);
859
- } else {
860
- form[key] = [form[key], value];
861
- }
862
- } else {
863
- if (!key.endsWith("[]")) {
864
- form[key] = value;
865
- } else {
866
- form[key] = [value];
867
- }
868
- }
869
- };
870
- var handleParsingNestedValues = (form, key, value) => {
871
- if (/(?:^|\.)__proto__\./.test(key)) {
872
- return;
873
- }
874
- let nestedForm = form;
875
- const keys = key.split(".");
876
- keys.forEach((key2, index) => {
877
- if (index === keys.length - 1) {
878
- nestedForm[key2] = value;
879
- } else {
880
- if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
881
- nestedForm[key2] = /* @__PURE__ */ Object.create(null);
882
- }
883
- nestedForm = nestedForm[key2];
884
- }
885
- });
886
- };
887
-
888
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/url.js
889
- var splitPath = (path) => {
890
- const paths = path.split("/");
891
- if (paths[0] === "") {
892
- paths.shift();
893
- }
894
- return paths;
895
- };
896
- var splitRoutingPath = (routePath) => {
897
- const { groups, path } = extractGroupsFromPath(routePath);
898
- const paths = splitPath(path);
899
- return replaceGroupMarks(paths, groups);
900
- };
901
- var extractGroupsFromPath = (path) => {
902
- const groups = [];
903
- path = path.replace(/\{[^}]+\}/g, (match2, index) => {
904
- const mark = `@${index}`;
905
- groups.push([mark, match2]);
906
- return mark;
907
- });
908
- return { groups, path };
909
- };
910
- var replaceGroupMarks = (paths, groups) => {
911
- for (let i = groups.length - 1; i >= 0; i--) {
912
- const [mark] = groups[i];
913
- for (let j = paths.length - 1; j >= 0; j--) {
914
- if (paths[j].includes(mark)) {
915
- paths[j] = paths[j].replace(mark, groups[i][1]);
916
- break;
917
- }
918
- }
919
- }
920
- return paths;
921
- };
922
- var patternCache = {};
923
- var getPattern = (label, next) => {
924
- if (label === "*") {
925
- return "*";
926
- }
927
- const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
928
- if (match2) {
929
- const cacheKey2 = `${label}#${next}`;
930
- if (!patternCache[cacheKey2]) {
931
- if (match2[2]) {
932
- patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
933
- } else {
934
- patternCache[cacheKey2] = [label, match2[1], true];
935
- }
936
- }
937
- return patternCache[cacheKey2];
938
- }
939
- return null;
940
- };
941
- var tryDecode = (str, decoder) => {
942
- try {
943
- return decoder(str);
944
- } catch {
945
- return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
946
- try {
947
- return decoder(match2);
948
- } catch {
949
- return match2;
950
- }
951
- });
952
- }
953
- };
954
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
955
- var getPath = (request) => {
956
- const url = request.url;
957
- const start = url.indexOf("/", url.indexOf(":") + 4);
958
- let i = start;
959
- for (; i < url.length; i++) {
960
- const charCode = url.charCodeAt(i);
961
- if (charCode === 37) {
962
- const queryIndex = url.indexOf("?", i);
963
- const hashIndex = url.indexOf("#", i);
964
- const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
965
- const path = url.slice(start, end);
966
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
967
- } else if (charCode === 63 || charCode === 35) {
968
- break;
969
- }
970
- }
971
- return url.slice(start, i);
972
- };
973
- var getPathNoStrict = (request) => {
974
- const result = getPath(request);
975
- return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
976
- };
977
- var mergePath = (base, sub, ...rest) => {
978
- if (rest.length) {
979
- sub = mergePath(sub, ...rest);
980
- }
981
- return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
982
- };
983
- var checkOptionalParameter = (path) => {
984
- if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
985
- return null;
986
- }
987
- const segments = path.split("/");
988
- const results = [];
989
- let basePath = "";
990
- segments.forEach((segment) => {
991
- if (segment !== "" && !/\:/.test(segment)) {
992
- basePath += "/" + segment;
993
- } else if (/\:/.test(segment)) {
994
- if (/\?/.test(segment)) {
995
- if (results.length === 0 && basePath === "") {
996
- results.push("/");
997
- } else {
998
- results.push(basePath);
999
- }
1000
- const optionalSegment = segment.replace("?", "");
1001
- basePath += "/" + optionalSegment;
1002
- results.push(basePath);
1003
- } else {
1004
- basePath += "/" + segment;
1005
- }
1006
- }
1007
- });
1008
- return results.filter((v, i, a) => a.indexOf(v) === i);
1009
- };
1010
- var _decodeURI = (value) => {
1011
- if (!/[%+]/.test(value)) {
1012
- return value;
1013
- }
1014
- if (value.indexOf("+") !== -1) {
1015
- value = value.replace(/\+/g, " ");
1016
- }
1017
- return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
1018
- };
1019
- var _getQueryParam = (url, key, multiple) => {
1020
- let encoded;
1021
- if (!multiple && key && !/[%+]/.test(key)) {
1022
- let keyIndex2 = url.indexOf("?", 8);
1023
- if (keyIndex2 === -1) {
1024
- return void 0;
1025
- }
1026
- if (!url.startsWith(key, keyIndex2 + 1)) {
1027
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1028
- }
1029
- while (keyIndex2 !== -1) {
1030
- const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
1031
- if (trailingKeyCode === 61) {
1032
- const valueIndex = keyIndex2 + key.length + 2;
1033
- const endIndex = url.indexOf("&", valueIndex);
1034
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
1035
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
1036
- return "";
1037
- }
1038
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1039
- }
1040
- encoded = /[%+]/.test(url);
1041
- if (!encoded) {
1042
- return void 0;
1043
- }
1044
- }
1045
- const results = {};
1046
- encoded ??= /[%+]/.test(url);
1047
- let keyIndex = url.indexOf("?", 8);
1048
- while (keyIndex !== -1) {
1049
- const nextKeyIndex = url.indexOf("&", keyIndex + 1);
1050
- let valueIndex = url.indexOf("=", keyIndex);
1051
- if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
1052
- valueIndex = -1;
1053
- }
1054
- let name = url.slice(
1055
- keyIndex + 1,
1056
- valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
1057
- );
1058
- if (encoded) {
1059
- name = _decodeURI(name);
1060
- }
1061
- keyIndex = nextKeyIndex;
1062
- if (name === "") {
1063
- continue;
1064
- }
1065
- let value;
1066
- if (valueIndex === -1) {
1067
- value = "";
1068
- } else {
1069
- value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
1070
- if (encoded) {
1071
- value = _decodeURI(value);
1072
- }
1073
- }
1074
- if (multiple) {
1075
- if (!(results[name] && Array.isArray(results[name]))) {
1076
- results[name] = [];
1077
- }
1078
- ;
1079
- results[name].push(value);
1080
- } else {
1081
- results[name] ??= value;
1082
- }
1083
- }
1084
- return key ? results[key] : results;
1085
- };
1086
- var getQueryParam = _getQueryParam;
1087
- var getQueryParams = (url, key) => {
1088
- return _getQueryParam(url, key, true);
1089
- };
1090
- var decodeURIComponent_ = decodeURIComponent;
1091
-
1092
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request.js
1093
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
1094
- var HonoRequest = class {
1095
- /**
1096
- * `.raw` can get the raw Request object.
1097
- *
1098
- * @see {@link https://hono.dev/docs/api/request#raw}
1099
- *
1100
- * @example
1101
- * ```ts
1102
- * // For Cloudflare Workers
1103
- * app.post('/', async (c) => {
1104
- * const metadata = c.req.raw.cf?.hostMetadata?
1105
- * ...
1106
- * })
1107
- * ```
1108
- */
1109
- raw;
1110
- #validatedData;
1111
- // Short name of validatedData
1112
- #matchResult;
1113
- routeIndex = 0;
1114
- /**
1115
- * `.path` can get the pathname of the request.
1116
- *
1117
- * @see {@link https://hono.dev/docs/api/request#path}
1118
- *
1119
- * @example
1120
- * ```ts
1121
- * app.get('/about/me', (c) => {
1122
- * const pathname = c.req.path // `/about/me`
1123
- * })
1124
- * ```
1125
- */
1126
- path;
1127
- bodyCache = {};
1128
- constructor(request, path = "/", matchResult = [[]]) {
1129
- this.raw = request;
1130
- this.path = path;
1131
- this.#matchResult = matchResult;
1132
- this.#validatedData = {};
1133
- }
1134
- param(key) {
1135
- return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
1136
- }
1137
- #getDecodedParam(key) {
1138
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
1139
- const param = this.#getParamValue(paramKey);
1140
- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
1141
- }
1142
- #getAllDecodedParams() {
1143
- const decoded = {};
1144
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
1145
- for (const key of keys) {
1146
- const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
1147
- if (value !== void 0) {
1148
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
1149
- }
1150
- }
1151
- return decoded;
1152
- }
1153
- #getParamValue(paramKey) {
1154
- return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
1155
- }
1156
- query(key) {
1157
- return getQueryParam(this.url, key);
1158
- }
1159
- queries(key) {
1160
- return getQueryParams(this.url, key);
1161
- }
1162
- header(name) {
1163
- if (name) {
1164
- return this.raw.headers.get(name) ?? void 0;
1165
- }
1166
- const headerData = {};
1167
- this.raw.headers.forEach((value, key) => {
1168
- headerData[key] = value;
1169
- });
1170
- return headerData;
1171
- }
1172
- async parseBody(options) {
1173
- return parseBody(this, options);
1174
- }
1175
- #cachedBody = (key) => {
1176
- const { bodyCache, raw: raw2 } = this;
1177
- const cachedBody = bodyCache[key];
1178
- if (cachedBody) {
1179
- return cachedBody;
1180
- }
1181
- const anyCachedKey = Object.keys(bodyCache)[0];
1182
- if (anyCachedKey) {
1183
- return bodyCache[anyCachedKey].then((body) => {
1184
- if (anyCachedKey === "json") {
1185
- body = JSON.stringify(body);
1186
- }
1187
- return new Response(body)[key]();
1188
- });
1189
- }
1190
- return bodyCache[key] = raw2[key]();
1191
- };
1192
- /**
1193
- * `.json()` can parse Request body of type `application/json`
1194
- *
1195
- * @see {@link https://hono.dev/docs/api/request#json}
1196
- *
1197
- * @example
1198
- * ```ts
1199
- * app.post('/entry', async (c) => {
1200
- * const body = await c.req.json()
1201
- * })
1202
- * ```
1203
- */
1204
- json() {
1205
- return this.#cachedBody("text").then((text) => JSON.parse(text));
1206
- }
1207
- /**
1208
- * `.text()` can parse Request body of type `text/plain`
1209
- *
1210
- * @see {@link https://hono.dev/docs/api/request#text}
1211
- *
1212
- * @example
1213
- * ```ts
1214
- * app.post('/entry', async (c) => {
1215
- * const body = await c.req.text()
1216
- * })
1217
- * ```
1218
- */
1219
- text() {
1220
- return this.#cachedBody("text");
1221
- }
1222
- /**
1223
- * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
1224
- *
1225
- * @see {@link https://hono.dev/docs/api/request#arraybuffer}
1226
- *
1227
- * @example
1228
- * ```ts
1229
- * app.post('/entry', async (c) => {
1230
- * const body = await c.req.arrayBuffer()
1231
- * })
1232
- * ```
1233
- */
1234
- arrayBuffer() {
1235
- return this.#cachedBody("arrayBuffer");
1236
- }
1237
- /**
1238
- * `.bytes()` parses the request body as a `Uint8Array`.
1239
- *
1240
- * @see {@link https://hono.dev/docs/api/request#bytes}
1241
- *
1242
- * @example
1243
- * ```ts
1244
- * app.post('/entry', async (c) => {
1245
- * const body = await c.req.bytes()
1246
- * })
1247
- * ```
1248
- */
1249
- bytes() {
1250
- return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
1251
- }
1252
- /**
1253
- * Parses the request body as a `Blob`.
1254
- * @example
1255
- * ```ts
1256
- * app.post('/entry', async (c) => {
1257
- * const body = await c.req.blob();
1258
- * });
1259
- * ```
1260
- * @see https://hono.dev/docs/api/request#blob
1261
- */
1262
- blob() {
1263
- return this.#cachedBody("blob");
1264
- }
1265
- /**
1266
- * Parses the request body as `FormData`.
1267
- * @example
1268
- * ```ts
1269
- * app.post('/entry', async (c) => {
1270
- * const body = await c.req.formData();
1271
- * });
1272
- * ```
1273
- * @see https://hono.dev/docs/api/request#formdata
1274
- */
1275
- formData() {
1276
- return this.#cachedBody("formData");
1277
- }
1278
- /**
1279
- * Adds validated data to the request.
1280
- *
1281
- * @param target - The target of the validation.
1282
- * @param data - The validated data to add.
1283
- */
1284
- addValidatedData(target, data) {
1285
- this.#validatedData[target] = data;
1286
- }
1287
- valid(target) {
1288
- return this.#validatedData[target];
1289
- }
1290
- /**
1291
- * `.url()` can get the request url strings.
1292
- *
1293
- * @see {@link https://hono.dev/docs/api/request#url}
1294
- *
1295
- * @example
1296
- * ```ts
1297
- * app.get('/about/me', (c) => {
1298
- * const url = c.req.url // `http://localhost:8787/about/me`
1299
- * ...
1300
- * })
1301
- * ```
1302
- */
1303
- get url() {
1304
- return this.raw.url;
1305
- }
1306
- /**
1307
- * `.method()` can get the method name of the request.
1308
- *
1309
- * @see {@link https://hono.dev/docs/api/request#method}
1310
- *
1311
- * @example
1312
- * ```ts
1313
- * app.get('/about/me', (c) => {
1314
- * const method = c.req.method // `GET`
1315
- * })
1316
- * ```
1317
- */
1318
- get method() {
1319
- return this.raw.method;
1320
- }
1321
- get [GET_MATCH_RESULT]() {
1322
- return this.#matchResult;
1323
- }
1324
- /**
1325
- * `.matchedRoutes()` can return a matched route in the handler
1326
- *
1327
- * @deprecated
1328
- *
1329
- * Use matchedRoutes helper defined in "hono/route" instead.
1330
- *
1331
- * @see {@link https://hono.dev/docs/api/request#matchedroutes}
1332
- *
1333
- * @example
1334
- * ```ts
1335
- * app.use('*', async function logger(c, next) {
1336
- * await next()
1337
- * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
1338
- * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
1339
- * console.log(
1340
- * method,
1341
- * ' ',
1342
- * path,
1343
- * ' '.repeat(Math.max(10 - path.length, 0)),
1344
- * name,
1345
- * i === c.req.routeIndex ? '<- respond from here' : ''
1346
- * )
1347
- * })
1348
- * })
1349
- * ```
1350
- */
1351
- get matchedRoutes() {
1352
- return this.#matchResult[0].map(([[, route]]) => route);
1353
- }
1354
- /**
1355
- * `routePath()` can retrieve the path registered within the handler
1356
- *
1357
- * @deprecated
1358
- *
1359
- * Use routePath helper defined in "hono/route" instead.
1360
- *
1361
- * @see {@link https://hono.dev/docs/api/request#routepath}
1362
- *
1363
- * @example
1364
- * ```ts
1365
- * app.get('/posts/:id', (c) => {
1366
- * return c.json({ path: c.req.routePath })
1367
- * })
1368
- * ```
1369
- */
1370
- get routePath() {
1371
- return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
1372
- }
1373
- };
1374
-
1375
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/html.js
1376
- var HtmlEscapedCallbackPhase = {
1377
- Stringify: 1,
1378
- BeforeStream: 2,
1379
- Stream: 3
1380
- };
1381
- var raw = (value, callbacks) => {
1382
- const escapedString = new String(value);
1383
- escapedString.isEscaped = true;
1384
- escapedString.callbacks = callbacks;
1385
- return escapedString;
1386
- };
1387
- var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
1388
- if (typeof str === "object" && !(str instanceof String)) {
1389
- if (!(str instanceof Promise)) {
1390
- str = str.toString();
1391
- }
1392
- if (str instanceof Promise) {
1393
- str = await str;
1394
- }
1395
- }
1396
- const callbacks = str.callbacks;
1397
- if (!callbacks?.length) {
1398
- return Promise.resolve(str);
1399
- }
1400
- if (buffer) {
1401
- buffer[0] += str;
1402
- } else {
1403
- buffer = [str];
1404
- }
1405
- const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
1406
- (res) => Promise.all(
1407
- res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
1408
- ).then(() => buffer[0])
1409
- );
1410
- if (preserveCallbacks) {
1411
- return raw(await resStr, callbacks);
1412
- } else {
1413
- return resStr;
1414
- }
1415
- };
1416
-
1417
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/context.js
1418
- var TEXT_PLAIN = "text/plain; charset=UTF-8";
1419
- var setDefaultContentType = (contentType, headers) => {
1420
- return {
1421
- "Content-Type": contentType,
1422
- ...headers
1423
- };
1424
- };
1425
- var createResponseInstance = (body, init) => new Response(body, init);
1426
- var Context = class {
1427
- #rawRequest;
1428
- #req;
1429
- /**
1430
- * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
1431
- *
1432
- * @see {@link https://hono.dev/docs/api/context#env}
1433
- *
1434
- * @example
1435
- * ```ts
1436
- * // Environment object for Cloudflare Workers
1437
- * app.get('*', async c => {
1438
- * const counter = c.env.COUNTER
1439
- * })
1440
- * ```
1441
- */
1442
- env = {};
1443
- #var;
1444
- finalized = false;
1445
- /**
1446
- * `.error` can get the error object from the middleware if the Handler throws an error.
1447
- *
1448
- * @see {@link https://hono.dev/docs/api/context#error}
1449
- *
1450
- * @example
1451
- * ```ts
1452
- * app.use('*', async (c, next) => {
1453
- * await next()
1454
- * if (c.error) {
1455
- * // do something...
1456
- * }
1457
- * })
1458
- * ```
1459
- */
1460
- error;
1461
- #status;
1462
- #executionCtx;
1463
- #res;
1464
- #layout;
1465
- #renderer;
1466
- #notFoundHandler;
1467
- #preparedHeaders;
1468
- #matchResult;
1469
- #path;
1470
- /**
1471
- * Creates an instance of the Context class.
1472
- *
1473
- * @param req - The Request object.
1474
- * @param options - Optional configuration options for the context.
1475
- */
1476
- constructor(req, options) {
1477
- this.#rawRequest = req;
1478
- if (options) {
1479
- this.#executionCtx = options.executionCtx;
1480
- this.env = options.env;
1481
- this.#notFoundHandler = options.notFoundHandler;
1482
- this.#path = options.path;
1483
- this.#matchResult = options.matchResult;
1484
- }
1485
- }
1486
- /**
1487
- * `.req` is the instance of {@link HonoRequest}.
1488
- */
1489
- get req() {
1490
- this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
1491
- return this.#req;
1492
- }
1493
- /**
1494
- * @see {@link https://hono.dev/docs/api/context#event}
1495
- * The FetchEvent associated with the current request.
1496
- *
1497
- * @throws Will throw an error if the context does not have a FetchEvent.
1498
- */
1499
- get event() {
1500
- if (this.#executionCtx && "respondWith" in this.#executionCtx) {
1501
- return this.#executionCtx;
1502
- } else {
1503
- throw Error("This context has no FetchEvent");
1504
- }
1505
- }
1506
- /**
1507
- * @see {@link https://hono.dev/docs/api/context#executionctx}
1508
- * The ExecutionContext associated with the current request.
1509
- *
1510
- * @throws Will throw an error if the context does not have an ExecutionContext.
1511
- */
1512
- get executionCtx() {
1513
- if (this.#executionCtx) {
1514
- return this.#executionCtx;
1515
- } else {
1516
- throw Error("This context has no ExecutionContext");
1517
- }
1518
- }
1519
- /**
1520
- * @see {@link https://hono.dev/docs/api/context#res}
1521
- * The Response object for the current request.
1522
- */
1523
- get res() {
1524
- return this.#res ||= createResponseInstance(null, {
1525
- headers: this.#preparedHeaders ??= new Headers()
1526
- });
1527
- }
1528
- /**
1529
- * Sets the Response object for the current request.
1530
- *
1531
- * @param _res - The Response object to set.
1532
- */
1533
- set res(_res) {
1534
- if (this.#res && _res) {
1535
- _res = createResponseInstance(_res.body, _res);
1536
- for (const [k, v] of this.#res.headers.entries()) {
1537
- if (k === "content-type") {
1538
- continue;
1539
- }
1540
- if (k === "set-cookie") {
1541
- const cookies = this.#res.headers.getSetCookie();
1542
- _res.headers.delete("set-cookie");
1543
- for (const cookie of cookies) {
1544
- _res.headers.append("set-cookie", cookie);
1545
- }
1546
- } else {
1547
- _res.headers.set(k, v);
1548
- }
1549
- }
1550
- }
1551
- this.#res = _res;
1552
- this.finalized = true;
1553
- }
1554
- /**
1555
- * `.render()` can create a response within a layout.
1556
- *
1557
- * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1558
- *
1559
- * @example
1560
- * ```ts
1561
- * app.get('/', (c) => {
1562
- * return c.render('Hello!')
1563
- * })
1564
- * ```
1565
- */
1566
- render = (...args) => {
1567
- this.#renderer ??= (content) => this.html(content);
1568
- return this.#renderer(...args);
1569
- };
1570
- /**
1571
- * Sets the layout for the response.
1572
- *
1573
- * @param layout - The layout to set.
1574
- * @returns The layout function.
1575
- */
1576
- setLayout = (layout) => this.#layout = layout;
1577
- /**
1578
- * Gets the current layout for the response.
1579
- *
1580
- * @returns The current layout function.
1581
- */
1582
- getLayout = () => this.#layout;
1583
- /**
1584
- * `.setRenderer()` can set the layout in the custom middleware.
1585
- *
1586
- * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1587
- *
1588
- * @example
1589
- * ```tsx
1590
- * app.use('*', async (c, next) => {
1591
- * c.setRenderer((content) => {
1592
- * return c.html(
1593
- * <html>
1594
- * <body>
1595
- * <p>{content}</p>
1596
- * </body>
1597
- * </html>
1598
- * )
1599
- * })
1600
- * await next()
1601
- * })
1602
- * ```
1603
- */
1604
- setRenderer = (renderer) => {
1605
- this.#renderer = renderer;
1606
- };
1607
- /**
1608
- * `.header()` can set headers.
1609
- *
1610
- * @see {@link https://hono.dev/docs/api/context#header}
1611
- *
1612
- * @example
1613
- * ```ts
1614
- * app.get('/welcome', (c) => {
1615
- * // Set headers
1616
- * c.header('X-Message', 'Hello!')
1617
- * c.header('Content-Type', 'text/plain')
1618
- *
1619
- * return c.body('Thank you for coming')
1620
- * })
1621
- * ```
1622
- */
1623
- header = (name, value, options) => {
1624
- if (this.finalized) {
1625
- this.#res = createResponseInstance(this.#res.body, this.#res);
1626
- }
1627
- const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
1628
- if (value === void 0) {
1629
- headers.delete(name);
1630
- } else if (options?.append) {
1631
- headers.append(name, value);
1632
- } else {
1633
- headers.set(name, value);
1634
- }
1635
- };
1636
- status = (status) => {
1637
- this.#status = status;
1638
- };
1639
- /**
1640
- * `.set()` can set the value specified by the key.
1641
- *
1642
- * @see {@link https://hono.dev/docs/api/context#set-get}
1643
- *
1644
- * @example
1645
- * ```ts
1646
- * app.use('*', async (c, next) => {
1647
- * c.set('message', 'Hono is hot!!')
1648
- * await next()
1649
- * })
1650
- * ```
1651
- */
1652
- set = (key, value) => {
1653
- this.#var ??= /* @__PURE__ */ new Map();
1654
- this.#var.set(key, value);
1655
- };
1656
- /**
1657
- * `.get()` can use the value specified by the key.
1658
- *
1659
- * @see {@link https://hono.dev/docs/api/context#set-get}
1660
- *
1661
- * @example
1662
- * ```ts
1663
- * app.get('/', (c) => {
1664
- * const message = c.get('message')
1665
- * return c.text(`The message is "${message}"`)
1666
- * })
1667
- * ```
1668
- */
1669
- get = (key) => {
1670
- return this.#var ? this.#var.get(key) : void 0;
1671
- };
1672
- /**
1673
- * `.var` can access the value of a variable.
1674
- *
1675
- * @see {@link https://hono.dev/docs/api/context#var}
1676
- *
1677
- * @example
1678
- * ```ts
1679
- * const result = c.var.client.oneMethod()
1680
- * ```
1681
- */
1682
- // c.var.propName is a read-only
1683
- get var() {
1684
- if (!this.#var) {
1685
- return {};
1686
- }
1687
- return Object.fromEntries(this.#var);
1688
- }
1689
- #newResponse(data, arg, headers) {
1690
- const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
1691
- if (typeof arg === "object" && "headers" in arg) {
1692
- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
1693
- for (const [key, value] of argHeaders) {
1694
- if (key.toLowerCase() === "set-cookie") {
1695
- responseHeaders.append(key, value);
1696
- } else {
1697
- responseHeaders.set(key, value);
1698
- }
1699
- }
1700
- }
1701
- if (headers) {
1702
- for (const [k, v] of Object.entries(headers)) {
1703
- if (typeof v === "string") {
1704
- responseHeaders.set(k, v);
1705
- } else {
1706
- responseHeaders.delete(k);
1707
- for (const v2 of v) {
1708
- responseHeaders.append(k, v2);
1709
- }
1710
- }
1711
- }
1712
- }
1713
- const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
1714
- return createResponseInstance(data, { status, headers: responseHeaders });
1715
- }
1716
- newResponse = (...args) => this.#newResponse(...args);
1717
- /**
1718
- * `.body()` can return the HTTP response.
1719
- * You can set headers with `.header()` and set HTTP status code with `.status`.
1720
- * This can also be set in `.text()`, `.json()` and so on.
1721
- *
1722
- * @see {@link https://hono.dev/docs/api/context#body}
1723
- *
1724
- * @example
1725
- * ```ts
1726
- * app.get('/welcome', (c) => {
1727
- * // Set headers
1728
- * c.header('X-Message', 'Hello!')
1729
- * c.header('Content-Type', 'text/plain')
1730
- * // Set HTTP status code
1731
- * c.status(201)
1732
- *
1733
- * // Return the response body
1734
- * return c.body('Thank you for coming')
1735
- * })
1736
- * ```
1737
- */
1738
- body = (data, arg, headers) => this.#newResponse(data, arg, headers);
1739
- /**
1740
- * `.text()` can render text as `Content-Type:text/plain`.
1741
- *
1742
- * @see {@link https://hono.dev/docs/api/context#text}
1743
- *
1744
- * @example
1745
- * ```ts
1746
- * app.get('/say', (c) => {
1747
- * return c.text('Hello!')
1748
- * })
1749
- * ```
1750
- */
1751
- text = (text, arg, headers) => {
1752
- return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
1753
- text,
1754
- arg,
1755
- setDefaultContentType(TEXT_PLAIN, headers)
1756
- );
1757
- };
1758
- /**
1759
- * `.json()` can render JSON as `Content-Type:application/json`.
1760
- *
1761
- * @see {@link https://hono.dev/docs/api/context#json}
1762
- *
1763
- * @example
1764
- * ```ts
1765
- * app.get('/api', (c) => {
1766
- * return c.json({ message: 'Hello!' })
1767
- * })
1768
- * ```
1769
- */
1770
- json = (object, arg, headers) => {
1771
- return this.#newResponse(
1772
- JSON.stringify(object),
1773
- arg,
1774
- setDefaultContentType("application/json", headers)
1775
- );
1776
- };
1777
- html = (html, arg, headers) => {
1778
- const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
1779
- return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
1780
- };
1781
- /**
1782
- * `.redirect()` can Redirect, default status code is 302.
1783
- *
1784
- * @see {@link https://hono.dev/docs/api/context#redirect}
1785
- *
1786
- * @example
1787
- * ```ts
1788
- * app.get('/redirect', (c) => {
1789
- * return c.redirect('/')
1790
- * })
1791
- * app.get('/redirect-permanently', (c) => {
1792
- * return c.redirect('/', 301)
1793
- * })
1794
- * ```
1795
- */
1796
- redirect = (location, status) => {
1797
- const locationString = String(location);
1798
- this.header(
1799
- "Location",
1800
- // Multibyes should be encoded
1801
- // eslint-disable-next-line no-control-regex
1802
- !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
1803
- );
1804
- return this.newResponse(null, status ?? 302);
1805
- };
1806
- /**
1807
- * `.notFound()` can return the Not Found Response.
1808
- *
1809
- * @see {@link https://hono.dev/docs/api/context#notfound}
1810
- *
1811
- * @example
1812
- * ```ts
1813
- * app.get('/notfound', (c) => {
1814
- * return c.notFound()
1815
- * })
1816
- * ```
1817
- */
1818
- notFound = () => {
1819
- this.#notFoundHandler ??= () => createResponseInstance();
1820
- return this.#notFoundHandler(this);
1821
- };
1822
- };
1823
-
1824
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router.js
1825
- var METHOD_NAME_ALL = "ALL";
1826
- var METHOD_NAME_ALL_LOWERCASE = "all";
1827
- var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1828
- var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1829
- var UnsupportedPathError = class extends Error {
1830
- };
1831
-
1832
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/constants.js
1833
- var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1834
-
1835
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono-base.js
1836
- var notFoundHandler = (c) => {
1837
- return c.text("404 Not Found", 404);
1838
- };
1839
- var errorHandler = (err, c) => {
1840
- if ("getResponse" in err) {
1841
- const res = err.getResponse();
1842
- return c.newResponse(res.body, res);
1843
- }
1844
- console.error(err);
1845
- return c.text("Internal Server Error", 500);
1846
- };
1847
- var Hono = class _Hono {
1848
- get;
1849
- post;
1850
- put;
1851
- delete;
1852
- options;
1853
- patch;
1854
- all;
1855
- on;
1856
- use;
1857
- /*
1858
- This class is like an abstract class and does not have a router.
1859
- To use it, inherit the class and implement router in the constructor.
1860
- */
1861
- router;
1862
- getPath;
1863
- // Cannot use `#` because it requires visibility at JavaScript runtime.
1864
- _basePath = "/";
1865
- #path = "/";
1866
- routes = [];
1867
- constructor(options = {}) {
1868
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1869
- allMethods.forEach((method) => {
1870
- this[method] = (args1, ...args) => {
1871
- if (typeof args1 === "string") {
1872
- this.#path = args1;
1873
- } else {
1874
- this.#addRoute(method, this.#path, args1);
1875
- }
1876
- args.forEach((handler) => {
1877
- this.#addRoute(method, this.#path, handler);
1878
- });
1879
- return this;
1880
- };
1881
- });
1882
- this.on = (method, path, ...handlers) => {
1883
- for (const p of [path].flat()) {
1884
- this.#path = p;
1885
- for (const m of [method].flat()) {
1886
- handlers.map((handler) => {
1887
- this.#addRoute(m.toUpperCase(), this.#path, handler);
1888
- });
1889
- }
1890
- }
1891
- return this;
1892
- };
1893
- this.use = (arg1, ...handlers) => {
1894
- if (typeof arg1 === "string") {
1895
- this.#path = arg1;
1896
- } else {
1897
- this.#path = "*";
1898
- handlers.unshift(arg1);
1899
- }
1900
- handlers.forEach((handler) => {
1901
- this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1902
- });
1903
- return this;
1904
- };
1905
- const { strict, ...optionsWithoutStrict } = options;
1906
- Object.assign(this, optionsWithoutStrict);
1907
- this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1908
- }
1909
- #clone() {
1910
- const clone = new _Hono({
1911
- router: this.router,
1912
- getPath: this.getPath
1913
- });
1914
- clone.errorHandler = this.errorHandler;
1915
- clone.#notFoundHandler = this.#notFoundHandler;
1916
- clone.routes = this.routes;
1917
- return clone;
1918
- }
1919
- #notFoundHandler = notFoundHandler;
1920
- // Cannot use `#` because it requires visibility at JavaScript runtime.
1921
- errorHandler = errorHandler;
1922
- /**
1923
- * `.route()` allows grouping other Hono instance in routes.
1924
- *
1925
- * @see {@link https://hono.dev/docs/api/routing#grouping}
1926
- *
1927
- * @param {string} path - base Path
1928
- * @param {Hono} app - other Hono instance
1929
- * @returns {Hono} routed Hono instance
1930
- *
1931
- * @example
1932
- * ```ts
1933
- * const app = new Hono()
1934
- * const app2 = new Hono()
1935
- *
1936
- * app2.get("/user", (c) => c.text("user"))
1937
- * app.route("/api", app2) // GET /api/user
1938
- * ```
1939
- */
1940
- route(path, app) {
1941
- const subApp = this.basePath(path);
1942
- app.routes.map((r) => {
1943
- let handler;
1944
- if (app.errorHandler === errorHandler) {
1945
- handler = r.handler;
1946
- } else {
1947
- handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
1948
- handler[COMPOSED_HANDLER] = r.handler;
1949
- }
1950
- subApp.#addRoute(r.method, r.path, handler, r.basePath);
1951
- });
1952
- return this;
1953
- }
1954
- /**
1955
- * `.basePath()` allows base paths to be specified.
1956
- *
1957
- * @see {@link https://hono.dev/docs/api/routing#base-path}
1958
- *
1959
- * @param {string} path - base Path
1960
- * @returns {Hono} changed Hono instance
1961
- *
1962
- * @example
1963
- * ```ts
1964
- * const api = new Hono().basePath('/api')
1965
- * ```
1966
- */
1967
- basePath(path) {
1968
- const subApp = this.#clone();
1969
- subApp._basePath = mergePath(this._basePath, path);
1970
- return subApp;
1971
- }
1972
- /**
1973
- * `.onError()` handles an error and returns a customized Response.
1974
- *
1975
- * @see {@link https://hono.dev/docs/api/hono#error-handling}
1976
- *
1977
- * @param {ErrorHandler} handler - request Handler for error
1978
- * @returns {Hono} changed Hono instance
1979
- *
1980
- * @example
1981
- * ```ts
1982
- * app.onError((err, c) => {
1983
- * console.error(`${err}`)
1984
- * return c.text('Custom Error Message', 500)
1985
- * })
1986
- * ```
1987
- */
1988
- onError = (handler) => {
1989
- this.errorHandler = handler;
1990
- return this;
1991
- };
1992
- /**
1993
- * `.notFound()` allows you to customize a Not Found Response.
1994
- *
1995
- * @see {@link https://hono.dev/docs/api/hono#not-found}
1996
- *
1997
- * @param {NotFoundHandler} handler - request handler for not-found
1998
- * @returns {Hono} changed Hono instance
1999
- *
2000
- * @example
2001
- * ```ts
2002
- * app.notFound((c) => {
2003
- * return c.text('Custom 404 Message', 404)
2004
- * })
2005
- * ```
2006
- */
2007
- notFound = (handler) => {
2008
- this.#notFoundHandler = handler;
2009
- return this;
2010
- };
2011
- /**
2012
- * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
2013
- *
2014
- * @see {@link https://hono.dev/docs/api/hono#mount}
2015
- *
2016
- * @param {string} path - base Path
2017
- * @param {Function} applicationHandler - other Request Handler
2018
- * @param {MountOptions} [options] - options of `.mount()`
2019
- * @returns {Hono} mounted Hono instance
2020
- *
2021
- * @example
2022
- * ```ts
2023
- * import { Router as IttyRouter } from 'itty-router'
2024
- * import { Hono } from 'hono'
2025
- * // Create itty-router application
2026
- * const ittyRouter = IttyRouter()
2027
- * // GET /itty-router/hello
2028
- * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
2029
- *
2030
- * const app = new Hono()
2031
- * app.mount('/itty-router', ittyRouter.handle)
2032
- * ```
2033
- *
2034
- * @example
2035
- * ```ts
2036
- * const app = new Hono()
2037
- * // Send the request to another application without modification.
2038
- * app.mount('/app', anotherApp, {
2039
- * replaceRequest: (req) => req,
2040
- * })
2041
- * ```
2042
- */
2043
- mount(path, applicationHandler, options) {
2044
- let replaceRequest;
2045
- let optionHandler;
2046
- if (options) {
2047
- if (typeof options === "function") {
2048
- optionHandler = options;
2049
- } else {
2050
- optionHandler = options.optionHandler;
2051
- if (options.replaceRequest === false) {
2052
- replaceRequest = (request) => request;
2053
- } else {
2054
- replaceRequest = options.replaceRequest;
2055
- }
2056
- }
2057
- }
2058
- const getOptions = optionHandler ? (c) => {
2059
- const options2 = optionHandler(c);
2060
- return Array.isArray(options2) ? options2 : [options2];
2061
- } : (c) => {
2062
- let executionContext = void 0;
2063
- try {
2064
- executionContext = c.executionCtx;
2065
- } catch {
2066
- }
2067
- return [c.env, executionContext];
2068
- };
2069
- replaceRequest ||= (() => {
2070
- const mergedPath = mergePath(this._basePath, path);
2071
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
2072
- return (request) => {
2073
- const url = new URL(request.url);
2074
- url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
2075
- return new Request(url, request);
2076
- };
2077
- })();
2078
- const handler = async (c, next) => {
2079
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
2080
- if (res) {
2081
- return res;
2082
- }
2083
- await next();
2084
- };
2085
- this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
2086
- return this;
2087
- }
2088
- #addRoute(method, path, handler, baseRoutePath) {
2089
- method = method.toUpperCase();
2090
- path = mergePath(this._basePath, path);
2091
- const r = {
2092
- basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
2093
- path,
2094
- method,
2095
- handler
2096
- };
2097
- this.router.add(method, path, [handler, r]);
2098
- this.routes.push(r);
2099
- }
2100
- #handleError(err, c) {
2101
- if (err instanceof Error) {
2102
- return this.errorHandler(err, c);
2103
- }
2104
- throw err;
2105
- }
2106
- #dispatch(request, executionCtx, env, method) {
2107
- if (method === "HEAD") {
2108
- return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
2109
- }
2110
- const path = this.getPath(request, { env });
2111
- const matchResult = this.router.match(method, path);
2112
- const c = new Context(request, {
2113
- path,
2114
- matchResult,
2115
- env,
2116
- executionCtx,
2117
- notFoundHandler: this.#notFoundHandler
2118
- });
2119
- if (matchResult[0].length === 1) {
2120
- let res;
2121
- try {
2122
- res = matchResult[0][0][0][0](c, async () => {
2123
- c.res = await this.#notFoundHandler(c);
2124
- });
2125
- } catch (err) {
2126
- return this.#handleError(err, c);
2127
- }
2128
- return res instanceof Promise ? res.then(
2129
- (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
2130
- ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
2131
- }
2132
- const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
2133
- return (async () => {
2134
- try {
2135
- const context = await composed(c);
2136
- if (!context.finalized) {
2137
- throw new Error(
2138
- "Context is not finalized. Did you forget to return a Response object or `await next()`?"
2139
- );
2140
- }
2141
- return context.res;
2142
- } catch (err) {
2143
- return this.#handleError(err, c);
2144
- }
2145
- })();
2146
- }
2147
- /**
2148
- * `.fetch()` will be entry point of your app.
2149
- *
2150
- * @see {@link https://hono.dev/docs/api/hono#fetch}
2151
- *
2152
- * @param {Request} request - request Object of request
2153
- * @param {Env} Env - env Object
2154
- * @param {ExecutionContext} - context of execution
2155
- * @returns {Response | Promise<Response>} response of request
2156
- *
2157
- */
2158
- fetch = (request, ...rest) => {
2159
- return this.#dispatch(request, rest[1], rest[0], request.method);
2160
- };
2161
- /**
2162
- * `.request()` is a useful method for testing.
2163
- * You can pass a URL or pathname to send a GET request.
2164
- * app will return a Response object.
2165
- * ```ts
2166
- * test('GET /hello is ok', async () => {
2167
- * const res = await app.request('/hello')
2168
- * expect(res.status).toBe(200)
2169
- * })
2170
- * ```
2171
- * @see https://hono.dev/docs/api/hono#request
2172
- */
2173
- request = (input, requestInit, Env, executionCtx) => {
2174
- if (input instanceof Request) {
2175
- return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
2176
- }
2177
- input = input.toString();
2178
- return this.fetch(
2179
- new Request(
2180
- /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
2181
- requestInit
2182
- ),
2183
- Env,
2184
- executionCtx
2185
- );
2186
- };
2187
- /**
2188
- * `.fire()` automatically adds a global fetch event listener.
2189
- * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
2190
- * @deprecated
2191
- * Use `fire` from `hono/service-worker` instead.
2192
- * ```ts
2193
- * import { Hono } from 'hono'
2194
- * import { fire } from 'hono/service-worker'
2195
- *
2196
- * const app = new Hono()
2197
- * // ...
2198
- * fire(app)
2199
- * ```
2200
- * @see https://hono.dev/docs/api/hono#fire
2201
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
2202
- * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
2203
- */
2204
- fire = () => {
2205
- addEventListener("fetch", (event) => {
2206
- event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
2207
- });
2208
- };
2209
- };
2210
-
2211
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/matcher.js
2212
- var emptyParam = [];
2213
- function match(method, path) {
2214
- const matchers = this.buildAllMatchers();
2215
- const match2 = ((method2, path2) => {
2216
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
2217
- const staticMatch = matcher[2][path2];
2218
- if (staticMatch) {
2219
- return staticMatch;
2220
- }
2221
- const match3 = path2.match(matcher[0]);
2222
- if (!match3) {
2223
- return [[], emptyParam];
2224
- }
2225
- const index = match3.indexOf("", 1);
2226
- return [matcher[1][index], match3];
2227
- });
2228
- this.match = match2;
2229
- return match2(method, path);
2230
- }
2231
-
2232
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/node.js
2233
- var LABEL_REG_EXP_STR = "[^/]+";
2234
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
2235
- var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
2236
- var PATH_ERROR = /* @__PURE__ */ Symbol();
2237
- var regExpMetaChars = new Set(".\\+*[^]$()");
2238
- function compareKey(a, b) {
2239
- if (a.length === 1) {
2240
- return b.length === 1 ? a < b ? -1 : 1 : -1;
2241
- }
2242
- if (b.length === 1) {
2243
- return 1;
2244
- }
2245
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2246
- return 1;
2247
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2248
- return -1;
2249
- }
2250
- if (a === LABEL_REG_EXP_STR) {
2251
- return 1;
2252
- } else if (b === LABEL_REG_EXP_STR) {
2253
- return -1;
2254
- }
2255
- return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2256
- }
2257
- var Node = class _Node {
2258
- #index;
2259
- #varIndex;
2260
- #children = /* @__PURE__ */ Object.create(null);
2261
- insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2262
- if (tokens.length === 0) {
2263
- if (this.#index !== void 0) {
2264
- throw PATH_ERROR;
2265
- }
2266
- if (pathErrorCheckOnly) {
2267
- return;
2268
- }
2269
- this.#index = index;
2270
- return;
2271
- }
2272
- const [token, ...restTokens] = tokens;
2273
- const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2274
- let node;
2275
- if (pattern) {
2276
- const name = pattern[1];
2277
- let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2278
- if (name && pattern[2]) {
2279
- if (regexpStr === ".*") {
2280
- throw PATH_ERROR;
2281
- }
2282
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2283
- if (/\((?!\?:)/.test(regexpStr)) {
2284
- throw PATH_ERROR;
2285
- }
2286
- }
2287
- node = this.#children[regexpStr];
2288
- if (!node) {
2289
- if (Object.keys(this.#children).some(
2290
- (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2291
- )) {
2292
- throw PATH_ERROR;
2293
- }
2294
- if (pathErrorCheckOnly) {
2295
- return;
2296
- }
2297
- node = this.#children[regexpStr] = new _Node();
2298
- if (name !== "") {
2299
- node.#varIndex = context.varIndex++;
2300
- }
2301
- }
2302
- if (!pathErrorCheckOnly && name !== "") {
2303
- paramMap.push([name, node.#varIndex]);
2304
- }
2305
- } else {
2306
- node = this.#children[token];
2307
- if (!node) {
2308
- if (Object.keys(this.#children).some(
2309
- (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2310
- )) {
2311
- throw PATH_ERROR;
2312
- }
2313
- if (pathErrorCheckOnly) {
2314
- return;
2315
- }
2316
- node = this.#children[token] = new _Node();
2317
- }
2318
- }
2319
- node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
2320
- }
2321
- buildRegExpStr() {
2322
- const childKeys = Object.keys(this.#children).sort(compareKey);
2323
- const strList = childKeys.map((k) => {
2324
- const c = this.#children[k];
2325
- return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
2326
- });
2327
- if (typeof this.#index === "number") {
2328
- strList.unshift(`#${this.#index}`);
2329
- }
2330
- if (strList.length === 0) {
2331
- return "";
2332
- }
2333
- if (strList.length === 1) {
2334
- return strList[0];
2335
- }
2336
- return "(?:" + strList.join("|") + ")";
2337
- }
2338
- };
2339
-
2340
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/trie.js
2341
- var Trie = class {
2342
- #context = { varIndex: 0 };
2343
- #root = new Node();
2344
- insert(path, index, pathErrorCheckOnly) {
2345
- const paramAssoc = [];
2346
- const groups = [];
2347
- for (let i = 0; ; ) {
2348
- let replaced = false;
2349
- path = path.replace(/\{[^}]+\}/g, (m) => {
2350
- const mark = `@\\${i}`;
2351
- groups[i] = [mark, m];
2352
- i++;
2353
- replaced = true;
2354
- return mark;
2355
- });
2356
- if (!replaced) {
2357
- break;
2358
- }
2359
- }
2360
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2361
- for (let i = groups.length - 1; i >= 0; i--) {
2362
- const [mark] = groups[i];
2363
- for (let j = tokens.length - 1; j >= 0; j--) {
2364
- if (tokens[j].indexOf(mark) !== -1) {
2365
- tokens[j] = tokens[j].replace(mark, groups[i][1]);
2366
- break;
2367
- }
2368
- }
2369
- }
2370
- this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
2371
- return paramAssoc;
2372
- }
2373
- buildRegExp() {
2374
- let regexp = this.#root.buildRegExpStr();
2375
- if (regexp === "") {
2376
- return [/^$/, [], []];
2377
- }
2378
- let captureIndex = 0;
2379
- const indexReplacementMap = [];
2380
- const paramReplacementMap = [];
2381
- regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
2382
- if (handlerIndex !== void 0) {
2383
- indexReplacementMap[++captureIndex] = Number(handlerIndex);
2384
- return "$()";
2385
- }
2386
- if (paramIndex !== void 0) {
2387
- paramReplacementMap[Number(paramIndex)] = ++captureIndex;
2388
- return "";
2389
- }
2390
- return "";
2391
- });
2392
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
2393
- }
2394
- };
2395
-
2396
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/router.js
2397
- var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2398
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2399
- function buildWildcardRegExp(path) {
2400
- return wildcardRegExpCache[path] ??= new RegExp(
2401
- path === "*" ? "" : `^${path.replace(
2402
- /\/\*$|([.\\+*[^\]$()])/g,
2403
- (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
2404
- )}$`
2405
- );
2406
- }
2407
- function clearWildcardRegExpCache() {
2408
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2409
- }
2410
- function buildMatcherFromPreprocessedRoutes(routes) {
2411
- const trie = new Trie();
2412
- const handlerData = [];
2413
- if (routes.length === 0) {
2414
- return nullMatcher;
2415
- }
2416
- const routesWithStaticPathFlag = routes.map(
2417
- (route) => [!/\*|\/:/.test(route[0]), ...route]
2418
- ).sort(
2419
- ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
2420
- );
2421
- const staticMap = /* @__PURE__ */ Object.create(null);
2422
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
2423
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
2424
- if (pathErrorCheckOnly) {
2425
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
2426
- } else {
2427
- j++;
2428
- }
2429
- let paramAssoc;
2430
- try {
2431
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
2432
- } catch (e) {
2433
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
2434
- }
2435
- if (pathErrorCheckOnly) {
2436
- continue;
2437
- }
2438
- handlerData[j] = handlers.map(([h, paramCount]) => {
2439
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
2440
- paramCount -= 1;
2441
- for (; paramCount >= 0; paramCount--) {
2442
- const [key, value] = paramAssoc[paramCount];
2443
- paramIndexMap[key] = value;
2444
- }
2445
- return [h, paramIndexMap];
2446
- });
2447
- }
2448
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
2449
- for (let i = 0, len = handlerData.length; i < len; i++) {
2450
- for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
2451
- const map = handlerData[i][j]?.[1];
2452
- if (!map) {
2453
- continue;
2454
- }
2455
- const keys = Object.keys(map);
2456
- for (let k = 0, len3 = keys.length; k < len3; k++) {
2457
- map[keys[k]] = paramReplacementMap[map[keys[k]]];
2458
- }
2459
- }
2460
- }
2461
- const handlerMap = [];
2462
- for (const i in indexReplacementMap) {
2463
- handlerMap[i] = handlerData[indexReplacementMap[i]];
2464
- }
2465
- return [regexp, handlerMap, staticMap];
2466
- }
2467
- function findMiddleware(middleware, path) {
2468
- if (!middleware) {
2469
- return void 0;
2470
- }
2471
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
2472
- if (buildWildcardRegExp(k).test(path)) {
2473
- return [...middleware[k]];
2474
- }
2475
- }
2476
- return void 0;
2477
- }
2478
- var RegExpRouter = class {
2479
- name = "RegExpRouter";
2480
- #middleware;
2481
- #routes;
2482
- constructor() {
2483
- this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2484
- this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2485
- }
2486
- add(method, path, handler) {
2487
- const middleware = this.#middleware;
2488
- const routes = this.#routes;
2489
- if (!middleware || !routes) {
2490
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2491
- }
2492
- if (!middleware[method]) {
2493
- ;
2494
- [middleware, routes].forEach((handlerMap) => {
2495
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
2496
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
2497
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
2498
- });
2499
- });
2500
- }
2501
- if (path === "/*") {
2502
- path = "*";
2503
- }
2504
- const paramCount = (path.match(/\/:/g) || []).length;
2505
- if (/\*$/.test(path)) {
2506
- const re = buildWildcardRegExp(path);
2507
- if (method === METHOD_NAME_ALL) {
2508
- Object.keys(middleware).forEach((m) => {
2509
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2510
- });
2511
- } else {
2512
- middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2513
- }
2514
- Object.keys(middleware).forEach((m) => {
2515
- if (method === METHOD_NAME_ALL || method === m) {
2516
- Object.keys(middleware[m]).forEach((p) => {
2517
- re.test(p) && middleware[m][p].push([handler, paramCount]);
2518
- });
2519
- }
2520
- });
2521
- Object.keys(routes).forEach((m) => {
2522
- if (method === METHOD_NAME_ALL || method === m) {
2523
- Object.keys(routes[m]).forEach(
2524
- (p) => re.test(p) && routes[m][p].push([handler, paramCount])
2525
- );
2526
- }
2527
- });
2528
- return;
2529
- }
2530
- const paths = checkOptionalParameter(path) || [path];
2531
- for (let i = 0, len = paths.length; i < len; i++) {
2532
- const path2 = paths[i];
2533
- Object.keys(routes).forEach((m) => {
2534
- if (method === METHOD_NAME_ALL || method === m) {
2535
- routes[m][path2] ||= [
2536
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
2537
- ];
2538
- routes[m][path2].push([handler, paramCount - len + i + 1]);
2539
- }
2540
- });
2541
- }
2542
- }
2543
- match = match;
2544
- buildAllMatchers() {
2545
- const matchers = /* @__PURE__ */ Object.create(null);
2546
- Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
2547
- matchers[method] ||= this.#buildMatcher(method);
2548
- });
2549
- this.#middleware = this.#routes = void 0;
2550
- clearWildcardRegExpCache();
2551
- return matchers;
2552
- }
2553
- #buildMatcher(method) {
2554
- const routes = [];
2555
- let hasOwnRoute = method === METHOD_NAME_ALL;
2556
- [this.#middleware, this.#routes].forEach((r) => {
2557
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
2558
- if (ownRoute.length !== 0) {
2559
- hasOwnRoute ||= true;
2560
- routes.push(...ownRoute);
2561
- } else if (method !== METHOD_NAME_ALL) {
2562
- routes.push(
2563
- ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
2564
- );
2565
- }
2566
- });
2567
- if (!hasOwnRoute) {
2568
- return null;
2569
- } else {
2570
- return buildMatcherFromPreprocessedRoutes(routes);
2571
- }
2572
- }
2573
- };
2574
-
2575
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/smart-router/router.js
2576
- var SmartRouter = class {
2577
- name = "SmartRouter";
2578
- #routers = [];
2579
- #routes = [];
2580
- constructor(init) {
2581
- this.#routers = init.routers;
2582
- }
2583
- add(method, path, handler) {
2584
- if (!this.#routes) {
2585
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2586
- }
2587
- this.#routes.push([method, path, handler]);
2588
- }
2589
- match(method, path) {
2590
- if (!this.#routes) {
2591
- throw new Error("Fatal error");
2592
- }
2593
- const routers = this.#routers;
2594
- const routes = this.#routes;
2595
- const len = routers.length;
2596
- let i = 0;
2597
- let res;
2598
- for (; i < len; i++) {
2599
- const router = routers[i];
2600
- try {
2601
- for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
2602
- router.add(...routes[i2]);
2603
- }
2604
- res = router.match(method, path);
2605
- } catch (e) {
2606
- if (e instanceof UnsupportedPathError) {
2607
- continue;
2608
- }
2609
- throw e;
2610
- }
2611
- this.match = router.match.bind(router);
2612
- this.#routers = [router];
2613
- this.#routes = void 0;
2614
- break;
2615
- }
2616
- if (i === len) {
2617
- throw new Error("Fatal error");
2618
- }
2619
- this.name = `SmartRouter + ${this.activeRouter.name}`;
2620
- return res;
2621
- }
2622
- get activeRouter() {
2623
- if (this.#routes || this.#routers.length !== 1) {
2624
- throw new Error("No active router has been determined yet.");
2625
- }
2626
- return this.#routers[0];
2627
- }
2628
- };
2629
-
2630
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/trie-router/node.js
2631
- var emptyParams = /* @__PURE__ */ Object.create(null);
2632
- var hasChildren = (children) => {
2633
- for (const _ in children) {
2634
- return true;
2635
- }
2636
- return false;
2637
- };
2638
- var Node2 = class _Node2 {
2639
- #methods;
2640
- #children;
2641
- #patterns;
2642
- #order = 0;
2643
- #params = emptyParams;
2644
- constructor(method, handler, children) {
2645
- this.#children = children || /* @__PURE__ */ Object.create(null);
2646
- this.#methods = [];
2647
- if (method && handler) {
2648
- const m = /* @__PURE__ */ Object.create(null);
2649
- m[method] = { handler, possibleKeys: [], score: 0 };
2650
- this.#methods = [m];
2651
- }
2652
- this.#patterns = [];
2653
- }
2654
- insert(method, path, handler) {
2655
- this.#order = ++this.#order;
2656
- let curNode = this;
2657
- const parts = splitRoutingPath(path);
2658
- const possibleKeys = [];
2659
- for (let i = 0, len = parts.length; i < len; i++) {
2660
- const p = parts[i];
2661
- const nextP = parts[i + 1];
2662
- const pattern = getPattern(p, nextP);
2663
- const key = Array.isArray(pattern) ? pattern[0] : p;
2664
- if (key in curNode.#children) {
2665
- curNode = curNode.#children[key];
2666
- if (pattern) {
2667
- possibleKeys.push(pattern[1]);
2668
- }
2669
- continue;
2670
- }
2671
- curNode.#children[key] = new _Node2();
2672
- if (pattern) {
2673
- curNode.#patterns.push(pattern);
2674
- possibleKeys.push(pattern[1]);
2675
- }
2676
- curNode = curNode.#children[key];
2677
- }
2678
- curNode.#methods.push({
2679
- [method]: {
2680
- handler,
2681
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
2682
- score: this.#order
2683
- }
2684
- });
2685
- return curNode;
2686
- }
2687
- #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
2688
- for (let i = 0, len = node.#methods.length; i < len; i++) {
2689
- const m = node.#methods[i];
2690
- const handlerSet = m[method] || m[METHOD_NAME_ALL];
2691
- const processedSet = {};
2692
- if (handlerSet !== void 0) {
2693
- handlerSet.params = /* @__PURE__ */ Object.create(null);
2694
- handlerSets.push(handlerSet);
2695
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
2696
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
2697
- const key = handlerSet.possibleKeys[i2];
2698
- const processed = processedSet[handlerSet.score];
2699
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
2700
- processedSet[handlerSet.score] = true;
2701
- }
2702
- }
2703
- }
2704
- }
2705
- }
2706
- search(method, path) {
2707
- const handlerSets = [];
2708
- this.#params = emptyParams;
2709
- const curNode = this;
2710
- let curNodes = [curNode];
2711
- const parts = splitPath(path);
2712
- const curNodesQueue = [];
2713
- const len = parts.length;
2714
- let partOffsets = null;
2715
- for (let i = 0; i < len; i++) {
2716
- const part = parts[i];
2717
- const isLast = i === len - 1;
2718
- const tempNodes = [];
2719
- for (let j = 0, len2 = curNodes.length; j < len2; j++) {
2720
- const node = curNodes[j];
2721
- const nextNode = node.#children[part];
2722
- if (nextNode) {
2723
- nextNode.#params = node.#params;
2724
- if (isLast) {
2725
- if (nextNode.#children["*"]) {
2726
- this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
2727
- }
2728
- this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
2729
- } else {
2730
- tempNodes.push(nextNode);
2731
- }
2732
- }
2733
- for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
2734
- const pattern = node.#patterns[k];
2735
- const params = node.#params === emptyParams ? {} : { ...node.#params };
2736
- if (pattern === "*") {
2737
- const astNode = node.#children["*"];
2738
- if (astNode) {
2739
- this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
2740
- astNode.#params = params;
2741
- tempNodes.push(astNode);
2742
- }
2743
- continue;
2744
- }
2745
- const [key, name, matcher] = pattern;
2746
- if (!part && !(matcher instanceof RegExp)) {
2747
- continue;
2748
- }
2749
- const child = node.#children[key];
2750
- if (matcher instanceof RegExp) {
2751
- if (partOffsets === null) {
2752
- partOffsets = new Array(len);
2753
- let offset = path[0] === "/" ? 1 : 0;
2754
- for (let p = 0; p < len; p++) {
2755
- partOffsets[p] = offset;
2756
- offset += parts[p].length + 1;
2757
- }
2758
- }
2759
- const restPathString = path.substring(partOffsets[i]);
2760
- const m = matcher.exec(restPathString);
2761
- if (m) {
2762
- params[name] = m[0];
2763
- this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
2764
- if (hasChildren(child.#children)) {
2765
- child.#params = params;
2766
- const componentCount = m[0].match(/\//)?.length ?? 0;
2767
- const targetCurNodes = curNodesQueue[componentCount] ||= [];
2768
- targetCurNodes.push(child);
2769
- }
2770
- continue;
2771
- }
2772
- }
2773
- if (matcher === true || matcher.test(part)) {
2774
- params[name] = part;
2775
- if (isLast) {
2776
- this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
2777
- if (child.#children["*"]) {
2778
- this.#pushHandlerSets(
2779
- handlerSets,
2780
- child.#children["*"],
2781
- method,
2782
- params,
2783
- node.#params
2784
- );
2785
- }
2786
- } else {
2787
- child.#params = params;
2788
- tempNodes.push(child);
2789
- }
2790
- }
2791
- }
2792
- }
2793
- const shifted = curNodesQueue.shift();
2794
- curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
2795
- }
2796
- if (handlerSets.length > 1) {
2797
- handlerSets.sort((a, b) => {
2798
- return a.score - b.score;
2799
- });
2800
- }
2801
- return [handlerSets.map(({ handler, params }) => [handler, params])];
2802
- }
2803
- };
2804
-
2805
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/trie-router/router.js
2806
- var TrieRouter = class {
2807
- name = "TrieRouter";
2808
- #node;
2809
- constructor() {
2810
- this.#node = new Node2();
2811
- }
2812
- add(method, path, handler) {
2813
- const results = checkOptionalParameter(path);
2814
- if (results) {
2815
- for (let i = 0, len = results.length; i < len; i++) {
2816
- this.#node.insert(method, results[i], handler);
2817
- }
2818
- return;
2819
- }
2820
- this.#node.insert(method, path, handler);
2821
- }
2822
- match(method, path) {
2823
- return this.#node.search(method, path);
2824
- }
2825
- };
2826
-
2827
- // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono.js
2828
- var Hono2 = class extends Hono {
2829
- /**
2830
- * Creates an instance of the Hono class.
2831
- *
2832
- * @param options - Optional configuration options for the Hono instance.
2833
- */
2834
- constructor(options = {}) {
2835
- super(options);
2836
- this.router = options.router ?? new SmartRouter({
2837
- routers: [new RegExpRouter(), new TrieRouter()]
2838
- });
2839
- }
2840
- };
112
+ // src/receiver/start.ts
113
+ var import_hono = require("hono");
2841
114
 
2842
115
  // src/receiver/hono/index.ts
2843
116
  function webhookMiddleware(options) {
2844
117
  return async function check(c, next) {
2845
- const headers = headersBag(c.req.raw.headers);
118
+ const headers = headers_bag(c.req.raw.headers);
2846
119
  const rawBody = await c.req.text();
2847
120
  const result = await checkWebhook(headers, rawBody, options);
2848
121
  if (!result.ok) {
@@ -2852,7 +125,7 @@ function webhookMiddleware(options) {
2852
125
  await next();
2853
126
  };
2854
127
  }
2855
- function headersBag(headers) {
128
+ function headers_bag(headers) {
2856
129
  const out = {};
2857
130
  headers.forEach((value, key) => {
2858
131
  out[key] = value;
@@ -2862,7 +135,7 @@ function headersBag(headers) {
2862
135
 
2863
136
  // src/receiver/start.ts
2864
137
  function receiver(options) {
2865
- const app = new Hono2();
138
+ const app = new import_hono.Hono();
2866
139
  const middleware = webhookMiddleware({
2867
140
  store: options.store,
2868
141
  secret: options.secret
@@ -2912,8 +185,8 @@ function receiver(options) {
2912
185
  let server;
2913
186
  return {
2914
187
  async listen() {
2915
- const { serve: serve2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
2916
- const launched = serve2({ fetch: app.fetch, port: options.port });
188
+ const { serve } = await import("@hono/node-server");
189
+ const launched = serve({ fetch: app.fetch, port: options.port });
2917
190
  server = launched;
2918
191
  await new Promise((resolve) => {
2919
192
  launched.once("listening", () => resolve());