@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/globals.js CHANGED
@@ -24,6 +24,84 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
 
25
25
  // src/globals.ts
26
26
  var import_node_crypto = __toESM(require("crypto"));
27
+
28
+ // src/utils.ts
29
+ var buildOutgoingHttpHeaders = (headers) => {
30
+ const res = {};
31
+ const cookies = [];
32
+ for (const [k, v] of headers) {
33
+ if (k === "set-cookie") {
34
+ cookies.push(v);
35
+ } else {
36
+ res[k] = v;
37
+ }
38
+ }
39
+ if (cookies.length > 0) {
40
+ res["set-cookie"] = cookies;
41
+ }
42
+ res["content-type"] ??= "text/plain;charset=UTF-8";
43
+ return res;
44
+ };
45
+
46
+ // src/response.ts
47
+ var responseCache = Symbol("responseCache");
48
+ var cacheKey = Symbol("cache");
49
+ var globalResponse = global.Response;
50
+ var Response = class {
51
+ #body;
52
+ #init;
53
+ // @ts-ignore
54
+ get cache() {
55
+ delete this[cacheKey];
56
+ return this[responseCache] ||= new globalResponse(this.#body, this.#init);
57
+ }
58
+ constructor(body, init) {
59
+ this.#body = body;
60
+ this.#init = init;
61
+ if (typeof body === "string" || body instanceof ReadableStream) {
62
+ let headers = init?.headers || { "content-type": "text/plain;charset=UTF-8" };
63
+ if (headers instanceof Headers) {
64
+ headers = buildOutgoingHttpHeaders(headers);
65
+ }
66
+ this[cacheKey] = [init?.status || 200, body, headers];
67
+ }
68
+ }
69
+ };
70
+ [
71
+ "body",
72
+ "bodyUsed",
73
+ "headers",
74
+ "ok",
75
+ "redirected",
76
+ "status",
77
+ "statusText",
78
+ "trailers",
79
+ "type",
80
+ "url"
81
+ ].forEach((k) => {
82
+ Object.defineProperty(Response.prototype, k, {
83
+ get() {
84
+ return this.cache[k];
85
+ }
86
+ });
87
+ });
88
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
89
+ Object.defineProperty(Response.prototype, k, {
90
+ value: function() {
91
+ return this.cache[k]();
92
+ }
93
+ });
94
+ });
95
+ Object.setPrototypeOf(Response, globalResponse);
96
+ Object.setPrototypeOf(Response.prototype, globalResponse.prototype);
97
+ Object.defineProperty(global, "Response", {
98
+ value: Response
99
+ });
100
+
101
+ // src/globals.ts
102
+ Object.defineProperty(global, "Response", {
103
+ value: Response
104
+ });
27
105
  var webFetch = global.fetch;
28
106
  if (typeof global.crypto === "undefined") {
29
107
  global.crypto = import_node_crypto.default;
package/dist/globals.mjs CHANGED
@@ -1,5 +1,83 @@
1
1
  // src/globals.ts
2
2
  import crypto from "crypto";
3
+
4
+ // src/utils.ts
5
+ var buildOutgoingHttpHeaders = (headers) => {
6
+ const res = {};
7
+ const cookies = [];
8
+ for (const [k, v] of headers) {
9
+ if (k === "set-cookie") {
10
+ cookies.push(v);
11
+ } else {
12
+ res[k] = v;
13
+ }
14
+ }
15
+ if (cookies.length > 0) {
16
+ res["set-cookie"] = cookies;
17
+ }
18
+ res["content-type"] ??= "text/plain;charset=UTF-8";
19
+ return res;
20
+ };
21
+
22
+ // src/response.ts
23
+ var responseCache = Symbol("responseCache");
24
+ var cacheKey = Symbol("cache");
25
+ var globalResponse = global.Response;
26
+ var Response = class {
27
+ #body;
28
+ #init;
29
+ // @ts-ignore
30
+ get cache() {
31
+ delete this[cacheKey];
32
+ return this[responseCache] ||= new globalResponse(this.#body, this.#init);
33
+ }
34
+ constructor(body, init) {
35
+ this.#body = body;
36
+ this.#init = init;
37
+ if (typeof body === "string" || body instanceof ReadableStream) {
38
+ let headers = init?.headers || { "content-type": "text/plain;charset=UTF-8" };
39
+ if (headers instanceof Headers) {
40
+ headers = buildOutgoingHttpHeaders(headers);
41
+ }
42
+ this[cacheKey] = [init?.status || 200, body, headers];
43
+ }
44
+ }
45
+ };
46
+ [
47
+ "body",
48
+ "bodyUsed",
49
+ "headers",
50
+ "ok",
51
+ "redirected",
52
+ "status",
53
+ "statusText",
54
+ "trailers",
55
+ "type",
56
+ "url"
57
+ ].forEach((k) => {
58
+ Object.defineProperty(Response.prototype, k, {
59
+ get() {
60
+ return this.cache[k];
61
+ }
62
+ });
63
+ });
64
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
65
+ Object.defineProperty(Response.prototype, k, {
66
+ value: function() {
67
+ return this.cache[k]();
68
+ }
69
+ });
70
+ });
71
+ Object.setPrototypeOf(Response, globalResponse);
72
+ Object.setPrototypeOf(Response.prototype, globalResponse.prototype);
73
+ Object.defineProperty(global, "Response", {
74
+ value: Response
75
+ });
76
+
77
+ // src/globals.ts
78
+ Object.defineProperty(global, "Response", {
79
+ value: Response
80
+ });
3
81
  var webFetch = global.fetch;
