@hono/node-server 1.19.14 → 2.0.0-rc.2

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 (63) hide show
  1. package/README.md +56 -18
  2. package/dist/conninfo.cjs +22 -0
  3. package/dist/{conninfo.d.ts → conninfo.d.cts} +4 -3
  4. package/dist/conninfo.d.mts +4 -3
  5. package/dist/conninfo.mjs +19 -16
  6. package/dist/constants-BLSFu_RU.mjs +5 -0
  7. package/dist/constants-BXAKTxRC.cjs +11 -0
  8. package/dist/index.cjs +1006 -0
  9. package/dist/index.d.cts +73 -0
  10. package/dist/index.d.mts +73 -8
  11. package/dist/index.mjs +976 -637
  12. package/dist/serve-static.cjs +135 -0
  13. package/dist/serve-static.d.cts +18 -0
  14. package/dist/serve-static.d.mts +14 -13
  15. package/dist/serve-static.mjs +127 -145
  16. package/dist/utils/response.cjs +8 -0
  17. package/dist/utils/response.d.cts +4 -0
  18. package/dist/utils/response.d.mts +3 -2
  19. package/dist/utils/response.mjs +6 -9
  20. package/package.json +53 -40
  21. package/dist/conninfo.js +0 -42
  22. package/dist/globals.d.mts +0 -2
  23. package/dist/globals.d.ts +0 -2
  24. package/dist/globals.js +0 -29
  25. package/dist/globals.mjs +0 -5
  26. package/dist/index.d.ts +0 -8
  27. package/dist/index.js +0 -702
  28. package/dist/listener.d.mts +0 -13
  29. package/dist/listener.d.ts +0 -13
  30. package/dist/listener.js +0 -670
  31. package/dist/listener.mjs +0 -635
  32. package/dist/request.d.mts +0 -25
  33. package/dist/request.d.ts +0 -25
  34. package/dist/request.js +0 -238
  35. package/dist/request.mjs +0 -206
  36. package/dist/response.d.mts +0 -26
  37. package/dist/response.d.ts +0 -26
  38. package/dist/response.js +0 -112
  39. package/dist/response.mjs +0 -85
  40. package/dist/serve-static.d.ts +0 -17
  41. package/dist/serve-static.js +0 -177
  42. package/dist/server.d.mts +0 -10
  43. package/dist/server.d.ts +0 -10
  44. package/dist/server.js +0 -696
  45. package/dist/server.mjs +0 -660
  46. package/dist/types.d.mts +0 -44
  47. package/dist/types.d.ts +0 -44
  48. package/dist/types.js +0 -18
  49. package/dist/types.mjs +0 -0
  50. package/dist/utils/response/constants.d.mts +0 -3
  51. package/dist/utils/response/constants.d.ts +0 -3
  52. package/dist/utils/response/constants.js +0 -30
  53. package/dist/utils/response/constants.mjs +0 -5
  54. package/dist/utils/response.d.ts +0 -3
  55. package/dist/utils/response.js +0 -37
  56. package/dist/utils.d.mts +0 -9
  57. package/dist/utils.d.ts +0 -9
  58. package/dist/utils.js +0 -99
  59. package/dist/utils.mjs +0 -71
  60. package/dist/vercel.d.mts +0 -7
  61. package/dist/vercel.d.ts +0 -7
  62. package/dist/vercel.js +0 -677
  63. package/dist/vercel.mjs +0 -640
package/dist/index.mjs CHANGED
@@ -1,662 +1,1001 @@
1
- // src/server.ts
2
- import { createServer as createServerHTTP } from "http";
1
+ import { t as X_ALREADY_SENT } from "./constants-BLSFu_RU.mjs";
2
+ import { STATUS_CODES, createServer } from "node:http";
3
+ import { Http2ServerRequest, constants } from "node:http2";
4
+ import { Readable } from "node:stream";
5
+ import { defineWebSocketHelper } from "hono/ws";
3
6
 
