caveat-cli 0.14.4 → 0.14.6

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.
@@ -12,46 +12,85 @@ import {
12
12
  stderrLogger
13
13
  } from "./chunk-EH3S6X6X.js";
14
14
 
15
- // ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.14/node_modules/@hono/node-server/dist/index.mjs
16
- import { createServer as createServerHTTP } from "node:http";
17
- import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "node:http2";
18
- import { Http2ServerRequest } from "node:http2";
15
+ // ../../node_modules/.pnpm/@hono+node-server@2.0.1_hono@4.12.17/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs
16
+ var X_ALREADY_SENT = "x-hono-already-sent";
17
+
18
+ // ../../node_modules/.pnpm/@hono+node-server@2.0.1_hono@4.12.17/node_modules/@hono/node-server/dist/index.mjs
19
+ import { STATUS_CODES, createServer } from "node:http";
20
+ import { Http2ServerRequest, constants } from "node:http2";
19
21
  import { Readable } from "node:stream";
20
- import crypto from "node:crypto";
22
+
23
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/helper/websocket/index.js
24
+ var defineWebSocketHelper = (handler) => {
25
+ return ((...args) => {
26
+ if (typeof args[0] === "function") {
27
+ const [createEvents, options] = args;
28
+ return async function upgradeWebSocket2(c, next) {
29
+ const events = await createEvents(c);
30
+ const result = await handler(c, events, options);
31
+ if (result) {
32
+ return result;
33
+ }
34
+ await next();
35
+ };
36
+ } else {
37
+ const [c, events, options] = args;
38
+ return (async () => {
39
+ const upgraded = await handler(c, events, options);
40
+ if (!upgraded) {
41
+ throw new Error("Failed to upgrade WebSocket");
42
+ }
43
+ return upgraded;
44
+ })();
45
+ }
46
+ });
47
+ };
48
+
49
+ // ../../node_modules/.pnpm/@hono+node-server@2.0.1_hono@4.12.17/node_modules/@hono/node-server/dist/index.mjs
21
50
  var RequestError = class extends Error {
22
51
  constructor(message, options) {
23
52
  super(message, options);
24
53
  this.name = "RequestError";
25
54
  }
26
55
  };
27
- var toRequestError = (e) => {
28
- if (e instanceof RequestError) {
29
- return e;
56
+ var reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
57
+ var reDotSegment = /\/\.\.?(?:[/?#]|$)/;
58
+ var reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
59
+ var buildUrl = (scheme, host, incomingUrl) => {
60
+ const url = `${scheme}://${host}${incomingUrl}`;
61
+ if (!reValidHost.test(host)) {
62
+ const urlObj = new URL(url);
63
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
64
+ return urlObj.href;
65
+ } else if (incomingUrl.length === 0) return url + "/";
66
+ else {
67
+ if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
68
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
69
+ return url;
30
70
  }
71
+ };
72
+ var toRequestError = (e) => {
73
+ if (e instanceof RequestError) return e;
31
74
  return new RequestError(e.message, { cause: e });
32
75
  };
33
76
  var GlobalRequest = global.Request;
34
- var Request2 = class extends GlobalRequest {
77
+ var Request$1 = class extends GlobalRequest {
35
78
  constructor(input, options) {
36
79
  if (typeof input === "object" && getRequestCache in input) {
80
+ const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
81
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
37
82
  input = input[getRequestCache]();
38
83
  }
39
- if (typeof options?.body?.getReader !== "undefined") {
40
- ;
41
- options.duplex ??= "half";
42
- }
84
+ if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
43
85
  super(input, options);
44
86
  }
45
87
  };
46
88
  var newHeadersFromIncoming = (incoming) => {
47
89
  const headerRecord = [];
48
90
  const rawHeaders = incoming.rawHeaders;
49
- for (let i = 0; i < rawHeaders.length; i += 2) {
50
- const { [i]: key, [i + 1]: value } = rawHeaders;
51
- if (key.charCodeAt(0) !== /*:*/
52
- 58) {
53
- headerRecord.push([key, value]);
54
- }
91
+ for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
92
+ const key = rawHeaders[i];
93
+ if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
55
94
  }
56
95
  return new Headers(headerRecord);
57
96
  };
@@ -64,55 +103,190 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
64
103
  };
65
104
  if (method === "TRACE") {
66
105
  init.method = "GET";
67
- const req = new Request2(url, init);
68
- Object.defineProperty(req, "method", {
69
- get() {
70
- return "TRACE";
71
- }
72
- });
106
+ const req = new Request$1(url, init);
107
+ Object.defineProperty(req, "method", { get() {
108
+ return "TRACE";
109
+ } });
73
110
  return req;
74
111
  }
75
- if (!(method === "GET" || method === "HEAD")) {
76
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
77
- init.body = new ReadableStream({
78
- start(controller) {
79
- controller.enqueue(incoming.rawBody);
80
- controller.close();
81
- }
82
- });
83
- } else if (incoming[wrapBodyStream]) {
84
- let reader;
85
- init.body = new ReadableStream({
86
- async pull(controller) {
87
- try {
88
- reader ||= Readable.toWeb(incoming).getReader();
89
- const { done, value } = await reader.read();
90
- if (done) {
91
- controller.close();
92
- } else {
93
- controller.enqueue(value);
94
- }
95
- } catch (error2) {
96
- controller.error(error2);
97
- }
98
- }
99
- });
100
- } else {
101
- init.body = Readable.toWeb(incoming);
102
- }
103
- }
104
- return new Request2(url, init);
112
+ if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
113
+ controller.enqueue(incoming.rawBody);
114
+ controller.close();
115
+ } });
116
+ else if (incoming[wrapBodyStream]) {
117
+ let reader;
118
+ init.body = new ReadableStream({ async pull(controller) {
119
+ try {
120
+ reader ||= Readable.toWeb(incoming).getReader();
121
+ const { done, value } = await reader.read();
122
+ if (done) controller.close();
123
+ else controller.enqueue(value);
124
+ } catch (error2) {
125
+ controller.error(error2);
126
+ }
127
+ } });
128
+ } else init.body = Readable.toWeb(incoming);
129
+ return new Request$1(url, init);
105
130
  };
106
131
  var getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
107
132
  var requestCache = /* @__PURE__ */ Symbol("requestCache");
108
133
  var incomingKey = /* @__PURE__ */ Symbol("incomingKey");
109
134
  var urlKey = /* @__PURE__ */ Symbol("urlKey");
135
+ var methodKey = /* @__PURE__ */ Symbol("methodKey");
110
136
  var headersKey = /* @__PURE__ */ Symbol("headersKey");
111
137
  var abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
112
138
  var getAbortController = /* @__PURE__ */ Symbol("getAbortController");
