@hono/node-server 1.2.3 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/listener.mjs CHANGED
@@ -1,21 +1,5 @@
1
- // src/listener.ts
2
- import { Readable } from "stream";
3
-
4
1
  // src/globals.ts
5
2
  import crypto from "crypto";
6
- var webFetch = global.fetch;
7
- if (typeof global.crypto === "undefined") {
8
- global.crypto = crypto;
9
- }
10
- global.fetch = (info, init) => {
11
- init = {
12
- // Disable compression handling so people can return the result of a fetch
13
- // directly in the loader without messing with the Content-Encoding header.
14
- compress: false,
15
- ...init
16
- };
17
- return webFetch(info, init);
18
- };
19
3
 
20
4
  // src/utils.ts
21
5
  function writeFromReadableStream(stream, writable) {
@@ -56,75 +40,239 @@ function writeFromReadableStream(stream, writable) {
56
40
  }
57
41
  }
58
42
  }
43
+ var buildOutgoingHttpHeaders = (headers) => {
44
+ const res = {};
45
+ const cookies = [];
46
+ for (const [k, v] of headers) {
47
+ if (k === "set-cookie") {
48
+ cookies.push(v);
49
+ } else {
50
+ res[k] = v;
51
+ }
52
+ }
53
+ if (cookies.length > 0) {
54
+ res["set-cookie"] = cookies;
55
+ }
56
+ res["content-type"] ??= "text/plain;charset=UTF-8";
57
+ return res;
58
+ };
59
+
60
+ // src/response.ts
61
+ var responseCache = Symbol("responseCache");
62
+ var cacheKey = Symbol("cache");
63
+ var globalResponse = global.Response;
64
+ var Response2 = class {
65
+ #body;
66
+ #init;
67
+ // @ts-ignore
68
+ get cache() {
69
+ delete this[cacheKey];
70
+ return this[responseCache] ||= new globalResponse(this.#body, this.#init);
71
+ }
72
+ constructor(body, init) {
73
+ this.#body = body;
74
+ this.#init = init;
75
+ if (typeof body === "string" || body instanceof ReadableStream) {
76
+ let headers = init?.headers || { "content-type": "text/plain;charset=UTF-8" };
77
+ if (headers instanceof Headers) {
78
+ headers = buildOutgoingHttpHeaders(headers);
79
+ }
80
+ this[cacheKey] = [init?.status || 200, body, headers];
81
+ }
82
+ }
83
+ };
84
+ [
85
+ "body",
86
+ "bodyUsed",
87
+ "headers",
88
+ "ok",
89
+ "redirected",
90
+ "status",
91
+ "statusText",
92
+ "trailers",
93
+ "type",
94
+ "url"
95
+ ].forEach((k) => {
96
+ Object.defineProperty(Response2.prototype, k, {
97
+ get() {
98
+ return this.cache[k];
99
+ }
100
+ });
101
+ });
102
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
103
+ Object.defineProperty(Response2.prototype, k, {
104
+ value: function() {
105
+ return this.cache[k]();
106
+ }
107
+ });
108
+ });
109
+ Object.setPrototypeOf(Response2, globalResponse);
110
+ Object.setPrototypeOf(Response2.prototype, globalResponse.prototype);
111
+ Object.defineProperty(global, "Response", {
112
+ value: Response2
113
+ });
114
+
115
+ // src/globals.ts
116
+ Object.defineProperty(global, "Response", {
117
+ value: Response2
118
+ });
119
+ var webFetch = global.fetch;
120
+ if (typeof global.crypto === "undefined") {
121
+ global.crypto = crypto;
122
+ }
123
+ global.fetch = (info, init) => {
124
+ init = {
125
+ // Disable compression handling so people can return the result of a fetch
126
+ // directly in the loader without messing with the Content-Encoding header.
127
+ compress: false,
128
+ ...init
129
+ };
130
+ return webFetch(info, init);
131
+ };
132
+
133
+ // src/request.ts
134
+ import { Readable } from "stream";
135
+ var newRequestFromIncoming = (method, url, incoming) => {
136
+ const headerRecord = [];
137
+ const len = incoming.rawHeaders.length;
138
+ for (let i = 0; i < len; i += 2) {
139
+ headerRecord.push([incoming.rawHeaders[i], incoming.rawHeaders[i + 1]]);
140
+ }
141
+ const init = {
142
+ method,
143
+ headers: headerRecord
144
+ };
145
+ if (!(method === "GET" || method === "HEAD")) {
146
+ init.body = Readable.toWeb(incoming);
147
+ init.duplex = "half";
148
+ }
149
+ return new Request(url, init);
150
+ };
151
+ var getRequestCache = Symbol("getRequestCache");
152
+ var requestCache = Symbol("requestCache");
153
+ var incomingKey = Symbol("incomingKey");
154
+ var requestPrototype = {
155
+ get method() {
156
+ return this[incomingKey].method || "GET";
157
+ },
158
+ get url() {
159
+ return `http://${this[incomingKey].headers.host}${this[incomingKey].url}`;
160
+ },
161
+ [getRequestCache]() {
162
+ return this[requestCache] ||= newRequestFromIncoming(this.method, this.url, this[incomingKey]);
163
+ }
164
+ };
165
+ [
166
+ "body",
167
+ "bodyUsed",
168
+ "cache",
169
+ "credentials",
170
+ "destination",
171
+ "headers",
172
+ "integrity",
173
+ "mode",
174
+ "redirect",
175
+ "referrer",
176
+ "referrerPolicy",
177
+ "signal"
178
+ ].forEach((k) => {
179
+ Object.defineProperty(requestPrototype, k, {
180
+ get() {
181
+ return this[getRequestCache]()[k];
182
+ }
183
+ });
184
+ });
185
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
186
+ Object.defineProperty(requestPrototype, k, {
187
+ value: function() {
188
+ return this[getRequestCache]()[k]();
189
+ }
190
+ });
191
+ });
192
+ Object.setPrototypeOf(requestPrototype, global.Request.prototype);
193
+ var newRequest = (incoming) => {
194
+ const req = Object.create(requestPrototype);
195
+ req[incomingKey] = incoming;
196
+ return req;
197
+ };
59
198
 
