@ngrok/app-server 0.2.0 → 0.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.
Files changed (108) hide show
  1. package/README.md +652 -77
  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-browser.d.ts +12 -0
  9. package/dist/client-browser.js +3 -0
  10. package/dist/client.d.ts +21 -0
  11. package/dist/client.js +27 -0
  12. package/dist/client.js.map +1 -0
  13. package/dist/compression-7_gToa8R.js +97 -0
  14. package/dist/compression-7_gToa8R.js.map +1 -0
  15. package/dist/create-server-DkTeIJ8L.js +1409 -0
  16. package/dist/create-server-DkTeIJ8L.js.map +1 -0
  17. package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
  18. package/dist/deno-aqhikNMG.js.map +1 -0
  19. package/dist/entry-CM6Ma-Tv.d.ts +626 -0
  20. package/dist/entry-CenmvESk.js +116 -0
  21. package/dist/entry-CenmvESk.js.map +1 -0
  22. package/dist/gzip-Doi4wqjX.js +294 -0
  23. package/dist/gzip-Doi4wqjX.js.map +1 -0
  24. package/dist/header-hook-Vzw9J9BY.js +159 -0
  25. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  26. package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
  27. package/dist/index.d.ts +99 -269
  28. package/dist/index.js +47 -59
  29. package/dist/index.js.map +1 -1
  30. package/dist/listen-options-7TaXjyrk.js.map +1 -1
  31. package/dist/{load-entry-C03qqmhr.js → load-entry-CmkdlmDX.js} +8 -4
  32. package/dist/{load-entry-C03qqmhr.js.map → load-entry-CmkdlmDX.js.map} +1 -1
  33. package/dist/log-BP6xXXZl.js +122 -0
  34. package/dist/log-BP6xXXZl.js.map +1 -0
  35. package/dist/node-BFH82eeL.js +333 -0
  36. package/dist/node-BFH82eeL.js.map +1 -0
  37. package/dist/node-tBVQPjQv.js +41 -0
  38. package/dist/node-tBVQPjQv.js.map +1 -0
  39. package/dist/node-vite.d.ts +5 -4
  40. package/dist/node-vite.js +2 -17
  41. package/dist/node.d.ts +23 -4
  42. package/dist/node.js +2 -2
  43. package/dist/react-router-vite.d.ts +4 -3
  44. package/dist/react-router-vite.js +2 -20
  45. package/dist/react-router.d.ts +1 -1
  46. package/dist/react-router.js +8 -7
  47. package/dist/react-router.js.map +1 -1
  48. package/dist/request-context-BtQ87VYb.js +40 -0
  49. package/dist/request-context-BtQ87VYb.js.map +1 -0
  50. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  51. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  52. package/dist/response-writer-B7FoJjEE.js +289 -0
  53. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  54. package/dist/script-hashes-hqUk6kG7.js +53 -0
  55. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  56. package/dist/{serve-Cleo8RMO.js → serve-Cc-ADdhZ.js} +3 -3
  57. package/dist/{serve-Cleo8RMO.js.map → serve-Cc-ADdhZ.js.map} +1 -1
  58. package/dist/stale-build-navigation-PnMLtTF8.js +339 -0
  59. package/dist/stale-build-navigation-PnMLtTF8.js.map +1 -0
  60. package/dist/stale-build-navigation-ypV7Ow4o.d.ts +141 -0
  61. package/dist/{start-CINALHxy.js → start-Cb3kknlF.js} +14 -19
  62. package/dist/start-Cb3kknlF.js.map +1 -0
  63. package/dist/static-files-Beju9riB.js +302 -0
  64. package/dist/static-files-Beju9riB.js.map +1 -0
  65. package/dist/tanstack-start-vite.d.ts +6 -5
  66. package/dist/tanstack-start-vite.js +2 -23
  67. package/dist/tanstack-start.d.ts +19 -2
  68. package/dist/tanstack-start.js +5 -14
  69. package/dist/tanstack-start.js.map +1 -1
  70. package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
  71. package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
  72. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  73. package/dist/types-DLYxYS6M.d.ts +392 -0
  74. package/dist/vercel-vite.d.ts +35 -0
  75. package/dist/vercel-vite.js +142 -0
  76. package/dist/vercel-vite.js.map +1 -0
  77. package/dist/vercel.d.ts +35 -0
  78. package/dist/vercel.js +89 -0
  79. package/dist/vercel.js.map +1 -0
  80. package/dist/vite-B-GfswoH.js +22 -0
  81. package/dist/vite-B-GfswoH.js.map +1 -0
  82. package/dist/vite-D4hfj3ph.js +19 -0
  83. package/dist/vite-D4hfj3ph.js.map +1 -0
  84. package/dist/vite-DyrhyKEr.js +25 -0
  85. package/dist/vite-DyrhyKEr.js.map +1 -0
  86. package/dist/vite-iioAoxSt.js +752 -0
  87. package/dist/vite-iioAoxSt.js.map +1 -0
  88. package/dist/vite.d.ts +2 -2
  89. package/dist/vite.js +1 -1
  90. package/package.json +25 -4
  91. package/dist/build-manifest-8NfD1wnO.js.map +0 -1
  92. package/dist/deno-DNRgzHrk.js.map +0 -1
  93. package/dist/entry-BkdUub2S.js +0 -638
  94. package/dist/entry-BkdUub2S.js.map +0 -1
  95. package/dist/log-CsjaKM8U.js +0 -59
  96. package/dist/log-CsjaKM8U.js.map +0 -1
  97. package/dist/node-CG7qXuWZ.js +0 -58
  98. package/dist/node-CG7qXuWZ.js.map +0 -1
  99. package/dist/node-YWPGmzAk.js +0 -215
  100. package/dist/node-YWPGmzAk.js.map +0 -1
  101. package/dist/node-ZMowKZDB.js +0 -3
  102. package/dist/node-vite.js.map +0 -1
  103. package/dist/react-router-vite.js.map +0 -1
  104. package/dist/start-CINALHxy.js.map +0 -1
  105. package/dist/tanstack-start-vite.js.map +0 -1
  106. package/dist/types-BfCkS7kQ.d.ts +0 -203
  107. package/dist/vite-mYZ2Y69u.js +0 -144
  108. package/dist/vite-mYZ2Y69u.js.map +0 -1