4
- // src/listener.ts
5
- import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
6
-
7
- // src/request.ts
8
- import { Http2ServerRequest } from "http2";
9
- import { Readable } from "stream";
7
+ //#region src/error.ts
10
8
  var RequestError = class extends Error {
11
- constructor(message, options) {
12
- super(message, options);
13
- this.name = "RequestError";
14
- }
15
- };
16
- var toRequestError = (e) => {
17
- if (e instanceof RequestError) {
18
- return e;
19
- }
20
- return new RequestError(e.message, { cause: e });
21
- };
22
- var GlobalRequest = global.Request;
23
- var Request = class extends GlobalRequest {
24
- constructor(input, options) {
25
- if (typeof input === "object" && getRequestCache in input) {
26
- input = input[getRequestCache]();
27
- }
28
- if (typeof options?.body?.getReader !== "undefined") {
29
- ;
30
- options.duplex ??= "half";
31
- }
32
- super(input, options);
33
- }
34
- };
35
- var newHeadersFromIncoming = (incoming) => {
36
- const headerRecord = [];
37
- const rawHeaders = incoming.rawHeaders;
38
- for (let i = 0; i < rawHeaders.length; i += 2) {
39
- const { [i]: key, [i + 1]: value } = rawHeaders;
40
- if (key.charCodeAt(0) !== /*:*/
41
- 58) {
42
- headerRecord.push([key, value]);
43
- }
44
- }
45
- return new Headers(headerRecord);
46
- };
47
- var wrapBodyStream = Symbol("wrapBodyStream");
48
- var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
49
- const init = {
50
- method,
51
- headers,
52
- signal: abortController.signal
53
- };
54
- if (method === "TRACE") {
55
- init.method = "GET";
56
- const req = new Request(url, init);
57
- Object.defineProperty(req, "method", {
58
- get() {
59
- return "TRACE";
60
- }
61
- });
62
- return req;
63
- }
64
- if (!(method === "GET" || method === "HEAD")) {
65
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
66
- init.body = new ReadableStream({
67
- start(controller) {
68
- controller.enqueue(incoming.rawBody);
69
- controller.close();
70
- }
71
- });
72
- } else if (incoming[wrapBodyStream]) {
73
- let reader;
74
- init.body = new ReadableStream({
75
- async pull(controller) {
76
- try {
77
- reader ||= Readable.toWeb(incoming).getReader();
78
- const { done, value } = await reader.read();
79
- if (done) {
80
- controller.close();
81
- } else {
82
- controller.enqueue(value);
83
- }
84
- } catch (error) {
85
- controller.error(error);
86
- }
87
- }
88
- });
89
- } else {
90
- init.body = Readable.toWeb(incoming);
91
- }
92
- }
93
- return new Request(url, init);
94
- };
95
- var getRequestCache = Symbol("getRequestCache");
96
- var requestCache = Symbol("requestCache");
97
- var incomingKey = Symbol("incomingKey");
98
- var urlKey = Symbol("urlKey");
99
- var headersKey = Symbol("headersKey");
100
- var abortControllerKey = Symbol("abortControllerKey");
101
- var getAbortController = Symbol("getAbortController");
102
- var requestPrototype = {
103
- get method() {
104
- return this[incomingKey].method || "GET";
105
- },
106
- get url() {
107
- return this[urlKey];
108
- },
109
- get headers() {
110
- return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
111
- },
112
- [getAbortController]() {
113
- this[getRequestCache]();
114
- return this[abortControllerKey];
115
- },
116
- [getRequestCache]() {
117
- this[abortControllerKey] ||= new AbortController();
118
- return this[requestCache] ||= newRequestFromIncoming(
119
- this.method,
120
- this[urlKey],
121
- this.headers,
122
- this[incomingKey],
123
- this[abortControllerKey]
124
- );
125
- }
9
+ constructor(message, options) {
10
+ super(message, options);
11
+ this.name = "RequestError";
12
+ }
13
+ };
14
+
15
+ //#endregion
16
+ //#region src/url.ts
17
+ const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
18
+ const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
19
+ const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
20
+ const buildUrl = (scheme, host, incomingUrl) => {
21
+ const url = `${scheme}://${host}${incomingUrl}`;
22
+ if (!reValidHost.test(host)) {
23
+ const urlObj = new URL(url);
24
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
25
+ return urlObj.href;
26
+ } else if (incomingUrl.length === 0) return url + "/";
27
+ else {
28
+ if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
29
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
30
+ return url;
31
+ }
32
+ };
33
+
34
+ //#endregion
35
+ //#region src/request.ts
36
+ const toRequestError = (e) => {
37
+ if (e instanceof RequestError) return e;
38
+ return new RequestError(e.message, { cause: e });
39
+ };
40
+ const GlobalRequest = global.Request;
41
+ var Request$1 = class extends GlobalRequest {
42
+ constructor(input, options) {
43
+ if (typeof input === "object" && getRequestCache in input) {
44
+ const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
45
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
46
+ input = input[getRequestCache]();
47
+ }
48
+ if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
49
+ super(input, options);
50
+ }
51
+ };
52
+ const newHeadersFromIncoming = (incoming) => {
53
+ const headerRecord = [];
54
+ const rawHeaders = incoming.rawHeaders;
55
+ for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
56
+ const key = rawHeaders[i];
57
+ if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
58
+ }
59
+ return new Headers(headerRecord);
60
+ };
61
+ const wrapBodyStream = Symbol("wrapBodyStream");
62
+ const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
63
+ const init = {
64
+ method,
65
+ headers,
66
+ signal: abortController.signal
67
+ };
68
+ if (method === "TRACE") {
69
+ init.method = "GET";
70
+ const req = new Request$1(url, init);
71
+ Object.defineProperty(req, "method", { get() {
72
+ return "TRACE";
73
+ } });
74
+ return req;
75
+ }
76
+ if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
77
+ controller.enqueue(incoming.rawBody);
78
+ controller.close();
79
+ } });
80
+ else if (incoming[wrapBodyStream]) {
81
+ let reader;
82
+ init.body = new ReadableStream({ async pull(controller) {
83
+ try {
84
+ reader ||= Readable.toWeb(incoming).getReader();
85
+ const { done, value } = await reader.read();
86
+ if (done) controller.close();
87
+ else controller.enqueue(value);
88
+ } catch (error) {
89
+ controller.error(error);
90
+ }
91
+ } });
92
+ } else init.body = Readable.toWeb(incoming);
93
+ return new Request$1(url, init);
94
+ };
95
+ const getRequestCache = Symbol("getRequestCache");
96
+ const requestCache = Symbol("requestCache");
97
+ const incomingKey = Symbol("incomingKey");
98
+ const urlKey = Symbol("urlKey");
99
+ const methodKey = Symbol("methodKey");
100
+ const headersKey = Symbol("headersKey");
101
+ const abortControllerKey = Symbol("abortControllerKey");
102
+ const getAbortController = Symbol("getAbortController");
103
+ const abortRequest = Symbol("abortRequest");
104
+ const bodyBufferKey = Symbol("bodyBuffer");
105
+ const bodyReadPromiseKey = Symbol("bodyReadPromise");
106
+ const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
107
+ const bodyLockReaderKey = Symbol("bodyLockReader");
108
+ const abortReasonKey = Symbol("abortReason");
109
+ const newBodyUnusableError = () => {
110
+ return /* @__PURE__ */ new TypeError("Body is unusable");
111
+ };
112
+ const rejectBodyUnusable = () => {
113
+ return Promise.reject(newBodyUnusableError());
114
+ };
115
+ const textDecoder = new TextDecoder();
116
+ const consumeBodyDirectOnce = (request) => {
117
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
118
+ request[bodyConsumedDirectlyKey] = true;
119
+ };
120
+ const toArrayBuffer = (buf) => {
121
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
126
122
  };
