@ngrok/app-server 0.1.1 → 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 (105) hide show
  1. package/README.md +659 -70
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/build-manifest-UDNk81Ce.js +63 -0
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/{bun-DCGnDEPn.js → bun-BCz6K_Xv.js} +12 -8
  7. package/dist/bun-BCz6K_Xv.js.map +1 -0
  8. package/dist/cli.js +47 -27
  9. package/dist/cli.js.map +1 -1
  10. package/dist/client.d.ts +141 -0
  11. package/dist/client.js +326 -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-iE1-s6Bi.js +1409 -0
  16. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  17. package/dist/{deno-BnMfk2n1.js → deno-aqhikNMG.js} +5 -5
  18. package/dist/deno-aqhikNMG.js.map +1 -0
  19. package/dist/entry-DZ3qo7qF.js +116 -0
  20. package/dist/entry-DZ3qo7qF.js.map +1 -0
  21. package/dist/entry-DmJEqVfd.d.ts +622 -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-Bo5G9LuQ.d.ts +127 -0
  27. package/dist/index.d.ts +110 -95
  28. package/dist/index.js +56 -57
  29. package/dist/index.js.map +1 -1
  30. package/dist/{listen-options-DHWmSWGi.js → listen-options-7TaXjyrk.js} +2 -2
  31. package/dist/listen-options-7TaXjyrk.js.map +1 -0
  32. package/dist/load-entry-AfYS_zS9.js +37 -0
  33. package/dist/load-entry-AfYS_zS9.js.map +1 -0
  34. package/dist/log-BP6xXXZl.js +122 -0
  35. package/dist/log-BP6xXXZl.js.map +1 -0
  36. package/dist/node-BFH82eeL.js +333 -0
  37. package/dist/node-BFH82eeL.js.map +1 -0
  38. package/dist/node-tBVQPjQv.js +41 -0
  39. package/dist/node-tBVQPjQv.js.map +1 -0
  40. package/dist/node-vite.d.ts +11 -0
  41. package/dist/node-vite.js +3 -0
  42. package/dist/node.d.ts +86 -0
  43. package/dist/node.js +4 -0
  44. package/dist/react-router-vite.d.ts +10 -0
  45. package/dist/react-router-vite.js +3 -0
  46. package/dist/react-router.d.ts +11 -24
  47. package/dist/react-router.js +21 -30
  48. package/dist/react-router.js.map +1 -1
  49. package/dist/request-context-BtQ87VYb.js +40 -0
  50. package/dist/request-context-BtQ87VYb.js.map +1 -0
  51. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  52. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  53. package/dist/response-writer-B7FoJjEE.js +289 -0
  54. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  55. package/dist/script-hashes-hqUk6kG7.js +53 -0
  56. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  57. package/dist/serve-CDNgThjk.js +29 -0
  58. package/dist/serve-CDNgThjk.js.map +1 -0
  59. package/dist/{start-BVMb8Pyt.js → start-TLIprD74.js} +96 -81
  60. package/dist/start-TLIprD74.js.map +1 -0
  61. package/dist/static-files-Beju9riB.js +302 -0
  62. package/dist/static-files-Beju9riB.js.map +1 -0
  63. package/dist/tanstack-start-vite.d.ts +12 -0
  64. package/dist/tanstack-start-vite.js +3 -0
  65. package/dist/tanstack-start.d.ts +34 -0
  66. package/dist/tanstack-start.js +41 -0
  67. package/dist/tanstack-start.js.map +1 -0
  68. package/dist/{tcp-Dau_IONd.js → tcp-Dd1Mt6sN.js} +8 -7
  69. package/dist/tcp-Dd1Mt6sN.js.map +1 -0
  70. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  71. package/dist/types-DLYxYS6M.d.ts +392 -0
  72. package/dist/vercel-vite.d.ts +35 -0
  73. package/dist/vercel-vite.js +142 -0
  74. package/dist/vercel-vite.js.map +1 -0
  75. package/dist/vercel.d.ts +35 -0
  76. package/dist/vercel.js +89 -0
  77. package/dist/vercel.js.map +1 -0
  78. package/dist/vite-B-GfswoH.js +22 -0
  79. package/dist/vite-B-GfswoH.js.map +1 -0
  80. package/dist/vite-D4hfj3ph.js +19 -0
  81. package/dist/vite-D4hfj3ph.js.map +1 -0
  82. package/dist/vite-DyrhyKEr.js +25 -0
  83. package/dist/vite-DyrhyKEr.js.map +1 -0
  84. package/dist/vite-iioAoxSt.js +752 -0
  85. package/dist/vite-iioAoxSt.js.map +1 -0
  86. package/dist/vite.d.ts +2 -27
  87. package/dist/vite.js +2 -2
  88. package/package.json +50 -4
  89. package/dist/bun-DCGnDEPn.js.map +0 -1
  90. package/dist/captured-headers-ewL_t3MQ.js +0 -48
  91. package/dist/captured-headers-ewL_t3MQ.js.map +0 -1
  92. package/dist/deno-BnMfk2n1.js.map +0 -1
  93. package/dist/entry-CIpwaayZ.d.ts +0 -293
  94. package/dist/entry-ChjmFwX5.js +0 -755
  95. package/dist/entry-ChjmFwX5.js.map +0 -1
  96. package/dist/listen-options-DHWmSWGi.js.map +0 -1
  97. package/dist/node-2wWBMFeO.js +0 -3
  98. package/dist/node-79my3Uix.js +0 -58
  99. package/dist/node-79my3Uix.js.map +0 -1
  100. package/dist/serve-ByeedcRB.js +0 -16
  101. package/dist/serve-ByeedcRB.js.map +0 -1
  102. package/dist/start-BVMb8Pyt.js.map +0 -1
  103. package/dist/tcp-Dau_IONd.js.map +0 -1
  104. package/dist/vite-CrNqpoeK.js +0 -102
  105. package/dist/vite-CrNqpoeK.js.map +0 -1
