@ngrok/app-server 0.4.1 → 0.5.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 (119) hide show
  1. package/README.md +223 -64
  2. package/dist/brotli-only-BVAagKt3.js +63 -0
  3. package/dist/build-id-CwMbED1n.js +245 -0
  4. package/dist/{build-manifest-DBMWe3Lx.js → build-manifest-CoBztw_6.js} +13 -4
  5. package/dist/bun-BCz6K_Xv.js +1 -2
  6. package/dist/check-count-DQl5z_qe.js +17 -0
  7. package/dist/cli.js +9 -6
  8. package/dist/client-browser.d.ts +2 -3
  9. package/dist/client-browser.js +1 -1
  10. package/dist/client.d.ts +5 -4
  11. package/dist/client.js +9 -6
  12. package/dist/{compress-Cp5NfXCC.js → compress-2w3jqBh7.js} +2 -3
  13. package/dist/{compression-CT2mWlKM.js → compression-uJxu0JVb.js} +32 -5
  14. package/dist/content-types-Le-5BNEC.js +10 -0
  15. package/dist/{create-server-Bp1yILQk.js → create-server-DVTZun6D.js} +617 -306
  16. package/dist/create-server-PA0qniaK.js +3 -0
  17. package/dist/{create-server-X2GR-U6t.d.ts → create-server-UVsHFQyK.d.ts} +116 -54
  18. package/dist/deno-aqhikNMG.js +1 -2
  19. package/dist/{entry-BoxCqc6w.js → entry-CMhX3yf8.js} +85 -65
  20. package/dist/entry-CvZ4U0ia.js +3 -0
  21. package/dist/{entry-DZTCaL3d.d.ts → entry-DBq_3s8X.d.ts} +10 -36
  22. package/dist/entry-protocol-C30UPXzy.js +14 -0
  23. package/dist/entry-source-DSE5NAJu.js +70 -0
  24. package/dist/entry-source-SHoE-DUP.js +3 -0
  25. package/dist/exit-Hh-O3gp4.js +83 -0
  26. package/dist/{header-hook-Vzw9J9BY.js → header-hook-JfqaTt34.js} +69 -23
  27. package/dist/{index-B8LsM6Mh.d.ts → index-gzGs53Ue.d.ts} +43 -38
  28. package/dist/index.d.ts +88 -44
  29. package/dist/index.js +216 -84
  30. package/dist/listen-options-7TaXjyrk.js +1 -2
  31. package/dist/{load-entry-CCPWbsrj.js → load-entry-Bgq1_HDV.js} +11 -12
  32. package/dist/{log-DQAS5gGT.js → log-DfC9D5_T.js} +70 -49
  33. package/dist/{node-D6m6e6EI.js → node-DQPrMFyc.js} +20 -8
  34. package/dist/node-DyKDFII0.js +263 -0
  35. package/dist/node-vite.d.ts +2 -3
  36. package/dist/node-vite.js +1 -1
  37. package/dist/node.d.ts +41 -64
  38. package/dist/node.js +3 -3
  39. package/dist/react-router-vite.d.ts +2 -3
  40. package/dist/react-router-vite.js +1 -1
  41. package/dist/react-router.d.ts +6 -17
  42. package/dist/react-router.js +9 -14
  43. package/dist/request-context-Cslbrscf.js +163 -0
  44. package/dist/{response-edge-CU8ZvL_F.js → response-edge-Ow5Pi5qF.js} +13 -10
  45. package/dist/{response-writer-D7KHfr8n.js → response-writer-Dd4Ey99f.js} +57 -21
  46. package/dist/{script-hashes-CU7P9oZU.js → script-hashes-BdvJ0QI_.js} +2 -3
  47. package/dist/serve-AatMo9k6.js +26 -0
  48. package/dist/{stale-build-navigation-rg5xxmTr.js → stale-build-navigation-Qf_Lem39.js} +4 -5
  49. package/dist/{stale-build-navigation-ypV7Ow4o.d.ts → stale-build-navigation-WjhD8zHi.d.ts} +4 -4
  50. package/dist/start-DYFyGKsM.js +470 -0
  51. package/dist/static-files-BdTPam5b.js +438 -0
  52. package/dist/static-pages-6IBHdYQc.d.ts +30 -0
  53. package/dist/tanstack-start-vite.d.ts +2 -3
  54. package/dist/tanstack-start-vite.js +1 -1
  55. package/dist/tanstack-start.d.ts +3 -4
  56. package/dist/tanstack-start.js +2 -3
  57. package/dist/tcp-3v4pmnYU.js +58 -0
  58. package/dist/testing.d.ts +8 -6
  59. package/dist/testing.js +19 -17
  60. package/dist/{trailing-slash-D2QWKWEu.d.ts → trailing-slash-C-yBKCib.d.ts} +2 -3
  61. package/dist/{types-MgFtkNQW.d.ts → types-KsKRDwAv.d.ts} +97 -46
  62. package/dist/vercel-pages.d.ts +3 -16
  63. package/dist/vercel-pages.js +1 -2
  64. package/dist/vercel-vite.d.ts +4 -5
  65. package/dist/vercel-vite.js +48 -44
  66. package/dist/vercel.d.ts +13 -10
  67. package/dist/vercel.js +48 -35
  68. package/dist/{vite-D4hfj3ph.js → vite-Brb8YR9I.js} +2 -7
  69. package/dist/{vite-B-GfswoH.js → vite-CHppJWp_.js} +5 -7
  70. package/dist/{vite-DyrhyKEr.js → vite-DjlHdyTM.js} +2 -7
  71. package/dist/vite.d.ts +2 -2
  72. package/dist/vite.js +885 -2
  73. package/package.json +13 -12
  74. package/dist/brotli-only-DrA29Ecw.js +0 -97
  75. package/dist/brotli-only-DrA29Ecw.js.map +0 -1
  76. package/dist/build-id-B0448vZH.js +0 -151
  77. package/dist/build-id-B0448vZH.js.map +0 -1
  78. package/dist/build-manifest-DBMWe3Lx.js.map +0 -1
  79. package/dist/bun-BCz6K_Xv.js.map +0 -1
  80. package/dist/cli.js.map +0 -1
  81. package/dist/client.js.map +0 -1
  82. package/dist/compress-Cp5NfXCC.js.map +0 -1
  83. package/dist/compression-CT2mWlKM.js.map +0 -1
  84. package/dist/create-server-Bp1yILQk.js.map +0 -1
  85. package/dist/deno-aqhikNMG.js.map +0 -1
  86. package/dist/entry-BoxCqc6w.js.map +0 -1
  87. package/dist/header-hook-Vzw9J9BY.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/listen-options-7TaXjyrk.js.map +0 -1
  90. package/dist/load-entry-CCPWbsrj.js.map +0 -1
  91. package/dist/log-DQAS5gGT.js.map +0 -1
  92. package/dist/node-CVVdk2N6.js +0 -334
  93. package/dist/node-CVVdk2N6.js.map +0 -1
  94. package/dist/node-D6m6e6EI.js.map +0 -1
  95. package/dist/react-router.js.map +0 -1
  96. package/dist/request-context-Bxdbk5P1.js +0 -80
  97. package/dist/request-context-Bxdbk5P1.js.map +0 -1
  98. package/dist/response-edge-CU8ZvL_F.js.map +0 -1
  99. package/dist/response-writer-D7KHfr8n.js.map +0 -1
  100. package/dist/script-hashes-CU7P9oZU.js.map +0 -1
  101. package/dist/serve-W4WacdOw.js +0 -29
  102. package/dist/serve-W4WacdOw.js.map +0 -1
  103. package/dist/stale-build-navigation-rg5xxmTr.js.map +0 -1
  104. package/dist/start-j0VlxeiI.js +0 -324
  105. package/dist/start-j0VlxeiI.js.map +0 -1
  106. package/dist/static-files-C2ea8KQ6.js +0 -310
  107. package/dist/static-files-C2ea8KQ6.js.map +0 -1
  108. package/dist/tanstack-start.js.map +0 -1
  109. package/dist/tcp-BgDXbjOG.js +0 -42
  110. package/dist/tcp-BgDXbjOG.js.map +0 -1
  111. package/dist/testing.js.map +0 -1
  112. package/dist/vercel-pages.js.map +0 -1
  113. package/dist/vercel-vite.js.map +0 -1
  114. package/dist/vercel.js.map +0 -1
  115. package/dist/vite-B-GfswoH.js.map +0 -1
  116. package/dist/vite-D4hfj3ph.js.map +0 -1
  117. package/dist/vite-DPiSKHDn.js +0 -870
  118. package/dist/vite-DPiSKHDn.js.map +0 -1
  119. package/dist/vite-DyrhyKEr.js.map +0 -1