123
+ const contentType = (request) => {
124
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
125
+ };
126
+ const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
127
+ const normalizeIncomingMethod = (method) => {
128
+ if (typeof method !== "string" || method.length === 0) return "GET";
129
+ switch (method) {
130
+ case "DELETE":
131
+ case "GET":
132
+ case "HEAD":
133
+ case "OPTIONS":
134
+ case "POST":
135
+ case "PUT": return method;
136
+ }
137
+ const upper = method.toUpperCase();
138
+ switch (upper) {
139
+ case "DELETE":
140
+ case "GET":
141
+ case "HEAD":
142
+ case "OPTIONS":
143
+ case "POST":
144
+ case "PUT": return upper;
145
+ default: return method;
146
+ }
147
+ };
148
+ const validateDirectReadMethod = (method) => {
149
+ if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
150
+ const normalized = method.toUpperCase();
151
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
152
+ };
153
+ const readBodyWithFastPath = (request, method, fromBuffer) => {
154
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
155
+ const methodName = request.method;
156
+ if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
157
+ const methodValidationError = validateDirectReadMethod(methodName);
158
+ if (methodValidationError) return Promise.reject(methodValidationError);
159
+ if (request[requestCache]) {
160
+ if (methodName !== "TRACE") return request[requestCache][method]();
161
+ }
162
+ const alreadyUsedError = consumeBodyDirectOnce(request);
163
+ if (alreadyUsedError) return alreadyUsedError;
164
+ const raw = readRawBodyIfAvailable(request);
165
+ if (raw) {
166
+ const result = Promise.resolve(fromBuffer(raw, request));
167
+ request[bodyBufferKey] = void 0;
168
+ return result;
169
+ }
170
+ return readBodyDirect(request).then((buf) => {
171
+ const result = fromBuffer(buf, request);
172
+ request[bodyBufferKey] = void 0;
173
+ return result;
174
+ });
175
+ };
176
+ const readRawBodyIfAvailable = (request) => {
177
+ const incoming = request[incomingKey];
178
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
179
+ };
180
+ const readBodyDirect = (request) => {
181
+ if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
182
+ if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
183
+ const incoming = request[incomingKey];
184
+ if (Readable.isDisturbed(incoming)) return rejectBodyUnusable();
185
+ const promise = new Promise((resolve, reject) => {
186
+ const chunks = [];
187
+ let settled = false;
188
+ const finish = (callback) => {
189
+ if (settled) return;
190
+ settled = true;
191
+ cleanup();
192
+ callback();
193
+ };
194
+ const onData = (chunk) => {
195
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
196
+ };
197
+ const onEnd = () => {
198
+ finish(() => {
199
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
200
+ request[bodyBufferKey] = buffer;
201
+ resolve(buffer);
202
+ });
203
+ };
204
+ const onError = (error) => {
205
+ finish(() => {
206
+ reject(error);
207
+ });
208
+ };
209
+ const onClose = () => {
210
+ if (incoming.readableEnded) {
211
+ onEnd();
212
+ return;
213
+ }
214
+ finish(() => {
215
+ if (incoming.errored) {
216
+ reject(incoming.errored);
217
+ return;
218
+ }
219
+ const reason = request[abortReasonKey];
220
+ if (reason !== void 0) {
221
+ reject(reason instanceof Error ? reason : new Error(String(reason)));
222
+ return;
223
+ }
224
+ reject(/* @__PURE__ */ new Error("Client connection prematurely closed."));
225
+ });
226
+ };
227
+ const cleanup = () => {
228
+ incoming.off("data", onData);
229
+ incoming.off("end", onEnd);
230
+ incoming.off("error", onError);
231
+ incoming.off("close", onClose);
232
+ request[bodyReadPromiseKey] = void 0;
233
+ };
234
+ incoming.on("data", onData);
235
+ incoming.on("end", onEnd);
236
+ incoming.on("error", onError);
237
+ incoming.on("close", onClose);
238
+ queueMicrotask(() => {
239
+ if (settled) return;
240
+ if (incoming.readableEnded) onEnd();
241
+ else if (incoming.errored) onError(incoming.errored);
242
+ else if (incoming.destroyed) onClose();
243
+ });
244
+ });
245
+ request[bodyReadPromiseKey] = promise;
246
+ return promise;
247
+ };
248
+ const requestPrototype = {
249
+ get method() {
250
+ return this[methodKey];
251
+ },
252
+ get url() {
253
+ return this[urlKey];
254
+ },
255
+ get headers() {
256
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
257
+ },
258
+ [abortRequest](reason) {
259
+ if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
260
+ const abortController = this[abortControllerKey];
261
+ if (abortController && !abortController.signal.aborted) abortController.abort(reason);
262
+ },
263
+ [getAbortController]() {
264
+ this[abortControllerKey] ||= new AbortController();
265
+ if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
266
+ return this[abortControllerKey];
267
+ },
268
+ [getRequestCache]() {
269
+ const abortController = this[getAbortController]();
270
+ if (this[requestCache]) return this[requestCache];
271
+ const method = this.method;
272
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
273
+ this[bodyBufferKey] = void 0;
274
+ const init = {
275
+ method: method === "TRACE" ? "GET" : method,
276
+ headers: this.headers,
277
+ signal: abortController.signal
278
+ };
279
+ if (method !== "TRACE") {
280
+ init.body = new ReadableStream({ start(c) {
281
+ c.close();
282
+ } });
283
+ init.duplex = "half";
284
+ }
285
+ const req = new Request$1(this[urlKey], init);
286
+ if (method === "TRACE") Object.defineProperty(req, "method", { get() {
287
+ return "TRACE";
288
+ } });
289
+ return this[requestCache] = req;
290
+ }
291
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
292
+ },
293
+ get body() {
294
+ if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
295
+ const request = this[getRequestCache]();
296
+ if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
297
+ return request.body;
298
+ },
299
+ get bodyUsed() {
300
+ if (this[bodyConsumedDirectlyKey]) return true;
301
+ if (this[requestCache]) return this[requestCache].bodyUsed;
302
+ return false;
303
+ }
304
+ };
305
+ Object.defineProperty(requestPrototype, "signal", { get() {
306
+ return this[getAbortController]().signal;
307
+ } });
127
308
  [
128
- "body",
129
- "bodyUsed",
130
- "cache",
131
- "credentials",
132
- "destination",
133
- "integrity",
134
- "mode",
135
- "redirect",
136
- "referrer",
137
- "referrerPolicy",
138
- "signal",
139
- "keepalive"
309
+ "cache",
310
+ "credentials",
311
+ "destination",
312
+ "integrity",
313
+ "mode",
314
+ "redirect",
315
+ "referrer",
316
+ "referrerPolicy",
317
+ "keepalive"
140
318
  ].forEach((k) => {
141
- Object.defineProperty(requestPrototype, k, {
142
- get() {
143
- return this[getRequestCache]()[k];
144
- }
145
- });
146
- });
147
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
148
- Object.defineProperty(requestPrototype, k, {
149
- value: function() {
150
- return this[getRequestCache]()[k]();
151
- }
152
- });
319
+ Object.defineProperty(requestPrototype, k, { get() {
320
+ return this[getRequestCache]()[k];
321
+ } });
153
322
  });
154
- Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
155
- value: function(depth, options, inspectFn) {
156
- const props = {
157
- method: this.method,
158
- url: this.url,
159
- headers: this.headers,
160
- nativeRequest: this[requestCache]
161
- };
162
- return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
163
- }
323
+ ["clone", "formData"].forEach((k) => {
324
+ Object.defineProperty(requestPrototype, k, { value: function() {
325
+ if (this[bodyConsumedDirectlyKey]) {
326
+ if (k === "clone") throw newBodyUnusableError();
327
+ return rejectBodyUnusable();
328
+ }
329
+ return this[getRequestCache]()[k]();
330
+ } });
164
331
  });
