@ngrok/app-server 0.2.0 → 0.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.
Files changed (103) hide show
  1. package/README.md +610 -76
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/{build-manifest-8NfD1wnO.js → build-manifest-UDNk81Ce.js} +24 -6
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/cli.js +45 -25
  7. package/dist/cli.js.map +1 -1
  8. package/dist/client.d.ts +141 -0
  9. package/dist/client.js +326 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/compression-7_gToa8R.js +97 -0
  12. package/dist/compression-7_gToa8R.js.map +1 -0
  13. package/dist/create-server-iE1-s6Bi.js +1409 -0
  14. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  15. package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
  16. package/dist/deno-aqhikNMG.js.map +1 -0
  17. package/dist/entry-DZ3qo7qF.js +116 -0
  18. package/dist/entry-DZ3qo7qF.js.map +1 -0
  19. package/dist/entry-DmJEqVfd.d.ts +622 -0
  20. package/dist/gzip-Doi4wqjX.js +294 -0
  21. package/dist/gzip-Doi4wqjX.js.map +1 -0
  22. package/dist/header-hook-Vzw9J9BY.js +159 -0
  23. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  24. package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
  25. package/dist/index.d.ts +99 -269
  26. package/dist/index.js +47 -59
  27. package/dist/index.js.map +1 -1
  28. package/dist/listen-options-7TaXjyrk.js.map +1 -1
  29. package/dist/{load-entry-C03qqmhr.js → load-entry-AfYS_zS9.js} +8 -4
  30. package/dist/{load-entry-C03qqmhr.js.map → load-entry-AfYS_zS9.js.map} +1 -1
  31. package/dist/log-BP6xXXZl.js +122 -0
  32. package/dist/log-BP6xXXZl.js.map +1 -0
  33. package/dist/node-BFH82eeL.js +333 -0
  34. package/dist/node-BFH82eeL.js.map +1 -0
  35. package/dist/node-tBVQPjQv.js +41 -0
  36. package/dist/node-tBVQPjQv.js.map +1 -0
  37. package/dist/node-vite.d.ts +5 -4
  38. package/dist/node-vite.js +2 -17
  39. package/dist/node.d.ts +23 -4
  40. package/dist/node.js +2 -2
  41. package/dist/react-router-vite.d.ts +4 -3
  42. package/dist/react-router-vite.js +2 -20
  43. package/dist/react-router.d.ts +1 -1
  44. package/dist/react-router.js +8 -7
  45. package/dist/react-router.js.map +1 -1
  46. package/dist/request-context-BtQ87VYb.js +40 -0
  47. package/dist/request-context-BtQ87VYb.js.map +1 -0
  48. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  49. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  50. package/dist/response-writer-B7FoJjEE.js +289 -0
  51. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  52. package/dist/script-hashes-hqUk6kG7.js +53 -0
  53. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  54. package/dist/{serve-Cleo8RMO.js → serve-CDNgThjk.js} +3 -3
  55. package/dist/{serve-Cleo8RMO.js.map → serve-CDNgThjk.js.map} +1 -1
  56. package/dist/{start-CINALHxy.js → start-TLIprD74.js} +14 -19
  57. package/dist/start-TLIprD74.js.map +1 -0
  58. package/dist/static-files-Beju9riB.js +302 -0
  59. package/dist/static-files-Beju9riB.js.map +1 -0
  60. package/dist/tanstack-start-vite.d.ts +6 -5
  61. package/dist/tanstack-start-vite.js +2 -23
  62. package/dist/tanstack-start.d.ts +19 -2
  63. package/dist/tanstack-start.js +5 -14
  64. package/dist/tanstack-start.js.map +1 -1
  65. package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
  66. package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
  67. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  68. package/dist/types-DLYxYS6M.d.ts +392 -0
  69. package/dist/vercel-vite.d.ts +35 -0
  70. package/dist/vercel-vite.js +142 -0
  71. package/dist/vercel-vite.js.map +1 -0
  72. package/dist/vercel.d.ts +35 -0
  73. package/dist/vercel.js +89 -0
  74. package/dist/vercel.js.map +1 -0
  75. package/dist/vite-B-GfswoH.js +22 -0
  76. package/dist/vite-B-GfswoH.js.map +1 -0
  77. package/dist/vite-D4hfj3ph.js +19 -0
  78. package/dist/vite-D4hfj3ph.js.map +1 -0
  79. package/dist/vite-DyrhyKEr.js +25 -0
  80. package/dist/vite-DyrhyKEr.js.map +1 -0
  81. package/dist/vite-iioAoxSt.js +752 -0
  82. package/dist/vite-iioAoxSt.js.map +1 -0
  83. package/dist/vite.d.ts +2 -2
  84. package/dist/vite.js +1 -1
  85. package/package.json +24 -4
  86. package/dist/build-manifest-8NfD1wnO.js.map +0 -1
  87. package/dist/deno-DNRgzHrk.js.map +0 -1
  88. package/dist/entry-BkdUub2S.js +0 -638
  89. package/dist/entry-BkdUub2S.js.map +0 -1
  90. package/dist/log-CsjaKM8U.js +0 -59
  91. package/dist/log-CsjaKM8U.js.map +0 -1
  92. package/dist/node-CG7qXuWZ.js +0 -58
  93. package/dist/node-CG7qXuWZ.js.map +0 -1
  94. package/dist/node-YWPGmzAk.js +0 -215
  95. package/dist/node-YWPGmzAk.js.map +0 -1
  96. package/dist/node-ZMowKZDB.js +0 -3
  97. package/dist/node-vite.js.map +0 -1
  98. package/dist/react-router-vite.js.map +0 -1
  99. package/dist/start-CINALHxy.js.map +0 -1
  100. package/dist/tanstack-start-vite.js.map +0 -1
  101. package/dist/types-BfCkS7kQ.d.ts +0 -203
  102. package/dist/vite-mYZ2Y69u.js +0 -144
  103. package/dist/vite-mYZ2Y69u.js.map +0 -1