@@ -1,6 +1,4 @@
1
- import { t as createServer } from "./create-server-Bp1yILQk.js";
2
- import { n as isAppServerEntry, t as createEntry } from "./entry-BoxCqc6w.js";
3
- import { t as host } from "./node-CVVdk2N6.js";
1
+ import { t as isAppServerEntry } from "./entry-protocol-C30UPXzy.js";
4
2
 
5
3
  // src/cli/load-entry.ts
6
4
  /** Entries that this copy made for plain React Router builds, by build module. */
@@ -14,18 +12,20 @@ async function loadEntry(build) {
14
12
  if (typeof build !== "object" || build == null) throw new Error("The server build entry is not a module.");
15
13
  const exported = Reflect.get(build, "appServer");
16
14
  if (exported != null) {
17
- if (!isAppServerEntry(exported)) throw new Error(`The build's @ngrok/app-server does not use entry protocol ${2}. Install the same version of @ngrok/app-server that the build uses.`);
15
+ if (!isAppServerEntry(exported)) throw new Error(`The build's @ngrok/app-server does not use entry protocol ${3}. Install the same version of @ngrok/app-server that the build uses.`);
18
16
  return exported;
19
17
  }
20
18
  const known = plainEntries.get(build);
21
19
  if (known != null) return known;
22
- const { isServerBuild, runtime } = await import("./react-router.js");
23
- if (!isServerBuild(build)) throw new Error("The server build entry is not a React Router server build.");
20
+ const [{ createServer }, { createEntry }, { host }, { runtime }, { environmentOptions }] = await Promise.all([
21
+ import("./create-server-PA0qniaK.js"),
22
+ import("./entry-CvZ4U0ia.js"),
23
+ import("./node.js"),
24
+ import("./react-router.js"),
25
+ import("./entry-source-SHoE-DUP.js")
26
+ ]);
24
27
  const entry = createEntry({
25
- app: createServer({
26
- trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1",
27
- trustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0)
28
- }),
28
+ app: createServer(environmentOptions(process.env)),
29
29
  host,
30
30
  framework: (mode) => runtime(build, { mode })
31
31
  });