4
82
  if (typeof global.crypto === "undefined") {
5
83
  global.crypto = crypto;
package/dist/index.js CHANGED
@@ -39,24 +39,8 @@ module.exports = __toCommonJS(src_exports);
39
39
  // src/server.ts
40
40
  var import_node_http = require("http");
41
41
 
42
- // src/listener.ts
43
- var import_node_stream = require("stream");
44
-
45
42
  // src/globals.ts
46
43
  var import_node_crypto = __toESM(require("crypto"));
47
- var webFetch = global.fetch;
48
- if (typeof global.crypto === "undefined") {
49
- global.crypto = import_node_crypto.default;
50
- }
51
- global.fetch = (info, init) => {
52
- init = {
53
- // Disable compression handling so people can return the result of a fetch
54
- // directly in the loader without messing with the Content-Encoding header.
55
- compress: false,
56
- ...init
57
- };
58
- return webFetch(info, init);
59
- };
60
44
 
61
45
  // src/utils.ts
62
46
  function writeFromReadableStream(stream, writable) {
@@ -97,75 +81,239 @@ function writeFromReadableStream(stream, writable) {
97
81
  }
98
82
  }
99
83
  }
84
+ var buildOutgoingHttpHeaders = (headers) => {
85
+ const res = {};
86
+ const cookies = [];
87
+ for (const [k, v] of headers) {
88
+ if (k === "set-cookie") {
89
+ cookies.push(v);
90
+ } else {
91
+ res[k] = v;
92
+ }
93
+ }
94
+ if (cookies.length > 0) {
95
+ res["set-cookie"] = cookies;
96
+ }
97
+ res["content-type"] ??= "text/plain;charset=UTF-8";
98
+ return res;
99
+ };
100
+
101
+ // src/response.ts
102
+ var responseCache = Symbol("responseCache");
103
+ var cacheKey = Symbol("cache");
104
+ var globalResponse = global.Response;
105
+ var Response2 = class {
106
+ #body;
107
+ #init;
108
+ // @ts-ignore
109
+ get cache() {
110
+ delete this[cacheKey];
111
+ return this[responseCache] ||= new globalResponse(this.#body, this.#init);
112
+ }
113
+ constructor(body, init) {
114
+ this.#body = body;
115
+ this.#init = init;
116
+ if (typeof body === "string" || body instanceof ReadableStream) {
117
+ let headers = init?.headers || { "content-type": "text/plain;charset=UTF-8" };
118
+ if (headers instanceof Headers) {
119
+ headers = buildOutgoingHttpHeaders(headers);
120
+ }
121
+ this[cacheKey] = [init?.status || 200, body, headers];
122
+ }
123
+ }
124
+ };
125
+ [
126
+ "body",
127
+ "bodyUsed",
128
+ "headers",
129
+ "ok",
130
+ "redirected",
131
+ "status",
132
+ "statusText",
133
+ "trailers",
134
+ "type",
135
+ "url"
136
+ ].forEach((k) => {
137
+ Object.defineProperty(Response2.prototype, k, {
138
+ get() {
139
+ return this.cache[k];
140
+ }
141
+ });
142
+ });
143
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
144
+ Object.defineProperty(Response2.prototype, k, {
145
+ value: function() {
146
+ return this.cache[k]();
147
+ }
148
+ });
149
+ });
150
+ Object.setPrototypeOf(Response2, globalResponse);
151
+ Object.setPrototypeOf(Response2.prototype, globalResponse.prototype);
152
+ Object.defineProperty(global, "Response", {
153
+ value: Response2
154
+ });
155
+
156
+ // src/globals.ts
157
+ Object.defineProperty(global, "Response", {
158
+ value: Response2
159
+ });
160
+ var webFetch = global.fetch;
161
+ if (typeof global.crypto === "undefined") {
162
+ global.crypto = import_node_crypto.default;
163
+ }
164
+ global.fetch = (info, init) => {
165
+ init = {
166
+ // Disable compression handling so people can return the result of a fetch
167
+ // directly in the loader without messing with the Content-Encoding header.
168
+ compress: false,
169
+ ...init
170
+ };
171
+ return webFetch(info, init);
172
+ };
173
+
174
+ // src/request.ts
175
+ var import_node_stream = require("stream");
176
+ var newRequestFromIncoming = (method, url, incoming) => {
177
+ const headerRecord = [];
178
+ const len = incoming.rawHeaders.length;
179
+ for (let i = 0; i < len; i += 2) {
180
+ headerRecord.push([incoming.rawHeaders[i], incoming.rawHeaders[i + 1]]);
181
+ }
182
+ const init = {
183
+ method,
184
+ headers: headerRecord
185
+ };
186
+ if (!(method === "GET" || method === "HEAD")) {
187
+ init.body = import_node_stream.Readable.toWeb(incoming);
188
+ init.duplex = "half";
189
+ }
190
+ return new Request(url, init);
191
+ };
192
+ var getRequestCache = Symbol("getRequestCache");
193
+ var requestCache = Symbol("requestCache");
194
+ var incomingKey = Symbol("incomingKey");
195
+ var requestPrototype = {
196
+ get method() {
197
+ return this[incomingKey].method || "GET";
198
+ },
199
+ get url() {
200
+ return `http://${this[incomingKey].headers.host}${this[incomingKey].url}`;
201
+ },
202
+ [getRequestCache]() {
203
+ return this[requestCache] ||= newRequestFromIncoming(this.method, this.url, this[incomingKey]);
204
+ }
205
+ };
206
+ [
207
+ "body",
208
+ "bodyUsed",
209
+ "cache",
210
+ "credentials",
211
+ "destination",
212
+ "headers",
213
+ "integrity",
214
+ "mode",
215
+ "redirect",
216
+ "referrer",
217
+ "referrerPolicy",
218
+ "signal"
219
+ ].forEach((k) => {
220
+ Object.defineProperty(requestPrototype, k, {
221
+ get() {
222
+ return this[getRequestCache]()[k];
223
+ }
224
+ });
225
+ });
226
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
227
+ Object.defineProperty(requestPrototype, k, {
228
+ value: function() {
229
+ return this[getRequestCache]()[k]();
230
+ }
231
+ });
232
+ });
233
+ Object.setPrototypeOf(requestPrototype, global.Request.prototype);
234
+ var newRequest = (incoming) => {
235
+ const req = Object.create(requestPrototype);
236
+ req[incomingKey] = incoming;
237
+ return req;
238
+ };
100
239
 