139
+ var abortRequest = /* @__PURE__ */ Symbol("abortRequest");
140
+ var bodyBufferKey = /* @__PURE__ */ Symbol("bodyBuffer");
141
+ var bodyReadPromiseKey = /* @__PURE__ */ Symbol("bodyReadPromise");
142
+ var bodyConsumedDirectlyKey = /* @__PURE__ */ Symbol("bodyConsumedDirectly");
143
+ var bodyLockReaderKey = /* @__PURE__ */ Symbol("bodyLockReader");
144
+ var abortReasonKey = /* @__PURE__ */ Symbol("abortReason");
145
+ var newBodyUnusableError = () => {
146
+ return /* @__PURE__ */ new TypeError("Body is unusable");
147
+ };
148
+ var rejectBodyUnusable = () => {
149
+ return Promise.reject(newBodyUnusableError());
150
+ };
151
+ var textDecoder = new TextDecoder();
152
+ var consumeBodyDirectOnce = (request) => {
153
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
154
+ request[bodyConsumedDirectlyKey] = true;
155
+ };
156
+ var toArrayBuffer = (buf) => {
157
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
158
+ };
159
+ var contentType = (request) => {
160
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
161
+ };
162
+ var methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
163
+ var normalizeIncomingMethod = (method) => {
164
+ if (typeof method !== "string" || method.length === 0) return "GET";
165
+ switch (method) {
166
+ case "DELETE":
167
+ case "GET":
168
+ case "HEAD":
169
+ case "OPTIONS":
170
+ case "POST":
171
+ case "PUT":
172
+ return method;
173
+ }
174
+ const upper = method.toUpperCase();
175
+ switch (upper) {
176
+ case "DELETE":
177
+ case "GET":
178
+ case "HEAD":
179
+ case "OPTIONS":
180
+ case "POST":
181
+ case "PUT":
182
+ return upper;
183
+ default:
184
+ return method;
185
+ }
186
+ };
187
+ var validateDirectReadMethod = (method) => {
188
+ if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
189
+ const normalized = method.toUpperCase();
190
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
191
+ };
192
+ var readBodyWithFastPath = (request, method, fromBuffer) => {
193
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
194
+ const methodName = request.method;
195
+ if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
196
+ const methodValidationError = validateDirectReadMethod(methodName);
197
+ if (methodValidationError) return Promise.reject(methodValidationError);
198
+ if (request[requestCache]) {
199
+ if (methodName !== "TRACE") return request[requestCache][method]();
200
+ }
201
+ const alreadyUsedError = consumeBodyDirectOnce(request);
202
+ if (alreadyUsedError) return alreadyUsedError;
203
+ const raw2 = readRawBodyIfAvailable(request);
204
+ if (raw2) {
205
+ const result = Promise.resolve(fromBuffer(raw2, request));
206
+ request[bodyBufferKey] = void 0;
207
+ return result;
208
+ }
209
+ return readBodyDirect(request).then((buf) => {
210
+ const result = fromBuffer(buf, request);
211
+ request[bodyBufferKey] = void 0;
212
+ return result;
213
+ });
214
+ };
215
+ var readRawBodyIfAvailable = (request) => {
216
+ const incoming = request[incomingKey];
217
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
218
+ };
219
+ var readBodyDirect = (request) => {
220
+ if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
221
+ if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
222
+ const incoming = request[incomingKey];
223
+ if (Readable.isDisturbed(incoming)) return rejectBodyUnusable();
224
+ const promise = new Promise((resolve, reject) => {
225
+ const chunks = [];
226
+ let settled = false;
227
+ const finish = (callback) => {
228
+ if (settled) return;
229
+ settled = true;
230
+ cleanup();
231
+ callback();
232
+ };
233
+ const onData = (chunk) => {
234
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
235
+ };
236
+ const onEnd = () => {
237
+ finish(() => {
238
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
239
+ request[bodyBufferKey] = buffer;
240
+ resolve(buffer);
241
+ });
242
+ };
243
+ const onError = (error2) => {
244
+ finish(() => {
245
+ reject(error2);
246
+ });
247
+ };
248
+ const onClose = () => {
249
+ if (incoming.readableEnded) {
250
+ onEnd();
251
+ return;
252
+ }
253
+ finish(() => {
254
+ if (incoming.errored) {
255
+ reject(incoming.errored);
256
+ return;
257
+ }
258
+ const reason = request[abortReasonKey];
259
+ if (reason !== void 0) {
260
+ reject(reason instanceof Error ? reason : new Error(String(reason)));
261
+ return;
262
+ }
263
+ reject(/* @__PURE__ */ new Error("Client connection prematurely closed."));
264
+ });
265
+ };
266
+ const cleanup = () => {
267
+ incoming.off("data", onData);
268
+ incoming.off("end", onEnd);
269
+ incoming.off("error", onError);
270
+ incoming.off("close", onClose);
271
+ request[bodyReadPromiseKey] = void 0;
272
+ };
273
+ incoming.on("data", onData);
274
+ incoming.on("end", onEnd);
275
+ incoming.on("error", onError);
276
+ incoming.on("close", onClose);
277
+ queueMicrotask(() => {
278
+ if (settled) return;
279
+ if (incoming.readableEnded) onEnd();
280
+ else if (incoming.errored) onError(incoming.errored);
281
+ else if (incoming.destroyed) onClose();
282
+ });
283
+ });
284
+ request[bodyReadPromiseKey] = promise;
285
+ return promise;
286
+ };
113
287
  var requestPrototype = {
114
288
  get method() {
115
- return this[incomingKey].method || "GET";
289
+ return this[methodKey];
116
290
  },
117
291
  get url() {
118
292
  return this[urlKey];
@@ -120,24 +294,57 @@ var requestPrototype = {
120
294
  get headers() {
121
295
  return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
122
296
  },
297
+ [abortRequest](reason) {
298
+ if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
299
+ const abortController = this[abortControllerKey];
300
+ if (abortController && !abortController.signal.aborted) abortController.abort(reason);
301
+ },
123
302
  [getAbortController]() {
124
- this[getRequestCache]();
303
+ this[abortControllerKey] ||= new AbortController();
304
+ if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
125
305
  return this[abortControllerKey];
126
306
  },
127
307
  [getRequestCache]() {
128
- this[abortControllerKey] ||= new AbortController();
129
- return this[requestCache] ||= newRequestFromIncoming(
130
- this.method,
131
- this[urlKey],
132
- this.headers,
133
- this[incomingKey],
134
- this[abortControllerKey]
135
- );
308
+ const abortController = this[getAbortController]();
309
+ if (this[requestCache]) return this[requestCache];
310
+ const method = this.method;
311
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
312
+ this[bodyBufferKey] = void 0;
313
+ const init = {
314
+ method: method === "TRACE" ? "GET" : method,
315
+ headers: this.headers,
316
+ signal: abortController.signal
317
+ };
318
+ if (method !== "TRACE") {
319
+ init.body = new ReadableStream({ start(c) {
320
+ c.close();
321
+ } });
322
+ init.duplex = "half";
323
+ }
324
+ const req = new Request$1(this[urlKey], init);
325
+ if (method === "TRACE") Object.defineProperty(req, "method", { get() {
326
+ return "TRACE";
327
+ } });
328
+ return this[requestCache] = req;
329
+ }
330
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
331
+ },
332
+ get body() {
333
+ if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
334
+ const request = this[getRequestCache]();
335
+ if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
336
+ return request.body;
337
+ },
338
+ get bodyUsed() {
339
+ if (this[bodyConsumedDirectlyKey]) return true;
340
+ if (this[requestCache]) return this[requestCache].bodyUsed;
341
+ return false;
136
342
  }
137
343
  };
344
+ Object.defineProperty(requestPrototype, "signal", { get() {
345
+ return this[getAbortController]().signal;
346
+ } });
138
347
  [
139
- "body",
140
- "bodyUsed",
141
348
  "cache",
142
349
  "credentials",
143
350
  "destination",
@@ -146,76 +353,85 @@ var requestPrototype = {
146
353
  "redirect",
147
354
  "referrer",
148
355
  "referrerPolicy",
149
- "signal",
150
356
  "keepalive"
151
357
  ].forEach((k) => {
152
- Object.defineProperty(requestPrototype, k, {
153
- get() {
154
- return this[getRequestCache]()[k];
155
- }
156
- });
358
+ Object.defineProperty(requestPrototype, k, { get() {
359
+ return this[getRequestCache]()[k];
360
+ } });
157
361
  });
158
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
159
- Object.defineProperty(requestPrototype, k, {
160
- value: function() {
161
- return this[getRequestCache]()[k]();
162
- }
163
- });
164
- });
165
- Object.defineProperty(requestPrototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
166
- value: function(depth, options, inspectFn) {
167
- const props = {
168
- method: this.method,
169
- url: this.url,
170
- headers: this.headers,
171
- nativeRequest: this[requestCache]
172
- };
173
- return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
174
- }
362
+ ["clone", "formData"].forEach((k) => {
363
+ Object.defineProperty(requestPrototype, k, { value: function() {
364
+ if (this[bodyConsumedDirectlyKey]) {
365
+ if (k === "clone") throw newBodyUnusableError();
366
+ return rejectBodyUnusable();
367
+ }
368
+ return this[getRequestCache]()[k]();
369
+ } });
175
370
  });
176
- Object.setPrototypeOf(requestPrototype, Request2.prototype);
371
+ Object.defineProperty(requestPrototype, "text", { value: function() {
372
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
373
+ } });
374
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
375
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
376
+ } });
377
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
378
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
379
+ const type = contentType(request);
380
+ const init = type ? { headers: { "content-type": type } } : void 0;
381
+ return new Response(buf, init).blob();
382
+ });
383
+ } });
384
+ Object.defineProperty(requestPrototype, "json", { value: function() {
385
+ if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
386
+ return this.text().then(JSON.parse);
387
+ } });
388
+ Object.defineProperty(requestPrototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
389
+ return `Request (lightweight) ${inspectFn({
390
+ method: this.method,
391
+ url: this.url,
392
+ headers: this.headers,
393
+ nativeRequest: this[requestCache]
394
+ }, {
395
+ ...options,
396
+ depth: depth == null ? null : depth - 1
397
+ })}`;
398
+ } });
399
+ Object.setPrototypeOf(requestPrototype, Request$1.prototype);
177
400
  var newRequest = (incoming, defaultHostname) => {
178
401
  const req = Object.create(requestPrototype);
179
402
  req[incomingKey] = incoming;
403
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
180
404
  const incomingUrl = incoming.url || "";
181
- if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
182
- (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
183
- if (incoming instanceof Http2ServerRequest) {
184
- throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
185
- }
405
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
406
+ if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
186
407
  try {
187
- const url2 = new URL(incomingUrl);
188
- req[urlKey] = url2.href;
408
+ req[urlKey] = new URL(incomingUrl).href;
189
409
  } catch (e) {
190
410
  throw new RequestError("Invalid absolute URL", { cause: e });
191
411
  }
192
412
  return req;
193
413
  }
194
414
  const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
195
- if (!host) {
196
- throw new RequestError("Missing host header");
197
- }
415
+ if (!host) throw new RequestError("Missing host header");
198
416
  let scheme;
199
417
  if (incoming instanceof Http2ServerRequest) {
200
418
  scheme = incoming.scheme;
201
- if (!(scheme === "http" || scheme === "https")) {
202
- throw new RequestError("Unsupported scheme");
203
- }
204
- } else {
205
- scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
206
- }
207
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
208
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
209
- throw new RequestError("Invalid host header");
419
+ if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
420
+ } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
421
+ try {
422
+ req[urlKey] = buildUrl(scheme, host, incomingUrl);
423
+ } catch (e) {
424
+ if (e instanceof RequestError) throw e;
425
+ else throw new RequestError("Invalid URL", { cause: e });
210
426
  }