@@ -33,5 +33,4 @@ async function loadEntry(build) {
33
33
  return entry;
34
34
  }
35
35
 
36
- export { loadEntry as t };
37
- //# sourceMappingURL=load-entry-CCPWbsrj.js.map
36
+ export { loadEntry as t };
@@ -1,52 +1,51 @@
1
1
  // src/core/log.ts
2
- /** The standard output (stdout) lines that wait for {@link flushLogs}. */
3
- let pending = "";
4
- /** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */
5
- let exiting = false;
6
- process.on("exit", () => {
7
- exiting = true;
8
- process.stdout._handle?.setBlocking?.(true);
9
- for (const line of pending.match(/[^\n]*\n/gu) ?? []) process.stdout.write(line);
10
- pending = "";
11
- });
2
+ /** The log writer of the host, when it has one. */
3
+ let hostWriter;
12
4
  /**
13
- * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it
14
- * before the process exits.
5
+ * Sets the writer of each {@link jsonSink} and {@link textSink} that gets no
6
+ * `write`. `createEntry` gives it the host's. The last call wins.
15
7
  */
16
- function flushLogs() {
17
- if (pending === "") return;
18
- const lines = pending;
19
- pending = "";
20
- process.stdout.write(lines);
8
+ function setLogWriter(writer) {
9
+ hostWriter = writer;
21
10
  }
22
11
  /**
23
- * Adds `line` to the next stdout write. Why one write for each turn of the
24
- * event loop: a write to a pipe, such as stdout in Docker, is a system call,
25
- * and under load many requests end in one turn.
12
+ * Writes each line that the host's log writer keeps. Call it before an error
13
+ * leaves the server, because the runtime can end with no next turn of the
14
+ * event loop.
26
15
  */
27
- function writeStdout(line) {
28
- if (exiting) {
29
- process.stdout.write(line);
16
+ function flushLogs() {
17
+ hostWriter?.flush();
18
+ }
19
+ /** Gives `line` to the host's log writer, else to `console.log`. */
20
+ function writeLine(line) {
21
+ if (hostWriter == null) {
22
+ console.log(line.slice(0, -1));
30
23
  return;
31
24
  }
32
- if (pending === "") setImmediate(flushLogs);
33
- pending += line;
25
+ hostWriter.write(line);
26
+ }
27
+ /** Gives `line` to the host's log writer, and makes the writer write it at once. */
28
+ function writeLineNow(line) {
29
+ writeLine(line);
30
+ hostWriter?.flush();
34
31
  }
35
32
  /** The end of a {@link jsonSink} line whose attributes have no JSON. */
36
33
  const NO_JSON = "\"log.error\":\"attributes not written as JSON\"}";
37
34
  /**
38
35
  * A log sink that writes one JSON object per line. Each line has `time`,
39
36
  * `level`, `message`, and the flat attributes, which Datadog reads as its
40
- * standard attributes. The default writes the lines of one event-loop turn
41
- * to stdout at the end of the turn.
37
+ * standard attributes.
42
38
  *
43
- * @param write - Where each line goes. Defaults to stdout.
39
+ * @param write - Where each line goes. Defaults to the log writer of the
40
+ * host. The node host and the vercel host write the lines of one event-loop
41
+ * turn to standard output (stdout) at the end of the turn. On a host with no
42
+ * log writer, and before `createEntry` runs, `console.log` writes each line.
44
43
  *
45
44
  * @example
46
45
  * createServer({ logger: jsonSink() });
47
46
  * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
48
47
  */
49
- function jsonSink(write = writeStdout) {
48
+ function jsonSink(write = writeLine) {
50
49
  return { log: ({ level, message, attributes }) => {
51
50
  const time = isoNow();
52
51
  const head = `{"time":"${time}","level":"${level}","message":${JSON.stringify(message)}`;
@@ -66,21 +65,21 @@ function jsonSink(write = writeStdout) {
66
65
  * A log sink that writes one line of `key=value` pairs per event, in the text
67
66
  * format of Go's `log/slog`. A value with a space, a quote, `=`, or a control
68
67
  * character is quoted, so an escape sequence cannot reach the terminal.
69
- * `app-server start` uses it, because a person reads those lines.
68
+ * `app-server start` uses it, and so does the default sink of `createServer`
69
+ * in development, because a person reads those lines.
70
70
  *
71
- * @param write - Where each line goes. Defaults to stdout, at once. Why not
72
- * one write for each turn: the lines then keep their order with Vite's lines.
71
+ * @param write - Where each line goes. Defaults to the log writer of the
72
+ * host, with a flush after each line, else to `console.log`. Why not one
73
+ * write for each turn: the lines then keep their order with Vite's lines.
73
74
  *
74
75
  * @example
75
- * textSink().log({ level: "info", message: "port in use, trying the next port", attributes: { "server.port": 3000 } });
76
- * // time=2026-11-11T12:00:00.000Z level=INFO msg="port in use, trying the next port" server.port=3000
76
+ * textSink().log({ level: "error", message: "dev request failed", attributes: { "error.kind": "TypeError" } });
77
+ * // time=2026-11-11T12:00:00.000Z level=ERROR msg="dev request failed" error.kind=TypeError
77
78
  */
78
- function textSink(write = (line) => {
79
- process.stdout.write(line);
80
- }) {
79
+ function textSink(write = writeLineNow) {
81
80
  return { log: ({ level, message, attributes }) => {
82
81
  let line = `time=${isoNow()} level=${level.toUpperCase()} msg=${textValue(message)}`;
83
- for (const [key, value] of Object.entries(attributes)) line += ` ${key}=${textValue(value)}`;
82
+ for (const [key, value] of Object.entries(attributes)) if (value !== void 0) line += ` ${key}=${textValue(value)}`;
84
83
  write(`${line}\n`);
85
84
  } };
86
85
  }
@@ -205,6 +204,13 @@ function errorFields(error, prefix) {
205
204
  return fields;
206
205
  }
207
206
  /**
207
+ * What a line gets in place of the fields that a `log` hook that threw was to
208
+ * give. Why not the fields that the hook got: the hook can redact a value.
209
+ */
210
+ function hookFailure(hook, thrown) {
211
+ return { "log.error": `the ${hook} hook of the log option threw: ${asError(thrown).message}` };
212
+ }
213
+ /**
208
214
  * `attributes` with each `Error` value replaced by its fields, after the
209
215
  * `change` hook. Each other attribute, such as `http.method`, wins over an
210
216
  * error field of the same name.
@@ -219,19 +225,25 @@ function flattenErrors(attributes, change) {
219
225
  const flat = {};
220
226
  const entries = Object.entries(attributes);
221
227
  for (const [key, value] of entries) if (value instanceof Error) {
222
- const fields = errorFields(value, key);
223
- Object.assign(flat, change == null ? fields : change({
224
- error: value,
225
- prefix: key,
226
- fields
227
- }));
228
+ let fields = errorFields(value, key);
229
+ if (change != null) try {
230
+ fields = change({
231
+ error: value,
232
+ prefix: key,
233
+ fields
234
+ });
235
+ } catch (error) {
236
+ fields = hookFailure("error", error);
237
+ }
238
+ Object.assign(flat, fields);
228
239
  } else flat[key] = value;
229
240
  for (const [key, value] of entries) if (!(value instanceof Error)) flat[key] = value;
230
241
  return flat;
231
242
  }
232
243
  /**
233
244
  * A sink that writes each line to `sink`, after it replaces each `Error`
234
- * value with its fields, and then runs the `attributes` hook.
245
+ * value with its fields, and then runs the `attributes` hook. A hook that
246
+ * throws does not stop the line: `log.error` takes the place of its fields.
235
247
  *
236
248
  * @example
237
249
  * hookSink(jsonSink()).log({ level: "error", message: "failed", attributes: { error: new Error("boom") } });
@@ -244,9 +256,19 @@ function hookSink(sink, { attributes: changeAttributes, error: changeError } = {
244
256
  ...line,
245
257
  attributes: flat
246
258
  };
247
- sink.log(changeAttributes == null ? flatLine : {
259
+ if (changeAttributes == null) {
260
+ sink.log(flatLine);
261
+ return;
262
+ }
263
+ let attributes;
264
+ try {
265
+ attributes = changeAttributes(flatLine);
266
+ } catch (error) {
267
+ attributes = hookFailure("attributes", error);
268
+ }
269
+ sink.log({
248
270
  ...flatLine,
249
- attributes: changeAttributes(flatLine)
271
+ attributes
250
272
  });
251
273
  } };
252
274
  }
@@ -310,5 +332,4 @@ function requestLogger(sink, context) {
310
332
  });
311
333
  }
312
334
 
313
- export { requestLogger as a, jsonSink as i, flushLogs as n, sinkLogger as o, hookSink as r, textSink as s, asError as t };
314
- //# sourceMappingURL=log-DQAS5gGT.js.map
335
+ export { requestLogger as a, textSink as c, jsonSink as i, flushLogs as n, setLogWriter as o, hookSink as r, sinkLogger as s, asError as t };
@@ -1,14 +1,22 @@
1
- import { t as requestListener } from "./response-writer-D7KHfr8n.js";
1
+ import { t as requestListener } from "./response-writer-Dd4Ey99f.js";
2
2
  import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
3
3
  import { createServer } from "node:http";
4
4
 
5
5
  // src/node/runtimes/node.ts
6
+ /** Node's default `requestTimeout`. */
7
+ const DEFAULT_REQUEST_TIMEOUT_MS = 3e5;
6
8
  /** Listens with `node:http`, and writes each response with the node response writer. */
7
9
  async function listen(fetch, options) {
8
- const listener = requestListener(fetch, { trustForwardedProto: options.trustForwardedProto });
10
+ let draining = false;
11
+ const listener = requestListener(fetch, {
12
+ trustForwardedProto: options.trustForwardedProto,
13
+ isDraining: () => draining
14
+ });
15
+ const headersTimeout = options.idleTimeoutMs + 1e3;
9
16
  const server = createServer({
10
17
  keepAliveTimeout: options.idleTimeoutMs,
11
- headersTimeout: options.idleTimeoutMs + 1e3
18
+ headersTimeout,
19
+ requestTimeout: Math.max(DEFAULT_REQUEST_TIMEOUT_MS, headersTimeout)
12
20
  }, (incoming, outgoing) => {
13
21
  listener(incoming, outgoing);
14
22
  });
@@ -24,18 +32,22 @@ async function listen(fetch, options) {
24
32
  return {
25
33
  url: listenerUrl(options.hostname, port),
26
34
  stop: async ({ deadlineMs }) => new Promise((resolve, reject) => {
35
+ draining = true;
36
+ server.keepAliveTimeout = 1;
37
+ server.keepAliveTimeoutBuffer = 0;
38
+ let cut = false;
27
39
  const deadline = setTimeout(() => {
40
+ cut = true;
28
41
  server.closeAllConnections();
29
42
  }, deadlineMs);
30
43
  server.close((error) => {
31
44
  clearTimeout(deadline);
32
- if (error == null) resolve();
33
- else reject(error);
45
+ if (error != null) reject(error);
46
+ else if (cut) setTimeout(resolve, 0);
47
+ else resolve();
34
48
  });
35
- server.closeIdleConnections();
36
49
  })
37
50
  };
38
51
  }
39
52
 
40
- export { listen };
41
- //# sourceMappingURL=node-D6m6e6EI.js.map
53
+ export { listen };
@@ -0,0 +1,263 @@
1
+ import { t as asError } from "./log-DfC9D5_T.js";
2
+ import { n as logger } from "./request-context-Cslbrscf.js";
3
+ import { r as logWriter, t as exitAfterFlush } from "./exit-Hh-O3gp4.js";
4
+ import { n as gzipStream, t as brotliStream } from "./compress-2w3jqBh7.js";
5
+ import { n as tcp } from "./tcp-3v4pmnYU.js";
6
+ import { constants } from "node:fs";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ import { access, open, readdir, stat } from "node:fs/promises";
9
+ import { join, resolve, sep } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ // src/node/files.ts
13
+ /** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */
14
+ const CHUNK_BYTES = 65536;
15
+ /**
16
+ * A file's bytes, one chunk for each pull. With `range`, it reads only those
17
+ * bytes. The file opens on the first pull and closes at the end, on an error,
18
+ * or on cancel.
19
+ *
20
+ * Why open on the first pull: a stage can drop a response that no one reads,
21
+ * such as when a later stage throws. Node.js 26 throws an uncaught error when
22
+ * garbage collection closes an open `FileHandle`.
23
+ */
24
+ function fileStream(path, range) {
25
+ let handle;
26
+ let position = range?.start ?? 0;
27
+ const end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;
28
+ const close = async () => {
29
+ const opened = handle;
30
+ handle = void 0;
31
+ await opened?.close();
32
+ };
33
+ return new ReadableStream({
34
+ async pull(controller) {
35
+ try {
36
+ const length = Math.min(CHUNK_BYTES, end - position);
37
+ if (length > 0) handle ??= await open(path);
38
+ const { bytesRead, buffer } = length <= 0 || handle == null ? {
39
+ bytesRead: 0,
40
+ buffer: /* @__PURE__ */ new Uint8Array(0)
41
+ } : await handle.read({
42
+ buffer: new Uint8Array(length),
43
+ position
44
+ });
45
+ if (bytesRead === 0) {
46
+ await close();
47
+ controller.close();
48
+ } else {
49
+ position += bytesRead;
50
+ controller.enqueue(buffer.subarray(0, bytesRead));
51
+ }
52
+ } catch (error) {
53
+ await close();
54
+ throw error;
55
+ }
56
+ },
57
+ cancel: close
58
+ }, { highWaterMark: 0 });
59
+ }
60
+ /** The bytes of `range` in the file at `path`, usually from one read. */
61
+ async function readRange(path, range) {
62
+ const buffer = new Uint8Array(range.end - range.start + 1);
63
+ const handle = await open(path);
64
+ try {
65
+ let filled = 0;
66
+ while (filled < buffer.byteLength) {
67
+ const { bytesRead } = await handle.read({
68
+ buffer,
69
+ offset: filled,
70
+ position: range.start + filled
71
+ });
72
+ if (bytesRead === 0) break;
73
+ filled += bytesRead;
74
+ }
75
+ return buffer.subarray(0, filled);
76
+ } finally {
77
+ await handle.close();
78
+ }
79
+ }
80
+ /** A stream of one chunk. */
81
+ function oneChunk(chunk) {
82
+ return new ReadableStream({ start(controller) {
83
+ if (chunk.byteLength > 0) controller.enqueue(chunk);
84
+ controller.close();
85
+ } });
86
+ }
87
+ /** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */
88
+ const MISSING_CODES = /* @__PURE__ */ new Set([
89
+ "ENOENT",
90
+ "ENOTDIR",
91
+ "ENAMETOOLONG"
92
+ ]);
93
+ /** The value of `promise`, or `undefined` when it fails because nothing is at its path. */
94
+ async function orMissing(promise) {
95
+ try {
96
+ return await promise;
97
+ } catch (error) {
98
+ if (error instanceof Error && "code" in error && MISSING_CODES.has(String(error.code))) return;
99
+ throw error;
100
+ }
101
+ }
102
+ /** The {@link FileInfo} of a file or a directory, else `undefined`. */
103
+ function fileInfo(stats) {
104
+ if (stats?.isFile() === true) return {
105
+ kind: "file",
106
+ size: stats.size,
107
+ mtimeMs: stats.mtimeMs
108
+ };
109
+ return stats?.isDirectory() === true ? { kind: "directory" } : void 0;
110
+ }
111
+ /**
112
+ * Files whose `stat` answers from `entries`, the {@link FileInfo} of each file
113
+ * and directory by its URL path, and whose bytes come from `openFile`.
114
+ *
115
+ * @example
116
+ * listedFiles(new Map([["/llms.txt", { kind: "file", size: 12, mtimeMs: 0 }]]), files.open).stat("/llms.txt");
117
+ */
118
+ function listedFiles(entries, openFile) {
119
+ return {
120
+ stat: async (path) => {
121
+ const trimmed = path.length > 1 ? path.replace(/\/$/u, "") : path;
122
+ const info = entries.get(trimmed);
123
+ return trimmed === path || info?.kind === "directory" ? info : void 0;
124
+ },
125
+ open: openFile
126
+ };
127
+ }
128
+ /**
129
+ * The most file system calls of one `snapshot` in flight. Why a limit: each
130
+ * call in flight holds about 4 KiB for its request, its path, and its
131
+ * result, and a walk with no limit has a call in flight for each entry of
132
+ * the client build. Why 64: a build of 100 pages then starts as fast as with
133
+ * no limit, and with 8 it starts 11% slower.
134
+ */
135
+ const SNAPSHOT_CALLS = 64;
136
+ /**
137
+ * The client build on the file system. A relative `clientDirectory` is
138
+ * relative to the working directory.
139
+ *
140
+ * Its `snapshot` reads each file and directory once, with at most 64 file
141
+ * system calls in flight. It throws for an error that does not mean a
142
+ * missing file, so the server does not start.
143
+ *
144
+ * @example
145
+ * nodeFiles("build/client").stat("/llms.txt");
146
+ */
147
+ function nodeFiles(clientDirectory) {
148
+ const root = resolve(clientDirectory.startsWith("file:") ? fileURLToPath(clientDirectory) : clientDirectory);
149
+ const filePath = (path) => {
150
+ const candidate = join(root, path);
151
+ if (candidate !== root && !candidate.startsWith(`${root}${sep}`)) throw new Error(`The path ${path} is outside the client build.`);
152
+ return candidate;
153
+ };
154
+ const files = {
155
+ stat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),
156
+ open: async (path, options) => {
157
+ const candidate = filePath(path);
158
+ const range = options?.range;
159
+ if (range != null && range.end - range.start < CHUNK_BYTES) return oneChunk(await readRange(candidate, range));
160
+ await access(candidate, constants.R_OK);
161
+ return fileStream(candidate, range);
162
+ },
163
+ snapshot: async () => {
164
+ const entries = /* @__PURE__ */ new Map();
165
+ /** Reads the entry at `path`, and adds the entries of a directory to `found`. */
166
+ const read = async ([path, parents], found) => {
167
+ const stats = await orMissing(stat(path === "/" ? root : filePath(path)));
168
+ const info = fileInfo(stats);
169
+ if (stats == null || info == null) return;
170
+ entries.set(path, info);
171
+ const inode = `${stats.dev}:${stats.ino}`;
172
+ if (info.kind === "file" || parents.has(inode)) return;
173
+ const inside = new Set(parents).add(inode);
174
+ const prefix = path === "/" ? "" : path;
175
+ for (const name of await orMissing(readdir(filePath(path))) ?? []) found.push([`${prefix}/${name}`, inside]);
176
+ };
177
+ let depth = [["/", /* @__PURE__ */ new Set()]];
178
+ while (depth.length > 0) {
179
+ const unread = depth;
180
+ const found = [];
181
+ let next = 0;
182
+ let failure;
183
+ const worker = async () => {
184
+ for (let entry = unread[next]; entry != null && failure == null; entry = unread[next]) {
185
+ next += 1;
186
+ try {
187
+ await read(entry, found);
188
+ } catch (error) {
189
+ failure ??= { error };
190
+ }
191
+ }
192
+ };
193
+ await Promise.all(Array.from({ length: Math.min(SNAPSHOT_CALLS, unread.length) }, worker));
194
+ if (failure != null) throw failure.error;
195
+ depth = found;
196
+ }
197
+ return listedFiles(entries, files.open);
198
+ }
199
+ };
200
+ return files;
201
+ }
202
+
203
+ // src/node/index.ts
204
+ const storage = new AsyncLocalStorage();
205
+ /** The crash handler of each stop that the host registered, for a rejection that no app listener handles on Bun. */
206
+ const rejectionCrashes = /* @__PURE__ */ new Set();
207
+ /**
208
+ * Crashes each registered server for a rejection that the app does not handle.
209
+ * Why one listener before the others: an app's `process.once` listener
210
+ * removes itself before it runs, and a listener for each server would count
211
+ * as an app listener.
212
+ */
213
+ function onRejection(reason) {
214
+ if (process.listenerCount("unhandledRejection") > 1) return;
215
+ process.off("unhandledRejection", onRejection);
216
+ const crashes = [...rejectionCrashes];
217
+ rejectionCrashes.clear();
218
+ for (const crash of crashes) crash(reason, "unhandledRejection");
219
+ }
220
+ /**
221
+ * The node host: one long-lived process on Node, Bun, or Deno, such as a
222
+ * Docker image. It listens with `tcp()`, reads the client build from the file
223
+ * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or
224
+ * `SIGINT`, it shuts down, then exits the process. After an uncaught error, it
225
+ * logs `uncaught exception`, shuts down, then exits with code 1.
226
+ *
227
+ * @example
228
+ * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
229
+ */
230
+ const host = {
231
+ files: nodeFiles,
232
+ listeners: [tcp()],
233
+ storage: {
234
+ run: (value, work) => storage.run(value, work),
235
+ get: () => storage.getStore()
236
+ },
237
+ gzip: gzipStream,
238
+ brotli: brotliStream,
239
+ logWriter,
240
+ lifecycle: { onStop: (stop) => {
241
+ const exit = () => {
242
+ stop().catch(() => {
243
+ process.exitCode = 1;
244
+ }).finally(exitAfterFlush);
245
+ };
246
+ for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, exit);
247
+ const crash = (error, origin) => {
248
+ logger().error("uncaught exception", {
249
+ error: asError(error),
250
+ "app_server.origin": origin
251
+ });
252
+ process.exitCode = 1;
253
+ exit();
254
+ };
255
+ process.once("uncaughtException", crash);
256
+ if ("Bun" in globalThis) {
257
+ if (rejectionCrashes.size === 0) process.prependListener("unhandledRejection", onRejection);
258
+ rejectionCrashes.add(crash);
259
+ }
260
+ } }
261
+ };
262
+
263
+ export { listedFiles as n, nodeFiles as r, host as t };
@@ -1,4 +1,4 @@
1
- import { r as HostBuild } from "./index-B8LsM6Mh.js";
1
+ import { r as HostBuild } from "./index-gzGs53Ue.js";
2
2
  /**
3
3
  * The build side of the node host, the default host of `appServer`. The
4
4
  * server build gets `server/app-server.js`. Run it with `node`, `bun`, or
@@ -7,5 +7,4 @@ import { r as HostBuild } from "./index-B8LsM6Mh.js";
7
7
  * @example
8
8
  * appServer({ host: node() });
9
9
  */
10
- export declare function node(): HostBuild;
11
- //# sourceMappingURL=node-vite.d.ts.map
10
+ export declare function node(): HostBuild;
package/dist/node-vite.js CHANGED
@@ -1,3 +1,3 @@
1
- import { t as node } from "./vite-D4hfj3ph.js";
1
+ import { t as node } from "./vite-Brb8YR9I.js";
2
2
 
3
3
  export { node };