@@ -0,0 +1,122 @@
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
+ });
12
+ /**
13
+ * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it
14
+ * before the process exits.
15
+ */
16
+ function flushLogs() {
17
+ if (pending === "") return;
18
+ const lines = pending;
19
+ pending = "";
20
+ process.stdout.write(lines);
21
+ }
22
+ /**
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.
26
+ */
27
+ function writeStdout(line) {
28
+ if (exiting) {
29
+ process.stdout.write(line);
30
+ return;
31
+ }
32
+ if (pending === "") setImmediate(flushLogs);
33
+ pending += line;
34
+ }
35
+ /**
36
+ * A log sink that writes one JSON object per line. Each line has `time`,
37
+ * `level`, `message`, and the flat attributes, which Datadog reads as its
38
+ * standard attributes. The default writes the lines of one event-loop turn
39
+ * to stdout at the end of the turn.
40
+ *
41
+ * @param write - Where each line goes. Defaults to stdout.
42
+ *
43
+ * @example
44
+ * createServer({ logger: jsonSink() });
45
+ * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
46
+ */
47
+ function jsonSink(write = writeStdout) {
48
+ return { log: (level, message, attributes) => {
49
+ write(`${JSON.stringify({
50
+ time: isoNow(),
51
+ level,
52
+ message,
53
+ ...attributes
54
+ })}\n`);
55
+ } };
56
+ }
57
+ /** The millisecond of the last `time`, and its ISO string. */
58
+ let lastMs = NaN;
59
+ let lastTime = "";
60
+ /** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */
61
+ let lastSecond = NaN;
62
+ let secondPrefix = "";
63
+ /**
64
+ * The time now, as `new Date().toISOString()` gives it. Why keep the last
65
+ * time: under load, many lines share a millisecond. Why keep the prefix of
66
+ * the second: `toISOString()` costs more than the rest of a line.
67
+ */
68
+ function isoNow() {
69
+ const now = Date.now();
70
+ if (now !== lastMs) {
71
+ lastMs = now;
72
+ const second = Math.floor(now / 1e3);
73
+ if (second !== lastSecond) {
74
+ lastSecond = second;
75
+ secondPrefix = new Date(now).toISOString().slice(0, -4);
76
+ }
77
+ lastTime = `${secondPrefix}${String(now - second * 1e3).padStart(3, "0")}Z`;
78
+ }
79
+ return lastTime;
80
+ }
81
+ /** Flat `error.*` attributes for a thrown value. */
82
+ function errorAttributes(error) {
83
+ if (error instanceof Error) return {
84
+ "error.kind": error.name,
85
+ "error.message": error.message,
86
+ "error.stack": error.stack
87
+ };
88
+ return { "error.message": String(error) };
89
+ }
90
+ /**
91
+ * A logger that writes to `sink`. `withBase` gives the attributes of each
92
+ * line as a new object, from the attributes that the caller gives.
93
+ */
94
+ function sinkLogger(sink, withBase = (attributes) => ({ ...attributes })) {
95
+ return {
96
+ debug: (message, attributes = {}) => {
97
+ sink.log("debug", message, withBase(attributes));
98
+ },
99
+ info: (message, attributes = {}) => {
100
+ sink.log("info", message, withBase(attributes));
101
+ },
102
+ warn: (message, attributes = {}) => {
103
+ sink.log("warn", message, withBase(attributes));
104
+ },
105
+ error: (message, attributes = {}) => {
106
+ sink.log("error", message, withBase(attributes));
107
+ }
108
+ };
109
+ }
110
+ /** A logger whose lines carry the request's ID, method, path, and `logAttributes`. */
111
+ function requestLogger(sink, context) {
112
+ return sinkLogger(sink, (attributes) => ({
113
+ "http.request_id": context.get("requestId"),
114
+ "http.method": context.req.method,
115
+ "http.url_details.path": context.req.path,
116
+ ...context.get("logAttributes"),
117
+ ...attributes
118
+ }));
119
+ }
120
+
121
+ export { sinkLogger as a, requestLogger as i, flushLogs as n, jsonSink as r, errorAttributes as t };
122
+ //# sourceMappingURL=log-BP6xXXZl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-BP6xXXZl.js","names":[],"sources":["../src/core/log.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogSink, RequestLogger } from \"./types.js\";\n\n/** The standard output (stdout) lines that wait for {@link flushLogs}. */\nlet pending = \"\";\n/** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */\nlet exiting = false;\n\n/** The libuv handle of stdout on Node.js. Bun and Deno have none. */\ntype StdoutHandle = { _handle?: { setBlocking?: (blocking: boolean) => number } };\n\n// Why: a process that crashes or calls `process.exit()` before the next turn keeps its last lines.\nprocess.on(\"exit\", () => {\n\texiting = true;\n\t// Why block: the exit drops a write that waits for a full pipe. On POSIX, a write to a file or\n\t// a terminal already blocks.\n\t// oxlint-disable-next-line no-underscore-dangle -- Node.js has no public way to block stdout.\n\t(process.stdout as NodeJS.WriteStream & StdoutHandle)._handle?.setBlocking?.(true);\n\t// Why one write for each line: Bun cannot block. Between small writes, the reader can empty the pipe.\n\tfor (const line of pending.match(/[^\\n]*\\n/gu) ?? []) {\n\t\tprocess.stdout.write(line);\n\t}\n\tpending = \"\";\n});\n\n/**\n * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it\n * before the process exits.\n */\nexport function flushLogs(): void {\n\tif (pending === \"\") {\n\t\treturn;\n\t}\n\tconst lines = pending;\n\tpending = \"\";\n\tprocess.stdout.write(lines);\n}\n\n/**\n * Adds `line` to the next stdout write. Why one write for each turn of the\n * event loop: a write to a pipe, such as stdout in Docker, is a system call,\n * and under load many requests end in one turn.\n */\nfunction writeStdout(line: string): void {\n\tif (exiting) {\n\t\tprocess.stdout.write(line);\n\t\treturn;\n\t}\n\tif (pending === \"\") {\n\t\tsetImmediate(flushLogs);\n\t}\n\tpending += line;\n}\n\n/**\n * A log sink that writes one JSON object per line. Each line has `time`,\n * `level`, `message`, and the flat attributes, which Datadog reads as its\n * standard attributes. The default writes the lines of one event-loop turn\n * to stdout at the end of the turn.\n *\n * @param write - Where each line goes. Defaults to stdout.\n *\n * @example\n * createServer({ logger: jsonSink() });\n * // {\"time\":\"2026-10-28T12:00:00.000Z\",\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200}\n */\nexport function jsonSink(write: (line: string) => void = writeStdout): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\twrite(`${JSON.stringify({ time: isoNow(), level, message, ...attributes })}\\n`);\n\t\t},\n\t};\n}\n\n/** The millisecond of the last `time`, and its ISO string. */\nlet lastMs = Number.NaN;\nlet lastTime = \"\";\n/** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */\nlet lastSecond = Number.NaN;\nlet secondPrefix = \"\";\n\n/**\n * The time now, as `new Date().toISOString()` gives it. Why keep the last\n * time: under load, many lines share a millisecond. Why keep the prefix of\n * the second: `toISOString()` costs more than the rest of a line.\n */\nfunction isoNow(): string {\n\tconst now = Date.now();\n\tif (now !== lastMs) {\n\t\tlastMs = now;\n\t\tconst second = Math.floor(now / 1000);\n\t\tif (second !== lastSecond) {\n\t\t\tlastSecond = second;\n\t\t\tsecondPrefix = new Date(now).toISOString().slice(0, -4);\n\t\t}\n\t\tlastTime = `${secondPrefix}${String(now - second * 1000).padStart(3, \"0\")}Z`;\n\t}\n\treturn lastTime;\n}\n\n/** Flat `error.*` attributes for a thrown value. */\nexport function errorAttributes(error: unknown): Record<string, unknown> {\n\tif (error instanceof Error) {\n\t\treturn { \"error.kind\": error.name, \"error.message\": error.message, \"error.stack\": error.stack };\n\t}\n\treturn { \"error.message\": String(error) };\n}\n\ntype Attributes = Readonly<Record<string, unknown>>;\n\n/**\n * A logger that writes to `sink`. `withBase` gives the attributes of each\n * line as a new object, from the attributes that the caller gives.\n */\nexport function sinkLogger(\n\tsink: LogSink,\n\twithBase: (attributes: Attributes) => Attributes = (attributes) => ({ ...attributes }),\n): RequestLogger {\n\t// Why four functions in one scope: a function that makes each one adds a scope for each, on each request.\n\treturn {\n\t\tdebug: (message, attributes = {}) => {\n\t\t\tsink.log(\"debug\", message, withBase(attributes));\n\t\t},\n\t\tinfo: (message, attributes = {}) => {\n\t\t\tsink.log(\"info\", message, withBase(attributes));\n\t\t},\n\t\twarn: (message, attributes = {}) => {\n\t\t\tsink.log(\"warn\", message, withBase(attributes));\n\t\t},\n\t\terror: (message, attributes = {}) => {\n\t\t\tsink.log(\"error\", message, withBase(attributes));\n\t\t},\n\t};\n}\n\n/** A logger whose lines carry the request's ID, method, path, and `logAttributes`. */\nexport function requestLogger(sink: LogSink, context: Context<AppServerEnv>): RequestLogger {\n\t// Why read at call time: the `requestId` plugin runs after this logger is made. Why one object:\n\t// a base object and then a merge copy each attribute two times.\n\treturn sinkLogger(sink, (attributes) => ({\n\t\t\"http.request_id\": context.get(\"requestId\"),\n\t\t\"http.method\": context.req.method,\n\t\t\"http.url_details.path\": context.req.path,\n\t\t...context.get(\"logAttributes\"),\n\t\t...attributes,\n\t}));\n}\n"],"mappings":";;AAIA,IAAI,UAAU;;AAEd,IAAI,UAAU;AAMd,QAAQ,GAAG,cAAc;CACxB,UAAU;CAIV,AAAC,QAAQ,OAA6C,SAAS,cAAc,IAAI;CAEjF,KAAK,MAAM,QAAQ,QAAQ,MAAM,YAAY,KAAK,CAAC,GAClD,QAAQ,OAAO,MAAM,IAAI;CAE1B,UAAU;AACX,CAAC;;;;;AAMD,SAAgB,YAAkB;CACjC,IAAI,YAAY,IACf;CAED,MAAM,QAAQ;CACd,UAAU;CACV,QAAQ,OAAO,MAAM,KAAK;AAC3B;;;;;;AAOA,SAAS,YAAY,MAAoB;CACxC,IAAI,SAAS;EACZ,QAAQ,OAAO,MAAM,IAAI;EACzB;CACD;CACA,IAAI,YAAY,IACf,aAAa,SAAS;CAEvB,WAAW;AACZ;;;;;;;;;;;;;AAcA,SAAgB,SAAS,QAAgC,aAAsB;CAC9E,OAAO,EACN,MAAM,OAAO,SAAS,eAAe;EACpC,MAAM,GAAG,KAAK,UAAU;GAAE,MAAM,OAAO;GAAG;GAAO;GAAS,GAAG;EAAW,CAAC,EAAE,GAAG;CAC/E,EACD;AACD;;AAGA,IAAI,SAAS;AACb,IAAI,WAAW;;AAEf,IAAI,aA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}
@@ -0,0 +1,333 @@
1
+ import { n as tcp } from "./tcp-Dd1Mt6sN.js";
2
+ import { n as flushLogs } from "./log-BP6xXXZl.js";
3
+ import { t as gzipStream } from "./gzip-Doi4wqjX.js";
4
+ import { n as publicScriptHashes } from "./script-hashes-hqUk6kG7.js";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { setTimeout } from "node:timers";
7
+ import { constants } from "node:fs";
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
+ import { IncomingMessage, ServerResponse } from "node:http";
12
+ import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
13
+
14
+ // src/node/exit.ts
15
+ /** How long the exit waits for stdout and stderr. */
16
+ const FLUSH_TIMEOUT_MS = 1e3;
17
+ /**
18
+ * Exits the process after stdout and stderr write what they hold, so the last
19
+ * log lines are not lost. The exit code is `process.exitCode`, else 0.
20
+ *
21
+ * Why exit at all: when shutdown is done, the server holds nothing open. A
22
+ * timer that the app left, such as the render abort timer in React Router's
23
+ * `entry.server`, would otherwise keep the stopped process alive.
24
+ */
25
+ function exitAfterFlush() {
26
+ flushLogs();
27
+ let pending = 2;
28
+ const done = () => {
29
+ pending -= 1;
30
+ if (pending === 0) process.exit();
31
+ };
32
+ flush(process.stdout, done);
33
+ flush(process.stderr, done);
34
+ setTimeout(() => {
35
+ process.exit();
36
+ }, FLUSH_TIMEOUT_MS).unref();
37
+ }
38
+ /** Calls `done` after `stream` writes what it holds. */
39
+ function flush(stream, done) {
40
+ if ("Bun" in globalThis) {
41
+ stream.end(done);
42
+ return;
43
+ }
44
+ stream.write("", done);
45
+ }
46
+
47
+ // src/node/files.ts
48
+ /** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */
49
+ const CHUNK_BYTES = 65536;
50
+ /**
51
+ * A file's bytes, one chunk for each pull. With `range`, it reads only those
52
+ * bytes. The file opens on the first pull and closes at the end, on an error,
53
+ * or on cancel.
54
+ *
55
+ * Why open on the first pull: a stage can drop a response that no one reads,
56
+ * such as when a later stage throws. Node.js 26 throws an uncaught error when
57
+ * garbage collection closes an open `FileHandle`.
58
+ */
59
+ function fileStream(path, range) {
60
+ let handle;
61
+ let position = range?.start ?? 0;
62
+ const end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;
63
+ const close = async () => {
64
+ const opened = handle;
65
+ handle = void 0;
66
+ await opened?.close();
67
+ };
68
+ return new ReadableStream({
69
+ async pull(controller) {
70
+ try {
71
+ const length = Math.min(CHUNK_BYTES, end - position);
72
+ if (length > 0) handle ??= await open(path);
73
+ const { bytesRead, buffer } = length <= 0 || handle == null ? {
74
+ bytesRead: 0,
75
+ buffer: /* @__PURE__ */ new Uint8Array(0)
76
+ } : await handle.read({
77
+ buffer: new Uint8Array(length),
78
+ position
79
+ });
80
+ if (bytesRead === 0) {
81
+ await close();
82
+ controller.close();
83
+ } else {
84
+ position += bytesRead;
85
+ controller.enqueue(buffer.subarray(0, bytesRead));
86
+ }
87
+ } catch (error) {
88
+ await close();
89
+ throw error;
90
+ }
91
+ },
92
+ cancel: close
93
+ }, { highWaterMark: 0 });
94
+ }
95
+ /** The bytes of `range` in the file at `path`, usually from one read. */
96
+ async function readRange(path, range) {
97
+ const buffer = new Uint8Array(range.end - range.start + 1);
98
+ const handle = await open(path);
99
+ try {
100
+ let filled = 0;
101
+ while (filled < buffer.byteLength) {
102
+ const { bytesRead } = await handle.read({
103
+ buffer,
104
+ offset: filled,
105
+ position: range.start + filled
106
+ });
107
+ if (bytesRead === 0) break;
108
+ filled += bytesRead;
109
+ }
110
+ return buffer.subarray(0, filled);
111
+ } finally {
112
+ await handle.close();
113
+ }
114
+ }
115
+ /** A stream of one chunk. */
116
+ function oneChunk(chunk) {
117
+ return new ReadableStream({ start(controller) {
118
+ if (chunk.byteLength > 0) controller.enqueue(chunk);
119
+ controller.close();
120
+ } });
121
+ }
122
+ /** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */
123
+ const MISSING_CODES = /* @__PURE__ */ new Set([
124
+ "ENOENT",
125
+ "ENOTDIR",
126
+ "ENAMETOOLONG"
127
+ ]);
128
+ /** The value of `promise`, or `undefined` when it fails because nothing is at its path. */
129
+ async function orMissing(promise) {
130
+ try {
131
+ return await promise;
132
+ } catch (error) {
133
+ if (error instanceof Error && "code" in error && MISSING_CODES.has(String(error.code))) return;
134
+ throw error;
135
+ }
136
+ }
137
+ /** The {@link FileInfo} of a file or a directory, else `undefined`. */
138
+ function fileInfo(stats) {
139
+ if (stats?.isFile() === true) return {
140
+ kind: "file",
141
+ size: stats.size,
142
+ mtimeMs: stats.mtimeMs
143
+ };
144
+ return stats?.isDirectory() === true ? {
145
+ kind: "directory",
146
+ size: 0,
147
+ mtimeMs: stats.mtimeMs
148
+ } : void 0;
149
+ }
150
+ /**
151
+ * The client build on the file system. A relative `clientDirectory` is
152
+ * relative to the working directory.
153
+ *
154
+ * Its `snapshot` reads each file and directory once. It throws for an error
155
+ * that does not mean a missing file, so the server does not start.
156
+ *
157
+ * @example
158
+ * nodeFiles("build/client").stat("/llms.txt");
159
+ */
160
+ function nodeFiles(clientDirectory) {
161
+ const root = resolve(clientDirectory.startsWith("file:") ? fileURLToPath(clientDirectory) : clientDirectory);
162
+ const filePath = (path) => {
163
+ const candidate = join(root, path);
164
+ if (candidate !== root && !candidate.startsWith(`${root}${sep}`)) throw new Error(`The path ${path} is outside the client build.`);
165
+ return candidate;
166
+ };
167
+ const files = {
168
+ stat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),
169
+ open: async (path, range) => {
170
+ const candidate = filePath(path);
171
+ if (range != null && range.end - range.start < CHUNK_BYTES) return oneChunk(await readRange(candidate, range));
172
+ await access(candidate, constants.R_OK);
173
+ return fileStream(candidate, range);
174
+ },
175
+ snapshot: async () => {
176
+ const entries = /* @__PURE__ */ new Map();
177
+ const walk = async (path, stats, parents) => {
178
+ const info = fileInfo(stats);
179
+ if (info == null) return;
180
+ entries.set(path, info);
181
+ const inode = `${stats.dev}:${stats.ino}`;
182
+ if (info.kind === "file" || parents.has(inode)) return;
183
+ const inside = new Set(parents).add(inode);
184
+ const prefix = path === "/" ? "" : path;
185
+ const names = await orMissing(readdir(filePath(path))) ?? [];
186
+ await Promise.all(names.map(async (name) => {
187
+ const childPath = `${prefix}/${name}`;
188
+ const childStats = await orMissing(stat(filePath(childPath)));
189
+ if (childStats != null) await walk(childPath, childStats, inside);
190
+ }));
191
+ };
192
+ const rootStats = await orMissing(stat(root));
193
+ if (rootStats != null) await walk("/", rootStats, /* @__PURE__ */ new Set());
194
+ return {
195
+ stat: async (path) => {
196
+ const trimmed = path.length > 1 ? path.replace(/\/$/u, "") : path;
197
+ const info = entries.get(trimmed);
198
+ return trimmed === path || info?.kind === "directory" ? info : void 0;
199
+ },
200
+ open: files.open
201
+ };
202
+ }
203
+ };
204
+ return files;
205
+ }
206
+
207
+ // src/node/dev-server.ts
208
+ function isServerResponse(value) {
209
+ return value instanceof ServerResponse;
210
+ }
211
+ /**
212
+ * Makes `outgoing` run `hooks` before it sends its head, and returns the
213
+ * function that undoes it. Why `writeHead`: Node calls it for each
214
+ * response, also from `write` and `end`.
215
+ */
216
+ function runHooksAtHead(outgoing, hooks) {
217
+ const headers = {
218
+ get: (name) => {
219
+ const value = outgoing.getHeader(name);
220
+ return value == null ? null : String(value);
221
+ },
222
+ has: (name) => outgoing.hasHeader(name),
223
+ set: (name, value) => {
224
+ outgoing.setHeader(name, value);
225
+ },
226
+ append: (name, value) => {
227
+ outgoing.appendHeader(name, value);
228
+ },
229
+ delete: (name) => {
230
+ outgoing.removeHeader(name);
231
+ }
232
+ };
233
+ const writeHead = outgoing.writeHead.bind(outgoing);
234
+ outgoing.writeHead = (statusCode, reason, values) => {
235
+ const [message, given] = typeof reason === "string" ? [reason, values] : [void 0, reason];
236
+ if (Array.isArray(given)) {
237
+ const names = given.filter((_, index) => index % 2 === 0).map(String);
238
+ for (const name of names) outgoing.removeHeader(name);
239
+ for (const [index, name] of names.entries()) {
240
+ const value = given[index * 2 + 1];
241
+ if (value != null) outgoing.appendHeader(name, typeof value === "number" ? String(value) : value);
242
+ }
243
+ } else if (given != null) {
244
+ for (const [name, value] of Object.entries(given)) if (value != null) outgoing.setHeader(name, value);
245
+ }
246
+ for (const hook of hooks.toReversed()) hook(headers);
247
+ return message == null ? writeHead(statusCode) : writeHead(statusCode, message);
248
+ };
249
+ return () => {
250
+ outgoing.writeHead = writeHead;
251
+ };
252
+ }
253
+ /** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */
254
+ function publicFileHashes({ directory, base }, pathname) {
255
+ const prefix = base.replace(/\/$/u, "");
256
+ return publicScriptHashes(directory, pathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname);
257
+ }
258
+ /**
259
+ * Runs a Connect middleware, such as Vite's, inside the pipeline. The
260
+ * middleware answers or calls `next`. A request with no Node request and
261
+ * response goes on.
262
+ *
263
+ * @example
264
+ * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {
265
+ * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),
266
+ * }));
267
+ */
268
+ function devServerStage(middleware, { publicFiles } = {}) {
269
+ return async (context, next) => {
270
+ const { incoming, outgoing } = context.env;
271
+ if (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) return next();
272
+ const hashes = publicFiles == null ? void 0 : publicFileHashes(publicFiles(), new URL(context.req.url).pathname);
273
+ const earlierHashes = context.get("documentScriptHashes");
274
+ if (hashes != null) context.set("documentScriptHashes", hashes);
275
+ for (const [name, value] of context.res.headers) outgoing.appendHeader(name, value);
276
+ const hooks = context.get("headerHooks") ?? [];
277
+ const undoHooks = runHooksAtHead(outgoing, hooks);
278
+ if (await new Promise((resolve, reject) => {
279
+ const onFinish = () => {
280
+ resolve(true);
281
+ };
282
+ outgoing.once("finish", onFinish);
283
+ middleware(incoming, outgoing, (error) => {
284
+ outgoing.off("finish", onFinish);
285
+ undoHooks();
286
+ if (hashes != null) context.set("documentScriptHashes", earlierHashes);
287
+ if (error == null) resolve(false);
288
+ else reject(new Error("The dev server middleware failed", { cause: error }));
289
+ });
290
+ })) {
291
+ hooks.length = 0;
292
+ const headers = new Headers(RESPONSE_ALREADY_SENT.headers);
293
+ for (const [name, value] of Object.entries(outgoing.getHeaders())) for (const each of Array.isArray(value) ? value : [value]) if (each != null) headers.append(name, String(each));
294
+ return new Response(null, {
295
+ status: outgoing.statusCode,
296
+ headers
297
+ });
298
+ }
299
+ return next();
300
+ };
301
+ }
302
+
303
+ // src/node/index.ts
304
+ const storage = new AsyncLocalStorage();
305
+ /**
306
+ * The node host: one long-lived process on Node, Bun, or Deno, such as a
307
+ * Docker image. It listens with `tcp()`, reads the client build from the file
308
+ * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or
309
+ * `SIGINT`, it shuts down, then exits the process.
310
+ *
311
+ * @example
312
+ * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
313
+ */
314
+ const host = {
315
+ name: "node",
316
+ files: nodeFiles,
317
+ listeners: () => [tcp()],
318
+ storage: {
319
+ run: (value, work) => storage.run(value, work),
320
+ get: () => storage.getStore()
321
+ },
322
+ gzip: gzipStream,
323
+ lifecycle: { onStop: (stop) => {
324
+ for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
325
+ stop().catch(() => {
326
+ process.exitCode = 1;
327
+ }).finally(exitAfterFlush);
328
+ });
329
+ } }
330
+ };
331
+
332
+ export { exitAfterFlush as i, devServerStage as n, nodeFiles as r, host as t };
333
+ //# sourceMappingURL=node-BFH82eeL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-BFH82eeL.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\nimport { flushLogs } from \"../core/log.js\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tflushLogs();\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { constants } from \"node:fs\";\nimport { access, open, readdir, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ByteRange, FileInfo, StaticFiles } from \"../core/types.js\";\n\n/** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */\nconst CHUNK_BYTES = 65_536;\n\n/**\n * A file's bytes, one chunk for each pull. With `range`, it reads only those\n * bytes. The file opens on the first pull and closes at the end, on an error,\n * or on cancel.\n *\n * Why open on the first pull: a stage can drop a response that no one reads,\n * such as when a later stage throws. Node.js 26 throws an uncaught error when\n * garbage collection closes an open `FileHandle`.\n */\nfunction fileStream(path: string, range: ByteRange | undefined): ReadableStream<Uint8Array> {\n\tlet handle: FileHandle | undefined;\n\tlet position = range?.start ?? 0;\n\tconst end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;\n\tconst close = async () => {\n\t\tconst opened = handle;\n\t\thandle = undefined;\n\t\tawait opened?.close();\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst length = Math.min(CHUNK_BYTES, end - position);\n\t\t\t\t\tif (length > 0) {\n\t\t\t\t\t\thandle ??= await open(path);\n\t\t\t\t\t}\n\t\t\t\t\tconst { bytesRead, buffer } =\n\t\t\t\t\t\tlength <= 0 || handle == null\n\t\t\t\t\t\t\t? { bytesRead: 0, buffer: new Uint8Array(0) }\n\t\t\t\t\t\t\t: await handle.read({ buffer: new Uint8Array(length), position });\n\t\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\t\tawait close();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition += bytesRead;\n\t\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: close,\n\t\t},\n\t\t// Why 0: the stream opens and reads nothing until the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** The bytes of `range` in the file at `path`, usually from one read. */\nasync function readRange(path: string, range: ByteRange): Promise<Uint8Array> {\n\tconst buffer = new Uint8Array(range.end - range.start + 1);\n\tconst handle = await open(path);\n\ttry {\n\t\tlet filled = 0;\n\t\t// Why a loop: a read can give fewer bytes than it asks for before the end of the file.\n\t\twhile (filled < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read({\n\t\t\t\tbuffer,\n\t\t\t\toffset: filled,\n\t\t\t\tposition: range.start + filled,\n\t\t\t});\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfilled += bytesRead;\n\t\t}\n\t\treturn buffer.subarray(0, filled);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\n/** A stream of one chunk. */\nfunction oneChunk(chunk: Uint8Array): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tif (chunk.byteLength > 0) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n}\n\n/** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */\nconst MISSING_CODES = new Set([\"ENOENT\", \"ENOTDIR\", \"ENAMETOOLONG\"]);\n\n/** The value of `promise`, or `undefined` when it fails because nothing is at its path. */\nasync function orMissing<T>(promise: Promise<T>): Promise<T | undefined> {\n\ttry {\n\t\treturn await promise;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && MISSING_CODES.has(String(error.code))) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The {@link FileInfo} of a file or a directory, else `undefined`. */\nfunction fileInfo(stats: Stats | undefined): FileInfo | undefined {\n\tif (stats?.isFile() === true) {\n\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\treturn stats?.isDirectory() === true\n\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t: undefined;\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * Its `snapshot` reads each file and directory once. It throws for an error\n * that does not mean a missing file, so the server does not start.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\tconst files: StaticFiles = {\n\t\tstat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),\n\t\topen: async (path, range) => {\n\t\t\tconst candidate = filePath(path);\n\t\t\tif (range != null && range.end - range.start < CHUNK_BYTES) {\n\t\t\t\treturn oneChunk(await readRange(candidate, range));\n\t\t\t}\n\t\t\t// Why: an unreadable file then gets a logged 500, not a 200 whose body fails. The check\n\t\t\t// holds no `FileHandle`, so a response that no one reads leaves nothing open.\n\t\t\tawait access(candidate, constants.R_OK);\n\t\t\treturn fileStream(candidate, range);\n\t\t},\n\t\tsnapshot: async () => {\n\t\t\tconst entries = new Map<string, FileInfo>();\n\t\t\t// Why the inodes of the parents: a symbolic link to a parent directory must not make the\n\t\t\t// walk endless. A link to another directory, such as a sibling, still lists its files.\n\t\t\tconst walk = async (\n\t\t\t\tpath: string,\n\t\t\t\tstats: Stats,\n\t\t\t\tparents: ReadonlySet<string>,\n\t\t\t): Promise<void> => {\n\t\t\t\tconst info = fileInfo(stats);\n\t\t\t\tif (info == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentries.set(path, info);\n\t\t\t\tconst inode = `${stats.dev}:${stats.ino}`;\n\t\t\t\tif (info.kind === \"file\" || parents.has(inode)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst inside = new Set(parents).add(inode);\n\t\t\t\tconst prefix = path === \"/\" ? \"\" : path;\n\t\t\t\t// Why: a deploy can remove a directory between its `stat` and this read.\n\t\t\t\tconst names = (await orMissing(readdir(filePath(path)))) ?? [];\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tnames.map(async (name) => {\n\t\t\t\t\t\tconst childPath = `${prefix}/${name}`;\n\t\t\t\t\t\tconst childStats = await orMissing(stat(filePath(childPath)));\n\t\t\t\t\t\tif (childStats != null) {\n\t\t\t\t\t\t\tawait walk(childPath, childStats, inside);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst rootStats = await orMissing(stat(root));\n\t\t\tif (rootStats != null) {\n\t\t\t\tawait walk(\"/\", rootStats, new Set());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstat: async (path) => {\n\t\t\t\t\tconst trimmed = path.length > 1 ? path.replace(/\\/$/u, \"\") : path;\n\t\t\t\t\tconst info = entries.get(trimmed);\n\t\t\t\t\t// Why only a directory after a `/`: as on the disk, `/docs/` finds `/docs`, and\n\t\t\t\t\t// `/llms.txt/` finds nothing.\n\t\t\t\t\treturn trimmed === path || info?.kind === \"directory\" ? info : undefined;\n\t\t\t\t},\n\t\t\t\topen: files.open,\n\t\t\t};\n\t\t},\n\t};\n\treturn files;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OutgoingHttpHeader, OutgoingHttpHeaders } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ListenerBindings, ResponseHeaders } from \"../core/types.js\";\nimport { publicScriptHashes } from \"./script-hashes.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Makes `outgoing` run `hooks` before it sends its head, and returns the\n * function that undoes it. Why `writeHead`: Node calls it for each\n * response, also from `write` and `end`.\n */\nfunction runHooksAtHead(outgoing: ServerResponse, hooks: readonly HeaderHook[]): () => void {\n\tconst headers: ResponseHeaders = {\n\t\tget: (name) => {\n\t\t\tconst value = outgoing.getHeader(name);\n\t\t\treturn value == null ? null : String(value);\n\t\t},\n\t\thas: (name) => outgoing.hasHeader(name),\n\t\tset: (name, value) => {\n\t\t\toutgoing.setHeader(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\toutgoing.removeHeader(name);\n\t\t},\n\t};\n\tconst writeHead = outgoing.writeHead.bind(outgoing);\n\toutgoing.writeHead = (\n\t\tstatusCode: number,\n\t\treason?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\tvalues?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t) => {\n\t\tconst [message, given] = typeof reason === \"string\" ? [reason, values] : [undefined, reason];\n\t\t// Why: the hooks must see the headers that `writeHead` gets, such as the content type of a file.\n\t\tif (Array.isArray(given)) {\n\t\t\t// Why remove, then append: Node reads a flat `[name, value, …]` list so. A name replaces the old value and can repeat.\n\t\t\tconst names = given.filter((_, index) => index % 2 === 0).map(String);\n\t\t\tfor (const name of names) {\n\t\t\t\toutgoing.removeHeader(name);\n\t\t\t}\n\t\t\tfor (const [index, name] of names.entries()) {\n\t\t\t\tconst value = given[index * 2 + 1];\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.appendHeader(name, typeof value === \"number\" ? String(value) : value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (given != null) {\n\t\t\tfor (const [name, value] of Object.entries(given)) {\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.setHeader(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Why reversed: in production, the hook of an inner stage runs first, so an outer stage has the last word.\n\t\tfor (const hook of hooks.toReversed()) {\n\t\t\thook(headers);\n\t\t}\n\t\treturn message == null ? writeHead(statusCode) : writeHead(statusCode, message);\n\t};\n\treturn () => {\n\t\toutgoing.writeHead = writeHead;\n\t};\n}\n\n/** Options for {@link devServerStage}. */\nexport type DevServerStageOptions = {\n\t/**\n\t * The directory that the middleware serves as it is, and the URL base that\n\t * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML\n\t * file from it gets the `contentSecurityPolicy` with the hashes of its\n\t * inline scripts, as it does in production. Why a function: a Vite restart\n\t * can change both.\n\t */\n\tpublicFiles?: () => { directory: string; base: string };\n};\n\n/** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */\nfunction publicFileHashes(\n\t{ directory, base }: { directory: string; base: string },\n\tpathname: string,\n): string[] | undefined {\n\tconst prefix = base.replace(/\\/$/u, \"\");\n\t// Why both forms: in middleware mode, Vite's base middleware passes a path with no base on as it is.\n\treturn publicScriptHashes(\n\t\tdirectory,\n\t\tpathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname,\n\t);\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {\n * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n * }));\n */\nexport function devServerStage(\n\tmiddleware: NodeMiddleware,\n\t{ publicFiles }: DevServerStageOptions = {},\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\tconst hashes =\n\t\t\tpublicFiles == null\n\t\t\t\t? undefined\n\t\t\t\t: publicFileHashes(publicFiles(), new URL(context.req.url).pathname);\n\t\tconst earlierHashes = context.get(\"documentScriptHashes\");\n\t\tif (hashes != null) {\n\t\t\tcontext.set(\"documentScriptHashes\", hashes);\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t\tconst undoHooks = runHooksAtHead(outgoing, hooks);\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\t// Why: the later stages answer, and each hook runs on their response.\n\t\t\t\tundoHooks();\n\t\t\t\t// Why: the middleware did not send the public file, so its hashes do not apply.\n\t\t\t\tif (hashes != null) {\n\t\t\t\t\tcontext.set(\"documentScriptHashes\", earlierHashes);\n\t\t\t\t}\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why empty the list: the hooks ran on the head that the middleware sent, so the server must\n\t\t\t// not run them again on the response below.\n\t\t\thooks.length = 0;\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and the\n\t\t\t// headers are the ones that the middleware sent, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\t\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\t\t\tif (each != null) {\n\t\t\t\t\t\theaders.append(name, String(each));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { gzipStream } from \"./gzip.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tDevServerStageOptions,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tstop()\n\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.finally(exitAfterFlush);\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t},\n};\n"],"mappings":";;;;;;;;;;;;;;;AAIA,MAAM,mBAAmB;;;;;;;;;AAUzB,SAAgB,iBAAuB;CACtC,UAAU;CACV,IAAI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Z,QAAQ,KAAK;SAEb,OAAO,IAAI,MAAM,oCAAoC,EAAE,OAAO,MAAM,CAAC,CAAC;GAExE,CAAC;EACF,CAAC,GACa;GAGb,MAAM,SAAS;GAIf,MAAM,UAAU,IAAI,QAAQ,sBAAsB,OAAO;GACzD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,SAAS,WAAW,CAAC,GAC/D,KAAK,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GACvD,IAAI,QAAQ,MACX,QAAQ,OAAO,MAAM,OAAO,IAAI,CAAC;GAIpC,OAAO,IAAI,SAAS,MAAM;IAAE,QAAQ,SAAS;IAAY;GAAQ,CAAC;EACnE;EACA,OAAO,KAAK;CACb;AACD;;;ACvJA,MAAM,UAAU,IAAI,kBAAyC;;;;;;;;;;AAW7D,MAAa,OAAoB;CAChC,MAAM;CACN,OAAO;CACP,iBAAiB,CAAC,IAAI,CAAC;CACvB,SAAS;EACR,MAAM,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI;EAC7C,WAAW,QAAQ,SAAS;CAC7B;CACA,MAAM;CACN,WAAW,EACV,SAAS,SAAS;EACjB,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;GAC1B,KAAK,CAAC,CACJ,YAAY;IACZ,QAAQ,WAAW;GACpB,CAAC,CAAC,CACD,QAAQ,cAAc;EACzB,CAAC;CAEH,EACD;AACD"}
@@ -0,0 +1,41 @@
1
+ import { t as requestListener } from "./response-writer-B7FoJjEE.js";
2
+ import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
3
+ import { createServer } from "node:http";
4
+
5
+ // src/node/runtimes/node.ts
6
+ /** Listens with `node:http`, and writes each response with the node response writer. */
7
+ async function listen(fetch, options) {
8
+ const listener = requestListener(fetch, { trustForwardedProto: options.trustForwardedProto });
9
+ const server = createServer({
10
+ keepAliveTimeout: options.idleTimeoutMs,
11
+ headersTimeout: options.idleTimeoutMs + 1e3
12
+ }, (incoming, outgoing) => {
13
+ listener(incoming, outgoing);
14
+ });
15
+ await new Promise((resolve, reject) => {
16
+ server.once("error", reject);
17
+ server.listen(options.port, options.hostname, () => {
18
+ server.off("error", reject);
19
+ resolve();
20
+ });
21
+ });
22
+ const address = server.address();
23
+ const port = typeof address === "object" && address != null ? address.port : options.port;
24
+ return {
25
+ url: listenerUrl(options.hostname, port),
26
+ stop: async ({ deadlineMs }) => new Promise((resolve, reject) => {
27
+ const deadline = setTimeout(() => {
28
+ server.closeAllConnections();
29
+ }, deadlineMs);
30
+ server.close((error) => {
31
+ clearTimeout(deadline);
32
+ if (error == null) resolve();
33
+ else reject(error);
34
+ });
35
+ server.closeIdleConnections();
36
+ })
37
+ };
38
+ }
39
+
40
+ export { listen };
41
+ //# sourceMappingURL=node-tBVQPjQv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-tBVQPjQv.js","names":[],"sources":["../src/node/runtimes/node.ts"],"sourcesContent":["import { createServer } from \"node:http\";\nimport type { FetchHandler, StartedListener } from \"../../core/types.js\";\nimport { requestListener } from \"../response-writer.js\";\nimport { listenerUrl } from \"./listen-options.js\";\nimport type { ListenOptions } from \"./listen-options.js\";\n\n/** Listens with `node:http`, and writes each response with the node response writer. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\tconst listener = requestListener(fetch, { trustForwardedProto: options.trustForwardedProto });\n\tconst server = createServer(\n\t\t{\n\t\t\tkeepAliveTimeout: options.idleTimeoutMs,\n\t\t\t// Why above the keep-alive timeout: Node closes a socket that is between requests when its\n\t\t\t// headers timer runs out first.\n\t\t\theadersTimeout: options.idleTimeoutMs + 1_000,\n\t\t},\n\t\t(incoming, outgoing) => {\n\t\t\tvoid listener(incoming, outgoing);\n\t\t},\n\t);\n\tawait new Promise<void>((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(options.port, options.hostname, () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\tconst address = server.address();\n\tconst port = typeof address === \"object\" && address != null ? address.port : options.port;\n\treturn {\n\t\turl: listenerUrl(options.hostname, port),\n\t\tstop: async ({ deadlineMs }) =>\n\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\tserver.closeAllConnections();\n\t\t\t\t}, deadlineMs);\n\t\t\t\tserver.close((error) => {\n\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\tif (error == null) {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tserver.closeIdleConnections();\n\t\t\t}),\n\t};\n}\n"],"mappings":";;;;;;AAOA,eAAsB,OACrB,OACA,SAC2B;CAC3B,MAAM,WAAW,gBAAgB,OAAO,EAAE,qBAAqB,QAAQ,oBAAoB,CAAC;CAC5F,MAAM,SAAS,aACd;EACC,kBAAkB,QAAQ;EAG1B,gBAAgB,QAAQ,gBAAgB;CACzC,IACC,UAAU,aAAa;EACvB,AAAK,SAAS,UAAU,QAAQ;CACjC,CACD;CACA,MAAM,IAAI,SAAe,SAAS,WAAW;EAC5C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,QAAQ,MAAM,QAAQ,gBAAgB;GACnD,OAAO,IAAI,SAAS,MAAM;GAC1B,QAAQ;EACT,CAAC;CACF,CAAC;CACD,MAAM,UAAU,OAAO,QAAQ;CAC/B,MAAM,OAAO,OAAO,YAAY,YAAY,WAAW,OAAO,QAAQ,OAAO,QAAQ;CACrF,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,IAAI;EACvC,MAAM,OAAO,EAAE,iBACd,IAAI,SAAe,SAAS,WAAW;GACtC,MAAM,WAAW,iBAAiB;IACjC,OAAO,oBAAoB;GAC5B,GAAG,UAAU;GACb,OAAO,OAAO,UAAU;IACvB,aAAa,QAAQ;IACrB,IAAI,SAAS,MACZ,QAAQ;SAER,OAAO,KAAK;GAEd,CAAC;GACD,OAAO,qBAAqB;EAC7B,CAAC;CACH;AACD"}
@@ -0,0 +1,11 @@
1
+ import { r as HostBuild } from "./index-Bo5G9LuQ.js";
2
+ /**
3
+ * The build side of the node host, the default host of `appServer`. The
4
+ * server build gets `server/app-server.js`. Run it with `node`, `bun`, or
5
+ * `deno run`, or load it with `app-server serve`.
6
+ *
7
+ * @example
8
+ * appServer({ host: node() });
9
+ */
10
+ export declare function node(): HostBuild;
11
+ //# sourceMappingURL=node-vite.d.ts.map
@@ -0,0 +1,3 @@
1
+ import { t as node } from "./vite-D4hfj3ph.js";
2
+
3
+ export { node };