211
- req[urlKey] = url.href;
212
427
  return req;
213
428
  };
429
+ var defaultContentType = "text/plain; charset=UTF-8";
214
430
  var responseCache = /* @__PURE__ */ Symbol("responseCache");
215
431
  var getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
216
432
  var cacheKey = /* @__PURE__ */ Symbol("cache");
217
433
  var GlobalResponse = global.Response;
218
- var Response2 = class _Response {
434
+ var Response$1 = class Response$12 {
219
435
  #body;
220
436
  #init;
221
437
  [getResponseCache]() {
@@ -225,7 +441,7 @@ var Response2 = class _Response {
225
441
  constructor(body, init) {
226
442
  let headers;
227
443
  this.#body = body;
228
- if (init instanceof _Response) {
444
+ if (init instanceof Response$12) {
229
445
  const cachedGlobalResponse = init[responseCache];
230
446
  if (cachedGlobalResponse) {
231
447
  this.#init = cachedGlobalResponse;
@@ -235,22 +451,17 @@ var Response2 = class _Response {
235
451
  this.#init = init.#init;
236
452
  headers = new Headers(init.#init.headers);
237
453
  }
238
- } else {
239
- this.#init = init;
240
- }
241
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
242
- ;
243
- this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
244
- }
454
+ } else this.#init = init;
455
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
456
+ init?.status || 200,
457
+ body ?? null,
458
+ headers || init?.headers
459
+ ];
245
460
  }
246
461
  get headers() {
247
462
  const cache = this[cacheKey];
248
463
  if (cache) {
249
- if (!(cache[2] instanceof Headers)) {
250
- cache[2] = new Headers(
251
- cache[2] || { "content-type": "text/plain; charset=UTF-8" }
252
- );
253
- }
464
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
254
465
  return cache[2];
255
466
  }
256
467
  return this[getResponseCache]().headers;
@@ -263,33 +474,87 @@ var Response2 = class _Response {
263
474
  return status >= 200 && status < 300;
264
475
  }
265
476
  };
266
- ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
267
- Object.defineProperty(Response2.prototype, k, {
268
- get() {
269
- return this[getResponseCache]()[k];
270
- }
271
- });
477
+ [
478
+ "body",
479
+ "bodyUsed",
480
+ "redirected",
481
+ "statusText",
482
+ "trailers",
483
+ "type",
484
+ "url"
485
+ ].forEach((k) => {
486
+ Object.defineProperty(Response$1.prototype, k, { get() {
487
+ return this[getResponseCache]()[k];
488
+ } });
272
489
  });
273
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
274
- Object.defineProperty(Response2.prototype, k, {
275
- value: function() {
276
- return this[getResponseCache]()[k]();
277
- }
278
- });
490
+ [
491
+ "arrayBuffer",
492
+ "blob",
493
+ "clone",
494
+ "formData",
495
+ "json",
496
+ "text"
497
+ ].forEach((k) => {
498
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
499
+ return this[getResponseCache]()[k]();
500
+ } });
279
501
  });
280
- Object.defineProperty(Response2.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
281
- value: function(depth, options, inspectFn) {
282
- const props = {
283
- status: this.status,
284
- headers: this.headers,
285
- ok: this.ok,
286
- nativeResponse: this[responseCache]
287
- };
288
- return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
289
- }
502
+ Object.defineProperty(Response$1.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
503
+ return `Response (lightweight) ${inspectFn({
504
+ status: this.status,
505
+ headers: this.headers,
506
+ ok: this.ok,
507
+ nativeResponse: this[responseCache]
508
+ }, {
509
+ ...options,
510
+ depth: depth == null ? null : depth - 1
511
+ })}`;
512
+ } });
513
+ Object.setPrototypeOf(Response$1, GlobalResponse);
514
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
515
+ var validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
516
+ var parseRedirectUrl = (url) => {
517
+ if (url instanceof URL) return url.href;
518
+ if (validRedirectUrl.test(url)) return url;
519
+ return new URL(url).href;
520
+ };
521
+ var validRedirectStatuses = /* @__PURE__ */ new Set([
522
+ 301,
523
+ 302,
524
+ 303,
525
+ 307,
526
+ 308
527
+ ]);
528
+ Object.defineProperty(Response$1, "redirect", {
529
+ value: function redirect(url, status = 302) {
530
+ if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
531
+ return new Response$1(null, {
532
+ status,
533
+ headers: { location: parseRedirectUrl(url) }
534
+ });
535
+ },
536
+ writable: true,
537
+ configurable: true
538
+ });
539
+ Object.defineProperty(Response$1, "json", {
540
+ value: function json(data, init) {
541
+ const body = JSON.stringify(data);
542
+ if (body === void 0) throw new TypeError("The data is not JSON serializable");
543
+ const initHeaders = init?.headers;
544
+ let headers;
545
+ if (initHeaders) {
546
+ headers = new Headers(initHeaders);
547
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
548
+ } else headers = { "content-type": "application/json" };
549
+ return new Response$1(body, {
550
+ status: init?.status ?? 200,
551
+ statusText: init?.statusText,
552
+ headers
553
+ });
554
+ },
555
+ writable: true,
556
+ configurable: true
290
557
  });