165
- Object.setPrototypeOf(requestPrototype, Request.prototype);
166
- var newRequest = (incoming, defaultHostname) => {
167
- const req = Object.create(requestPrototype);
168
- req[incomingKey] = incoming;
169
- const incomingUrl = incoming.url || "";
170
- if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
171
- (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
172
- if (incoming instanceof Http2ServerRequest) {
173
- throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
174
- }
175
- try {
176
- const url2 = new URL(incomingUrl);
177
- req[urlKey] = url2.href;
178
- } catch (e) {
179
- throw new RequestError("Invalid absolute URL", { cause: e });
180
- }
181
- return req;
182
- }
183
- const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
184
- if (!host) {
185
- throw new RequestError("Missing host header");
186
- }
187
- let scheme;
188
- if (incoming instanceof Http2ServerRequest) {
189
- scheme = incoming.scheme;
190
- if (!(scheme === "http" || scheme === "https")) {
191
- throw new RequestError("Unsupported scheme");
192
- }
193
- } else {
194
- scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
195
- }
196
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
197
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
198
- throw new RequestError("Invalid host header");
199
- }
200
- req[urlKey] = url.href;
201
- return req;
332
+ Object.defineProperty(requestPrototype, "text", { value: function() {
333
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
334
+ } });
335
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
336
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
337
+ } });
338
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
339
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
340
+ const type = contentType(request);
341
+ const init = type ? { headers: { "content-type": type } } : void 0;
342
+ return new Response(buf, init).blob();
343
+ });
344
+ } });
345
+ Object.defineProperty(requestPrototype, "json", { value: function() {
346
+ if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
347
+ return this.text().then(JSON.parse);
348
+ } });
349
+ Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
350
+ return `Request (lightweight) ${inspectFn({
351
+ method: this.method,
352
+ url: this.url,
353
+ headers: this.headers,
354
+ nativeRequest: this[requestCache]
355
+ }, {
356
+ ...options,
357
+ depth: depth == null ? null : depth - 1
358
+ })}`;
359
+ } });
360
+ Object.setPrototypeOf(requestPrototype, Request$1.prototype);
361
+ const newRequest = (incoming, defaultHostname) => {
362
+ const req = Object.create(requestPrototype);
363
+ req[incomingKey] = incoming;
364
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
365
+ const incomingUrl = incoming.url || "";
366
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
367
+ if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
368
+ try {
369
+ req[urlKey] = new URL(incomingUrl).href;
370
+ } catch (e) {
371
+ throw new RequestError("Invalid absolute URL", { cause: e });
372
+ }
373
+ return req;
374
+ }
375
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
376
+ if (!host) throw new RequestError("Missing host header");
377
+ let scheme;
378
+ if (incoming instanceof Http2ServerRequest) {
379
+ scheme = incoming.scheme;
380
+ if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
381
+ } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
382
+ try {
383
+ req[urlKey] = buildUrl(scheme, host, incomingUrl);
384
+ } catch (e) {
385
+ if (e instanceof RequestError) throw e;
386
+ else throw new RequestError("Invalid URL", { cause: e });
387
+ }
388
+ return req;
202
389
  };
203
390
 
204
- // src/response.ts
205
- var responseCache = Symbol("responseCache");
206
- var getResponseCache = Symbol("getResponseCache");
207
- var cacheKey = Symbol("cache");
208
- var GlobalResponse = global.Response;
209
- var Response2 = class _Response {
210
- #body;
211
- #init;
212
- [getResponseCache]() {
213
- delete this[cacheKey];
214
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
215
- }
216
- constructor(body, init) {
217
- let headers;
218
- this.#body = body;
219
- if (init instanceof _Response) {
220
- const cachedGlobalResponse = init[responseCache];
221
- if (cachedGlobalResponse) {
222
- this.#init = cachedGlobalResponse;
223
- this[getResponseCache]();
224
- return;
225
- } else {
226
- this.#init = init.#init;
227
- headers = new Headers(init.#init.headers);
228
- }
229
- } else {
230
- this.#init = init;
231
- }
232
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
233
- ;
234
- this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
235
- }
236
- }
237
- get headers() {
238
- const cache = this[cacheKey];
239
- if (cache) {
240
- if (!(cache[2] instanceof Headers)) {
241
- cache[2] = new Headers(
242
- cache[2] || { "content-type": "text/plain; charset=UTF-8" }
243
- );
244
- }
245
- return cache[2];
246
- }
247
- return this[getResponseCache]().headers;
248
- }
249
- get status() {
250
- return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
251
- }
252
- get ok() {
253
- const status = this.status;
254
- return status >= 200 && status < 300;
255
- }
256
- };
257
- ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
258
- Object.defineProperty(Response2.prototype, k, {
259
- get() {
260
- return this[getResponseCache]()[k];
261
- }
262
- });
391
+ //#endregion
392
+ //#region src/response.ts
393
+ const defaultContentType = "text/plain; charset=UTF-8";
394
+ const responseCache = Symbol("responseCache");
395
+ const getResponseCache = Symbol("getResponseCache");
396
+ const cacheKey = Symbol("cache");
397
+ const GlobalResponse = global.Response;
398
+ var Response$1 = class Response$1 {
399
+ #body;
400
+ #init;
401
+ [getResponseCache]() {
402
+ delete this[cacheKey];
403
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
404
+ }
405
+ constructor(body, init) {
406
+ let headers;
407
+ this.#body = body;
408
+ if (init instanceof Response$1) {
409
+ const cachedGlobalResponse = init[responseCache];
410
+ if (cachedGlobalResponse) {
411
+ this.#init = cachedGlobalResponse;
412
+ this[getResponseCache]();
413
+ return;
414
+ } else {
415
+ this.#init = init.#init;
416
+ headers = new Headers(init.#init.headers);
417
+ }
418
+ } else this.#init = init;
419
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
420
+ init?.status || 200,
421
+ body ?? null,
422
+ headers || init?.headers
423
+ ];
424
+ }
425
+ get headers() {
426
+ const cache = this[cacheKey];
427
+ if (cache) {
428
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
429
+ return cache[2];
430
+ }
431
+ return this[getResponseCache]().headers;
432
+ }
433
+ get status() {
434
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
435
+ }
436
+ get ok() {
437
+ const status = this.status;
438
+ return status >= 200 && status < 300;
439
+ }
440
+ };
441
+ [
442
+ "body",
443
+ "bodyUsed",
444
+ "redirected",
445
+ "statusText",
446
+ "trailers",
447
+ "type",
448
+ "url"
449
+ ].forEach((k) => {
450
+ Object.defineProperty(Response$1.prototype, k, { get() {
451
+ return this[getResponseCache]()[k];
452
+ } });
263
453
  });
