@hono/node-server 1.2.2 → 1.3.0

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,43 +39,24 @@ 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) {
63
47
  if (stream.locked) {
64
48
  throw new TypeError("ReadableStream is locked.");
65
- }
66
- const reader = stream.getReader();
67
- if (writable.destroyed) {
68
- reader.cancel();
49
+ } else if (writable.destroyed) {
50
+ stream.cancel();
69
51
  return;
70
52
  }
71
- writable.on("drain", onDrain);
53
+ const reader = stream.getReader();
72
54
  writable.on("close", cancel);
73
55
  writable.on("error", cancel);
74
56
  reader.read().then(flow, cancel);
75
57
  return reader.closed.finally(() => {
76
58
  writable.off("close", cancel);
77
59
  writable.off("error", cancel);
78
- writable.off("drain", onDrain);
79
60
  });
80
61
  function cancel(error) {
81
62
  reader.cancel(error).catch(() => {
@@ -90,7 +71,9 @@ function writeFromReadableStream(stream, writable) {
90
71
  try {
91
72
  if (done) {
92
73
  writable.end();
93
- } else if (writable.write(value)) {
74
+ } else if (!writable.write(value)) {
75
+ writable.once("drain", onDrain);
76
+ } else {
94
77
  return reader.read().then(flow, cancel);
95
78
  }
96
79
  } catch (e) {
@@ -98,75 +81,239 @@ function writeFromReadableStream(stream, writable) {
98
81
  }
99
82
  }
100
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
+ };
101
239
 
102
240
  // src/listener.ts
103
241
  var regBuffer = /^no$/i;
104
242
  var regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
105
- var getRequestListener = (fetchCallback) => {
106
- return async (incoming, outgoing) => {
107
- const method = incoming.method || "GET";
108
- const url = `http://${incoming.headers.host}${incoming.url}`;
109
- const headerRecord = [];
110
- const len = incoming.rawHeaders.length;
111
- for (let i = 0; i < len; i += 2) {
112
- headerRecord.push([incoming.rawHeaders[i], incoming.rawHeaders[i + 1]]);
113
- }
114
- const init = {
115
- method,
116
- headers: headerRecord
117
- };
118
- if (!(method === "GET" || method === "HEAD")) {
119
- init.body = import_node_stream.Readable.toWeb(incoming);
120
- init.duplex = "half";
121
- }
122
- 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) {
123
273
  try {
124
- res = await fetchCallback(new Request(url, init));
274
+ return responseViaCache(res, outgoing);
125
275
  } catch (e) {
126
- res = new Response(null, { status: 500 });
127
- if (e instanceof Error) {
128
- if (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") {
129
- res = new Response(null, { status: 504 });
130
- }
131
- }
276
+ return handleResponseError(e, outgoing);
132
277
  }
133
- const resHeaderRecord = {};
134
- const cookies = [];
135
- for (const [k, v] of res.headers) {
136
- if (k === "set-cookie") {
137
- 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);
138
286
  } else {
139
- 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));
140
291
  }
292
+ } catch (e) {
293
+ handleResponseError(e, outgoing);
141
294
  }
142
- if (cookies.length > 0) {
143
- resHeaderRecord["set-cookie"] = cookies;
144
- }
145
- if (res.body) {
146
- try {
147
- if (resHeaderRecord["transfer-encoding"] || resHeaderRecord["content-encoding"] || resHeaderRecord["content-length"] || // nginx buffering variant
148
- resHeaderRecord["x-accel-buffering"] && regBuffer.test(resHeaderRecord["x-accel-buffering"]) || !regContentType.test(resHeaderRecord["content-type"])) {
149
- outgoing.writeHead(res.status, resHeaderRecord);
150
- await writeFromReadableStream(res.body, outgoing);
151
- } else {
152
- const buffer = await res.arrayBuffer();
153
- resHeaderRecord["content-length"] = buffer.byteLength;
154
- outgoing.writeHead(res.status, resHeaderRecord);
155
- outgoing.end(new Uint8Array(buffer));
156
- }
157
- } catch (e) {
158
- const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
159
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
160
- console.info("The user aborted a request.");
161
- } else {
162
- console.error(e);
163
- outgoing.destroy(err);
164
- }
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);
165
314
  }
166
- } else {
167
- outgoing.writeHead(res.status, resHeaderRecord);
168
- outgoing.end();
169
315
  }
316
+ return responseViaResponseObject(res, outgoing);
170
317
  };
171
318
  };
172
319