291
- Object.setPrototypeOf(Response2, GlobalResponse);
292
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
293
558
  async function readWithoutBlocking(readPromise) {
294
559
  return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
295
560
  }
@@ -306,72 +571,49 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
306
571
  writable.off("error", cancel);
307
572
  });
308
573
  function handleStreamError(error2) {
309
- if (error2) {
310
- writable.destroy(error2);
311
- }
574
+ if (error2) writable.destroy(error2);
312
575
  }
313
576
  function onDrain() {
314
577
  reader.read().then(flow, handleStreamError);
315
578
  }
316
579
  function flow({ done, value }) {
317
580
  try {
318
- if (done) {
319
- writable.end();
320
- } else if (!writable.write(value)) {
321
- writable.once("drain", onDrain);
322
- } else {
323
- return reader.read().then(flow, handleStreamError);
324
- }
581
+ if (done) writable.end();
582
+ else if (!writable.write(value)) writable.once("drain", onDrain);
583
+ else return reader.read().then(flow, handleStreamError);
325
584
  } catch (e) {
326
585
  handleStreamError(e);
327
586
  }
328
587
  }
329
588
  }
330
589
  function writeFromReadableStream(stream, writable) {
331
- if (stream.locked) {
332
- throw new TypeError("ReadableStream is locked.");
333
- } else if (writable.destroyed) {
334
- return;
335
- }
590
+ if (stream.locked) throw new TypeError("ReadableStream is locked.");
591
+ else if (writable.destroyed) return;
336
592
  return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
337
593
  }