101
240
  // src/listener.ts
102
241
  var regBuffer = /^no$/i;
103
242
  var regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
104
- var getRequestListener = (fetchCallback) => {
105
- return async (incoming, outgoing) => {
106
- const method = incoming.method || "GET";
107
- const url = `http://${incoming.headers.host}${incoming.url}`;
108
- const headerRecord = [];
109
- const len = incoming.rawHeaders.length;
110
- for (let i = 0; i < len; i += 2) {
111
- headerRecord.push([incoming.rawHeaders[i], incoming.rawHeaders[i + 1]]);
112
- }
113
- const init = {
114
- method,
115
- headers: headerRecord
116
- };
117
- if (!(method === "GET" || method === "HEAD")) {
118
- init.body = import_node_stream.Readable.toWeb(incoming);
119
- init.duplex = "half";
120
- }
121
- let res;
243
+ var handleFetchError = (e) => new Response(null, {
244
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
245
+ });
246
+ var handleResponseError = (e, outgoing) => {
247
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
248
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
249
+ console.info("The user aborted a request.");
250
+ } else {
251
+ console.error(e);
252
+ outgoing.destroy(err);
253
+ }
254
+ };
255
+ var responseViaCache = (res, outgoing) => {
256
+ const [status, body, header] = res[cacheKey];
257
+ if (typeof body === "string") {
258
+ header["Content-Length"] = Buffer.byteLength(body);
259
+ outgoing.writeHead(status, header);
260
+ outgoing.end(body);
261
+ } else {
262
+ outgoing.writeHead(status, header);
263
+ return writeFromReadableStream(body, outgoing)?.catch(
264
+ (e) => handleResponseError(e, outgoing)
265
+ );
266
+ }
267
+ };
268
+ var responseViaResponseObject = async (res, outgoing) => {
269
+ if (res instanceof Promise) {
270
+ res = await res.catch(handleFetchError);
271
+ }
272
+ if (cacheKey in res) {
122
273
  try {
123
- res = await fetchCallback(new Request(url, init));
274
+ return responseViaCache(res, outgoing);
124
275
  } catch (e) {
125
- res = new Response(null, { status: 500 });
126
- if (e instanceof Error) {
127
- if (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") {
128
- res = new Response(null, { status: 504 });
129
- }
130
- }
276
+ return handleResponseError(e, outgoing);
131
277
  }
132
- const resHeaderRecord = {};
133
- const cookies = [];
134
- for (const [k, v] of res.headers) {
135
- if (k === "set-cookie") {
136
- cookies.push(v);
278
+ }
279
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
280
+ if (res.body) {
281
+ try {
282
+ if (resHeaderRecord["transfer-encoding"] || resHeaderRecord["content-encoding"] || resHeaderRecord["content-length"] || // nginx buffering variant
283
+ resHeaderRecord["x-accel-buffering"] && regBuffer.test(resHeaderRecord["x-accel-buffering"]) || !regContentType.test(resHeaderRecord["content-type"])) {
284
+ outgoing.writeHead(res.status, resHeaderRecord);
285
+ await writeFromReadableStream(res.body, outgoing);
137
286
  } else {
138
- resHeaderRecord[k] = v;
287
+ const buffer = await res.arrayBuffer();
288
+ resHeaderRecord["content-length"] = buffer.byteLength;
289
+ outgoing.writeHead(res.status, resHeaderRecord);
290
+ outgoing.end(new Uint8Array(buffer));
139
291
  }
292
+ } catch (e) {
293
+ handleResponseError(e, outgoing);
140
294
  }
141
- if (cookies.length > 0) {
142
- resHeaderRecord["set-cookie"] = cookies;
143
- }
144
- if (res.body) {
145
- try {
146
- if (resHeaderRecord["transfer-encoding"] || resHeaderRecord["content-encoding"] || resHeaderRecord["content-length"] || // nginx buffering variant
147
- resHeaderRecord["x-accel-buffering"] && regBuffer.test(resHeaderRecord["x-accel-buffering"]) || !regContentType.test(resHeaderRecord["content-type"])) {
148
- outgoing.writeHead(res.status, resHeaderRecord);
149
- await writeFromReadableStream(res.body, outgoing);
150
- } else {
151
- const buffer = await res.arrayBuffer();
152
- resHeaderRecord["content-length"] = buffer.byteLength;
153
- outgoing.writeHead(res.status, resHeaderRecord);
154
- outgoing.end(new Uint8Array(buffer));
155
- }
156
- } catch (e) {
157
- const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
158
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
159
- console.info("The user aborted a request.");
160
- } else {
161
- console.error(e);
162
- outgoing.destroy(err);
163
- }
295
+ } else {
296
+ outgoing.writeHead(res.status, resHeaderRecord);
297
+ outgoing.end();
298
+ }
299
+ };
300
+ var getRequestListener = (fetchCallback) => {
301
+ return (incoming, outgoing) => {
302
+ let res;
303
+ const req = newRequest(incoming);
304
+ try {
305
+ res = fetchCallback(req);
306
+ if (cacheKey in res) {
307
+ return responseViaCache(res, outgoing);
308
+ }
309
+ } catch (e) {
310
+ if (!res) {
311
+ res = handleFetchError(e);
312
+ } else {
313
+ return handleResponseError(e, outgoing);
164
314
  }
165
- } else {
166
- outgoing.writeHead(res.status, resHeaderRecord);
167
- outgoing.end();
168
315
  }
316
+ return responseViaResponseObject(res, outgoing);
169
317
  };
170
318
  };
171
319