60
199
  // src/listener.ts
61
200
  var regBuffer = /^no$/i;
62
201
  var regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
63
- var getRequestListener = (fetchCallback) => {
64
- return async (incoming, outgoing) => {
65
- const method = incoming.method || "GET";
66
- const url = `http://${incoming.headers.host}${incoming.url}`;
67
- const headerRecord = [];
68
- const len = incoming.rawHeaders.length;
69
- for (let i = 0; i < len; i += 2) {
70
- headerRecord.push([incoming.rawHeaders[i], incoming.rawHeaders[i + 1]]);
71
- }
72
- const init = {
73
- method,
74
- headers: headerRecord
75
- };
76
- if (!(method === "GET" || method === "HEAD")) {
77
- init.body = Readable.toWeb(incoming);
78
- init.duplex = "half";
79
- }
80
- let res;
202
+ var handleFetchError = (e) => new Response(null, {
203
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
204
+ });
205
+ var handleResponseError = (e, outgoing) => {
206
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
207
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
208
+ console.info("The user aborted a request.");
209
+ } else {
210
+ console.error(e);
211
+ outgoing.destroy(err);
212
+ }
213
+ };
214
+ var responseViaCache = (res, outgoing) => {
215
+ const [status, body, header] = res[cacheKey];
216
+ if (typeof body === "string") {
217
+ header["Content-Length"] = Buffer.byteLength(body);
218
+ outgoing.writeHead(status, header);
219
+ outgoing.end(body);
220
+ } else {
221
+ outgoing.writeHead(status, header);
222
+ return writeFromReadableStream(body, outgoing)?.catch(
223
+ (e) => handleResponseError(e, outgoing)
224
+ );
225
+ }
226
+ };
227
+ var responseViaResponseObject = async (res, outgoing) => {
228
+ if (res instanceof Promise) {
229
+ res = await res.catch(handleFetchError);
230
+ }
231
+ if (cacheKey in res) {
81
232
  try {
82
- res = await fetchCallback(new Request(url, init));
233
+ return responseViaCache(res, outgoing);
83
234
  } catch (e) {
84
- res = new Response(null, { status: 500 });
85
- if (e instanceof Error) {
86
- if (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") {
87
- res = new Response(null, { status: 504 });
88
- }
89
- }
235
+ return handleResponseError(e, outgoing);
90
236
  }
91
- const resHeaderRecord = {};
92
- const cookies = [];
93
- for (const [k, v] of res.headers) {
94
- if (k === "set-cookie") {
95
- cookies.push(v);
237
+ }
238
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
239
+ if (res.body) {
240
+ try {
241
+ if (resHeaderRecord["transfer-encoding"] || resHeaderRecord["content-encoding"] || resHeaderRecord["content-length"] || // nginx buffering variant
242
+ resHeaderRecord["x-accel-buffering"] && regBuffer.test(resHeaderRecord["x-accel-buffering"]) || !regContentType.test(resHeaderRecord["content-type"])) {
243
+ outgoing.writeHead(res.status, resHeaderRecord);
244
+ await writeFromReadableStream(res.body, outgoing);
96
245
  } else {
97
- resHeaderRecord[k] = v;
246
+ const buffer = await res.arrayBuffer();
247
+ resHeaderRecord["content-length"] = buffer.byteLength;
248
+ outgoing.writeHead(res.status, resHeaderRecord);
249
+ outgoing.end(new Uint8Array(buffer));
98
250
  }
251
+ } catch (e) {
252
+ handleResponseError(e, outgoing);
99
253
  }
100
- if (cookies.length > 0) {
101
- resHeaderRecord["set-cookie"] = cookies;
102
- }
103
- if (res.body) {
104
- try {
105
- if (resHeaderRecord["transfer-encoding"] || resHeaderRecord["content-encoding"] || resHeaderRecord["content-length"] || // nginx buffering variant
106
- resHeaderRecord["x-accel-buffering"] && regBuffer.test(resHeaderRecord["x-accel-buffering"]) || !regContentType.test(resHeaderRecord["content-type"])) {
107
- outgoing.writeHead(res.status, resHeaderRecord);
108
- await writeFromReadableStream(res.body, outgoing);
109
- } else {
110
- const buffer = await res.arrayBuffer();
111
- resHeaderRecord["content-length"] = buffer.byteLength;
112
- outgoing.writeHead(res.status, resHeaderRecord);
113
- outgoing.end(new Uint8Array(buffer));
114
- }
115
- } catch (e) {
116
- const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
117
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
118
- console.info("The user aborted a request.");
119
- } else {
120
- console.error(e);
121
- outgoing.destroy(err);
122
- }
254
+ } else {
255
+ outgoing.writeHead(res.status, resHeaderRecord);
256
+ outgoing.end();
257
+ }
258
+ };
259
+ var getRequestListener = (fetchCallback) => {
260
+ return (incoming, outgoing) => {
261
+ let res;
262
+ const req = newRequest(incoming);
263
+ try {
264
+ res = fetchCallback(req);
265
+ if (cacheKey in res) {
266
+ return responseViaCache(res, outgoing);
267
+ }
268
+ } catch (e) {
269
+ if (!res) {
270
+ res = handleFetchError(e);
271
+ } else {
272
+ return handleResponseError(e, outgoing);
123
273
  }
124
- } else {
125
- outgoing.writeHead(res.status, resHeaderRecord);
126
- outgoing.end();
127
274
  }
275
+ return responseViaResponseObject(res, outgoing);
128
276
  };
129
277
  };
130
278
  export {
@@ -0,0 +1,6 @@
1
+ import { IncomingMessage } from 'node:http';
2
+ import { Http2ServerRequest } from 'node:http2';
3
+
4
+ declare const newRequest: (incoming: IncomingMessage | Http2ServerRequest) => any;
5
+
6
+ export { newRequest };
@@ -0,0 +1,6 @@
1
+ import { IncomingMessage } from 'node:http';
2
+ import { Http2ServerRequest } from 'node:http2';
3
+
4
+ declare const newRequest: (incoming: IncomingMessage | Http2ServerRequest) => any;
5
+
6
+ export { newRequest };
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/request.ts
21
+ var request_exports = {};
22
+ __export(request_exports, {
23
+ newRequest: () => newRequest
24
+ });
25
+ module.exports = __toCommonJS(request_exports);
26
+ var import_node_stream = require("stream");
27
+ var newRequestFromIncoming = (method, url, incoming) => {
28
+ const headerRecord = [];
29
+ const len = incoming.rawHeaders.length;
30
+ for (let i = 0; i < len; i += 2) {
31
+ headerRecord.push([incoming.rawHeaders[i], incoming.rawHeaders[i + 1]]);
32
+ }
33
+ const init = {
34
+ method,
35
+ headers: headerRecord
36
+ };
37
+ if (!(method === "GET" || method === "HEAD")) {
38
+ init.body = import_node_stream.Readable.toWeb(incoming);
39
+ init.duplex = "half";
40
+ }
41
+ return new Request(url, init);
42
+ };
43
+ var getRequestCache = Symbol("getRequestCache");
44
+ var requestCache = Symbol("requestCache");
45
+ var incomingKey = Symbol("incomingKey");
46
+ var requestPrototype = {
47
+ get method() {
48
+ return this[incomingKey].method || "GET";
49
+ },
50
+ get url() {
51
+ return `http://${this[incomingKey].headers.host}${this[incomingKey].url}`;
52
+ },
53
+ [getRequestCache]() {
54
+ return this[requestCache] ||= newRequestFromIncoming(this.method, this.url, this[incomingKey]);
55
+ }
56
+ };
57
+ [
58
+ "body",
59
+ "bodyUsed",
60
+ "cache",
61
+ "credentials",
62
+ "destination",
63
+ "headers",
64
+ "integrity",
65
+ "mode",
66
+ "redirect",
67
+ "referrer",
68
+ "referrerPolicy",
69
+ "signal"
70
+ ].forEach((k) => {
71
+ Object.defineProperty(requestPrototype, k, {
72
+ get() {
73
+ return this[getRequestCache]()[k];
74
+ }
75
+ });
76
+ });
77
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
78
+ Object.defineProperty(requestPrototype, k, {
79
+ value: function() {
80
+ return this[getRequestCache]()[k]();
81
+ }
82
+ });
83
+ });
84
+ Object.setPrototypeOf(requestPrototype, global.Request.prototype);
85
+ var newRequest = (incoming) => {
86
+ const req = Object.create(requestPrototype);
87
+ req[incomingKey] = incoming;
88
+ return req;
89
+ };
90
+ // Annotate the CommonJS export names for ESM import in node:
91
+ 0 && (module.exports = {
92
+ newRequest
93
+ });
@@ -0,0 +1,68 @@
1
+ // src/request.ts
2
+ import { Readable } from "stream";
3
+ var newRequestFromIncoming = (method, url, incoming) => {
4
+ const headerRecord = [];
5
+ const len = incoming.rawHeaders.length;
6
+ for (let i = 0; i < len; i += 2) {
7
+ headerRecord.push([incoming.rawHeaders[i], incoming.rawHeaders[i + 1]]);
8
+ }
9
+ const init = {
10
+ method,
11
+ headers: headerRecord
12
+ };
13
+ if (!(method === "GET" || method === "HEAD")) {
14
+ init.body = Readable.toWeb(incoming);
15
+ init.duplex = "half";
16
+ }
17
+ return new Request(url, init);
18
+ };
19
+ var getRequestCache = Symbol("getRequestCache");
20
+ var requestCache = Symbol("requestCache");
21
+ var incomingKey = Symbol("incomingKey");
22
+ var requestPrototype = {
23
+ get method() {
24
+ return this[incomingKey].method || "GET";
25
+ },
26
+ get url() {
27
+ return `http://${this[incomingKey].headers.host}${this[incomingKey].url}`;
28
+ },
29
+ [getRequestCache]() {
30
+ return this[requestCache] ||= newRequestFromIncoming(this.method, this.url, this[incomingKey]);
31
+ }
32
+ };
33
+ [
34
+ "body",
35
+ "bodyUsed",
36
+ "cache",
37
+ "credentials",
38
+ "destination",
39
+ "headers",
40
+ "integrity",
41
+ "mode",
42
+ "redirect",
43
+ "referrer",
44
+ "referrerPolicy",
45
+ "signal"
46
+ ].forEach((k) => {
47
+ Object.defineProperty(requestPrototype, k, {
48
+ get() {
49
+ return this[getRequestCache]()[k];
50
+ }
51
+ });
52
+ });
53
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
54
+ Object.defineProperty(requestPrototype, k, {
55
+ value: function() {
56
+ return this[getRequestCache]()[k]();
57
+ }
58
+ });
59
+ });
60
+ Object.setPrototypeOf(requestPrototype, global.Request.prototype);
61
+ var newRequest = (incoming) => {
62
+ const req = Object.create(requestPrototype);
63
+ req[incomingKey] = incoming;
64
+ return req;
65
+ };
66
+ export {
67
+ newRequest
68
+ };
@@ -0,0 +1,15 @@
1
+ declare const cacheKey: unique symbol;
2
+ declare const globalResponse: {
3
+ new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): globalThis.Response;
4
+ prototype: globalThis.Response;
5
+ error(): globalThis.Response;
6
+ json(data: any, init?: ResponseInit | undefined): globalThis.Response;
7
+ redirect(url: string | URL, status?: number | undefined): globalThis.Response;
8
+ };
9
+ declare class Response {
10
+ #private;
11
+ private get cache();
12
+ constructor(body?: BodyInit | null, init?: ResponseInit);
13
+ }
14
+
15
+ export { Response, cacheKey, globalResponse };
@@ -0,0 +1,15 @@
1
+ declare const cacheKey: unique symbol;
2
+ declare const globalResponse: {
3
+ new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): globalThis.Response;
4
+ prototype: globalThis.Response;
5
+ error(): globalThis.Response;
6
+ json(data: any, init?: ResponseInit | undefined): globalThis.Response;
7
+ redirect(url: string | URL, status?: number | undefined): globalThis.Response;
8
+ };
9
+ declare class Response {
10
+ #private;
11
+ private get cache();
12
+ constructor(body?: BodyInit | null, init?: ResponseInit);
13
+ }
14
+
15
+ export { Response, cacheKey, globalResponse };
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/response.ts
21
+ var response_exports = {};
22
+ __export(response_exports, {
23
+ Response: () => Response,
24
+ cacheKey: () => cacheKey,
25
+ globalResponse: () => globalResponse
26
+ });
27
+ module.exports = __toCommonJS(response_exports);
28
+
29
+ // src/utils.ts
30
+ var buildOutgoingHttpHeaders = (headers) => {
31
+ const res = {};
32
+ const cookies = [];
33
+ for (const [k, v] of headers) {
34
+ if (k === "set-cookie") {
35
+ cookies.push(v);
36
+ } else {
37
+ res[k] = v;
38
+ }
39
+ }
40
+ if (cookies.length > 0) {
41
+ res["set-cookie"] = cookies;
42
+ }
43
+ res["content-type"] ??= "text/plain;charset=UTF-8";
44
+ return res;
45
+ };
46
+
47
+ // src/response.ts
48
+ var responseCache = Symbol("responseCache");
49
+ var cacheKey = Symbol("cache");
50
+ var globalResponse = global.Response;
51
+ var Response = class {
52
+ #body;
53
+ #init;
54
+ // @ts-ignore
55
+ get cache() {
56
+ delete this[cacheKey];
57
+ return this[responseCache] ||= new globalResponse(this.#body, this.#init);
58
+ }
59
+ constructor(body, init) {
60
+ this.#body = body;
61
+ this.#init = init;
62
+ if (typeof body === "string" || body instanceof ReadableStream) {
63
+ let headers = init?.headers || { "content-type": "text/plain;charset=UTF-8" };
64
+ if (headers instanceof Headers) {
65
+ headers = buildOutgoingHttpHeaders(headers);
66
+ }
67
+ this[cacheKey] = [init?.status || 200, body, headers];
68
+ }
69
+ }
70
+ };
71
+ [
72
+ "body",
73
+ "bodyUsed",
74
+ "headers",
75
+ "ok",
76
+ "redirected",
77
+ "status",
78
+ "statusText",
79
+ "trailers",
80
+ "type",
81
+ "url"
82
+ ].forEach((k) => {
83
+ Object.defineProperty(Response.prototype, k, {
84
+ get() {
85
+ return this.cache[k];
86
+ }
87
+ });
88
+ });
89
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
90
+ Object.defineProperty(Response.prototype, k, {
91
+ value: function() {
92
+ return this.cache[k]();
93
+ }
94
+ });
95
+ });
96
+ Object.setPrototypeOf(Response, globalResponse);
97
+ Object.setPrototypeOf(Response.prototype, globalResponse.prototype);
98
+ Object.defineProperty(global, "Response", {
99
+ value: Response
100
+ });
101
+ // Annotate the CommonJS export names for ESM import in node:
102
+ 0 && (module.exports = {
103
+ Response,
104
+ cacheKey,
105
+ globalResponse
106
+ });