338
- var buildOutgoingHttpHeaders = (headers) => {
594
+ var buildOutgoingHttpHeaders = (headers, defaultContentType2) => {
339
595
  const res = {};
340
- if (!(headers instanceof Headers)) {
341
- headers = new Headers(headers ?? void 0);
342
- }
343
- const cookies = [];
344
- for (const [k, v] of headers) {
345
- if (k === "set-cookie") {
346
- cookies.push(v);
347
- } else {
348
- res[k] = v;
349
- }
350
- }
351
- if (cookies.length > 0) {
352
- res["set-cookie"] = cookies;
353
- }
354
- res["content-type"] ??= "text/plain; charset=UTF-8";
596
+ if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
597
+ if (headers.has("set-cookie")) {
598
+ const cookies = [];
599
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
600
+ else res[k] = v;
601
+ if (cookies.length > 0) res["set-cookie"] = cookies;
602
+ } else for (const [k, v] of headers) res[k] = v;
603
+ if (defaultContentType2) res["content-type"] ??= defaultContentType2;
355
604
  return res;
356
605
  };
357
- var X_ALREADY_SENT = "x-hono-already-sent";
358
- if (typeof global.crypto === "undefined") {
359
- global.crypto = crypto;
360
- }
361
606
  var outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
362
607
  var incomingDraining = /* @__PURE__ */ Symbol("incomingDraining");
363
608
  var DRAIN_TIMEOUT_MS = 500;
364
609
  var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
365
610
  var drainIncoming = (incoming) => {
366
611
  const incomingWithDrainState = incoming;
367
- if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
368
- return;
369
- }
612
+ if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
370
613
  incomingWithDrainState[incomingDraining] = true;
371
- if (incoming instanceof Http2ServerRequest2) {
614
+ if (incoming instanceof Http2ServerRequest) {
372
615
  try {
373
- ;
374
- incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
616
+ incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
375
617
  } catch {
376
618
  }
377
619
  return;
@@ -386,111 +628,119 @@ var drainIncoming = (incoming) => {
386
628
  const forceClose = () => {
387
629
  cleanup();
388
630
  const socket = incoming.socket;
389
- if (socket && !socket.destroyed) {
390
- socket.destroySoon();
391
- }
631
+ if (socket && !socket.destroyed) socket.destroySoon();
392
632
  };
393
633
  const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
394
634
  timer.unref?.();
395
635
  const onData = (chunk) => {
396
636
  bytesRead += chunk.length;
397
- if (bytesRead > MAX_DRAIN_BYTES) {
398
- forceClose();
399
- }
637
+ if (bytesRead > MAX_DRAIN_BYTES) forceClose();
400
638
  };
401
639
  incoming.on("data", onData);
402
640
  incoming.on("end", cleanup);
403
641
  incoming.on("error", cleanup);
404
642
  incoming.resume();
405
643
  };
406
- var handleRequestError = () => new Response(null, {
407
- status: 400
408
- });
409
- var handleFetchError = (e) => new Response(null, {
410
- status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
411
- });
644
+ var makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
645
+ if (incoming.errored) req[abortRequest](incoming.errored.toString());
646
+ else if (!outgoing.writableFinished) req[abortRequest]("Client connection prematurely closed.");
647
+ if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
648
+ if (!incoming.readableEnded) setTimeout(() => {
649
+ drainIncoming(incoming);
650
+ });
651
+ });
652
+ };
653
+ var isImmediateCacheableResponse = (res) => {
654
+ if (!(cacheKey in res)) return false;
655
+ const body = res[cacheKey][1];
656
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
657
+ };
658
+ var handleRequestError = () => new Response(null, { status: 400 });
659
+ var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
412
660
  var handleResponseError = (e, outgoing) => {
413
661
  const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
414
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
415
- console.info("The user aborted a request.");
416
- } else {
662
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
663
+ else {
417
664
  console.error(e);
418
- if (!outgoing.headersSent) {
419
- outgoing.writeHead(500, { "Content-Type": "text/plain" });
420
- }
665
+ if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
421
666
  outgoing.end(`Error: ${err.message}`);
422
667
  outgoing.destroy(err);
423
668
  }
424
669
  };
425
670
  var flushHeaders = (outgoing) => {
426
- if ("flushHeaders" in outgoing && outgoing.writable) {
427
- outgoing.flushHeaders();
428
- }
671
+ if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
429
672
  };
430
673
  var responseViaCache = async (res, outgoing) => {
431
674
  let [status, body, header] = res[cacheKey];
432
- let hasContentLength = false;
433
675
  if (!header) {
434
- header = { "content-type": "text/plain; charset=UTF-8" };
435
- } else if (header instanceof Headers) {
676
+ if (body === null) {
677
+ outgoing.writeHead(status);
678
+ outgoing.end();
679
+ } else if (typeof body === "string") {
680
+ outgoing.writeHead(status, {
681
+ "Content-Type": defaultContentType,
682
+ "Content-Length": Buffer.byteLength(body)
683
+ });
684
+ outgoing.end(body);
685
+ } else if (body instanceof Uint8Array) {
686
+ outgoing.writeHead(status, {
687
+ "Content-Type": defaultContentType,
688
+ "Content-Length": body.byteLength
689
+ });
690
+ outgoing.end(body);
691
+ } else if (body instanceof Blob) {
692
+ outgoing.writeHead(status, {
693
+ "Content-Type": defaultContentType,
694
+ "Content-Length": body.size
695
+ });
696
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
697
+ } else {
698
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
699
+ flushHeaders(outgoing);
700
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
701
+ }
702
+ outgoing[outgoingEnded]?.();
703
+ return;
704
+ }
705
+ let hasContentLength = false;
706
+ if (header instanceof Headers) {
436
707
  hasContentLength = header.has("content-length");
437
- header = buildOutgoingHttpHeaders(header);
708
+ header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
438
709
  } else if (Array.isArray(header)) {
439
710
  const headerObj = new Headers(header);
440
711
  hasContentLength = headerObj.has("content-length");
441
- header = buildOutgoingHttpHeaders(headerObj);
442
- } else {
443
- for (const key in header) {
444
- if (key.length === 14 && key.toLowerCase() === "content-length") {
445
- hasContentLength = true;
446
- break;
447
- }
448
- }
712
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
713
+ } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
714
+ hasContentLength = true;
715
+ break;
449
716
  }
450
717
  if (!hasContentLength) {
451
- if (typeof body === "string") {
452
- header["Content-Length"] = Buffer.byteLength(body);
453
- } else if (body instanceof Uint8Array) {
454
- header["Content-Length"] = body.byteLength;
455
- } else if (body instanceof Blob) {
456
- header["Content-Length"] = body.size;
457
- }
718
+ if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
719
+ else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
720
+ else if (body instanceof Blob) header["Content-Length"] = body.size;
458
721
  }
459
722
  outgoing.writeHead(status, header);
460
- if (typeof body === "string" || body instanceof Uint8Array) {
461
- outgoing.end(body);
462
- } else if (body instanceof Blob) {
463
- outgoing.end(new Uint8Array(await body.arrayBuffer()));
464
- } else {
723
+ if (body == null) outgoing.end();
724
+ else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
725
+ else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
726
+ else {
465
727
  flushHeaders(outgoing);
466
- await writeFromReadableStream(body, outgoing)?.catch(
467
- (e) => handleResponseError(e, outgoing)
468
- );
728
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
469
729
  }
470
- ;
471
730
  outgoing[outgoingEnded]?.();
472
731
  };
473
732
  var isPromise = (res) => typeof res.then === "function";
474
733
  var responseViaResponseObject = async (res, outgoing, options = {}) => {
475
- if (isPromise(res)) {
476
- if (options.errorHandler) {
477
- try {
478
- res = await res;
479
- } catch (err) {
480
- const errRes = await options.errorHandler(err);
481
- if (!errRes) {
482
- return;
483
- }
484
- res = errRes;
485
- }
486
- } else {
487
- res = await res.catch(handleFetchError);
488
- }
489
- }
490
- if (cacheKey in res) {
491
- return responseViaCache(res, outgoing);
492
- }
493
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
734
+ if (isPromise(res)) if (options.errorHandler) try {
735
+ res = await res;
736
+ } catch (err) {
737
+ const errRes = await options.errorHandler(err);
738
+ if (!errRes) return;
739
+ res = errRes;
740
+ }
741
+ else res = await res.catch(handleFetchError);
742
+ if (cacheKey in res) return responseViaCache(res, outgoing);
743
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
494
744
  if (res.body) {
495
745
  const reader = res.body.getReader();
496
746
  const values = [];
@@ -513,29 +763,21 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
513
763
  break;
514
764
  }
515
765
  currentReadPromise = void 0;
516
- if (chunk.value) {
517
- values.push(chunk.value);
518
- }
766
+ if (chunk.value) values.push(chunk.value);
519
767
  if (chunk.done) {
520
768
  done = true;
521
769
  break;
522
770
  }
523
771
  }