@@ -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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-writer-B7FoJjEE.js","names":["targeted"],"sources":["../src/node/response-writer.ts"],"sourcesContent":["import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { readIfQueued } from \"../core/compression.js\";\nimport type { ReadResult } from \"../core/compression.js\";\nimport { headerIndex, headerList } from \"../core/header-hook.js\";\nimport { ResponseEdge } from \"../core/response-edge.js\";\nimport type { ListenerBindings } from \"../core/types.js\";\nimport type { NodeBindings } from \"./dev-server.js\";\nimport { waitsForZlib } from \"./gzip.js\";\n\n/** The header of a response that went out through Node's response already, as the dev server stage sends it. */\nconst ALREADY_SENT_HEADER = \"x-hono-already-sent\";\n/** Why one object for all requests: `@hono/node-server` only reads its headers. */\nconst ALREADY_SENT = new Response(null, { headers: { [ALREADY_SENT_HEADER]: \"true\" } });\n/** The type that `@hono/node-server` gives a body with none. */\nconst DEFAULT_CONTENT_TYPE = \"text/plain; charset=UTF-8\";\n/** The body of the 500 that goes out when the response cannot. */\nconst ERROR_BODY = Buffer.from(\"Internal Server Error\");\n\n/** Resolves after the microtasks that are queued now, and the ones that they queue. */\nasync function afterMicrotasks(): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tprocess.nextTick(resolve);\n\t});\n}\n\n/** Resolves on the next `drain` of `outgoing`, or when it closes. */\nasync function drained(outgoing: ServerResponse): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tconst done = () => {\n\t\t\toutgoing.off(\"drain\", done);\n\t\t\toutgoing.off(\"close\", done);\n\t\t\tresolve();\n\t\t};\n\t\toutgoing.on(\"drain\", done);\n\t\toutgoing.on(\"close\", done);\n\t});\n}\n\n/** `value` as a body chunk. Why throw: a string chunk has no `byteLength`, and the Fetch standard allows bytes only. */\nfunction bytesOf(value: unknown): Uint8Array {\n\tif (value instanceof Uint8Array) {\n\t\treturn value;\n\t}\n\tthrow new TypeError(\"A response body gave a chunk that is not a Uint8Array.\");\n}\n\n/** The chunks that a body had queued in at most two reads, and the read that is still open. */\ntype Ahead = {\n\tchunks: Uint8Array[];\n\tsize: number;\n\tdone: boolean;\n\tpending: Promise<ReadResult> | undefined;\n};\n\n/**\n * Reads the chunks that `body` has queued, in at most two reads, and never\n * waits for its source. The exception is a stream of the host's gzip whose\n * source gave bytes: it waits for zlib's first chunk, so the head goes out\n * with it.\n */\nasync function readAhead(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tbody: ReadableStream<Uint8Array>,\n): Promise<Ahead> {\n\tconst ahead: Ahead = { chunks: [], size: 0, done: false, pending: undefined };\n\tfor (let reads = 0; reads < 2 && !ahead.done && ahead.pending == null; reads += 1) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- each read takes only a chunk that is queued already.\n\t\tlet next = await readIfQueued(reader);\n\t\tif (\"pending\" in next && reads === 0 && waitsForZlib(body) != null) {\n\t\t\t// Why wait: the host's gzip stream gets its source chunk in a later microtask.\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\tawait afterMicrotasks();\n\t\t\tif (waitsForZlib(body) === true) {\n\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\t\tnext = { result: await next.pending };\n\t\t\t}\n\t\t}\n\t\tif (\"pending\" in next) {\n\t\t\tahead.pending = next.pending;\n\t\t} else if (next.result.done) {\n\t\t\tahead.done = true;\n\t\t} else {\n\t\t\tconst chunk = bytesOf(next.result.value);\n\t\t\tahead.chunks.push(chunk);\n\t\t\tahead.size += chunk.byteLength;\n\t\t}\n\t}\n\treturn ahead;\n}\n\n/**\n * Writes the rest of the body at the pace of the client, then ends the\n * response. Why no length check: `strictContentLength` makes Node throw for a\n * body that does not match its `Content-Length`.\n */\nasync function pump(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tfirst: Promise<ReadResult>,\n\t{ outgoing, edge }: { outgoing: ServerResponse; edge: ResponseEdge },\n): Promise<void> {\n\tlet read = first;\n\tfor (;;) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- the next read waits for the socket.\n\t\tconst result = await read;\n\t\tif (outgoing.destroyed) {\n\t\t\treturn;\n\t\t}\n\t\tif (result.done) {\n\t\t\toutgoing.end();\n\t\t\treturn;\n\t\t}\n\t\tconst chunk = bytesOf(result.value);\n\t\tconst flowing = outgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t\tif (!flowing) {\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- the client sets the pace.\n\t\t\tawait drained(outgoing);\n\t\t}\n\t\tread = reader.read();\n\t}\n}\n\n/** The headers that `outgoing` sent, as a flat list. Why: the dev server stage sends its own head. */\nfunction sentHead(outgoing: ServerResponse): string[] {\n\tconst head: string[] = [];\n\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\tif (each != null) {\n\t\t\t\thead.push(name, String(each));\n\t\t\t}\n\t\t}\n\t}\n\treturn head;\n}\n\n/** Writes the head and the body of `response`, with `head` in place of its headers. */\nasync function writeBody(\n\tresponse: Response,\n\treader: ReadableStreamDefaultReader<Uint8Array> | undefined,\n\t{ outgoing, edge, head }: { outgoing: ServerResponse; edge: ResponseEdge; head: string[] },\n): Promise<void> {\n\tconst { body, status } = response;\n\tif (body == null || reader == null) {\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end();\n\t\treturn;\n\t}\n\tif (headerIndex(head, \"content-type\") === -1) {\n\t\thead.push(\"content-type\", DEFAULT_CONTENT_TYPE);\n\t}\n\tconst ahead = await readAhead(reader, body);\n\tif (outgoing.destroyed) {\n\t\treturn;\n\t}\n\tif (ahead.done) {\n\t\tconst index = headerIndex(head, \"content-length\");\n\t\tif (index === -1 && headerIndex(head, \"transfer-encoding\") === -1) {\n\t\t\thead.push(\"content-length\", String(ahead.size));\n\t\t} else if (index !== -1 && Number(head[index + 1]) !== ahead.size) {\n\t\t\tthrow new Error(\"The body does not match its Content-Length.\");\n\t\t}\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ahead.chunks.length === 1 ? ahead.chunks[0] : Buffer.concat(ahead.chunks));\n\t\tedge.bytes += ahead.size;\n\t\treturn;\n\t}\n\toutgoing.writeHead(status, head);\n\tfor (const chunk of ahead.chunks) {\n\t\toutgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t}\n\tif (ahead.chunks.length === 0) {\n\t\t// Why: the client gets the head at once, such as the open of an event stream.\n\t\toutgoing.flushHeaders();\n\t}\n\tawait pump(reader, ahead.pending ?? reader.read(), { outgoing, edge });\n}\n\n/**\n * Writes `response` to `outgoing`, with the headers that the server gave\n * `edge` for it, and counts the body bytes in `edge`. It never rejects.\n *\n * - A body that ends within two reads of the chunks that it has queued goes\n * out with its `Content-Length`, in one socket write with the head.\n * - When the first chunk is not ready, the head goes out at once, so an event\n * stream opens at once. A stream of the host's gzip whose source gave bytes\n * is the exception: zlib finishes it soon, so the head waits for it.\n * - It reads the next chunk only when Node takes the last one, and it cancels\n * the body when the socket closes.\n * - When a step fails before the head goes out, such as a body that fails or\n * a header that Node rejects, a 500 goes out. After the head, a failure or\n * a body that does not match its `Content-Length` destroys the socket, so\n * no client and no cache keeps a cut response as complete.\n */\nasync function writeResponse(\n\tresponse: Response,\n\toutgoing: ServerResponse,\n\tedge: ResponseEdge,\n): Promise<void> {\n\tconst { body } = response;\n\tlet { status } = response;\n\tconst sendsBody = outgoing.req.method !== \"HEAD\";\n\tif (body == null && response.headers.has(ALREADY_SENT_HEADER)) {\n\t\t// Why: the dev server stage answered through Node's response, and gave its status and length.\n\t\t// Node sends no body for HEAD.\n\t\tedge.bytes = sendsBody ? Number(response.headers.get(\"content-length\") ?? 0) : 0;\n\t\tedge.close(status, false, sentHead(outgoing));\n\t\treturn;\n\t}\n\t// Why one list: `writeBody` adds the headers that it sets, so the report gets the head that went out.\n\tlet head = edge.headersFor(response) ?? headerList(response.headers);\n\tif (outgoing.destroyed) {\n\t\tedge.close(status, true, head);\n\t\tawait body?.cancel().catch(() => {});\n\t\treturn;\n\t}\n\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t// Why one listener: it reports what went out and stops the body that the client no longer reads.\n\t// Why `on`: a response emits `close` once, and `once` adds a wrapper for each request.\n\toutgoing.on(\"close\", () => {\n\t\tedge.close(status, !outgoing.writableFinished, head);\n\t\treader?.cancel().catch(() => {});\n\t});\n\ttry {\n\t\treader = body?.getReader();\n\t\t// Why strict: Node then throws for a body that is longer or shorter than its `Content-Length`.\n\t\toutgoing.strictContentLength = true;\n\t\tawait writeBody(response, reader, { outgoing, edge, head });\n\t} catch (error) {\n\t\treader?.cancel(error).catch(() => {});\n\t\tedge.fail(error);\n\t\tif (outgoing.headersSent || outgoing.destroyed) {\n\t\t\toutgoing.destroy(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\t\tstatus = 500;\n\t\thead = [\"content-type\", DEFAULT_CONTENT_TYPE, \"content-length\", String(ERROR_BODY.byteLength)];\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ERROR_BODY);\n\t\tif (sendsBody) {\n\t\t\tedge.bytes += ERROR_BODY.byteLength;\n\t\t}\n\t}\n}\n\n/**\n * Runs `create`, which makes a listener of `@hono/node-server`, and keeps the\n * global `Response`. The listener makes its own `Request` class global.\n *\n * Why its `Request`: the listener gives each route a light request, and only\n * that class can copy it, such as `new Request(c.req.raw, init)` in Hono's\n * `methodOverride`. Why not its `Response`: a `fetch()` result must stay an\n * `instanceof Response`, as on Bun and Deno.\n *\n * @example\n * const listener = keepGlobalResponse(() => getRequestListener(app.fetch));\n */\nexport function keepGlobalResponse<T>(create: () => T): T {\n\t// Why the descriptor: on Deno, the listener leaves a `Response` that no one can assign.\n\tconst descriptor = Object.getOwnPropertyDescriptor(globalThis, \"Response\");\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tif (descriptor != null) {\n\t\t\tObject.defineProperty(globalThis, \"Response\", descriptor);\n\t\t}\n\t}\n}\n\n/** A `Host` header that a URL keeps as it is: a name or an address, and an optional port. */\nconst VALID_HOST = /^[a-z0-9.-]+(?::\\d{1,5})?$/iu;\n\n/** The request target that the client sent, on a request that {@link useForwardedProto} changed. */\nconst SENT_TARGET = Symbol(\"sentTarget\");\n\n/** A Node request whose target can carry the target that the client sent. */\ntype Targeted = IncomingMessage & { [SENT_TARGET]?: string };\n\n/**\n * Gives `incoming` an absolute target with the scheme of its\n * `X-Forwarded-Proto`. Why: `@hono/node-server` takes the scheme from the\n * socket, which is plain HTTP behind a proxy that ends TLS. A target with the\n * scheme gives the request its URL when it is made, so the server copies no\n * request to change it. {@link listenerOf} then puts the target that the\n * client sent back.\n */\nfunction useForwardedProto(incoming: Targeted): void {\n\tconst { host, \"x-forwarded-proto\": proto } = incoming.headers;\n\tconst target = incoming.url;\n\tif (\n\t\t(proto === \"https\" || proto === \"http\") &&\n\t\thost != null &&\n\t\tVALID_HOST.test(host) &&\n\t\ttarget?.startsWith(\"/\") === true\n\t) {\n\t\tincoming[SENT_TARGET] = target;\n\t\t// Why drop `:80` for https: a proxy can send the port of its own hop, and the server took the\n\t\t// scheme from the socket first, where 80 is the default port, so the URL never kept it.\n\t\tconst authority = proto === \"https\" && host.endsWith(\":80\") ? host.slice(0, -3) : host;\n\t\tincoming.url = `${proto}://${authority}${target}`;\n\t}\n}\n\n/**\n * Why not on Bun and Deno: their `node:http` does not always emit `close` or\n * set `destroyed`, so `@hono/node-server` writes the response there.\n */\nconst writesResponses = !(\"Bun\" in globalThis) && !(\"Deno\" in globalThis);\n\n/**\n * A `node:http` request listener. `@hono/node-server` builds each request,\n * `answer` makes the response, and the listener writes it. Each HTTP/1\n * request on Node.js gets an `edge` binding, so the server gives the listener\n * the headers after its header hooks, and the access log takes the bytes from\n * the listener.\n * With `trustForwardedProto`, each request takes its scheme from\n * `X-Forwarded-Proto`, as the server option does.\n *\n * @example\n * http.createServer(requestListener(async (request, bindings) => app.fetch(request, bindings)));\n */\nexport function requestListener(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n\t{ trustForwardedProto = false }: { trustForwardedProto?: boolean } = {},\n): ReturnType<typeof getRequestListener> {\n\tconst listener = listenerOf(answer);\n\treturn trustForwardedProto\n\t\t? async (incoming, outgoing) => {\n\t\t\t\tif (incoming instanceof IncomingMessage) {\n\t\t\t\t\tuseForwardedProto(incoming);\n\t\t\t\t}\n\t\t\t\treturn listener(incoming, outgoing);\n\t\t\t}\n\t\t: listener;\n}\n\n/** The listener of {@link requestListener}, with no scheme from `X-Forwarded-Proto`. */\nfunction listenerOf(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n): ReturnType<typeof getRequestListener> {\n\treturn keepGlobalResponse(() =>\n\t\tgetRequestListener(async (request, { incoming, outgoing }) => {\n\t\t\tconst { remoteAddress } = incoming.socket;\n\t\t\t// Why: an HTTP/2 response is not a `ServerResponse`, so `@hono/node-server` writes it.\n\t\t\tif (!(incoming instanceof IncomingMessage) || !(outgoing instanceof ServerResponse)) {\n\t\t\t\treturn answer(request, { remoteAddress } satisfies ListenerBindings);\n\t\t\t}\n\t\t\tconst targeted: Targeted = incoming;\n\t\t\tconst target = targeted[SENT_TARGET];\n\t\t\t// Why: the request has its URL now, and the app gets the target that the client sent.\n\t\t\tif (target != null) {\n\t\t\t\tincoming.url = target;\n\t\t\t}\n\t\t\tif (!writesResponses) {\n\t\t\t\tconst response = await answer(request, { remoteAddress, incoming, outgoing });\n\t\t\t\t// Why: `@hono/node-server` drops the body of a response whose socket closed, with no cancel.\n\t\t\t\tif (outgoing.destroyed) {\n\t\t\t\t\tawait response.body?.cancel();\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\tconst edge = new ResponseEdge();\n\t\t\tlet response: Response;\n\t\t\ttry {\n\t\t\t\tresponse = await answer(request, { remoteAddress, incoming, outgoing, edge });\n\t\t\t} catch (error) {\n\t\t\t\t// Why 500 with no headers: `@hono/node-server` answers a failed request with one.\n\t\t\t\tedge.close(500, false, []);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait writeResponse(response, outgoing, edge);\n\t\t\treturn ALREADY_SENT;\n\t\t}),\n\t);\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,sBAAsB;;AAE5B,MAAM,eAAe,IAAI,SAAS,MAAM,EAAE,SAAS,GAAG,sBAAsB,OAAO,EAAE,CAAC;;AAEtF,MAAM,uBAAuB;;AAE7B,MAAM,aAAa,OAAO,KAAK,uBAAuB;;AAGtD,eAAe,kBAAiC;CAC/C,OAAO,IAAI,SAAS,YAAY;EAC/B,QAAQ,SAAS,OAAO;CACzB,CAAC;AACF;;AAGA,eAAe,QAAQ,UAAyC;CAC/D,OAAO,IAAI,SAAS,YAAY;EAC/B,MAAM,aAAa;GAClB,SAAS,IAAI,SAAS,IAAI;GAC1B,SAAS,IAAI,SAAS,IAAI;GAC1B,QAAQ;EACT;EACA,SAAS,GAAG,SAAS,IAAI;EACzB,SAAS,GAAG,SAAS,IAAI;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GACH,WAAW,MAAM,OAAO,SAAS;IAAE;IAAe;IAAU;IAAU;GAAK,CAAC;EAC7E,SAAS,OAAO;GAEf,KAAK,MAAM,KAAK,OAAO,CAAC,CAAC;GACzB,MAAM;EACP;EACA,MAAM,cAAc,UAAU,UAAU,IAAI;EAC5C,OAAO;CACR,CAAC,CACF;AACD"}
@@ -0,0 +1,53 @@
1
+ import { t as contentType } from "./static-files-Beju9riB.js";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { resolve, sep } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+
6
+ // src/node/script-hashes.ts
7
+ /**
8
+ * An HTML comment, or a `<script>` element. The `attributes` group is the
9
+ * script's attributes, and the `text` group is its text. Why the comment: a
10
+ * `<script>` tag in a comment starts no element.
11
+ */
12
+ const COMMENT_OR_SCRIPT = /<!--[\s\S]*?-->|<script(?=[\s/>])(?<attributes>(?:[^>"']|"[^"]*"|'[^']*')*)>(?<text>[\s\S]*?)<\/script(?=[\s/>])/giu;
13
+ /** An attribute value, so that a `src=` in a value is not the `src` attribute. */
14
+ const ATTRIBUTE_VALUE = /[=]\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gu;
15
+ /** A `src` attribute, in attributes with no values. */
16
+ const SRC_ATTRIBUTE = /(?:^|[\s/])src(?:[\s/=]|$)/iu;
17
+ /**
18
+ * The base64 `SHA-256` of each inline script in `html`, once each, in
19
+ * document order. Why each type: a hash of a data block, such as JSON, trusts
20
+ * no code, and a scan that skips a type that runs breaks the page. Why LF:
21
+ * the browser changes each CRLF and CR to LF before it hashes a script.
22
+ *
23
+ * @example
24
+ * inlineScriptHashes("<script>go()<\/script>"); // => ["…base64…"]
25
+ */
26
+ function inlineScriptHashes(html) {
27
+ const hashes = [];
28
+ for (const { groups } of html.replaceAll(/\r\n?/gu, "\n").matchAll(COMMENT_OR_SCRIPT)) if (groups?.text != null && !SRC_ATTRIBUTE.test((groups.attributes ?? "").replaceAll(ATTRIBUTE_VALUE, "="))) hashes.push(createHash("sha256").update(groups.text).digest("base64"));
29
+ return [...new Set(hashes)];
30
+ }
31
+ /**
32
+ * The {@link inlineScriptHashes} of the HTML file at the URL `path` in
33
+ * `directory`, such as Vite's public directory, or `undefined` when it has no
34
+ * such file. Why it reads the file for each call: a developer can edit it at
35
+ * any time, and only a request for an HTML file reads it.
36
+ *
37
+ * @example
38
+ * publicScriptHashes("/app/public", "/offline.html"); // => ["…base64…"]
39
+ */
40
+ function publicScriptHashes(directory, path) {
41
+ if (directory === "") return;
42
+ try {
43
+ const decoded = decodeURIComponent(path);
44
+ const file = resolve(directory, `.${decoded}`);
45
+ if (!contentType(decoded, {}).startsWith("text/html") || !file.startsWith(`${resolve(directory)}${sep}`) || statSync(file, { throwIfNoEntry: false })?.isFile() !== true) return;
46
+ return inlineScriptHashes(readFileSync(file, "utf8"));
47
+ } catch {
48
+ return;
49
+ }
50
+ }
51
+
52
+ export { publicScriptHashes as n, inlineScriptHashes as t };
53
+ //# sourceMappingURL=script-hashes-hqUk6kG7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"script-hashes-hqUk6kG7.js","names":[],"sources":["../src/node/script-hashes.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFileSync, statSync } from \"node:fs\";\nimport { resolve, sep } from \"node:path\";\nimport { contentType } from \"../core/static-files.js\";\n\n/**\n * An HTML comment, or a `<script>` element. The `attributes` group is the\n * script's attributes, and the `text` group is its text. Why the comment: a\n * `<script>` tag in a comment starts no element.\n */\nconst COMMENT_OR_SCRIPT =\n\t/<!--[\\s\\S]*?-->|<script(?=[\\s/>])(?<attributes>(?:[^>\"']|\"[^\"]*\"|'[^']*')*)>(?<text>[\\s\\S]*?)<\\/script(?=[\\s/>])/giu;\n\n/** An attribute value, so that a `src=` in a value is not the `src` attribute. */\nconst ATTRIBUTE_VALUE = /[=]\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/gu;\n\n/** A `src` attribute, in attributes with no values. */\nconst SRC_ATTRIBUTE = /(?:^|[\\s/])src(?:[\\s/=]|$)/iu;\n\n/**\n * The base64 `SHA-256` of each inline script in `html`, once each, in\n * document order. Why each type: a hash of a data block, such as JSON, trusts\n * no code, and a scan that skips a type that runs breaks the page. Why LF:\n * the browser changes each CRLF and CR to LF before it hashes a script.\n *\n * @example\n * inlineScriptHashes(\"<script>go()</script>\"); // => [\"…base64…\"]\n */\nexport function inlineScriptHashes(html: string): string[] {\n\tconst hashes: string[] = [];\n\tfor (const { groups } of html.replaceAll(/\\r\\n?/gu, \"\\n\").matchAll(COMMENT_OR_SCRIPT)) {\n\t\tif (\n\t\t\tgroups?.text != null &&\n\t\t\t!SRC_ATTRIBUTE.test((groups.attributes ?? \"\").replaceAll(ATTRIBUTE_VALUE, \"=\"))\n\t\t) {\n\t\t\thashes.push(createHash(\"sha256\").update(groups.text).digest(\"base64\"));\n\t\t}\n\t}\n\treturn [...new Set(hashes)];\n}\n\n/**\n * The {@link inlineScriptHashes} of the HTML file at the URL `path` in\n * `directory`, such as Vite's public directory, or `undefined` when it has no\n * such file. Why it reads the file for each call: a developer can edit it at\n * any time, and only a request for an HTML file reads it.\n *\n * @example\n * publicScriptHashes(\"/app/public\", \"/offline.html\"); // => [\"…base64…\"]\n */\nexport function publicScriptHashes(directory: string, path: string): string[] | undefined {\n\tif (directory === \"\") {\n\t\treturn undefined;\n\t}\n\t// Why one `try`: a path that does not decode, a path with a null byte, and a file that the\n\t// developer deletes or locks between the checks each throw. The middleware then answers.\n\ttry {\n\t\tconst decoded = decodeURIComponent(path);\n\t\tconst file = resolve(directory, `.${decoded}`);\n\t\t// Why: a path such as `/../secret.html` must not leave the directory.\n\t\tif (\n\t\t\t!contentType(decoded, {}).startsWith(\"text/html\") ||\n\t\t\t!file.startsWith(`${resolve(directory)}${sep}`) ||\n\t\t\tstatSync(file, { throwIfNoEntry: false })?.isFile() !== true\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn inlineScriptHashes(readFileSync(file, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAM,oBACL;;AAGD,MAAM,kBAAkB;;AAGxB,MAAM,gBAAgB;;;;;;;;;;AAWtB,SAAgB,mBAAmB,MAAwB;CAC1D,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,EAAE,YAAY,KAAK,WAAW,WAAW,IAAI,CAAC,CAAC,SAAS,iBAAiB,GACnF,IACC,QAAQ,QAAQ,QAChB,CAAC,cAAc,MAAM,OAAO,cAAc,GAAE,CAAE,WAAW,iBAAiB,GAAG,CAAC,GAE9E,OAAO,KAAK,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,IAAI,CAAC,CAAC,OAAO,QAAQ,CAAC;CAGvE,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC3B;;;;;;;;;;AAWA,SAAgB,mBAAmB,WAAmB,MAAoC;CACzF,IAAI,cAAc,IACjB;CAID,IAAI;EACH,MAAM,UAAU,mBAAmB,IAAI;EACvC,MAAM,OAAO,QAAQ,WAAW,IAAI,SAAS;EAE7C,IACC,CAAC,YAAY,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,KAChD,CAAC,KAAK,WAAW,GAAG,QAAQ,SAAS,IAAI,KAAK,KAC9C,SAAS,MAAM,EAAE,gBAAgB,MAAM,CAAC,CAAC,EAAE,OAAO,MAAM,MAExD;EAED,OAAO,mBAAmB,aAAa,MAAM,MAAM,CAAC;CACrD,QAAQ;EACP;CACD;AACD"}
@@ -1,7 +1,7 @@
1
- import { t as loadEntry } from "./load-entry-C03qqmhr.js";
1
+ import { t as loadEntry } from "./load-entry-CmkdlmDX.js";
2
+ import { existsSync } from "node:fs";
2
3
  import { resolve } from "node:path";
3
4
  import { pathToFileURL } from "node:url";
4
- import { existsSync } from "node:fs";
5
5
 
6
6
  // src/cli/serve.ts
7
7
  /**
@@ -26,4 +26,4 @@ async function serve({ buildPath }) {
26
26
  }
27
27
 
28
28
  export { serve };
29
- //# sourceMappingURL=serve-Cleo8RMO.js.map
29
+ //# sourceMappingURL=serve-Cc-ADdhZ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve-Cleo8RMO.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
1
+ {"version":3,"file":"serve-Cc-ADdhZ.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}