264
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
265
- Object.defineProperty(Response2.prototype, k, {
266
- value: function() {
267
- return this[getResponseCache]()[k]();
268
- }
269
- });
454
+ [
455
+ "arrayBuffer",
456
+ "blob",
457
+ "clone",
458
+ "formData",
459
+ "json",
460
+ "text"
461
+ ].forEach((k) => {
462
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
463
+ return this[getResponseCache]()[k]();
464
+ } });
465
+ });
466
+ Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
467
+ return `Response (lightweight) ${inspectFn({
468
+ status: this.status,
469
+ headers: this.headers,
470
+ ok: this.ok,
471
+ nativeResponse: this[responseCache]
472
+ }, {
473
+ ...options,
474
+ depth: depth == null ? null : depth - 1
475
+ })}`;
476
+ } });
477
+ Object.setPrototypeOf(Response$1, GlobalResponse);
478
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
479
+ const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
480
+ const parseRedirectUrl = (url) => {
481
+ if (url instanceof URL) return url.href;
482
+ if (validRedirectUrl.test(url)) return url;
483
+ return new URL(url).href;
484
+ };
485
+ const validRedirectStatuses = new Set([
486
+ 301,
487
+ 302,
488
+ 303,
489
+ 307,
490
+ 308
491
+ ]);
492
+ Object.defineProperty(Response$1, "redirect", {
493
+ value: function redirect(url, status = 302) {
494
+ if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
495
+ return new Response$1(null, {
496
+ status,
497
+ headers: { location: parseRedirectUrl(url) }
498
+ });
499
+ },
500
+ writable: true,
501
+ configurable: true
270
502
  });
271
- Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
272
- value: function(depth, options, inspectFn) {
273
- const props = {
274
- status: this.status,
275
- headers: this.headers,
276
- ok: this.ok,
277
- nativeResponse: this[responseCache]
278
- };
279
- return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
280
- }
503
+ Object.defineProperty(Response$1, "json", {
504
+ value: function json(data, init) {
505
+ const body = JSON.stringify(data);
506
+ if (body === void 0) throw new TypeError("The data is not JSON serializable");
507
+ const initHeaders = init?.headers;
508
+ let headers;
509
+ if (initHeaders) {
510
+ headers = new Headers(initHeaders);
511
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
512
+ } else headers = { "content-type": "application/json" };
513
+ return new Response$1(body, {
514
+ status: init?.status ?? 200,
515
+ statusText: init?.statusText,
516
+ headers
517
+ });
518
+ },
519
+ writable: true,
520
+ configurable: true
281
521
  });
282
- Object.setPrototypeOf(Response2, GlobalResponse);
283
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
284
522
 
285
- // src/utils.ts
523
+ //#endregion
524
+ //#region src/utils.ts
286
525
  async function readWithoutBlocking(readPromise) {
287
- return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
526
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
288
527
  }
289
528
  function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
290
- const cancel = (error) => {
291
- reader.cancel(error).catch(() => {
292
- });
293
- };
294
- writable.on("close", cancel);
295
- writable.on("error", cancel);
296
- (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
297
- return reader.closed.finally(() => {
298
- writable.off("close", cancel);
299
- writable.off("error", cancel);
300
- });
301
- function handleStreamError(error) {
302
- if (error) {
303
- writable.destroy(error);
304
- }
305
- }
306
- function onDrain() {
307
- reader.read().then(flow, handleStreamError);
308
- }
309
- function flow({ done, value }) {
310
- try {
311
- if (done) {
312
- writable.end();
313
- } else if (!writable.write(value)) {
314
- writable.once("drain", onDrain);
315
- } else {
316
- return reader.read().then(flow, handleStreamError);
317
- }
318
- } catch (e) {
319
- handleStreamError(e);
320
- }
321
- }
529
+ const cancel = (error) => {
530
+ reader.cancel(error).catch(() => {});
531
+ };
532
+ writable.on("close", cancel);
533
+ writable.on("error", cancel);
534
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
535
+ return reader.closed.finally(() => {
536
+ writable.off("close", cancel);
537
+ writable.off("error", cancel);
538
+ });
539
+ function handleStreamError(error) {
540
+ if (error) writable.destroy(error);
541
+ }
542
+ function onDrain() {
543
+ reader.read().then(flow, handleStreamError);
544
+ }
545
+ function flow({ done, value }) {
546
+ try {
547
+ if (done) writable.end();
548
+ else if (!writable.write(value)) writable.once("drain", onDrain);
549
+ else return reader.read().then(flow, handleStreamError);
550
+ } catch (e) {
551
+ handleStreamError(e);
552
+ }
553
+ }
322
554
  }
323
555
  function writeFromReadableStream(stream, writable) {
324
- if (stream.locked) {
325
- throw new TypeError("ReadableStream is locked.");
326
- } else if (writable.destroyed) {
327
- return;
328
- }
329
- return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
556
+ if (stream.locked) throw new TypeError("ReadableStream is locked.");
557
+ else if (writable.destroyed) return;
558
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
330
559
  }
331
- var buildOutgoingHttpHeaders = (headers) => {
332
- const res = {};
333
- if (!(headers instanceof Headers)) {
334
- headers = new Headers(headers ?? void 0);
335
- }
336
- const cookies = [];
337
- for (const [k, v] of headers) {
338
- if (k === "set-cookie") {
339
- cookies.push(v);
340
- } else {
341
- res[k] = v;
342
- }
343
- }
344
- if (cookies.length > 0) {
345
- res["set-cookie"] = cookies;
346
- }
347
- res["content-type"] ??= "text/plain; charset=UTF-8";
348
- return res;
560
+ const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
561
+ const res = {};
562
+ if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
563
+ if (headers.has("set-cookie")) {
564
+ const cookies = [];
565
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
566
+ else res[k] = v;
567
+ if (cookies.length > 0) res["set-cookie"] = cookies;
568
+ } else for (const [k, v] of headers) res[k] = v;
569
+ if (defaultContentType) res["content-type"] ??= defaultContentType;
570
+ return res;
349
571
  };
350
572
 