524
- if (done && !("content-length" in resHeaderRecord)) {
525
- resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
526
- }
772
+ if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
527
773
  }
528
774
  outgoing.writeHead(res.status, resHeaderRecord);
529
775
  values.forEach((value) => {
530
- ;
531
776
  outgoing.write(value);
532
777
  });
533
- if (done) {
534
- outgoing.end();
535
- } else {
536
- if (values.length === 0) {
537
- flushHeaders(outgoing);
538
- }
778
+ if (done) outgoing.end();
779
+ else {
780
+ if (values.length === 0) flushHeaders(outgoing);
539
781
  await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
540
782
  }
541
783
  } else if (resHeaderRecord[X_ALREADY_SENT]) {
@@ -543,88 +785,56 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
543
785
  outgoing.writeHead(res.status, resHeaderRecord);
544
786
  outgoing.end();
545
787
  }
546
- ;
547
788
  outgoing[outgoingEnded]?.();
548
789
  };
549
790
  var getRequestListener = (fetchCallback, options = {}) => {
550
791
  const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
551
- if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
552
- Object.defineProperty(global, "Request", {
553
- value: Request2
554
- });
555
- Object.defineProperty(global, "Response", {
556
- value: Response2
557
- });
792
+ if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
793
+ Object.defineProperty(global, "Request", { value: Request$1 });
794
+ Object.defineProperty(global, "Response", { value: Response$1 });
558
795
  }