@@ -0,0 +1,327 @@
1
+ import { a as replaceResponse, i as listView, n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
2
+ import { t as errorAttributes } from "./log-BP6xXXZl.js";
3
+
4
+ // src/core/response-edge.ts
5
+ function ignore() {}
6
+ /** Calls `report` with `sent`, and drops a throw from it. */
7
+ function callReport(report, sent) {
8
+ try {
9
+ report(sent);
10
+ } catch {}
11
+ }
12
+ /** The `Set-Cookie` values of a flat header list, one on each line. */
13
+ function cookiesOf(head) {
14
+ let cookies = "";
15
+ for (let index = 0; index < head.length; index += 2) if (head[index] === "set-cookie") cookies += `${head[index + 1] ?? ""}\n`;
16
+ return cookies;
17
+ }
18
+ /** The value of the lowercase `name` in a flat header list with one entry for each name, or `undefined`. */
19
+ function valueOf(head, name) {
20
+ const index = headerIndex(head, name);
21
+ return index === -1 ? void 0 : head[index + 1];
22
+ }
23
+ /** Whether two flat header lists are the same. */
24
+ function sameHead(first, second) {
25
+ if (first.length !== second.length) return false;
26
+ for (let index = 0; index < first.length; index += 1) if (first[index] !== second[index]) return false;
27
+ return true;
28
+ }
29
+ /** `head` with the changes from `base` to `live`, two lists of the headers of the response before the hooks. */
30
+ function withChanges(head, base, live) {
31
+ const changed = [...head];
32
+ const view = listView(changed);
33
+ for (let index = 0; index < base.length; index += 2) {
34
+ const name = base[index] ?? "";
35
+ if (headerIndex(live, name) === -1) view.delete(name);
36
+ }
37
+ if (cookiesOf(base) !== cookiesOf(live)) {
38
+ view.delete("set-cookie");
39
+ for (let index = 0; index < live.length; index += 2) if (live[index] === "set-cookie") view.append("set-cookie", live[index + 1] ?? "");
40
+ }
41
+ for (let index = 0; index < live.length; index += 2) {
42
+ const name = live[index] ?? "";
43
+ const value = live[index + 1] ?? "";
44
+ if (name !== "set-cookie" && valueOf(base, name) !== value) view.set(name, value);
45
+ }
46
+ return changed;
47
+ }
48
+ /**
49
+ * What the server and a listener that writes each response itself share for
50
+ * one request. The listener makes one for each request and gives it as the
51
+ * `edge` binding. The server then runs the header hooks on a list of the
52
+ * headers, so it copies no response for them. The listener:
53
+ *
54
+ * - writes {@link ResponseEdge.headersFor} in place of the headers of the response
55
+ * - adds each body byte that it writes to {@link ResponseEdge.bytes}
56
+ * - gives an error that stops the response to {@link ResponseEdge.fail}
57
+ * - calls {@link ResponseEdge.close} once, when the response ends or its client goes away
58
+ *
59
+ * @example
60
+ * const edge = new ResponseEdge();
61
+ * const response = await fetch(request, { remoteAddress, edge });
62
+ * outgoing.writeHead(response.status, edge.headersFor(response) ?? [...response.headers].flat());
63
+ */
64
+ var ResponseEdge = class {
65
+ /** The body bytes that the listener gave to its socket. */
66
+ bytes = 0;
67
+ #logger = void 0;
68
+ #base = void 0;
69
+ #headers = void 0;
70
+ #reports = [];
71
+ #sent = void 0;
72
+ /**
73
+ * Gives the edge to the request of `logger`, and gives `true`, the first
74
+ * time only. The server calls it when a request starts. Why once: a
75
+ * request that the app sends through itself again with the same bindings
76
+ * must change its own response.
77
+ */
78
+ claim(logger) {
79
+ if (this.#logger != null) return false;
80
+ this.#logger = logger;
81
+ return true;
82
+ }
83
+ /**
84
+ * Keeps `headers`, the headers of the response after each header hook, and
85
+ * `base`, its headers before the hooks. The server calls it.
86
+ */
87
+ useHeaders(base, headers) {
88
+ this.#base = base;
89
+ this.#headers = headers;
90
+ }
91
+ /**
92
+ * The headers to write for `response`: lowercase names and their values in
93
+ * turn, as Node's `writeHead` takes them. They are the headers after the
94
+ * hooks, with each change that the headers of `response` have from the
95
+ * response that the hooks ran on. Why: Hono answers HEAD with a copy that
96
+ * has no body, and a wrapper of the app's `fetch` can change the headers or
97
+ * return a copy. It gives `undefined` when the server kept no headers.
98
+ */
99
+ headersFor(response) {
100
+ const base = this.#base;
101
+ const headers = this.#headers;
102
+ if (base == null || headers == null) return headers;
103
+ const live = headerList(response.headers);
104
+ return sameHead(base, live) ? headers : withChanges(headers, base, live);
105
+ }
106
+ /**
107
+ * Calls `report` once, when the response ends or its client goes away. It
108
+ * calls it at once when that happened already. A throw from `report` never
109
+ * reaches the listener.
110
+ */
111
+ onSent(report) {
112
+ if (this.#sent == null) this.#reports.push(report);
113
+ else callReport(report, this.#sent);
114
+ }
115
+ /** Logs `error`, which stopped the response, with the logger of the request. */
116
+ fail(error) {
117
+ try {
118
+ if (this.#logger != null) {
119
+ this.#logger.error("unhandled error", errorAttributes(error));
120
+ return;
121
+ }
122
+ } catch {}
123
+ console.error(error);
124
+ }
125
+ /**
126
+ * Reports what went out, once: the status and the headers that the
127
+ * listener sent, the bytes, and whether the body stopped before its end.
128
+ * `head` is the flat list that the listener gave `writeHead`.
129
+ */
130
+ close(status, aborted, head) {
131
+ if (this.#sent != null) return;
132
+ this.#sent = {
133
+ status,
134
+ headers: listView(head),
135
+ bytes: this.bytes,
136
+ aborted
137
+ };
138
+ for (const report of this.#reports) callReport(report, this.#sent);
139
+ }
140
+ };
141
+ /**
142
+ * `body` again, with a count of its bytes for `report`. `report` runs once:
143
+ * at the end of the body, at a failure, or at a cancel.
144
+ */
145
+ function countedBody(body, report) {
146
+ const reader = body.getReader();
147
+ let bytes = 0;
148
+ return new ReadableStream({
149
+ async pull(controller) {
150
+ let result;
151
+ try {
152
+ result = await reader.read();
153
+ } catch (error) {
154
+ report(bytes, true);
155
+ throw error;
156
+ }
157
+ if (result.done) {
158
+ controller.close();
159
+ report(bytes, false);
160
+ return;
161
+ }
162
+ bytes += result.value.byteLength;
163
+ controller.enqueue(result.value);
164
+ },
165
+ async cancel(reason) {
166
+ try {
167
+ report(bytes, true);
168
+ } finally {
169
+ await reader.cancel(reason);
170
+ }
171
+ }
172
+ }, { highWaterMark: 0 });
173
+ }
174
+ /**
175
+ * The body of `context.res` with a count for `report`, or `undefined` when
176
+ * `report` ran at once: a HEAD response and a response with no body send no
177
+ * body bytes. `headers` are the headers that go out with the response.
178
+ */
179
+ function reportedBody(context, headers, report) {
180
+ const { status, body } = context.res;
181
+ if (context.req.method === "HEAD") {
182
+ callReport(report, {
183
+ status,
184
+ headers,
185
+ bytes: 0,
186
+ aborted: false
187
+ });
188
+ return;
189
+ }
190
+ if (body == null) {
191
+ callReport(report, {
192
+ status,
193
+ headers,
194
+ bytes: Number(headers.get("Content-Length") ?? 0),
195
+ aborted: false
196
+ });
197
+ return;
198
+ }
199
+ return countedBody(body, (bytes, aborted) => {
200
+ callReport(report, {
201
+ status,
202
+ headers,
203
+ bytes,
204
+ aborted
205
+ });
206
+ });
207
+ }
208
+ /**
209
+ * Calls `report` once, when the response of the request ends or its client
210
+ * goes away: with the status and the headers that went out, the body bytes,
211
+ * and whether the body stopped before its end. In an app server, it reports the response that
212
+ * the server returns, after each stage and header hook. A listener with an
213
+ * `edge` counts the bytes as it writes them; else the server counts them with
214
+ * a stream around the body.
215
+ *
216
+ * @example
217
+ * middleware: async (c, next) => {
218
+ * await next();
219
+ * onResponseSent(c, ({ status, bytes }) => c.get("logger").info("sent", { status, bytes }));
220
+ * },
221
+ */
222
+ function onResponseSent(context, report) {
223
+ const reports = context.get("sentReports");
224
+ if (reports != null) {
225
+ reports.push(report);
226
+ return;
227
+ }
228
+ const response = context.res;
229
+ const body = reportedBody(context, response.headers, report);
230
+ if (body != null) replaceResponse(context, new Response(body, response));
231
+ }
232
+ /**
233
+ * Puts the response that `fail` gives for `error` in place of the response of
234
+ * the request, and cancels the body that no one reads now.
235
+ */
236
+ async function useErrorResponse(context, fail, error) {
237
+ const { body } = context.res;
238
+ context.res = void 0;
239
+ context.res = await fail(error, context);
240
+ body?.cancel().catch(ignore);
241
+ }
242
+ /**
243
+ * Gives `reports` the response of the request. With no edge, it makes one new
244
+ * response with `headers`, when the hooks made them, and a body that counts
245
+ * its bytes.
246
+ */
247
+ function reportResponse(context, reports, headers) {
248
+ const response = context.res;
249
+ const [only] = reports;
250
+ const report = reports.length > 1 ? (sent) => {
251
+ for (const each of reports) callReport(each, sent);
252
+ } : only;
253
+ const body = report == null ? void 0 : reportedBody(context, headers ?? response.headers, report);
254
+ if (headers == null && body == null) return;
255
+ context.res = void 0;
256
+ context.res = new Response(body ?? response.body, {
257
+ status: response.status,
258
+ statusText: response.statusText,
259
+ headers: headers ?? response.headers
260
+ });
261
+ }
262
+ /** Puts the error response for `error` in place, then runs the hooks from `from` on it. */
263
+ async function finishAfterError(context, finish, { error, from }) {
264
+ await useErrorResponse(context, finish.fail, error);
265
+ await finishFrom(context, finish, from);
266
+ }
267
+ /** Puts the error response for `error` in place, and gives it to the reports. */
268
+ async function reportErrorResponse(context, finish, error) {
269
+ await useErrorResponse(context, finish.fail, error);
270
+ reportResponse(context, finish.reports, void 0);
271
+ }
272
+ /** {@link finishResponse} from the hook at `from`, down to the first one. */
273
+ function finishFrom(context, finish, from) {
274
+ const { hooks, reports, edge } = finish;
275
+ const base = headerList(context.res.headers);
276
+ const head = edge == null ? base : [...base];
277
+ const view = listView(head);
278
+ for (let index = from; index >= 0; index -= 1) try {
279
+ hooks[index]?.(view);
280
+ } catch (error) {
281
+ return finishAfterError(context, finish, {
282
+ error,
283
+ from: index - 1
284
+ });
285
+ }
286
+ if (edge != null) {
287
+ edge.useHeaders(base, head);
288
+ for (const report of reports) edge.onSent(report);
289
+ return;
290
+ }
291
+ if (hooks.length === 0) {
292
+ reportResponse(context, reports, void 0);
293
+ return;
294
+ }
295
+ const headers = new Headers();
296
+ try {
297
+ for (let index = 0; index < head.length; index += 2) headers.append(head[index] ?? "", head[index + 1] ?? "");
298
+ } catch (error) {
299
+ return reportErrorResponse(context, finish, error);
300
+ }
301
+ reportResponse(context, reports, headers);
302
+ }
303
+ /**
304
+ * Finishes the response of the request, after each stage. The server calls it
305
+ * once, in the request's `requestContext()`.
306
+ *
307
+ * - It runs `hooks` on the head, in reverse order, so the hook of an inner
308
+ * stage runs first and an outer stage has the last word. When a hook
309
+ * throws, `fail` gives the response that takes the place of this one, and
310
+ * the hooks of the outer stages run on it, as when a stage throws.
311
+ * - It gives `reports` the response, so each one runs when it ends.
312
+ *
313
+ * With `edge`, the head stays a list that the listener writes, so the server
314
+ * copies no response. Else the server makes one new response with the head
315
+ * and a body that counts its bytes. It gives a promise only when a hook
316
+ * throws, so a response with no error waits for no microtask.
317
+ *
318
+ * @example
319
+ * await next();
320
+ * await finishResponse(context, { hooks, reports, edge, fail: (error, c) => onError(error, c) });
321
+ */
322
+ function finishResponse(context, finish) {
323
+ return finishFrom(context, finish, finish.hooks.length - 1);
324
+ }
325
+
326
+ export { finishResponse as n, onResponseSent as r, ResponseEdge as t };
327
+ //# sourceMappingURL=response-edge-Bc1-C_Cx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-edge-Bc1-C_Cx.js","names":[],"sources":["../src/core/response-edge.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { headerIndex, headerList, listView, replaceResponse } from \"./header-hook.js\";\nimport { errorAttributes } from \"./log.js\";\nimport type { AppServerEnv, HeaderHook, RequestLogger, SentResponse } from \"./types.js\";\n\nfunction ignore(): void {}\n\n/** Calls `report` with `sent`, and drops a throw from it. */\nfunction callReport(report: (sent: SentResponse) => void, sent: SentResponse): void {\n\ttry {\n\t\treport(sent);\n\t} catch {\n\t\t// Why drop it: a listener calls a report from an event of its socket, where a throw stops the process.\n\t}\n}\n\n/** The `Set-Cookie` values of a flat header list, one on each line. */\nfunction cookiesOf(head: readonly string[]): string {\n\tlet cookies = \"\";\n\tfor (let index = 0; index < head.length; index += 2) {\n\t\tif (head[index] === \"set-cookie\") {\n\t\t\tcookies += `${head[index + 1] ?? \"\"}\\n`;\n\t\t}\n\t}\n\treturn cookies;\n}\n\n/** The value of the lowercase `name` in a flat header list with one entry for each name, or `undefined`. */\nfunction valueOf(head: readonly string[], name: string): string | undefined {\n\tconst index = headerIndex(head, name);\n\treturn index === -1 ? undefined : head[index + 1];\n}\n\n/** Whether two flat header lists are the same. */\nfunction sameHead(first: readonly string[], second: readonly string[]): boolean {\n\tif (first.length !== second.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < first.length; index += 1) {\n\t\tif (first[index] !== second[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** `head` with the changes from `base` to `live`, two lists of the headers of the response before the hooks. */\nfunction withChanges(\n\thead: readonly string[],\n\tbase: readonly string[],\n\tlive: readonly string[],\n): string[] {\n\tconst changed = [...head];\n\tconst view = listView(changed);\n\tfor (let index = 0; index < base.length; index += 2) {\n\t\tconst name = base[index] ?? \"\";\n\t\tif (headerIndex(live, name) === -1) {\n\t\t\tview.delete(name);\n\t\t}\n\t}\n\tif (cookiesOf(base) !== cookiesOf(live)) {\n\t\tview.delete(\"set-cookie\");\n\t\tfor (let index = 0; index < live.length; index += 2) {\n\t\t\tif (live[index] === \"set-cookie\") {\n\t\t\t\tview.append(\"set-cookie\", live[index + 1] ?? \"\");\n\t\t\t}\n\t\t}\n\t}\n\tfor (let index = 0; index < live.length; index += 2) {\n\t\tconst name = live[index] ?? \"\";\n\t\tconst value = live[index + 1] ?? \"\";\n\t\tif (name !== \"set-cookie\" && valueOf(base, name) !== value) {\n\t\t\tview.set(name, value);\n\t\t}\n\t}\n\treturn changed;\n}\n\n/**\n * What the server and a listener that writes each response itself share for\n * one request. The listener makes one for each request and gives it as the\n * `edge` binding. The server then runs the header hooks on a list of the\n * headers, so it copies no response for them. The listener:\n *\n * - writes {@link ResponseEdge.headersFor} in place of the headers of the response\n * - adds each body byte that it writes to {@link ResponseEdge.bytes}\n * - gives an error that stops the response to {@link ResponseEdge.fail}\n * - calls {@link ResponseEdge.close} once, when the response ends or its client goes away\n *\n * @example\n * const edge = new ResponseEdge();\n * const response = await fetch(request, { remoteAddress, edge });\n * outgoing.writeHead(response.status, edge.headersFor(response) ?? [...response.headers].flat());\n */\nexport class ResponseEdge {\n\t/** The body bytes that the listener gave to its socket. */\n\tpublic bytes = 0;\n\t#logger: RequestLogger | undefined = undefined;\n\t#base: readonly string[] | undefined = undefined;\n\t#headers: string[] | undefined = undefined;\n\treadonly #reports: ((sent: SentResponse) => void)[] = [];\n\t#sent: SentResponse | undefined = undefined;\n\n\t/**\n\t * Gives the edge to the request of `logger`, and gives `true`, the first\n\t * time only. The server calls it when a request starts. Why once: a\n\t * request that the app sends through itself again with the same bindings\n\t * must change its own response.\n\t */\n\tpublic claim(logger: RequestLogger): boolean {\n\t\tif (this.#logger != null) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.#logger = logger;\n\t\treturn true;\n\t}\n\n\t/**\n\t * Keeps `headers`, the headers of the response after each header hook, and\n\t * `base`, its headers before the hooks. The server calls it.\n\t */\n\tpublic useHeaders(base: readonly string[], headers: string[]): void {\n\t\tthis.#base = base;\n\t\tthis.#headers = headers;\n\t}\n\n\t/**\n\t * The headers to write for `response`: lowercase names and their values in\n\t * turn, as Node's `writeHead` takes them. They are the headers after the\n\t * hooks, with each change that the headers of `response` have from the\n\t * response that the hooks ran on. Why: Hono answers HEAD with a copy that\n\t * has no body, and a wrapper of the app's `fetch` can change the headers or\n\t * return a copy. It gives `undefined` when the server kept no headers.\n\t */\n\tpublic headersFor(response: Response): string[] | undefined {\n\t\tconst base = this.#base;\n\t\tconst headers = this.#headers;\n\t\tif (base == null || headers == null) {\n\t\t\treturn headers;\n\t\t}\n\t\tconst live = headerList(response.headers);\n\t\treturn sameHead(base, live) ? headers : withChanges(headers, base, live);\n\t}\n\n\t/**\n\t * Calls `report` once, when the response ends or its client goes away. It\n\t * calls it at once when that happened already. A throw from `report` never\n\t * reaches the listener.\n\t */\n\tpublic onSent(report: (sent: SentResponse) => void): void {\n\t\tif (this.#sent == null) {\n\t\t\tthis.#reports.push(report);\n\t\t} else {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n\n\t/** Logs `error`, which stopped the response, with the logger of the request. */\n\tpublic fail(error: unknown): void {\n\t\ttry {\n\t\t\tif (this.#logger != null) {\n\t\t\t\tthis.#logger.error(\"unhandled error\", errorAttributes(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Why fall through: the sink failed, and the error must still reach the operator.\n\t\t}\n\t\t// oxlint-disable-next-line no-console -- no app logger took the edge, or its sink failed.\n\t\tconsole.error(error);\n\t}\n\n\t/**\n\t * Reports what went out, once: the status and the headers that the\n\t * listener sent, the bytes, and whether the body stopped before its end.\n\t * `head` is the flat list that the listener gave `writeHead`.\n\t */\n\tpublic close(status: number, aborted: boolean, head: string[]): void {\n\t\tif (this.#sent != null) {\n\t\t\treturn;\n\t\t}\n\t\tthis.#sent = { status, headers: listView(head), bytes: this.bytes, aborted };\n\t\tfor (const report of this.#reports) {\n\t\t\tcallReport(report, this.#sent);\n\t\t}\n\t}\n}\n\n/**\n * `body` again, with a count of its bytes for `report`. `report` runs once:\n * at the end of the body, at a failure, or at a cancel.\n */\nfunction countedBody(\n\tbody: ReadableStream<Uint8Array>,\n\treport: (bytes: number, aborted: boolean) => void,\n): ReadableStream<Uint8Array> {\n\tconst reader = body.getReader();\n\tlet bytes = 0;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\tlet result: ReadableStreamReadResult<Uint8Array>;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await reader.read();\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Why here: `cancel` does not run for a stream that failed.\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (result.done) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treport(bytes, false);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbytes += result.value.byteLength;\n\t\t\t\tcontroller.enqueue(result.value);\n\t\t\t},\n\t\t\tasync cancel(reason) {\n\t\t\t\ttry {\n\t\t\t\t\treport(bytes, true);\n\t\t\t\t} finally {\n\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// Why 0: a pass-through stream must not read ahead of the client.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * The body of `context.res` with a count for `report`, or `undefined` when\n * `report` ran at once: a HEAD response and a response with no body send no\n * body bytes. `headers` are the headers that go out with the response.\n */\nfunction reportedBody(\n\tcontext: Context<AppServerEnv>,\n\theaders: Headers,\n\treport: (sent: SentResponse) => void,\n): ReadableStream<Uint8Array> | undefined {\n\tconst { status, body } = context.res;\n\t// Why HEAD: Hono drops the body of a HEAD response, so no one reads it to its end.\n\tif (context.req.method === \"HEAD\") {\n\t\tcallReport(report, { status, headers, bytes: 0, aborted: false });\n\t\treturn undefined;\n\t}\n\t// Why `Content-Length`: a stage that answers through Node's response, such as Vite in\n\t// development, gives a response with no body and the length it sent.\n\tif (body == null) {\n\t\tconst length = Number(headers.get(\"Content-Length\") ?? 0);\n\t\tcallReport(report, { status, headers, bytes: length, aborted: false });\n\t\treturn undefined;\n\t}\n\treturn countedBody(body, (bytes, aborted) => {\n\t\tcallReport(report, { status, headers, bytes, aborted });\n\t});\n}\n\n/**\n * Calls `report` once, when the response of the request ends or its client\n * goes away: with the status and the headers that went out, the body bytes,\n * and whether the body stopped before its end. In an app server, it reports the response that\n * the server returns, after each stage and header hook. A listener with an\n * `edge` counts the bytes as it writes them; else the server counts them with\n * a stream around the body.\n *\n * @example\n * middleware: async (c, next) => {\n * \tawait next();\n * \tonResponseSent(c, ({ status, bytes }) => c.get(\"logger\").info(\"sent\", { status, bytes }));\n * },\n */\nexport function onResponseSent(\n\tcontext: Context<AppServerEnv>,\n\treport: (sent: SentResponse) => void,\n): void {\n\tconst reports = context.get(\"sentReports\");\n\tif (reports != null) {\n\t\treports.push(report);\n\t\treturn;\n\t}\n\t// Why now: outside an app server, nothing reports later, so this counts the response as it is.\n\tconst response = context.res;\n\tconst body = reportedBody(context, response.headers, report);\n\tif (body != null) {\n\t\treplaceResponse(context, new Response(body, response));\n\t}\n}\n\n/** What {@link finishResponse} needs from the server. */\ntype Finish = {\n\thooks: readonly HeaderHook[];\n\treports: readonly ((sent: SentResponse) => void)[];\n\t/** The edge that the request claimed, if any. */\n\tedge: ResponseEdge | undefined;\n\t/**\n\t * The response for an error that a header hook throws, as the app's\n\t * `onError` gives it. It runs while `context.res` is cleared.\n\t */\n\tfail: (error: unknown, context: Context<AppServerEnv>) => Response | Promise<Response>;\n};\n\n/**\n * Puts the response that `fail` gives for `error` in place of the response of\n * the request, and cancels the body that no one reads now.\n */\nasync function useErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfail: Finish[\"fail\"],\n\terror: unknown,\n): Promise<void> {\n\tconst { body } = context.res;\n\t// Why clear first: Hono's `c.text` copies each header of the response that the context holds.\n\tcontext.res = undefined;\n\tcontext.res = await fail(error, context);\n\tvoid body?.cancel().catch(ignore);\n}\n\n/**\n * Gives `reports` the response of the request. With no edge, it makes one new\n * response with `headers`, when the hooks made them, and a body that counts\n * its bytes.\n */\nfunction reportResponse(\n\tcontext: Context<AppServerEnv>,\n\treports: Finish[\"reports\"],\n\theaders: Headers | undefined,\n): void {\n\tconst response = context.res;\n\tconst [only] = reports;\n\tconst report =\n\t\treports.length > 1\n\t\t\t? (sent: SentResponse) => {\n\t\t\t\t\tfor (const each of reports) {\n\t\t\t\t\t\tcallReport(each, sent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t: only;\n\t// Why keep `headers`: Bun empties the headers of the response that it sends, but not this object.\n\tconst body =\n\t\treport == null ? undefined : reportedBody(context, headers ?? response.headers, report);\n\tif (headers == null && body == null) {\n\t\treturn;\n\t}\n\tcontext.res = undefined;\n\tcontext.res = new Response(body ?? response.body, {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders: headers ?? response.headers,\n\t});\n}\n\n/** Puts the error response for `error` in place, then runs the hooks from `from` on it. */\nasync function finishAfterError(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\t{ error, from }: { error: unknown; from: number },\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\tawait finishFrom(context, finish, from);\n}\n\n/** Puts the error response for `error` in place, and gives it to the reports. */\nasync function reportErrorResponse(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\terror: unknown,\n): Promise<void> {\n\tawait useErrorResponse(context, finish.fail, error);\n\treportResponse(context, finish.reports, undefined);\n}\n\n/** {@link finishResponse} from the hook at `from`, down to the first one. */\nfunction finishFrom(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n\tfrom: number,\n): Promise<void> | undefined {\n\tconst { hooks, reports, edge } = finish;\n\tconst base = headerList(context.res.headers);\n\t// Why a copy with an edge: the edge compares the response that the listener gets with `base`.\n\tconst head = edge == null ? base : [...base];\n\tconst view = listView(head);\n\tfor (let index = from; index >= 0; index -= 1) {\n\t\ttry {\n\t\t\thooks[index]?.(view);\n\t\t} catch (error) {\n\t\t\treturn finishAfterError(context, finish, { error, from: index - 1 });\n\t\t}\n\t}\n\tif (edge != null) {\n\t\tedge.useHeaders(base, head);\n\t\tfor (const report of reports) {\n\t\t\tedge.onSent(report);\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (hooks.length === 0) {\n\t\treportResponse(context, reports, undefined);\n\t\treturn undefined;\n\t}\n\tconst headers = new Headers();\n\ttry {\n\t\tfor (let index = 0; index < head.length; index += 2) {\n\t\t\theaders.append(head[index] ?? \"\", head[index + 1] ?? \"\");\n\t\t}\n\t} catch (error) {\n\t\t// Why: a hook set a value that `Headers` rejects. The error response keeps its own headers.\n\t\treturn reportErrorResponse(context, finish, error);\n\t}\n\treportResponse(context, reports, headers);\n\treturn undefined;\n}\n\n/**\n * Finishes the response of the request, after each stage. The server calls it\n * once, in the request's `requestContext()`.\n *\n * - It runs `hooks` on the head, in reverse order, so the hook of an inner\n * stage runs first and an outer stage has the last word. When a hook\n * throws, `fail` gives the response that takes the place of this one, and\n * the hooks of the outer stages run on it, as when a stage throws.\n * - It gives `reports` the response, so each one runs when it ends.\n *\n * With `edge`, the head stays a list that the listener writes, so the server\n * copies no response. Else the server makes one new response with the head\n * and a body that counts its bytes. It gives a promise only when a hook\n * throws, so a response with no error waits for no microtask.\n *\n * @example\n * await next();\n * await finishResponse(context, { hooks, reports, edge, fail: (error, c) => onError(error, c) });\n */\nexport function finishResponse(\n\tcontext: Context<AppServerEnv>,\n\tfinish: Finish,\n): Promise<void> | undefined {\n\treturn finishFrom(context, finish, finish.hooks.length - 1);\n}\n"],"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AAiB,SAAS,QAAQ;GAAE;GAAO,MAAM,QAAQ;EAAE,CAAC;CACpE;CAED,IAAI,QAAQ,MAAM;EACjB,KAAK,WAAW,MAAM,IAAI;EAC1B,KAAK,MAAM,UAAU,SACpB,KAAK,OAAO,MAAM;EAEnB;CACD;CACA,IAAI,MAAM,WAAW,GAAG;EACvB,eAAe,SAAS,SAAS,MAAS;EAC1C;CACD;CACA,MAAM,UAAU,IAAI,QAAQ;CAC5B,IAAI;EACH,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GACjD,QAAQ,OAAO,KAAK,UAAU,IAAI,KAAK,QAAQ,MAAM,EAAE;CAEzD,SAAS,OAAO;EAEf,OAAO,oBAAoB,SAAS,QAAQ,KAAK;CAClD;CACA,eAAe,SAAS,SAAS,OAAO;AAEzC;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,eACf,SACA,QAC4B;CAC5B,OAAO,WAAW,SAAS,QAAQ,OAAO,MAAM,SAAS,CAAC;AAC3D"}
@@ -0,0 +1,289 @@
1
+ import { n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
2
+ import { t as ResponseEdge } from "./response-edge-Bc1-C_Cx.js";
3
+ import { s as readIfQueued } from "./compression-7_gToa8R.js";
4
+ import { n as waitsForZlib } from "./gzip-Doi4wqjX.js";
5
+ import { IncomingMessage, ServerResponse } from "node:http";
6
+ import { getRequestListener } from "@hono/node-server";
7
+
8
+ // src/node/response-writer.ts
9
+ /** The header of a response that went out through Node's response already, as the dev server stage sends it. */
10
+ const ALREADY_SENT_HEADER = "x-hono-already-sent";
11
+ /** Why one object for all requests: `@hono/node-server` only reads its headers. */
12
+ const ALREADY_SENT = new Response(null, { headers: { [ALREADY_SENT_HEADER]: "true" } });
13
+ /** The type that `@hono/node-server` gives a body with none. */
14
+ const DEFAULT_CONTENT_TYPE = "text/plain; charset=UTF-8";
15
+ /** The body of the 500 that goes out when the response cannot. */
16
+ const ERROR_BODY = Buffer.from("Internal Server Error");
17
+ /** Resolves after the microtasks that are queued now, and the ones that they queue. */
18
+ async function afterMicrotasks() {
19
+ return new Promise((resolve) => {
20
+ process.nextTick(resolve);
21
+ });
22
+ }
23
+ /** Resolves on the next `drain` of `outgoing`, or when it closes. */
24
+ async function drained(outgoing) {
25
+ return new Promise((resolve) => {
26
+ const done = () => {
27
+ outgoing.off("drain", done);
28
+ outgoing.off("close", done);
29
+ resolve();
30
+ };
31
+ outgoing.on("drain", done);
32
+ outgoing.on("close", done);
33
+ });
34
+ }
35
+ /** `value` as a body chunk. Why throw: a string chunk has no `byteLength`, and the Fetch standard allows bytes only. */
36
+ function bytesOf(value) {
37
+ if (value instanceof Uint8Array) return value;
38
+ throw new TypeError("A response body gave a chunk that is not a Uint8Array.");
39
+ }
40
+ /**
41
+ * Reads the chunks that `body` has queued, in at most two reads, and never
42
+ * waits for its source. The exception is a stream of the host's gzip whose
43
+ * source gave bytes: it waits for zlib's first chunk, so the head goes out
44
+ * with it.
45
+ */
46
+ async function readAhead(reader, body) {
47
+ const ahead = {
48
+ chunks: [],
49
+ size: 0,
50
+ done: false,
51
+ pending: void 0
52
+ };
53
+ for (let reads = 0; reads < 2 && !ahead.done && ahead.pending == null; reads += 1) {
54
+ let next = await readIfQueued(reader);
55
+ if ("pending" in next && reads === 0 && waitsForZlib(body) != null) {
56
+ await afterMicrotasks();
57
+ if (waitsForZlib(body) === true) next = { result: await next.pending };
58
+ }
59
+ if ("pending" in next) ahead.pending = next.pending;
60
+ else if (next.result.done) ahead.done = true;
61
+ else {
62
+ const chunk = bytesOf(next.result.value);
63
+ ahead.chunks.push(chunk);
64
+ ahead.size += chunk.byteLength;
65
+ }
66
+ }
67
+ return ahead;
68
+ }
69
+ /**
70
+ * Writes the rest of the body at the pace of the client, then ends the
71
+ * response. Why no length check: `strictContentLength` makes Node throw for a
72
+ * body that does not match its `Content-Length`.
73
+ */
74
+ async function pump(reader, first, { outgoing, edge }) {
75
+ let read = first;
76
+ for (;;) {
77
+ const result = await read;
78
+ if (outgoing.destroyed) return;
79
+ if (result.done) {
80
+ outgoing.end();
81
+ return;
82
+ }
83
+ const chunk = bytesOf(result.value);
84
+ const flowing = outgoing.write(chunk);
85
+ edge.bytes += chunk.byteLength;
86
+ if (!flowing) await drained(outgoing);
87
+ read = reader.read();
88
+ }
89
+ }
90
+ /** The headers that `outgoing` sent, as a flat list. Why: the dev server stage sends its own head. */
91
+ function sentHead(outgoing) {
92
+ const head = [];
93
+ for (const [name, value] of Object.entries(outgoing.getHeaders())) for (const each of Array.isArray(value) ? value : [value]) if (each != null) head.push(name, String(each));
94
+ return head;
95
+ }
96
+ /** Writes the head and the body of `response`, with `head` in place of its headers. */
97
+ async function writeBody(response, reader, { outgoing, edge, head }) {
98
+ const { body, status } = response;
99
+ if (body == null || reader == null) {
100
+ outgoing.writeHead(status, head);
101
+ outgoing.end();
102
+ return;
103
+ }
104
+ if (headerIndex(head, "content-type") === -1) head.push("content-type", DEFAULT_CONTENT_TYPE);
105
+ const ahead = await readAhead(reader, body);
106
+ if (outgoing.destroyed) return;
107
+ if (ahead.done) {
108
+ const index = headerIndex(head, "content-length");
109
+ if (index === -1 && headerIndex(head, "transfer-encoding") === -1) head.push("content-length", String(ahead.size));
110
+ else if (index !== -1 && Number(head[index + 1]) !== ahead.size) throw new Error("The body does not match its Content-Length.");
111
+ outgoing.writeHead(status, head);
112
+ outgoing.end(ahead.chunks.length === 1 ? ahead.chunks[0] : Buffer.concat(ahead.chunks));
113
+ edge.bytes += ahead.size;
114
+ return;
115
+ }
116
+ outgoing.writeHead(status, head);
117
+ for (const chunk of ahead.chunks) {
118
+ outgoing.write(chunk);
119
+ edge.bytes += chunk.byteLength;
120
+ }
121
+ if (ahead.chunks.length === 0) outgoing.flushHeaders();
122
+ await pump(reader, ahead.pending ?? reader.read(), {
123
+ outgoing,
124
+ edge
125
+ });
126
+ }
127
+ /**
128
+ * Writes `response` to `outgoing`, with the headers that the server gave
129
+ * `edge` for it, and counts the body bytes in `edge`. It never rejects.
130
+ *
131
+ * - A body that ends within two reads of the chunks that it has queued goes
132
+ * out with its `Content-Length`, in one socket write with the head.
133
+ * - When the first chunk is not ready, the head goes out at once, so an event
134
+ * stream opens at once. A stream of the host's gzip whose source gave bytes
135
+ * is the exception: zlib finishes it soon, so the head waits for it.
136
+ * - It reads the next chunk only when Node takes the last one, and it cancels
137
+ * the body when the socket closes.
138
+ * - When a step fails before the head goes out, such as a body that fails or
139
+ * a header that Node rejects, a 500 goes out. After the head, a failure or
140
+ * a body that does not match its `Content-Length` destroys the socket, so
141
+ * no client and no cache keeps a cut response as complete.
142
+ */
143
+ async function writeResponse(response, outgoing, edge) {
144
+ const { body } = response;
145
+ let { status } = response;
146
+ const sendsBody = outgoing.req.method !== "HEAD";
147
+ if (body == null && response.headers.has(ALREADY_SENT_HEADER)) {
148
+ edge.bytes = sendsBody ? Number(response.headers.get("content-length") ?? 0) : 0;
149
+ edge.close(status, false, sentHead(outgoing));
150
+ return;
151
+ }
152
+ let head = edge.headersFor(response) ?? headerList(response.headers);
153
+ if (outgoing.destroyed) {
154
+ edge.close(status, true, head);
155
+ await body?.cancel().catch(() => {});
156
+ return;
157
+ }
158
+ let reader;
159
+ outgoing.on("close", () => {
160
+ edge.close(status, !outgoing.writableFinished, head);
161
+ reader?.cancel().catch(() => {});
162
+ });
163
+ try {
164
+ reader = body?.getReader();
165
+ outgoing.strictContentLength = true;
166
+ await writeBody(response, reader, {
167
+ outgoing,
168
+ edge,
169
+ head
170
+ });
171
+ } catch (error) {
172
+ reader?.cancel(error).catch(() => {});
173
+ edge.fail(error);
174
+ if (outgoing.headersSent || outgoing.destroyed) {
175
+ outgoing.destroy(error instanceof Error ? error : new Error(String(error)));
176
+ return;
177
+ }
178
+ status = 500;
179
+ head = [
180
+ "content-type",
181
+ DEFAULT_CONTENT_TYPE,
182
+ "content-length",
183
+ String(ERROR_BODY.byteLength)
184
+ ];
185
+ outgoing.writeHead(status, head);
186
+ outgoing.end(ERROR_BODY);
187
+ if (sendsBody) edge.bytes += ERROR_BODY.byteLength;
188
+ }
189
+ }
190
+ /**
191
+ * Runs `create`, which makes a listener of `@hono/node-server`, and keeps the
192
+ * global `Response`. The listener makes its own `Request` class global.
193
+ *
194
+ * Why its `Request`: the listener gives each route a light request, and only
195
+ * that class can copy it, such as `new Request(c.req.raw, init)` in Hono's
196
+ * `methodOverride`. Why not its `Response`: a `fetch()` result must stay an
197
+ * `instanceof Response`, as on Bun and Deno.
198
+ *
199
+ * @example
200
+ * const listener = keepGlobalResponse(() => getRequestListener(app.fetch));
201
+ */
202
+ function keepGlobalResponse(create) {
203
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "Response");
204
+ try {
205
+ return create();
206
+ } finally {
207
+ if (descriptor != null) Object.defineProperty(globalThis, "Response", descriptor);
208
+ }
209
+ }
210
+ /** A `Host` header that a URL keeps as it is: a name or an address, and an optional port. */
211
+ const VALID_HOST = /^[a-z0-9.-]+(?::\d{1,5})?$/iu;
212
+ /** The request target that the client sent, on a request that {@link useForwardedProto} changed. */
213
+ const SENT_TARGET = Symbol("sentTarget");
214
+ /**
215
+ * Gives `incoming` an absolute target with the scheme of its
216
+ * `X-Forwarded-Proto`. Why: `@hono/node-server` takes the scheme from the
217
+ * socket, which is plain HTTP behind a proxy that ends TLS. A target with the
218
+ * scheme gives the request its URL when it is made, so the server copies no
219
+ * request to change it. {@link listenerOf} then puts the target that the
220
+ * client sent back.
221
+ */
222
+ function useForwardedProto(incoming) {
223
+ const { host, "x-forwarded-proto": proto } = incoming.headers;
224
+ const target = incoming.url;
225
+ if ((proto === "https" || proto === "http") && host != null && VALID_HOST.test(host) && target?.startsWith("/") === true) {
226
+ incoming[SENT_TARGET] = target;
227
+ incoming.url = `${proto}://${proto === "https" && host.endsWith(":80") ? host.slice(0, -3) : host}${target}`;
228
+ }
229
+ }
230
+ /**
231
+ * Why not on Bun and Deno: their `node:http` does not always emit `close` or
232
+ * set `destroyed`, so `@hono/node-server` writes the response there.
233
+ */
234
+ const writesResponses = !("Bun" in globalThis) && !("Deno" in globalThis);
235
+ /**
236
+ * A `node:http` request listener. `@hono/node-server` builds each request,
237
+ * `answer` makes the response, and the listener writes it. Each HTTP/1
238
+ * request on Node.js gets an `edge` binding, so the server gives the listener
239
+ * the headers after its header hooks, and the access log takes the bytes from
240
+ * the listener.
241
+ * With `trustForwardedProto`, each request takes its scheme from
242
+ * `X-Forwarded-Proto`, as the server option does.
243
+ *
244
+ * @example
245
+ * http.createServer(requestListener(async (request, bindings) => app.fetch(request, bindings)));
246
+ */
247
+ function requestListener(answer, { trustForwardedProto = false } = {}) {
248
+ const listener = listenerOf(answer);
249
+ return trustForwardedProto ? async (incoming, outgoing) => {
250
+ if (incoming instanceof IncomingMessage) useForwardedProto(incoming);
251
+ return listener(incoming, outgoing);
252
+ } : listener;
253
+ }
254
+ /** The listener of {@link requestListener}, with no scheme from `X-Forwarded-Proto`. */
255
+ function listenerOf(answer) {
256
+ return keepGlobalResponse(() => getRequestListener(async (request, { incoming, outgoing }) => {
257
+ const { remoteAddress } = incoming.socket;
258
+ if (!(incoming instanceof IncomingMessage) || !(outgoing instanceof ServerResponse)) return answer(request, { remoteAddress });
259
+ const target = incoming[SENT_TARGET];
260
+ if (target != null) incoming.url = target;
261
+ if (!writesResponses) {
262
+ const response = await answer(request, {
263
+ remoteAddress,
264
+ incoming,
265
+ outgoing
266
+ });
267
+ if (outgoing.destroyed) await response.body?.cancel();
268
+ return response;
269
+ }
270
+ const edge = new ResponseEdge();
271
+ let response;
272
+ try {
273
+ response = await answer(request, {
274
+ remoteAddress,
275
+ incoming,
276
+ outgoing,
277
+ edge
278
+ });
279
+ } catch (error) {
280
+ edge.close(500, false, []);
281
+ throw error;
282
+ }
283
+ await writeResponse(response, outgoing, edge);
284
+ return ALREADY_SENT;
285
+ }));
286
+ }
287
+
288
+ export { requestListener as t };
289
+ //# sourceMappingURL=response-writer-B7FoJjEE.js.map