351
- // src/utils/response/constants.ts
352
- var X_ALREADY_SENT = "x-hono-already-sent";
353
-
354
- // src/globals.ts
355
- import crypto from "crypto";
356
- if (typeof global.crypto === "undefined") {
357
- global.crypto = crypto;
358
- }
573
+ //#endregion
574
+ //#region src/listener.ts
575
+ const outgoingEnded = Symbol("outgoingEnded");
576
+ const incomingDraining = Symbol("incomingDraining");
577
+ const DRAIN_TIMEOUT_MS = 500;
578
+ const MAX_DRAIN_BYTES = 64 * 1024 * 1024;
579
+ const drainIncoming = (incoming) => {
580
+ const incomingWithDrainState = incoming;
581
+ if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
582
+ incomingWithDrainState[incomingDraining] = true;
583
+ if (incoming instanceof Http2ServerRequest) {
584
+ try {
585
+ incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
586
+ } catch {}
587
+ return;
588
+ }
589
+ let bytesRead = 0;
590
+ const cleanup = () => {
591
+ clearTimeout(timer);
592
+ incoming.off("data", onData);
593
+ incoming.off("end", cleanup);
594
+ incoming.off("error", cleanup);
595
+ };
596
+ const forceClose = () => {
597
+ cleanup();
598
+ const socket = incoming.socket;
599
+ if (socket && !socket.destroyed) socket.destroySoon();
600
+ };
601
+ const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
602
+ timer.unref?.();
603
+ const onData = (chunk) => {
604
+ bytesRead += chunk.length;
605
+ if (bytesRead > MAX_DRAIN_BYTES) forceClose();
606
+ };
607
+ incoming.on("data", onData);
608
+ incoming.on("end", cleanup);
609
+ incoming.on("error", cleanup);
610
+ incoming.resume();
611
+ };
612
+ const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
613
+ if (incoming.errored) req[abortRequest](incoming.errored.toString());
614
+ else if (!outgoing.writableFinished) req[abortRequest]("Client connection prematurely closed.");
615
+ if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
616
+ if (!incoming.readableEnded) setTimeout(() => {
617
+ drainIncoming(incoming);
618
+ });
619
+ });
620
+ };
621
+ const isImmediateCacheableResponse = (res) => {
622
+ if (!(cacheKey in res)) return false;
623
+ const body = res[cacheKey][1];
624
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
625
+ };
626
+ const handleRequestError = () => new Response(null, { status: 400 });
627
+ const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
628
+ const handleResponseError = (e, outgoing) => {
629
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
630
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
631
+ else {
632
+ console.error(e);
633
+ if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
634
+ outgoing.end(`Error: ${err.message}`);
635
+ outgoing.destroy(err);
636
+ }
637
+ };
638
+ const flushHeaders = (outgoing) => {
639
+ if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
640
+ };
641
+ const responseViaCache = async (res, outgoing) => {
642
+ let [status, body, header] = res[cacheKey];
643
+ if (!header) {
644
+ if (body === null) {
645
+ outgoing.writeHead(status);
646
+ outgoing.end();
647
+ } else if (typeof body === "string") {
648
+ outgoing.writeHead(status, {
649
+ "Content-Type": defaultContentType,
650
+ "Content-Length": Buffer.byteLength(body)
651
+ });
652
+ outgoing.end(body);
653
+ } else if (body instanceof Uint8Array) {
654
+ outgoing.writeHead(status, {
655
+ "Content-Type": defaultContentType,
656
+ "Content-Length": body.byteLength
657
+ });
658
+ outgoing.end(body);
659
+ } else if (body instanceof Blob) {
660
+ outgoing.writeHead(status, {
661
+ "Content-Type": defaultContentType,
662
+ "Content-Length": body.size
663
+ });
664
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
665
+ } else {
666
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
667
+ flushHeaders(outgoing);
668
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
669
+ }
670
+ outgoing[outgoingEnded]?.();
671
+ return;
672
+ }
673
+ let hasContentLength = false;
674
+ if (header instanceof Headers) {
675
+ hasContentLength = header.has("content-length");
676
+ header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
677
+ } else if (Array.isArray(header)) {
678
+ const headerObj = new Headers(header);
679
+ hasContentLength = headerObj.has("content-length");
680
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
681
+ } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
682
+ hasContentLength = true;
683
+ break;
684
+ }
685
+ if (!hasContentLength) {
686
+ if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
687
+ else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
688
+ else if (body instanceof Blob) header["Content-Length"] = body.size;
689
+ }
690
+ outgoing.writeHead(status, header);
691
+ if (body == null) outgoing.end();
692
+ else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
693
+ else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
694
+ else {
695
+ flushHeaders(outgoing);
696
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
697
+ }
698
+ outgoing[outgoingEnded]?.();
699
+ };
700
+ const isPromise = (res) => typeof res.then === "function";
701
+ const responseViaResponseObject = async (res, outgoing, options = {}) => {
702
+ if (isPromise(res)) if (options.errorHandler) try {
703
+ res = await res;
704
+ } catch (err) {
705
+ const errRes = await options.errorHandler(err);
706
+ if (!errRes) return;
707
+ res = errRes;
708
+ }
709
+ else res = await res.catch(handleFetchError);
710
+ if (cacheKey in res) return responseViaCache(res, outgoing);
711
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
712
+ if (res.body) {
713
+ const reader = res.body.getReader();
714
+ const values = [];
715
+ let done = false;
716
+ let currentReadPromise = void 0;
717
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
718
+ let maxReadCount = 2;
719
+ for (let i = 0; i < maxReadCount; i++) {
720
+ currentReadPromise ||= reader.read();
721
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
722
+ console.error(e);
723
+ done = true;
724
+ });
725
+ if (!chunk) {
726
+ if (i === 1) {
727
+ await new Promise((resolve) => setTimeout(resolve));
728
+ maxReadCount = 3;
729
+ continue;
730
+ }
731
+ break;
732
+ }
733
+ currentReadPromise = void 0;
734
+ if (chunk.value) values.push(chunk.value);
735
+ if (chunk.done) {
736
+ done = true;
737
+ break;
738
+ }
739
+ }
740
+ if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
741
+ }
742
+ outgoing.writeHead(res.status, resHeaderRecord);
743
+ values.forEach((value) => {
744
+ outgoing.write(value);
745
+ });
746
+ if (done) outgoing.end();
747
+ else {
748
+ if (values.length === 0) flushHeaders(outgoing);
749
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
750
+ }
751
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
752
+ outgoing.writeHead(res.status, resHeaderRecord);
753
+ outgoing.end();
754
+ }
755
+ outgoing[outgoingEnded]?.();
756
+ };
757
+ const getRequestListener = (fetchCallback, options = {}) => {
758
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
759
+ if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
760
+ Object.defineProperty(global, "Request", { value: Request$1 });
761
+ Object.defineProperty(global, "Response", { value: Response$1 });
762
+ }
763
+ return async (incoming, outgoing) => {
764
+ let res, req;
765
+ let needsBodyCleanup = false;
766
+ let closeHandlerAttached = false;
767
+ const ensureCloseHandler = () => {
768
+ if (!req || closeHandlerAttached) return;
769
+ closeHandlerAttached = true;
770
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
771
+ };
772
+ try {
773
+ req = newRequest(incoming, options.hostname);
774
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
775
+ if (needsBodyCleanup) {
776
+ incoming[wrapBodyStream] = true;
777
+ if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
778
+ if (!incoming.readableEnded) setTimeout(() => {
779
+ if (!incoming.readableEnded) setTimeout(() => {
780
+ incoming.destroy();
781
+ outgoing.destroy();
782
+ });
783
+ });
784
+ };
785
+ }
786
+ res = fetchCallback(req, {
787
+ incoming,
788
+ outgoing
789
+ });
790
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
791
+ if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
792
+ if (!incoming.readableEnded) drainIncoming(incoming);
793
+ });
794
+ return responseViaCache(res, outgoing);
795
+ }
796
+ ensureCloseHandler();
797
+ } catch (e) {
798
+ if (!res) if (options.errorHandler) {
799
+ ensureCloseHandler();
800
+ res = await options.errorHandler(req ? e : toRequestError(e));
801
+ if (!res) return;
802
+ } else if (!req) res = handleRequestError();
803
+ else res = handleFetchError(e);
804
+ else return handleResponseError(e, outgoing);
805
+ }
806
+ try {
807
+ return await responseViaResponseObject(res, outgoing, options);
808
+ } catch (e) {
809
+ return handleResponseError(e, outgoing);
810
+ }
811
+ };
812
+ };
359
813
 