559
796
  return async (incoming, outgoing) => {
560
797
  let res, req;
798
+ let needsBodyCleanup = false;
799
+ let closeHandlerAttached = false;
800
+ const ensureCloseHandler = () => {
801
+ if (!req || closeHandlerAttached) return;
802
+ closeHandlerAttached = true;
803
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
804
+ };
561
805
  try {
562
806
  req = newRequest(incoming, options.hostname);
563
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
564
- if (!incomingEnded) {
565
- ;
807
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
808
+ if (needsBodyCleanup) {
566
809
  incoming[wrapBodyStream] = true;
567
- incoming.on("end", () => {
568
- incomingEnded = true;
569
- });
570
- if (incoming instanceof Http2ServerRequest2) {
571
- ;
572
- outgoing[outgoingEnded] = () => {
573
- if (!incomingEnded) {
574
- setTimeout(() => {
575
- if (!incomingEnded) {
576
- setTimeout(() => {
577
- drainIncoming(incoming);
578
- });
579
- }
580
- });
581
- }
582
- };
583
- }
584
- outgoing.on("finish", () => {
585
- if (!incomingEnded) {
586
- drainIncoming(incoming);
587
- }
588
- });
589
- }
590
- outgoing.on("close", () => {
591
- const abortController = req[abortControllerKey];
592
- if (abortController) {
593
- if (incoming.errored) {
594
- req[abortControllerKey].abort(incoming.errored.toString());
595
- } else if (!outgoing.writableFinished) {
596
- req[abortControllerKey].abort("Client connection prematurely closed.");
597
- }
598
- }
599
- if (!incomingEnded) {
600
- setTimeout(() => {
601
- if (!incomingEnded) {
602
- setTimeout(() => {
603
- drainIncoming(incoming);
604
- });
605
- }
810
+ if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
811
+ if (!incoming.readableEnded) setTimeout(() => {
812
+ if (!incoming.readableEnded) setTimeout(() => {
813
+ incoming.destroy();
814
+ outgoing.destroy();
815
+ });
606
816
  });
607
- }
817
+ };
818
+ }
819
+ res = fetchCallback(req, {
820
+ incoming,
821
+ outgoing
608
822
  });
609
- res = fetchCallback(req, { incoming, outgoing });
610
- if (cacheKey in res) {
823
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
824
+ if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
825
+ if (!incoming.readableEnded) drainIncoming(incoming);
826
+ });
611
827
  return responseViaCache(res, outgoing);
612
828
  }
829
+ ensureCloseHandler();
613
830
  } catch (e) {
614
- if (!res) {
615
- if (options.errorHandler) {
616
- res = await options.errorHandler(req ? e : toRequestError(e));
617
- if (!res) {
618
- return;
619
- }
620
- } else if (!req) {
621
- res = handleRequestError();
622
- } else {
623
- res = handleFetchError(e);
624
- }
625
- } else {
626
- return handleResponseError(e, outgoing);
627
- }
831
+ if (!res) if (options.errorHandler) {
832
+ ensureCloseHandler();
833
+ res = await options.errorHandler(req ? e : toRequestError(e));
834
+ if (!res) return;
835
+ } else if (!req) res = handleRequestError();
836
+ else res = handleFetchError(e);
837
+ else return handleResponseError(e, outgoing);
628
838
  }
629
839
  try {
630
840
  return await responseViaResponseObject(res, outgoing, options);
@@ -633,6 +843,192 @@ var getRequestListener = (fetchCallback, options = {}) => {
633
843
  }
634
844
  };
635
845
  };
846
+ var CloseEvent = globalThis.CloseEvent ?? class extends Event {
847
+ #eventInitDict;
848
+ constructor(type, eventInitDict = {}) {
849
+ super(type, eventInitDict);
850
+ this.#eventInitDict = eventInitDict;
851
+ }
852
+ get wasClean() {
853
+ return this.#eventInitDict.wasClean ?? false;
854
+ }
855
+ get code() {
856
+ return this.#eventInitDict.code ?? 0;
857
+ }
858
+ get reason() {
859
+ return this.#eventInitDict.reason ?? "";
860
+ }
861
+ };
862
+ var generateConnectionSymbol = () => /* @__PURE__ */ Symbol("connection");
863
+ var CONNECTION_SYMBOL_KEY = /* @__PURE__ */ Symbol("CONNECTION_SYMBOL_KEY");
864
+ var WAIT_FOR_WEBSOCKET_SYMBOL = /* @__PURE__ */ Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
865
+ var responseHeadersToSkip = /* @__PURE__ */ new Set([
866
+ "connection",
867
+ "content-length",
868
+ "keep-alive",
869
+ "proxy-authenticate",
870
+ "proxy-authorization",
871
+ "te",
872
+ "trailer",
873
+ "transfer-encoding",
874
+ "upgrade",
875
+ "sec-websocket-accept",
876
+ "sec-websocket-extensions",
877
+ "sec-websocket-protocol"
878
+ ]);
879
+ var appendResponseHeaders = (headers, responseHeaders) => {
880
+ if (!responseHeaders) return;
881
+ responseHeaders.forEach((value, key) => {
882
+ if (responseHeadersToSkip.has(key.toLowerCase())) return;
883
+ headers.push(`${key}: ${value}`);
884
+ });
885
+ };
886
+ var rejectUpgradeRequest = (socket, status, responseHeaders) => {
887
+ const responseLines = ["Connection: close", "Content-Length: 0"];
888
+ appendResponseHeaders(responseLines, responseHeaders);
889
+ socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r
890
+ ${responseLines.join("\r\n")}\r
891
+ \r
892
+ `);
893
+ };
894
+ var createUpgradeRequest = (request) => {
895
+ const protocol = request.socket.encrypted ? "https" : "http";
896
+ const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
897
+ const headers = new Headers();
898
+ for (const key in request.headers) {
899
+ const value = request.headers[key];
900
+ if (!value) continue;
901
+ headers.append(key, Array.isArray(value) ? value[0] : value);
902
+ }
903
+ return new Request(url, { headers });
904
+ };
905
+ var setupWebSocket = (options) => {
906
+ const { server, fetchCallback, wss } = options;
907
+ const waiterMap = /* @__PURE__ */ new Map();
908
+ wss.on("connection", (ws, request) => {
909
+ const waiter = waiterMap.get(request);
910
+ if (waiter) {
911
+ waiter.resolve(ws);
912
+ waiterMap.delete(request);
913
+ }
914
+ });
915
+ const waitForWebSocket = (request, connectionSymbol) => {
916
+ return new Promise((resolve) => {
917
+ waiterMap.set(request, {
918
+ resolve,
919
+ connectionSymbol
920
+ });
921
+ });
922
+ };
923
+ server.on("upgrade", async (request, socket, head) => {
924
+ if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
925
+ const env = {
926
+ incoming: request,
927
+ outgoing: void 0,
928
+ wss,
929
+ [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
930
+ };
931
+ let status = 400;
932
+ let responseHeaders;
933
+ try {
934
+ const response = await fetchCallback(createUpgradeRequest(request), env);
935
+ if (response instanceof Response) {
936
+ status = response.status;
937
+ responseHeaders = response.headers;
938
+ }
939
+ } catch {
940
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
941
+ return;
942
+ }
943
+ const waiter = waiterMap.get(request);
944
+ if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
945
+ waiterMap.delete(request);
946
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
947
+ return;
948
+ }
949
+ const addResponseHeaders = (headers) => {
950
+ appendResponseHeaders(headers, responseHeaders);
951
+ };
952
+ wss.on("headers", addResponseHeaders);
953
+ try {
954
+ wss.handleUpgrade(request, socket, head, (ws) => {
955
+ wss.emit("connection", ws, request);
956
+ });
957
+ } finally {
958
+ wss.off("headers", addResponseHeaders);
959
+ }
960
+ });
961
+ server.on("close", () => {
962
+ wss.close();
963
+ });
964
+ };
965
+ var upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {
966
+ if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return;
967
+ const env = c.env;
968
+ const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
969
+ if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });
970
+ const connectionSymbol = generateConnectionSymbol();
971
+ env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
972
+ (async () => {
973
+ const ws = await waitForWebSocket(env.incoming, connectionSymbol);
974
+ const messagesReceivedInStarting = [];
975
+ const bufferMessage = (data, isBinary) => {
976
+ messagesReceivedInStarting.push([data, isBinary]);
977
+ };
978
+ ws.on("message", bufferMessage);
979
+ const ctx = {
980
+ binaryType: "arraybuffer",
981
+ close(code2, reason) {
982
+ ws.close(code2, reason);
983
+ },
984
+ protocol: ws.protocol,
985
+ raw: ws,
986
+ get readyState() {
987
+ return ws.readyState;
988
+ },
989
+ send(source, opts) {
990
+ ws.send(source, { compress: opts?.compress });
991
+ },
992
+ url: new URL(c.req.url)
993
+ };
994
+ try {
995
+ events?.onOpen?.(new Event("open"), ctx);
996
+ } catch (e) {
997
+ (options?.onError ?? console.error)(e);
998
+ }
999
+ const handleMessage = (data, isBinary) => {
1000
+ const datas = Array.isArray(data) ? data : [data];
1001
+ for (const data2 of datas) try {
1002
+ events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data2 instanceof ArrayBuffer ? data2 : data2.buffer.slice(data2.byteOffset, data2.byteOffset + data2.byteLength) : data2.toString("utf-8") }), ctx);
1003
+ } catch (e) {
1004
+ (options?.onError ?? console.error)(e);
1005
+ }
1006
+ };
1007
+ ws.off("message", bufferMessage);
1008
+ for (const message of messagesReceivedInStarting) handleMessage(...message);
1009
+ ws.on("message", (data, isBinary) => {
1010
+ handleMessage(data, isBinary);
1011
+ });
1012
+ ws.on("close", (code2, reason) => {
1013
+ try {
1014
+ events?.onClose?.(new CloseEvent("close", {
1015
+ code: code2,
1016
+ reason: reason.toString()
1017
+ }), ctx);
1018
+ } catch (e) {
1019
+ (options?.onError ?? console.error)(e);
1020
+ }
1021
+ });
1022
+ ws.on("error", (error2) => {
1023
+ try {
1024
+ events?.onError?.(new ErrorEvent("error", { error: error2 }), ctx);
1025
+ } catch (e) {
1026
+ (options?.onError ?? console.error)(e);
1027
+ }
1028
+ });
1029
+ })();
1030
+ return new Response();
1031
+ });
636
1032
  var createAdaptorServer = (options) => {
637
1033
  const fetchCallback = options.fetch;
638
1034
  const requestListener = getRequestListener(fetchCallback, {
@@ -640,8 +1036,15 @@ var createAdaptorServer = (options) => {
640
1036
  overrideGlobalObjects: options.overrideGlobalObjects,
641
1037
  autoCleanupIncoming: options.autoCleanupIncoming
642
1038
  });
643
- const createServer = options.createServer || createServerHTTP;
644
- const server = createServer(options.serverOptions || {}, requestListener);
1039
+ const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
1040
+ if (options.websocket && options.websocket.server) {
1041
+ if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
1042
+ setupWebSocket({
1043
+ server,
1044
+ fetchCallback,
1045
+ wss: options.websocket.server
1046
+ });
1047
+ }
645
1048
  return server;
646
1049
  };
647
1050
  var serve = (options, listeningListener) => {
@@ -667,7 +1070,7 @@ function buildWebContext(overrides = {}) {
667
1070
  return { caveatHome, userHome, userConfigPath, config: config2, paths, logger, db };
668
1071
  }
669
1072
 
670
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/compose.js
1073
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/compose.js
671
1074
  var compose = (middleware, onError, onNotFound) => {
672
1075
  return (context, next) => {
673
1076
  let index = -1;
@@ -711,15 +1114,15 @@ var compose = (middleware, onError, onNotFound) => {
711
1114
  };
712
1115
  };
713
1116
 
714
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/request/constants.js
1117
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/request/constants.js
715
1118
  var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
716
1119
 
717
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/utils/body.js
1120
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/utils/body.js
718
1121
  var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
719
1122
  const { all = false, dot = false } = options;
720
1123
  const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
721
- const contentType = headers.get("Content-Type");
722
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
1124
+ const contentType2 = headers.get("Content-Type");
1125
+ if (contentType2?.startsWith("multipart/form-data") || contentType2?.startsWith("application/x-www-form-urlencoded")) {
723
1126
  return parseFormData(request, { all, dot });
724
1127
  }
725
1128
  return {};
@@ -786,7 +1189,7 @@ var handleParsingNestedValues = (form, key, value) => {
786
1189
  });
787
1190
  };
788
1191
 
789
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/utils/url.js
1192
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/utils/url.js
790
1193
  var splitPath = (path) => {
791
1194
  const paths = path.split("/");
792
1195
  if (paths[0] === "") {
@@ -990,7 +1393,7 @@ var getQueryParams = (url, key) => {
990
1393
  };
991
1394
  var decodeURIComponent_ = decodeURIComponent;
992
1395
 
993
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/request.js
1396
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/request.js
994
1397
  var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
995
1398
  var HonoRequest = class {
996
1399
  /**
@@ -1258,7 +1661,7 @@ var HonoRequest = class {
1258
1661
  }
1259
1662
  };
1260
1663
 
1261
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/utils/html.js
1664
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/utils/html.js
1262
1665
  var HtmlEscapedCallbackPhase = {
1263
1666
  Stringify: 1,
1264
1667
  BeforeStream: 2,
@@ -1300,11 +1703,11 @@ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) =>
1300
1703
  }
1301
1704
  };
1302
1705
 
1303
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/context.js
1706
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/context.js
1304
1707
  var TEXT_PLAIN = "text/plain; charset=UTF-8";
1305
- var setDefaultContentType = (contentType, headers) => {
1708
+ var setDefaultContentType = (contentType2, headers) => {
1306
1709
  return {
1307
- "Content-Type": contentType,
1710
+ "Content-Type": contentType2,
1308
1711
  ...headers
1309
1712
  };
1310
1713
  };
@@ -1707,7 +2110,7 @@ var Context = class {
1707
2110
  };
1708
2111
  };
1709
2112
 
1710
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/router.js
2113
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/router.js
1711
2114
  var METHOD_NAME_ALL = "ALL";
1712
2115
  var METHOD_NAME_ALL_LOWERCASE = "all";
1713
2116
  var METHODS = ["get", "post", "put", "delete", "options", "patch"];
@@ -1715,10 +2118,10 @@ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is
1715
2118
  var UnsupportedPathError = class extends Error {
1716
2119
  };
1717
2120
 
1718
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/utils/constants.js
2121
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/utils/constants.js
1719
2122
  var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1720
2123
 
1721
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/hono-base.js
2124
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/hono-base.js
1722
2125
  var notFoundHandler = (c) => {
1723
2126
  return c.text("404 Not Found", 404);
1724
2127
  };
@@ -2089,7 +2492,7 @@ var Hono = class _Hono {
2089
2492
  };
2090
2493
  };
2091
2494
 
2092
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/router/reg-exp-router/matcher.js
2495
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/router/reg-exp-router/matcher.js
2093
2496
  var emptyParam = [];
2094
2497
  function match(method, path) {
2095
2498
  const matchers = this.buildAllMatchers();
@@ -2110,7 +2513,7 @@ function match(method, path) {
2110
2513
  return match22(method, path);
2111
2514
  }
2112
2515
 
2113
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/router/reg-exp-router/node.js
2516
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/router/reg-exp-router/node.js
2114
2517
  var LABEL_REG_EXP_STR = "[^/]+";
2115
2518
  var ONLY_WILDCARD_REG_EXP_STR = ".*";
2116
2519
  var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
@@ -2218,7 +2621,7 @@ var Node = class _Node {
2218
2621
  }
2219
2622
  };
2220
2623
 
2221
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/router/reg-exp-router/trie.js
2624
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/router/reg-exp-router/trie.js
2222
2625
  var Trie = class {
2223
2626
  #context = { varIndex: 0 };
2224
2627
  #root = new Node();
@@ -2274,7 +2677,7 @@ var Trie = class {
2274
2677
  }
2275
2678
  };
2276
2679
 
2277
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/router/reg-exp-router/router.js
2680
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/router/reg-exp-router/router.js
2278
2681
  var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2279
2682
  var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2280
2683
  function buildWildcardRegExp(path) {
@@ -2453,7 +2856,7 @@ var RegExpRouter = class {
2453
2856
  }
2454
2857
  };
2455
2858
 
2456
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/router/smart-router/router.js
2859
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/router/smart-router/router.js
2457
2860
  var SmartRouter = class {
2458
2861
  name = "SmartRouter";
2459
2862
  #routers = [];
@@ -2508,7 +2911,7 @@ var SmartRouter = class {
2508
2911
  }
2509
2912
  };
2510
2913
 
2511
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/router/trie-router/node.js
2914
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/router/trie-router/node.js
2512
2915
  var emptyParams = /* @__PURE__ */ Object.create(null);
2513
2916
  var hasChildren = (children) => {
2514
2917
  for (const _ in children) {
@@ -2683,7 +3086,7 @@ var Node2 = class _Node2 {
2683
3086
  }
2684
3087
  };
2685
3088
 
2686
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/router/trie-router/router.js
3089
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/router/trie-router/router.js
2687
3090
  var TrieRouter = class {
2688
3091
  name = "TrieRouter";
2689
3092
  #node;
@@ -2705,7 +3108,7 @@ var TrieRouter = class {
2705
3108
  }
2706
3109
  };
2707
3110
 
2708
- // ../../node_modules/.pnpm/hono@4.12.14/node_modules/hono/dist/hono.js
3111
+ // ../../node_modules/.pnpm/hono@4.12.17/node_modules/hono/dist/hono.js
2709
3112
  var Hono2 = class extends Hono {
2710
3113
  /**
2711
3114
  * Creates an instance of the Hono class.
@@ -8489,4 +8892,4 @@ if (import.meta.url === `file://${process.argv[1]?.replace(/\\/g, "/")}`) {
8489
8892
  export {
8490
8893
  startServer
8491
8894
  };
8492
- //# sourceMappingURL=server-P4FQZD2N.js.map
8895
+ //# sourceMappingURL=server-RWVXGVXK.js.map