360
- // src/listener.ts
361
- var outgoingEnded = Symbol("outgoingEnded");
362
- var incomingDraining = Symbol("incomingDraining");
363
- var DRAIN_TIMEOUT_MS = 500;
364
- var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
365
- var drainIncoming = (incoming) => {
366
- const incomingWithDrainState = incoming;
367
- if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
368
- return;
369
- }
370
- incomingWithDrainState[incomingDraining] = true;
371
- if (incoming instanceof Http2ServerRequest2) {
372
- try {
373
- ;
374
- incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
375
- } catch {
376
- }
377
- return;
378
- }
379
- let bytesRead = 0;
380
- const cleanup = () => {
381
- clearTimeout(timer);
382
- incoming.off("data", onData);
383
- incoming.off("end", cleanup);
384
- incoming.off("error", cleanup);
385
- };
386
- const forceClose = () => {
387
- cleanup();
388
- const socket = incoming.socket;
389
- if (socket && !socket.destroyed) {
390
- socket.destroySoon();
391
- }
392
- };
393
- const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
394
- timer.unref?.();
395
- const onData = (chunk) => {
396
- bytesRead += chunk.length;
397
- if (bytesRead > MAX_DRAIN_BYTES) {
398
- forceClose();
399
- }
400
- };
401
- incoming.on("data", onData);
402
- incoming.on("end", cleanup);
403
- incoming.on("error", cleanup);
404
- incoming.resume();
405
- };
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
- });
412
- var handleResponseError = (e, outgoing) => {
413
- 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 {
417
- console.error(e);
418
- if (!outgoing.headersSent) {
419
- outgoing.writeHead(500, { "Content-Type": "text/plain" });
420
- }
421
- outgoing.end(`Error: ${err.message}`);
422
- outgoing.destroy(err);
423
- }
424
- };
425
- var flushHeaders = (outgoing) => {
426
- if ("flushHeaders" in outgoing && outgoing.writable) {
427
- outgoing.flushHeaders();
428
- }
429
- };
430
- var responseViaCache = async (res, outgoing) => {
431
- let [status, body, header] = res[cacheKey];
432
- let hasContentLength = false;
433
- if (!header) {
434
- header = { "content-type": "text/plain; charset=UTF-8" };
435
- } else if (header instanceof Headers) {
436
- hasContentLength = header.has("content-length");
437
- header = buildOutgoingHttpHeaders(header);
438
- } else if (Array.isArray(header)) {
439
- const headerObj = new Headers(header);
440
- 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
- }
449
- }
450
- 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
- }
458
- }
459
- 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 {
465
- flushHeaders(outgoing);
466
- await writeFromReadableStream(body, outgoing)?.catch(
467
- (e) => handleResponseError(e, outgoing)
468
- );
469
- }
470
- ;
471
- outgoing[outgoingEnded]?.();
472
- };
473
- var isPromise = (res) => typeof res.then === "function";
474
- 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);
494
- if (res.body) {
495
- const reader = res.body.getReader();
496
- const values = [];
497
- let done = false;
498
- let currentReadPromise = void 0;
499
- if (resHeaderRecord["transfer-encoding"] !== "chunked") {
500
- let maxReadCount = 2;
501
- for (let i = 0; i < maxReadCount; i++) {
502
- currentReadPromise ||= reader.read();
503
- const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
504
- console.error(e);
505
- done = true;
506
- });
507
- if (!chunk) {
508
- if (i === 1) {
509
- await new Promise((resolve) => setTimeout(resolve));
510
- maxReadCount = 3;
511
- continue;
512
- }
513
- break;
514
- }
515
- currentReadPromise = void 0;
516
- if (chunk.value) {
517
- values.push(chunk.value);
518
- }
519
- if (chunk.done) {
520
- done = true;
521
- break;
522
- }
523
- }
524
- if (done && !("content-length" in resHeaderRecord)) {
525
- resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
526
- }
527
- }
528
- outgoing.writeHead(res.status, resHeaderRecord);
529
- values.forEach((value) => {
530
- ;
531
- outgoing.write(value);
532
- });
533
- if (done) {
534
- outgoing.end();
535
- } else {
536
- if (values.length === 0) {
537
- flushHeaders(outgoing);
538
- }
539
- await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
540
- }
541
- } else if (resHeaderRecord[X_ALREADY_SENT]) {
542
- } else {
543
- outgoing.writeHead(res.status, resHeaderRecord);
544
- outgoing.end();
545
- }
546
- ;
547
- outgoing[outgoingEnded]?.();
548
- };
549
- var getRequestListener = (fetchCallback, options = {}) => {
550
- const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
551
- if (options.overrideGlobalObjects !== false && global.Request !== Request) {
552
- Object.defineProperty(global, "Request", {
553
- value: Request
554
- });
555
- Object.defineProperty(global, "Response", {
556
- value: Response2
557
- });
558
- }
559
- return async (incoming, outgoing) => {
560
- let res, req;
561
- try {
562
- req = newRequest(incoming, options.hostname);
563
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
564
- if (!incomingEnded) {
565
- ;
566
- 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
- }
606
- });
607
- }
608
- });
609
- res = fetchCallback(req, { incoming, outgoing });
610
- if (cacheKey in res) {
611
- return responseViaCache(res, outgoing);
612
- }
613
- } 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
- }
628
- }
629
- try {
630
- return await responseViaResponseObject(res, outgoing, options);
631
- } catch (e) {
632
- return handleResponseError(e, outgoing);
633
- }
634
- };
814
+ //#endregion
815
+ //#region src/websocket.ts
816
+ /**
817
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
818
+ */
819
+ const CloseEvent = globalThis.CloseEvent ?? class extends Event {
820
+ #eventInitDict;
821
+ constructor(type, eventInitDict = {}) {
822
+ super(type, eventInitDict);
823
+ this.#eventInitDict = eventInitDict;
824
+ }
825
+ get wasClean() {
826
+ return this.#eventInitDict.wasClean ?? false;
827
+ }
828
+ get code() {
829
+ return this.#eventInitDict.code ?? 0;
830
+ }
831
+ get reason() {
832
+ return this.#eventInitDict.reason ?? "";
833
+ }
834
+ };
835
+ const generateConnectionSymbol = () => Symbol("connection");
836
+ const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
837
+ const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
838
+ const rejectUpgradeRequest = (socket, status) => {
839
+ socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\nConnection: close\r
840
+ Content-Length: 0\r
841
+ \r
842
+ `);
635
843
  };
844
+ const createUpgradeRequest = (request) => {
845
+ const protocol = request.socket.encrypted ? "https" : "http";
846
+ const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
847
+ const headers = new Headers();
848
+ for (const key in request.headers) {
849
+ const value = request.headers[key];
850
+ if (!value) continue;
851
+ headers.append(key, Array.isArray(value) ? value[0] : value);
852
+ }
853
+ return new Request(url, { headers });
854
+ };
855
+ const setupWebSocket = (options) => {
856
+ const { server, fetchCallback, wss } = options;
857
+ const waiterMap = /* @__PURE__ */ new Map();
858
+ wss.on("connection", (ws, request) => {
859
+ const waiter = waiterMap.get(request);
860
+ if (waiter) {
861
+ waiter.resolve(ws);
862
+ waiterMap.delete(request);
863
+ }
864
+ });
865
+ const waitForWebSocket = (request, connectionSymbol) => {
866
+ return new Promise((resolve) => {
867
+ waiterMap.set(request, {
868
+ resolve,
869
+ connectionSymbol
870
+ });
871
+ });
872
+ };
873
+ server.on("upgrade", async (request, socket, head) => {
874
+ if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
875
+ const env = {
876
+ incoming: request,
877
+ outgoing: void 0,
878
+ wss,
879
+ [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
880
+ };
881
+ let status = 400;
882
+ try {
883
+ const response = await fetchCallback(createUpgradeRequest(request), env);
884
+ if (response instanceof Response) status = response.status;
885
+ } catch {
886
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
887
+ return;
888
+ }
889
+ const waiter = waiterMap.get(request);
890
+ if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
891
+ waiterMap.delete(request);
892
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status);
893
+ return;
894
+ }
895
+ wss.handleUpgrade(request, socket, head, (ws) => {
896
+ wss.emit("connection", ws, request);
897
+ });
898
+ });
899
+ server.on("close", () => {
900
+ wss.close();
901
+ });
902
+ };
903
+ const upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {
904
+ if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return;
905
+ const env = c.env;
906
+ const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
907
+ if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });
908
+ const connectionSymbol = generateConnectionSymbol();
909
+ env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
910
+ (async () => {
911
+ const ws = await waitForWebSocket(env.incoming, connectionSymbol);
912
+ const messagesReceivedInStarting = [];
913
+ const bufferMessage = (data, isBinary) => {
914
+ messagesReceivedInStarting.push([data, isBinary]);
915
+ };
916
+ ws.on("message", bufferMessage);
917
+ const ctx = {
918
+ binaryType: "arraybuffer",
919
+ close(code, reason) {
920
+ ws.close(code, reason);
921
+ },
922
+ protocol: ws.protocol,
923
+ raw: ws,
924
+ get readyState() {
925
+ return ws.readyState;
926
+ },
927
+ send(source, opts) {
928
+ ws.send(source, { compress: opts?.compress });
929
+ },
930
+ url: new URL(c.req.url)
931
+ };
932
+ try {
933
+ events?.onOpen?.(new Event("open"), ctx);
934
+ } catch (e) {
935
+ (options?.onError ?? console.error)(e);
936
+ }
937
+ const handleMessage = (data, isBinary) => {
938
+ const datas = Array.isArray(data) ? data : [data];
939
+ for (const data of datas) try {
940
+ events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : data.toString("utf-8") }), ctx);
941
+ } catch (e) {
942
+ (options?.onError ?? console.error)(e);
943
+ }
944
+ };
945
+ ws.off("message", bufferMessage);
946
+ for (const message of messagesReceivedInStarting) handleMessage(...message);
947
+ ws.on("message", (data, isBinary) => {
948
+ handleMessage(data, isBinary);
949
+ });
950
+ ws.on("close", (code, reason) => {
951
+ try {
952
+ events?.onClose?.(new CloseEvent("close", {
953
+ code,
954
+ reason: reason.toString()
955
+ }), ctx);
956
+ } catch (e) {
957
+ (options?.onError ?? console.error)(e);
958
+ }
959
+ });
960
+ ws.on("error", (error) => {
961
+ try {
962
+ events?.onError?.(new ErrorEvent("error", { error }), ctx);
963
+ } catch (e) {
964
+ (options?.onError ?? console.error)(e);
965
+ }
966
+ });
967
+ })();
968
+ return new Response();
969
+ });
636
970
 
637
- // src/server.ts
638
- var createAdaptorServer = (options) => {
639
- const fetchCallback = options.fetch;
640
- const requestListener = getRequestListener(fetchCallback, {
641
- hostname: options.hostname,
642
- overrideGlobalObjects: options.overrideGlobalObjects,
643
- autoCleanupIncoming: options.autoCleanupIncoming
644
- });
645
- const createServer = options.createServer || createServerHTTP;
646
- const server = createServer(options.serverOptions || {}, requestListener);
647
- return server;
648
- };
649
- var serve = (options, listeningListener) => {
650
- const server = createAdaptorServer(options);
651
- server.listen(options?.port ?? 3e3, options.hostname, () => {
652
- const serverInfo = server.address();
653
- listeningListener && listeningListener(serverInfo);
654
- });
655
- return server;
656
- };
657
- export {
658
- RequestError,
659
- createAdaptorServer,
660
- getRequestListener,
661
- serve
971
+ //#endregion
972
+ //#region src/server.ts
973
+ const createAdaptorServer = (options) => {
974
+ const fetchCallback = options.fetch;
975
+ const requestListener = getRequestListener(fetchCallback, {
976
+ hostname: options.hostname,
977
+ overrideGlobalObjects: options.overrideGlobalObjects,
978
+ autoCleanupIncoming: options.autoCleanupIncoming
979
+ });
980
+ const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
981
+ if (options.websocket && options.websocket.server) {
982
+ if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
983
+ setupWebSocket({
984
+ server,
985
+ fetchCallback,
986
+ wss: options.websocket.server
987
+ });
988
+ }
989
+ return server;
662
990
  };
991
+ const serve = (options, listeningListener) => {
992
+ const server = createAdaptorServer(options);
993
+ server.listen(options?.port ?? 3e3, options.hostname, () => {
994
+ const serverInfo = server.address();
995
+ listeningListener && listeningListener(serverInfo);
996
+ });
997
+ return server;
998
+ };
999
+
1000
+ //#endregion
1001
+ export { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };