@ngrok/app-server 0.0.0 → 0.1.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.
- package/README.md +6 -6
- package/dist/cli.js +13 -11
- package/dist/cli.js.map +1 -1
- package/dist/{entry-2XXp2Ukh.js → entry-ChjmFwX5.js} +3 -41
- package/dist/entry-ChjmFwX5.js.map +1 -0
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/react-router.js +1 -1
- package/dist/{start-kxw_NM4q.js → serve-ByeedcRB.js} +5 -5
- package/dist/{start-kxw_NM4q.js.map → serve-ByeedcRB.js.map} +1 -1
- package/dist/{dev-DCytOhpM.js → start-BVMb8Pyt.js} +93 -15
- package/dist/start-BVMb8Pyt.js.map +1 -0
- package/dist/tcp-Dau_IONd.js +41 -0
- package/dist/tcp-Dau_IONd.js.map +1 -0
- package/package.json +14 -16
- package/dist/dev-DCytOhpM.js.map +0 -1
- package/dist/entry-2XXp2Ukh.js.map +0 -1
package/README.md
CHANGED
|
@@ -52,8 +52,8 @@ Run it:
|
|
|
52
52
|
```json
|
|
53
53
|
{
|
|
54
54
|
"scripts": {
|
|
55
|
-
"start": "app-server
|
|
56
|
-
"serve": "app-server
|
|
55
|
+
"start": "app-server start",
|
|
56
|
+
"serve": "app-server serve"
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
59
|
```
|
|
@@ -62,14 +62,14 @@ Run it:
|
|
|
62
62
|
|
|
63
63
|
The build exports `appServer`, and the CLI calls it. So the copy of this package in the build runs the server, and the CLI's copy runs nothing. The CLI refuses a build from a version of this package with another entry protocol.
|
|
64
64
|
|
|
65
|
-
An app with no `serverEntry` also works: `app-server
|
|
65
|
+
An app with no `serverEntry` also works: `app-server serve` reads a plain React Router build and runs it with the CLI's copy and the default plugins. In that build, a route that calls `shutdownSignal()` or `eventStream()` must import the CLI's copy, so do not bundle `@ngrok/app-server` into it.
|
|
66
66
|
|
|
67
67
|
## Commands
|
|
68
68
|
|
|
69
|
-
- `app-server
|
|
70
|
-
- `app-server
|
|
69
|
+
- `app-server start`: development. Vite in middleware mode inside the pipeline, with HMR on the same port. Each request loads the latest server build, so an edit to a route or to `server.ts` applies at once. The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, `start` tries each next port, unless Vite's `server.strictPort` is true. The host is `HOST`, else Vite's `server.host`.
|
|
70
|
+
- `app-server serve [build/server/index.js]`: production. The port is `--port`, else `PORT`, else 3000. The host is `HOST`, else every interface. A port in use stops startup at once. Stops on `SIGTERM` or `SIGINT`.
|
|
71
71
|
|
|
72
|
-
On Bun, run `bun node_modules/@ngrok/app-server/dist/cli.js
|
|
72
|
+
On Bun, run `bun node_modules/@ngrok/app-server/dist/cli.js serve`. On Deno, run `deno run --allow-net --allow-env --allow-read --allow-sys node_modules/@ngrok/app-server/dist/cli.js serve`.
|
|
73
73
|
|
|
74
74
|
## The pipeline
|
|
75
75
|
|
package/dist/cli.js
CHANGED
|
@@ -1,27 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { t as parsePort } from "./tcp-Dau_IONd.js";
|
|
2
3
|
import process from "node:process";
|
|
3
4
|
import { parseArgs } from "node:util";
|
|
4
5
|
|
|
5
6
|
// src/cli.ts
|
|
6
|
-
const USAGE = "Usage: app-server
|
|
7
|
-
const { positionals } = parseArgs({
|
|
7
|
+
const USAGE = "Usage: app-server start [--port <port>] | app-server serve [--port <port>] [build/server/index.js]";
|
|
8
|
+
const { positionals, values } = parseArgs({
|
|
8
9
|
allowPositionals: true,
|
|
9
10
|
strict: true,
|
|
10
|
-
options: {}
|
|
11
|
+
options: { port: { type: "string" } }
|
|
11
12
|
});
|
|
12
13
|
const [command, buildPath = "build/server/index.js"] = positionals;
|
|
14
|
+
if (values.port != null) process.env.PORT = String(parsePort(values.port));
|
|
13
15
|
switch (command) {
|
|
14
16
|
case "start": {
|
|
15
|
-
process.env.NODE_ENV ??= "
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
await start({ buildPath });
|
|
17
|
+
process.env.NODE_ENV ??= "development";
|
|
18
|
+
const { start } = await import("./start-BVMb8Pyt.js");
|
|
19
|
+
await start();
|
|
19
20
|
break;
|
|
20
21
|
}
|
|
21
|
-
case "
|
|
22
|
-
process.env.NODE_ENV ??= "
|
|
23
|
-
|
|
24
|
-
await
|
|
22
|
+
case "serve": {
|
|
23
|
+
process.env.NODE_ENV ??= "production";
|
|
24
|
+
if (typeof process.setSourceMapsEnabled === "function") process.setSourceMapsEnabled(true);
|
|
25
|
+
const { serve } = await import("./serve-ByeedcRB.js");
|
|
26
|
+
await serve({ buildPath });
|
|
25
27
|
break;
|
|
26
28
|
}
|
|
27
29
|
default:
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n// The `app-server` command: `app-server
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n// The `app-server` command: `app-server start` or `app-server serve [build/server/index.js]`, each\n// with an optional `--port`.\nimport process from \"node:process\";\nimport { parseArgs } from \"node:util\";\nimport { parsePort } from \"./tcp.js\";\n\nconst USAGE =\n\t\"Usage: app-server start [--port <port>] | app-server serve [--port <port>] [build/server/index.js]\";\n\nconst { positionals, values } = parseArgs({\n\tallowPositionals: true,\n\tstrict: true,\n\toptions: { port: { type: \"string\" } },\n});\nconst [command, buildPath = \"build/server/index.js\"] = positionals;\n\n// Why set `PORT`: the copy of this package in the build reads it, so the flag needs no change to\n// the entry protocol.\nif (values.port != null) {\n\tprocess.env.PORT = String(parsePort(values.port));\n}\n\n// Why dynamic imports: React reads `NODE_ENV` when it loads, and a static import runs first.\nswitch (command) {\n\tcase \"start\": {\n\t\tprocess.env.NODE_ENV ??= \"development\";\n\t\tconst { start } = await import(\"./start.js\");\n\t\tawait start();\n\t\tbreak;\n\t}\n\tcase \"serve\": {\n\t\tprocess.env.NODE_ENV ??= \"production\";\n\t\tif (typeof process.setSourceMapsEnabled === \"function\") {\n\t\t\tprocess.setSourceMapsEnabled(true);\n\t\t}\n\t\tconst { serve } = await import(\"./serve.js\");\n\t\tawait serve({ buildPath });\n\t\tbreak;\n\t}\n\tdefault: {\n\t\tprocess.stderr.write(`${USAGE}\\n`);\n\t\tprocess.exitCode = 1;\n\t}\n}\n"],"mappings":";;;;;;AAOA,MAAM,QACL;AAED,MAAM,EAAE,aAAa,WAAW,UAAU;CACzC,kBAAkB;CAClB,QAAQ;CACR,SAAS,EAAE,MAAM,EAAE,MAAM,SAAS,EAAE;AACrC,CAAC;AACD,MAAM,CAAC,SAAS,YAAY,2BAA2B;AAIvD,IAAI,OAAO,QAAQ,MAClB,QAAQ,IAAI,OAAO,OAAO,UAAU,OAAO,IAAI,CAAC;AAIjD,QAAQ,SAAR;CACC,KAAK,SAAS;EACb,QAAQ,IAAI,aAAa;EACzB,MAAM,EAAE,UAAU,MAAM,OAAO;EAC/B,MAAM,MAAM;EACZ;CACD;CACA,KAAK,SAAS;EACb,QAAQ,IAAI,aAAa;EACzB,IAAI,OAAO,QAAQ,yBAAyB,YAC3C,QAAQ,qBAAqB,IAAI;EAElC,MAAM,EAAE,UAAU,MAAM,OAAO;EAC/B,MAAM,MAAM,EAAE,UAAU,CAAC;EACzB;CACD;CACA;EACC,QAAQ,OAAO,MAAM,GAAG,MAAM,GAAG;EACjC,QAAQ,WAAW;AAErB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { n as tcp } from "./tcp-Dau_IONd.js";
|
|
1
2
|
import { n as capturedHeadersKey, r as readCapturedHeaders } from "./captured-headers-ewL_t3MQ.js";
|
|
2
3
|
import { Hono } from "hono";
|
|
3
4
|
import { requestId } from "hono/request-id";
|
|
@@ -518,45 +519,6 @@ function abortShutdownSignal() {
|
|
|
518
519
|
controller.abort();
|
|
519
520
|
}
|
|
520
521
|
|
|
521
|
-
// src/tcp.ts
|
|
522
|
-
/** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */
|
|
523
|
-
const DEFAULT_IDLE_TIMEOUT_MS = 95e3;
|
|
524
|
-
/**
|
|
525
|
-
* Reads a port number. A value that is not an integer from 0 to 65535 throws,
|
|
526
|
-
* so a bad `PORT` stops startup.
|
|
527
|
-
*
|
|
528
|
-
* @example
|
|
529
|
-
* parsePort("8080"); // => 8080
|
|
530
|
-
*/
|
|
531
|
-
function parsePort(value) {
|
|
532
|
-
const port = Number(value);
|
|
533
|
-
if (value.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`PORT must be an integer from 0 to 65535, not "${value}".`);
|
|
534
|
-
return port;
|
|
535
|
-
}
|
|
536
|
-
/**
|
|
537
|
-
* The default listener: a TCP port, served by the runtime's own HTTP server
|
|
538
|
-
* (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
|
|
539
|
-
* `PORT` and `HOST` when it starts.
|
|
540
|
-
*
|
|
541
|
-
* @example
|
|
542
|
-
* createServer({ listeners: [tcp({ port: 8080 })] });
|
|
543
|
-
*/
|
|
544
|
-
function tcp({ port, host, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
|
|
545
|
-
return {
|
|
546
|
-
name: "tcp",
|
|
547
|
-
start: async (fetch) => {
|
|
548
|
-
const options = {
|
|
549
|
-
port: port ?? (process.env.PORT == null ? 3e3 : parsePort(process.env.PORT)),
|
|
550
|
-
hostname: host ?? (process.env.HOST || void 0),
|
|
551
|
-
idleTimeoutMs
|
|
552
|
-
};
|
|
553
|
-
if ("Bun" in globalThis) return (await import("./bun-DCGnDEPn.js")).listen(fetch, options);
|
|
554
|
-
if ("Deno" in globalThis) return (await import("./deno-BnMfk2n1.js")).listen(fetch, options);
|
|
555
|
-
return (await import("./node-2wWBMFeO.js")).listen(fetch, options);
|
|
556
|
-
}
|
|
557
|
-
};
|
|
558
|
-
}
|
|
559
|
-
|
|
560
522
|
// src/create-server.ts
|
|
561
523
|
const appInternals = /* @__PURE__ */ new WeakMap();
|
|
562
524
|
/**
|
|
@@ -789,5 +751,5 @@ async function loadEntry(build) {
|
|
|
789
751
|
return entry;
|
|
790
752
|
}
|
|
791
753
|
|
|
792
|
-
export {
|
|
793
|
-
//# sourceMappingURL=entry-
|
|
754
|
+
export { shutdownSignal as a, prerendered as c, errorAttributes as d, jsonSink as f, defaultPlugins as i, requestId$1 as l, loadEntry as n, streamingCompress as o, sinkLogger as p, createServer as r, assets as s, createEntry as t, accessLog as u };
|
|
755
|
+
//# sourceMappingURL=entry-ChjmFwX5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entry-ChjmFwX5.js","names":["requestId","honoRequestId","requestId"],"sources":["../src/log.ts","../src/plugins/access-log.ts","../src/plugins/request-id.ts","../src/static-files.ts","../src/plugins/static.ts","../src/plugins/streaming-compress.ts","../src/shutdown.ts","../src/create-server.ts","../src/entry.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogSink, RequestLogger } from \"./types.js\";\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.\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(\n\twrite: (line: string) => void = (line) => {\n\t\tprocess.stdout.write(line);\n\t},\n): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\twrite(\n\t\t\t\t`${JSON.stringify({ time: new Date().toISOString(), level, message, ...attributes })}\\n`,\n\t\t\t);\n\t\t},\n\t};\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\n/** A logger that writes to `sink`, with the attributes from `base` first on each line. */\nexport function sinkLogger(\n\tsink: LogSink,\n\tbase: () => Readonly<Record<string, unknown>> = () => ({}),\n): RequestLogger {\n\tconst line =\n\t\t(level: \"debug\" | \"info\" | \"warn\" | \"error\") =>\n\t\t(message: string, attributes: Readonly<Record<string, unknown>> = {}) => {\n\t\t\tsink.log(level, message, { ...base(), ...attributes });\n\t\t};\n\treturn { debug: line(\"debug\"), info: line(\"info\"), warn: line(\"warn\"), error: line(\"error\") };\n}\n\n/** A logger whose lines carry the request's ID, method, and path. */\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.\n\treturn sinkLogger(sink, () => ({\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}));\n}\n","import type { Context } from \"hono\";\nimport type { AppServerEnv, Plugin } from \"../types.js\";\n\n/** Options for {@link accessLog}. */\nexport type AccessLogOptions = {\n\t/**\n\t * Replace each query value with `REDACTED`, so a single-use code in a URL\n\t * never reaches a log.\n\t * @default true\n\t */\n\tredactQuery?: boolean;\n};\n\n/**\n * A URL's path and query, with each query value replaced when `redact` is set.\n *\n * @example\n * loggedUrl(new URL(\"https://example.com/verify?code=123\"), { redact: true }); // => \"/verify?code=REDACTED\"\n */\nexport function loggedUrl(url: URL, { redact }: { redact: boolean }): string {\n\tif (!redact || url.search === \"\") {\n\t\treturn `${url.pathname}${url.search}`;\n\t}\n\tconst query = Array.from(url.searchParams.keys())\n\t\t.map((key) => `${encodeURIComponent(key)}=REDACTED`)\n\t\t.join(\"&\");\n\treturn `${url.pathname}?${query}`;\n}\n\n/** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */\nfunction loggedReferer(referer: string | undefined, { redact }: { redact: boolean }) {\n\tif (referer == null || !redact) {\n\t\treturn referer;\n\t}\n\tconst url = URL.parse(referer);\n\treturn url == null ? undefined : `${url.origin}${loggedUrl(url, { redact })}`;\n}\n\n/**\n * One log line per request, static hits included, with Datadog standard\n * attribute names. The line goes out when the body ends or the client\n * disconnects, so a streamed response logs its full duration and size.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });\n * // {\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200,\"network.bytes_written\":5120,\"duration\":1830000,...}\n */\nexport function accessLog({ redactQuery = true }: AccessLogOptions = {}): Plugin {\n\treturn {\n\t\tname: \"access-log\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst started = performance.now();\n\t\t\tawait next();\n\t\t\tconst write = ({ bytes, aborted }: { bytes: number; aborted: boolean }) => {\n\t\t\t\tcontext.var.logger.info(\"request\", lineAttributes(context, { bytes, aborted, started }));\n\t\t\t};\n\t\t\tconst response = context.res;\n\t\t\t// Why HEAD: Hono drops the body of a HEAD response, so no one reads it to its end.\n\t\t\tif (context.req.method === \"HEAD\") {\n\t\t\t\twrite({ bytes: 0, aborted: false });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Why `Content-Length`: a stage that answers through Node's response, such as Vite in\n\t\t\t// development, gives a response with no body and the length it sent.\n\t\t\tif (response.body == null) {\n\t\t\t\twrite({ bytes: Number(response.headers.get(\"Content-Length\") ?? 0), aborted: false });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst reader = response.body.getReader();\n\t\t\tlet bytes = 0;\n\t\t\tconst counted = new ReadableStream<Uint8Array>({\n\t\t\t\tasync pull(controller) {\n\t\t\t\t\tlet result: ReadableStreamReadResult<Uint8Array>;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresult = await reader.read();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// Why here: `cancel` does not run for a stream that failed.\n\t\t\t\t\t\twrite({ bytes, aborted: true });\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tconst { done, value } = result;\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\twrite({ bytes, aborted: false });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tbytes += value.byteLength;\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t},\n\t\t\t\tasync cancel(reason) {\n\t\t\t\t\twrite({ bytes, aborted: true });\n\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t},\n\t\t\t});\n\t\t\tcontext.res = new Response(counted, response);\n\t\t},\n\t};\n\n\tfunction lineAttributes(\n\t\tcontext: Context<AppServerEnv>,\n\t\t{ bytes, aborted, started }: { bytes: number; aborted: boolean; started: number },\n\t): Record<string, unknown> {\n\t\treturn {\n\t\t\t\"http.url\": loggedUrl(new URL(context.req.url), { redact: redactQuery }),\n\t\t\t\"http.status_code\": context.res.status,\n\t\t\t\"http.useragent\": context.req.header(\"User-Agent\"),\n\t\t\t\"http.referer\": loggedReferer(context.req.header(\"Referer\"), { redact: redactQuery }),\n\t\t\t\"network.client.ip\": context.env.remoteAddress,\n\t\t\t\"network.bytes_written\": bytes,\n\t\t\t// Why nanoseconds: Datadog's standard `duration` attribute is in nanoseconds.\n\t\t\tduration: Math.round((performance.now() - started) * 1_000_000),\n\t\t\t...(aborted ? { \"http.client_aborted\": true } : {}),\n\t\t};\n\t}\n}\n","import { requestId as honoRequestId } from \"hono/request-id\";\nimport type { Plugin } from \"../types.js\";\n\n/** Options for {@link requestId}. */\nexport type RequestIdOptions = {\n\t/** @default \"X-Request-Id\" */\n\theaderName?: string;\n};\n\n/**\n * Gives each request an ID: a valid incoming header (up to 255 word\n * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on\n * every log line, and into the framework's context.\n *\n * @example\n * const app = createServer({ plugins: [requestId()] });\n * const response = await app.request(\"/\", { headers: { \"X-Request-Id\": \"abc-123\" } });\n * response.headers.get(\"X-Request-Id\"); // => \"abc-123\"\n */\nexport function requestId({ headerName = \"X-Request-Id\" }: RequestIdOptions = {}): Plugin {\n\tconst assign = honoRequestId({ headerName });\n\treturn {\n\t\tname: \"request-id\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait assign(context, next);\n\t\t\t// Why set it again: a `Response` that the framework returns replaces the headers set before `next`.\n\t\t\t// `context.header` also copies a response whose headers are immutable.\n\t\t\tconst id = context.get(\"requestId\");\n\t\t\tif (id != null) {\n\t\t\t\tcontext.header(headerName, id);\n\t\t\t}\n\t\t},\n\t};\n}\n","import { createHash } from \"node:crypto\";\nimport { open, stat, type FileHandle } from \"node:fs/promises\";\nimport { join, sep } from \"node:path\";\nimport type { Context } from \"hono\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport type { AppServerEnv } from \"./types.js\";\n\n/** A file under the client build that answers a request. */\nexport type StaticFile = {\n\t/** The absolute file path. */\n\tpath: string;\n\tsize: number;\n\tmtimeMs: number;\n};\n\n/**\n * Whether a URL path names a dotfile or goes through a dot directory.\n * `/.well-known/` stays reachable.\n */\nfunction hasDotSegment(path: string): boolean {\n\treturn path\n\t\t.split(\"/\")\n\t\t.some(\n\t\t\t(segment, index) => segment.startsWith(\".\") && !(index === 1 && segment === \".well-known\"),\n\t\t);\n}\n\nasync function fileStats(path: string) {\n\ttry {\n\t\treturn await stat(path);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Finds the file under `root` that answers a decoded URL path, such as\n * Hono's `context.req.path`. A directory answers with its `index.html` and no\n * redirect, so a prerendered page keeps its URL. Dotfiles and paths outside\n * `root` find nothing.\n *\n * Each file has one URL, because the headers for a file are keyed by that\n * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes\n * the path but keeps an encoded `/` as `%2F`, so this function does not\n * decode it again.\n *\n * @example\n * await findStaticFile(\"/app/build/client\", \"/components/button\");\n * // => { path: \"/app/build/client/components/button/index.html\", size: 5120, mtimeMs: 1761652800000 }\n */\nexport async function findStaticFile(root: string, path: string): Promise<StaticFile | undefined> {\n\tif (\n\t\tpath.includes(\"\\0\") ||\n\t\tpath.includes(\"\\\\\") ||\n\t\tpath.split(\"/\").includes(\"..\") ||\n\t\tpath.includes(\"//\") ||\n\t\tpath.endsWith(\"/index.html\") ||\n\t\thasDotSegment(path)\n\t) {\n\t\treturn undefined;\n\t}\n\tconst candidate = join(root, path);\n\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\treturn undefined;\n\t}\n\tconst stats = await fileStats(candidate);\n\tif (stats?.isFile()) {\n\t\treturn { path: candidate, size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\tif (stats?.isDirectory()) {\n\t\tconst index = join(candidate, \"index.html\");\n\t\tconst indexStats = await fileStats(index);\n\t\tif (indexStats?.isFile()) {\n\t\t\treturn { path: index, size: indexStats.size, mtimeMs: indexStats.mtimeMs };\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * A file's bytes, one chunk for each pull, so a slow client holds one chunk,\n * not the whole file. The handle closes at the end, on an error, or on cancel.\n */\nfunction fileStream(handle: FileHandle): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { bytesRead, buffer } = await handle.read({ buffer: new Uint8Array(65_536) });\n\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\tawait handle.close();\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tawait handle.close();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tcancel: () => handle.close(),\n\t});\n}\n\n/** The content type of a file, with the React Router and markdown types that `mime` lacks. */\nfunction contentType(path: string): string {\n\tif (path.endsWith(\".md\")) {\n\t\treturn \"text/markdown; charset=utf-8\";\n\t}\n\tif (path.endsWith(\".data\")) {\n\t\treturn \"text/x-script\";\n\t}\n\treturn getMimeType(path) ?? \"application/octet-stream\";\n}\n\n/** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */\nfunction opaqueTag(etag: string): string {\n\treturn etag.trim().replace(/^W\\//, \"\");\n}\n\n/** Whether an `If-None-Match` header lists an ETag. */\nfunction matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean {\n\treturn (\n\t\tifNoneMatch?.split(\",\").some((candidate) => {\n\t\t\tconst trimmed = candidate.trim();\n\t\t\treturn trimmed === \"*\" || opaqueTag(trimmed) === opaqueTag(etag);\n\t\t}) ?? false\n\t);\n}\n\n/** A weak ETag from a file's size, its modification time, and the request's `etagParts`. */\nfunction fileEtag(file: StaticFile, parts: readonly string[]): string {\n\tconst base = `${file.size.toString(16)}-${Math.trunc(file.mtimeMs).toString(16)}`;\n\tif (parts.length === 0) {\n\t\treturn `W/\"${base}\"`;\n\t}\n\tconst hash = createHash(\"sha256\").update(parts.join(\"\\0\")).digest(\"base64url\").slice(0, 16);\n\treturn `W/\"${base}-${hash}\"`;\n}\n\n/**\n * The response for a static file, with a weak ETag from its size,\n * modification time, and the request's `etagParts`. A matching\n * `If-None-Match` gets a 304, and `HEAD` gets the headers only. `headers`\n * replace the defaults, so a captured `Content-Type` wins over the one from\n * the file name.\n */\nexport async function staticResponse(\n\tcontext: Context<AppServerEnv>,\n\tfile: StaticFile,\n\theaders: Readonly<Record<string, string>>,\n): Promise<Response> {\n\tconst etag = fileEtag(file, context.get(\"etagParts\") ?? []);\n\tconst responseHeaders = new Headers({ \"Content-Type\": contentType(file.path), ETag: etag });\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tresponseHeaders.set(name, value);\n\t}\n\t// Why the final header: `headers` can replace the ETag.\n\tif (matchesEtag(context.req.header(\"If-None-Match\"), responseHeaders.get(\"ETag\") ?? etag)) {\n\t\tresponseHeaders.delete(\"Content-Type\");\n\t\treturn new Response(null, { status: 304, headers: responseHeaders });\n\t}\n\tif (context.req.method === \"HEAD\") {\n\t\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\t\treturn new Response(null, { headers: responseHeaders });\n\t}\n\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\treturn new Response(fileStream(await open(file.path)), { headers: responseHeaders });\n}\n","import { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport { capturedHeadersKey, readCapturedHeaders } from \"../captured-headers.js\";\nimport { findStaticFile, staticResponse } from \"../static-files.js\";\nimport type { AppServerEnv, NodeMiddleware, Plugin } from \"../types.js\";\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/** Runs Vite's middleware inside the pipeline. Vite answers or calls `next`. */\nfunction viteStage(viteMiddleware: NodeMiddleware): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (incoming == null || outgoing == null) {\n\t\t\treturn next();\n\t\t}\n\t\t// Why before Vite: it sends the headers itself, so the headers the earlier stages set, such\n\t\t// 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 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\tviteMiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\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(\"Vite 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 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 length\n\t\t\t// are Vite's, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tconst length = outgoing.getHeader(\"Content-Length\");\n\t\t\tif (length != null) {\n\t\t\t\theaders.set(\"Content-Length\", String(length));\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\n/**\n * Serves the hashed files under `/assets/` with a one-year immutable cache.\n * A missing asset gets a plain 404, not a rendered page. In development,\n * Vite serves the source modules, the HMR client, and the CSS here instead.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });\n */\nexport function assets(): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"assets\",\n\t\tsetup: (info) => {\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\tstage = viteStage(info.viteMiddleware);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst root = info.clientDirectory;\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method, path } = context.req;\n\t\t\t\tif (!path.startsWith(\"/assets/\") || (method !== \"GET\" && method !== \"HEAD\")) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst file = await findStaticFile(root, path);\n\t\t\t\tif (file == null) {\n\t\t\t\t\treturn context.text(\"Not Found\", 404);\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, file, { \"Cache-Control\": IMMUTABLE });\n\t\t\t};\n\t\t},\n\t\tmiddleware: (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n\n/** Options for {@link prerendered}. */\nexport type PrerenderedOptions = {\n\t/**\n\t * Extra headers for a served file, by its URL path. They replace the\n\t * headers captured at build time.\n\t */\n\theaders?: (\n\t\tpath: string,\n\t\tcontext: Context<AppServerEnv>,\n\t) => Readonly<Record<string, string>> | undefined;\n\t/**\n\t * Maps a request path to the URL path of the file to serve, for content\n\t * negotiation. Return the path unchanged to serve the usual file. The\n\t * returned path follows the rules of a request path: one URL for each\n\t * file, no dotfiles, and nothing outside the client build. When the\n\t * answer depends on a request header, add a `Vary` for it in a plugin.\n\t */\n\trewrite?: (path: string, context: Context<AppServerEnv>) => string;\n};\n\n/**\n * Serves the client build: prerendered pages at their own URL with a 200 and\n * no trailing-slash redirect, plus every other file in it. Each response gets\n * the headers its loader sent at build time (the `serverEntry` Vite plugin\n * captures them), an ETag, and a 304 for a matching `If-None-Match`. A path\n * with no file goes on to the framework. Off in development.\n *\n * At startup, it warns about each prerendered path that has no file.\n *\n * @example\n * prerendered({\n * \theaders: (path) => (path.startsWith(\"/api/\") ? { \"Access-Control-Allow-Origin\": \"*\" } : undefined),\n * });\n */\nexport function prerendered(options: PrerenderedOptions = {}): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"prerendered\",\n\t\tsetup: async (info) => {\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst root = info.clientDirectory;\n\t\t\tconst captured = await readCapturedHeaders(root);\n\t\t\tconst missing: string[] = [];\n\t\t\tfor (const path of info.prerenderedPaths) {\n\t\t\t\tif ((await findStaticFile(root, path)) == null) {\n\t\t\t\t\tmissing.push(path);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (missing.length > 0) {\n\t\t\t\t// Why a warning: a path with no file falls through to the framework, which still answers.\n\t\t\t\tinfo.logger.log(\"warn\", \"prerendered paths with no file\", {\n\t\t\t\t\t\"app_server.missing_paths\": missing,\n\t\t\t\t});\n\t\t\t}\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method } = context.req;\n\t\t\t\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst path = options.rewrite?.(context.req.path, context) ?? context.req.path;\n\t\t\t\tconst file = await findStaticFile(root, path);\n\t\t\t\tif (file == null) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, file, {\n\t\t\t\t\t...captured.get(capturedHeadersKey(path)),\n\t\t\t\t\t...options.headers?.(path, context),\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t\tmiddleware: (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import { accepts } from \"hono/accepts\";\nimport { constants, createGzip } from \"node:zlib\";\nimport type { Plugin } from \"../types.js\";\n\nconst COMPRESSIBLE =\n\t/^(text\\/|application\\/(json|javascript|xml|schema\\+json|manifest\\+json|x-ndjson|connect\\+json)|image\\/svg\\+xml)/;\n\n/**\n * Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at\n * once. It reads the next source chunk only when the consumer pulls, so a slow\n * client holds back the source.\n */\nfunction gzipStream(source: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n\tconst gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });\n\tconst reader = source.getReader();\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tgzip.on(\"data\", (chunk: Buffer) => {\n\t\t\t\tcontroller.enqueue(new Uint8Array(chunk));\n\t\t\t});\n\t\t\tgzip.on(\"end\", () => {\n\t\t\t\tcontroller.close();\n\t\t\t});\n\t\t\tgzip.on(\"error\", (error) => {\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\t\t},\n\t\tasync pull() {\n\t\t\ttry {\n\t\t\t\tlet chunk = await reader.read();\n\t\t\t\t// Why skip empty chunks: gzip writes nothing for one, and a pull that enqueues nothing\n\t\t\t\t// is not called again.\n\t\t\t\twhile (!chunk.done && chunk.value.byteLength === 0) {\n\t\t\t\t\tchunk = await reader.read();\n\t\t\t\t}\n\t\t\t\tif (chunk.done) {\n\t\t\t\t\tgzip.end();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst { value } = chunk;\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tgzip.write(value, (error) => {\n\t\t\t\t\t\tif (error == null) {\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tgzip.destroy();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\t// Why cancel the source: a client disconnect must reach the handler, so it stops its work.\n\t\tcancel(reason) {\n\t\t\tgzip.destroy();\n\t\t\treturn reader.cancel(reason);\n\t\t},\n\t});\n}\n\n/**\n * Gzips text responses and flushes after each chunk, so a streamed page shell\n * or a server-sent event reaches the client at once. `hono/compress` holds a\n * stream until it ends. Skips a response that is already encoded, a partial\n * response, and one marked `no-transform`. Always sets `Vary: Accept-Encoding`.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });\n */\nexport function streamingCompress(): Plugin {\n\treturn {\n\t\tname: \"streaming-compress\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\t// Why `context.header`: it copies a response whose headers are immutable, such as one from `fetch`.\n\t\t\tcontext.header(\"Vary\", \"Accept-Encoding\", { append: true });\n\t\t\tconst response = context.res;\n\t\t\tif (\n\t\t\t\tresponse.body == null ||\n\t\t\t\tcontext.req.method === \"HEAD\" ||\n\t\t\t\taccepts(context, { header: \"Accept-Encoding\", supports: [\"gzip\"], default: \"identity\" }) !==\n\t\t\t\t\t\"gzip\" ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: gzip changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\t/\\bno-transform\\b/.test(response.headers.get(\"Cache-Control\") ?? \"\") ||\n\t\t\t\t!COMPRESSIBLE.test(response.headers.get(\"Content-Type\") ?? \"\")\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontext.res = new Response(gzipStream(response.body), response);\n\t\t\t// Why after the assignment: Hono copies the old response's headers onto the new one.\n\t\t\tcontext.res.headers.set(\"Content-Encoding\", \"gzip\");\n\t\t\tcontext.res.headers.delete(\"Content-Length\");\n\t\t},\n\t};\n}\n","let controller = new AbortController();\n\n/**\n * A signal that aborts when the server starts to shut down. Read it for each\n * request: each start of a server makes a new one. A handler that\n * holds a response open, such as an event stream, stops on it so that the\n * drain does not wait for the deadline.\n *\n * @example\n * const timer = setInterval(sendUpdate, 1_000);\n * shutdownSignal().addEventListener(\"abort\", () => clearInterval(timer), { once: true });\n */\nexport function shutdownSignal(): AbortSignal {\n\treturn controller.signal;\n}\n\n/** Replaces {@link shutdownSignal} with a new one that has not aborted. */\nexport function renewShutdownSignal(): void {\n\tcontroller = new AbortController();\n}\n\n/** Aborts {@link shutdownSignal}. */\nexport function abortShutdownSignal(): void {\n\tcontroller.abort();\n}\n","import { Hono } from \"hono\";\nimport { errorAttributes, jsonSink, requestLogger } from \"./log.js\";\nimport { accessLog, type AccessLogOptions } from \"./plugins/access-log.js\";\nimport { requestId, type RequestIdOptions } from \"./plugins/request-id.js\";\nimport { assets, prerendered, type PrerenderedOptions } from \"./plugins/static.js\";\nimport { streamingCompress } from \"./plugins/streaming-compress.js\";\nimport { abortShutdownSignal, renewShutdownSignal } from \"./shutdown.js\";\nimport { tcp } from \"./tcp.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkAdapter,\n\tListener,\n\tLogSink,\n\tPlugin,\n\tSetupInfo,\n} from \"./types.js\";\n\n// Why a WeakMap: only this copy of the package reads an app's internals, through `createEntry`.\nconst appInternals = new WeakMap<AppServer, ServerInternals>();\n\n/** A Hono app from {@link createServer}. Add routes to it before you export it. */\nexport type AppServer = Hono<AppServerEnv>;\n\n/** A server that listens. */\nexport type RunningServer = {\n\t/** The URL of each listener. */\n\turls: readonly string[];\n\t/**\n\t * Aborts `shutdownSignal()`, then runs each plugin's `onShutdown` while the\n\t * listeners stop and drain open requests. Both stop at the deadline.\n\t */\n\tshutdown: () => Promise<void>;\n};\n\n/** What `createEntry` calls on an app. */\nexport type ServerInternals = {\n\tlogger: LogSink;\n\t/** Runs each plugin's `setup` once and adds the framework handler after the app's routes. */\n\tprepare: (info: SetupInfo) => Promise<void>;\n\t/** Starts the listeners. Call `prepare` first. */\n\tlisten: (framework: FrameworkAdapter) => Promise<RunningServer>;\n\t/** Runs each plugin's `onShutdown` once, and stops waiting for them at the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n};\n\n/** Options for {@link defaultPlugins}. */\nexport type DefaultPluginsOptions = {\n\trequestId?: RequestIdOptions;\n\taccessLog?: AccessLogOptions;\n\tprerendered?: PrerenderedOptions;\n\t/**\n\t * Plugins that go after compression and before the static stages, so they\n\t * see every response, prerendered pages included. `runtimeEnv` and\n\t * `buildId` go here.\n\t */\n\tbeforeStatic?: readonly Plugin[];\n};\n\n/**\n * The default pipeline, in order: `requestId`, `accessLog`,\n * `streamingCompress`, the `beforeStatic` plugins, `assets`, and\n * `prerendered`. It is a plain array, so an app can filter it or splice into it.\n *\n * @example\n * createServer({ plugins: defaultPlugins({ accessLog: { redactQuery: false }, beforeStatic: [env] }) });\n */\nexport function defaultPlugins(options: DefaultPluginsOptions = {}): Plugin[] {\n\treturn [\n\t\trequestId(options.requestId),\n\t\taccessLog(options.accessLog),\n\t\tstreamingCompress(),\n\t\t...(options.beforeStatic ?? []),\n\t\tassets(),\n\t\tprerendered(options.prerendered),\n\t];\n}\n\n/** Options for {@link createServer}. */\nexport type CreateServerOptions = {\n\t/** @default defaultPlugins() */\n\tplugins?: readonly Plugin[];\n\t/** @default jsonSink() */\n\tlogger?: LogSink;\n\t/** @default [tcp()] */\n\tlisteners?: readonly Listener[];\n\t/**\n\t * Read the request scheme from `X-Forwarded-Proto`. Set it only behind a\n\t * proxy that overwrites that header, else a client can spoof it.\n\t * @default false\n\t */\n\ttrustForwardedProto?: boolean;\n\t/**\n\t * How long open requests get to finish after a stop signal.\n\t * @default 10000\n\t */\n\tshutdownDeadlineMs?: number;\n};\n\n/** The request with the scheme from `X-Forwarded-Proto`, when that header holds one. */\nfunction withForwardedProto(request: Request): Request {\n\tconst proto = request.headers.get(\"X-Forwarded-Proto\");\n\tif (proto !== \"http\" && proto !== \"https\") {\n\t\treturn request;\n\t}\n\tconst url = new URL(request.url);\n\turl.protocol = `${proto}:`;\n\treturn new Request(url, request);\n}\n\n/**\n * Runs `step`, and rethrows a thrown value that is not an `Error` as one.\n * Hono sends only an `Error` to `onError`, and rethrows any other value.\n */\nasync function asError<Result>(step: () => Promise<Result>): Promise<Result> {\n\ttry {\n\t\treturn await step();\n\t} catch (error) {\n\t\tthrow error instanceof Error\n\t\t\t? error\n\t\t\t: new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });\n\t}\n}\n\n/** Whether `work` settles before `ms` pass. */\nasync function settlesWithin(work: Promise<void>, ms: number): Promise<boolean> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst settled = await Promise.race([\n\t\twork.then(() => true),\n\t\tnew Promise<boolean>((resolve) => {\n\t\t\ttimer = setTimeout(resolve, ms, false);\n\t\t}),\n\t]);\n\tclearTimeout(timer);\n\treturn settled;\n}\n\n/**\n * Builds an app server: a Hono app that runs the plugins in list order, then\n * the app's own routes, then the framework. It does not listen; the\n * `app-server` CLI starts it.\n *\n * @example\n * // server.ts\n * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ beforeStatic: [env] }) });\n * app.get(\"/livez\", (c) => c.text(\"ok\"));\n * export default app;\n */\nexport function createServer({\n\tplugins = defaultPlugins(),\n\tlogger = jsonSink(),\n\tlisteners = [tcp()],\n\ttrustForwardedProto = false,\n\tshutdownDeadlineMs = 10_000,\n}: CreateServerOptions = {}): AppServer {\n\tconst app = new Hono<AppServerEnv>();\n\tif (trustForwardedProto) {\n\t\t// Why wrap `fetch`: every plugin and route, not only the framework, must see the trusted scheme.\n\t\tconst dispatch = app.fetch;\n\t\tapp.fetch = (request, ...rest) => dispatch(withForwardedProto(request), ...rest);\n\t}\n\tapp.use(async (context, next) => {\n\t\tcontext.set(\"logger\", requestLogger(logger, context));\n\t\tawait next();\n\t\t// Why cancel: Hono drops the body of a HEAD response without a cancel, so a stream would run on.\n\t\tif (context.req.method === \"HEAD\") {\n\t\t\tawait context.res.body?.cancel();\n\t\t}\n\t});\n\t// Why `asError` at each step: a value that is not an `Error` becomes one where it is thrown,\n\t// so `onError` answers at once and each earlier plugin still sees the 500 after its `next`.\n\tfor (const { middleware, etagPart } of plugins) {\n\t\tapp.use((context, next) => {\n\t\t\tconst part = etagPart?.();\n\t\t\tif (part != null) {\n\t\t\t\tcontext.set(\"etagParts\", [...(context.get(\"etagParts\") ?? []), part]);\n\t\t\t}\n\t\t\treturn asError(async () => (middleware == null ? next() : middleware(context, next)));\n\t\t});\n\t}\n\tapp.use((_, next) => asError(next));\n\tapp.onError((error, context) => {\n\t\t// Why no `instanceof`: the app's routes can throw an `HTTPException` from another copy of Hono.\n\t\tif (\"getResponse\" in error && typeof error.getResponse === \"function\") {\n\t\t\tconst response: unknown = error.getResponse();\n\t\t\tif (response instanceof Response) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t}\n\t\tcontext.var.logger.error(\"unhandled error\", errorAttributes(error));\n\t\treturn context.text(\"Internal Server Error\", 500);\n\t});\n\n\tlet prepared: Promise<void> | undefined;\n\tlet running: RunningServer | undefined;\n\tlet stoppingPlugins: Promise<void> | undefined;\n\tconst internals: ServerInternals = {\n\t\tlogger,\n\t\tprepare: (info) => {\n\t\t\tprepared ??= (async () => {\n\t\t\t\tfor (const plugin of plugins) {\n\t\t\t\t\tawait plugin.setup?.(info);\n\t\t\t\t}\n\t\t\t\tapp.all(\"*\", (context) => context.env.framework.fetch(context.req.raw, context));\n\t\t\t})();\n\t\t\treturn prepared;\n\t\t},\n\t\tlisten: async (framework) => {\n\t\t\tif (running != null) {\n\t\t\t\tthrow new Error(\"This app server is already listening.\");\n\t\t\t}\n\t\t\trenewShutdownSignal();\n\t\t\tlet deadlinePassed = false;\n\t\t\tconst fetch: FetchHandler = async (request, bindings) => {\n\t\t\t\tconst response = await app.fetch(request, { ...bindings, framework });\n\t\t\t\t// Why: after the drain deadline, the listener closed the connection, so no one reads this\n\t\t\t\t// body. A cancel stops its producer, which can otherwise keep the process alive.\n\t\t\t\tif (deadlinePassed) {\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 starts = await Promise.allSettled(listeners.map((listener) => listener.start(fetch)));\n\t\t\tconst started = starts.flatMap((start) =>\n\t\t\t\tstart.status === \"fulfilled\" ? [start.value] : [],\n\t\t\t);\n\t\t\tconst failed = starts.find((start) => start.status === \"rejected\");\n\t\t\tif (failed != null) {\n\t\t\t\t// Why stop the others: the caller gets no handle to stop them.\n\t\t\t\tawait Promise.all(started.map((listener) => listener.stop({ deadlineMs: 0 })));\n\t\t\t\tthrow failed.reason;\n\t\t\t}\n\t\t\tconst urls = started.map((listener) => listener.url);\n\t\t\tlogger.log(\"info\", \"listening\", { \"app_server.urls\": urls });\n\t\t\tlet stopping: Promise<void> | undefined;\n\t\t\trunning = {\n\t\t\t\turls,\n\t\t\t\tshutdown: () => {\n\t\t\t\t\tstopping ??= (async () => {\n\t\t\t\t\t\tlogger.log(\"info\", \"draining\", { \"app_server.deadline_ms\": shutdownDeadlineMs });\n\t\t\t\t\t\tabortShutdownSignal();\n\t\t\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\t\t\tdeadlinePassed = true;\n\t\t\t\t\t\t}, shutdownDeadlineMs);\n\t\t\t\t\t\t// Why at the same time: a plugin that hangs must not keep the listeners open.\n\t\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\t\tinternals.stopPlugins(),\n\t\t\t\t\t\t\t...started.map((listener) => listener.stop({ deadlineMs: shutdownDeadlineMs })),\n\t\t\t\t\t\t]);\n\t\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\t\tlogger.log(\"info\", \"stopped\", {});\n\t\t\t\t\t})();\n\t\t\t\t\treturn stopping;\n\t\t\t\t},\n\t\t\t};\n\t\t\treturn running;\n\t\t},\n\t\tstopPlugins: () => {\n\t\t\tstoppingPlugins ??= (async () => {\n\t\t\t\tconst hooks = (async () => {\n\t\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\t\tplugins.map(async (plugin) => plugin.onShutdown?.()),\n\t\t\t\t\t);\n\t\t\t\t\tfor (const result of results) {\n\t\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\t\tlogger.log(\"error\", \"plugin shutdown failed\", errorAttributes(result.reason));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\tif (!(await settlesWithin(hooks, shutdownDeadlineMs))) {\n\t\t\t\t\tlogger.log(\"warn\", \"plugin shutdown passed the deadline\", {\n\t\t\t\t\t\t\"app_server.deadline_ms\": shutdownDeadlineMs,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn stoppingPlugins;\n\t\t},\n\t};\n\tappInternals.set(app, internals);\n\treturn app;\n}\n\n/** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */\nexport function serverInternals(app: AppServer): ServerInternals | undefined {\n\treturn appInternals.get(app);\n}\n","import { serverInternals, type AppServer } from \"./create-server.js\";\nimport { errorAttributes } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport type { FrameworkAdapter, ListenerBindings, NodeMiddleware, SetupInfo } from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 1;\n\n/**\n * What a server build exports as `appServer`. The CLI calls it, so the copy\n * of this package in the build runs the server, and the CLI's copy runs\n * nothing.\n */\nexport type AppServerEntry = {\n\t/** The CLI refuses an entry with another version. */\n\tprotocol: typeof ENTRY_PROTOCOL;\n\t/** The app. Two entries with the same app share its plugins. */\n\tapp: AppServer;\n\t/** Production: runs each plugin's `setup`, listens, and shuts down on `SIGTERM` or `SIGINT`. */\n\tstart: () => Promise<void>;\n\t/** Development: answers one request with Vite's middleware inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tviteMiddleware: NodeMiddleware,\n\t) => Promise<Response>;\n\t/** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Aborts `shutdownSignal()` of this copy of the package. */\n\tabortShutdownSignal: () => void;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer` and\n * the framework adapter for each mode. The `serverEntry` Vite plugin makes\n * this export for a React Router build. Call this for another framework.\n *\n * @example\n * export const appServer = createEntry({ app, framework: (mode) => myAdapter(build, mode) });\n */\nexport function createEntry({\n\tapp,\n\tframework,\n}: {\n\tapp: AppServer;\n\tframework: (mode: SetupInfo[\"mode\"]) => FrameworkAdapter;\n}): AppServerEntry {\n\tconst internals = serverInternals(app);\n\tif (internals == null) {\n\t\tthrow new Error(\n\t\t\t\"The app is not from `createServer()` of the copy of @ngrok/app-server in this build.\",\n\t\t);\n\t}\n\tlet development: FrameworkAdapter | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst adapter = framework(\"production\");\n\t\t\tawait internals.prepare({\n\t\t\t\tmode: \"production\",\n\t\t\t\tclientDirectory: adapter.clientDirectory,\n\t\t\t\tprerenderedPaths: adapter.prerenderedPaths,\n\t\t\t\tlogger: internals.logger,\n\t\t\t});\n\t\t\tconst server = await internals.listen(adapter);\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\t\tinternals.logger.log(\"error\", \"shutdown failed\", errorAttributes(error));\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\tfetchDev: async (request, bindings, viteMiddleware) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\tmode: \"development\",\n\t\t\t\tviteMiddleware,\n\t\t\t\tclientDirectory: development.clientDirectory,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tlogger: internals.logger,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\nfunction isAppServerEntry(value: unknown): value is AppServerEntry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"protocol\" in value &&\n\t\tvalue.protocol === ENTRY_PROTOCOL\n\t);\n}\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `serverEntry` Vite plugin made it, else this copy of the package over a\n * plain React Router build with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { appServerEntry, isServerBuild } = await import(\"./react-router.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = appServerEntry(build);\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAgB,SACf,SAAiC,SAAS;CACzC,QAAQ,OAAO,MAAM,IAAI;AAC1B,GACU;CACV,OAAO,EACN,MAAM,OAAO,SAAS,eAAe;EACpC,MACC,GAAG,KAAK,UAAU;GAAE,uBAAM,I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B,YAAY;IAC9B,QAAQ,UAAU;GACnB,CAAC;GACD,OAAO,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAY,CAAC;EAClE;EACA,aAAa,UAAU;EACvB;CACD;AACD;AAEA,SAAS,iBAAiB,OAAyC;CAClE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER;;AAGA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,gBAAgB,kBAAkB,MAAM,OAAO;CACvD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,eAAe,KAAK;CAClC,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as tcp } from "./tcp-Dau_IONd.js";
|
|
2
|
+
import { a as shutdownSignal, c as prerendered, f as jsonSink, i as defaultPlugins, l as requestId, o as streamingCompress, r as createServer, s as assets, t as createEntry, u as accessLog } from "./entry-ChjmFwX5.js";
|
|
2
3
|
|
|
3
4
|
// src/event-stream.ts
|
|
4
5
|
function formatEvent({ data, event, id }) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/event-stream.ts","../src/plugins/build-id.ts","../src/plugins/runtime-env.ts"],"sourcesContent":["import { shutdownSignal } from \"./shutdown.js\";\n\n/** One server-sent event. */\nexport type ServerSentEvent = {\n\tdata: string;\n\tevent?: string;\n\tid?: string;\n};\n\n/** What {@link eventStream} passes to its producer. */\nexport type EventStreamSink = {\n\tsend: (event: ServerSentEvent) => void;\n\t/** Aborts when the client disconnects or the server shuts down. Stop the work on it. */\n\tsignal: AbortSignal;\n};\n\n/** Options for {@link eventStream}. */\nexport type EventStreamOptions = {\n\t/** The request's signal, so a client disconnect stops the stream. */\n\tsignal?: AbortSignal;\n\t/**\n\t * How often a `: ping` comment goes out, so that a proxy keeps a quiet stream open.\n\t * @default 15000\n\t */\n\theartbeatMs?: number;\n\t/** Extra response headers. */\n\theaders?: HeadersInit;\n};\n\nfunction formatEvent({ data, event, id }: ServerSentEvent): string {\n\t// Why: a line break in `event` or `id` would start another field or event.\n\tif (/[\\r\\n]/.test(`${event ?? \"\"}${id ?? \"\"}`)) {\n\t\tthrow new TypeError(\"An event's `event` and `id` cannot contain a line break.\");\n\t}\n\tconst lines = [\n\t\t...(event == null ? [] : [`event: ${event}`]),\n\t\t...(id == null ? [] : [`id: ${id}`]),\n\t\t// Why `\\r` too: a client reads a lone carriage return as a line end.\n\t\t...data.split(/\\r\\n|\\r|\\n/).map((line) => `data: ${line}`),\n\t];\n\treturn `${lines.join(\"\\n\")}\\n\\n`;\n}\n\n/**\n * A `text/event-stream` response that stays correct for its whole life: it\n * sends a heartbeat comment, it stops when the client disconnects, and it\n * closes at server shutdown so the drain does not wait for the deadline. The\n * stream closes when `produce` resolves.\n *\n * @example\n * export async function loader({ request }: Route.LoaderArgs) {\n * \treturn eventStream({ signal: request.signal }, async ({ send, signal }) => {\n * \t\tfor await (const update of watchUpdates({ signal })) {\n * \t\t\tsend({ event: \"update\", data: JSON.stringify(update) });\n * \t\t}\n * \t});\n * }\n */\nexport function eventStream(\n\t{ signal, heartbeatMs = 15_000, headers }: EventStreamOptions,\n\tproduce: (sink: EventStreamSink) => void | Promise<void>,\n): Response {\n\tconst encoder = new TextEncoder();\n\tconst stopped = new AbortController();\n\tconst stopSignal = AbortSignal.any([\n\t\tstopped.signal,\n\t\tshutdownSignal(),\n\t\t...(signal == null ? [] : [signal]),\n\t]);\n\tlet heartbeat: ReturnType<typeof setInterval> | undefined;\n\tlet closed = false;\n\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst close = () => {\n\t\t\t\tif (closed) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclosed = true;\n\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t// Why: the listener lives on `shutdownSignal()`, which lasts the life of the process.\n\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\tcontroller.close();\n\t\t\t};\n\t\t\tconst write = (text: string) => {\n\t\t\t\tif (!closed) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t}\n\t\t\t};\n\t\t\theartbeat = setInterval(() => {\n\t\t\t\twrite(\": ping\\n\\n\");\n\t\t\t}, heartbeatMs);\n\t\t\tstopSignal.addEventListener(\"abort\", close, { once: true });\n\t\t\tif (stopSignal.aborted) {\n\t\t\t\tclose();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() => produce({ send: (event) => write(formatEvent(event)), signal: stopSignal }))\n\t\t\t\t.then(close, (error: unknown) => {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true;\n\t\t\tclearInterval(heartbeat);\n\t\t\tstopped.abort();\n\t\t},\n\t});\n\n\tconst responseHeaders = new Headers(headers);\n\tresponseHeaders.set(\"Content-Type\", \"text/event-stream; charset=utf-8\");\n\tresponseHeaders.set(\"Cache-Control\", \"no-cache\");\n\treturn new Response(body, { headers: responseHeaders });\n}\n","import type { Plugin } from \"../types.js\";\n\n/** Options for {@link buildId}. */\nexport type BuildIdOptions = {\n\t/** @default \"X-Build-Id\" */\n\theader?: string;\n\t/** The deployed build, such as the image tag. Read it from the runtime env, not the build. */\n\tvalue: string;\n};\n\n/**\n * Sets a build ID header on documents and React Router `.data` responses, so\n * a client can see that a deploy happened under it.\n *\n * @example\n * buildId({ value: env.values.PUBLIC_APP_VERSION });\n */\nexport function buildId({ header = \"X-Build-Id\", value }: BuildIdOptions): Plugin {\n\treturn {\n\t\tname: \"build-id\",\n\t\t// Why: a 304 has no `Content-Type`, so a document that did not change on disk must still\n\t\t// answer 200 when the build ID changes.\n\t\tetagPart: () => value,\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\tconst isDocument = context.res.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false;\n\t\t\tif (isDocument || context.req.path.endsWith(\".data\")) {\n\t\t\t\tcontext.header(header, value);\n\t\t\t}\n\t\t},\n\t};\n}\n","import type { Plugin } from \"../types.js\";\n\n// The Standard Schema interface (https://standardschema.dev), copied as its spec asks, so that\n// zod, valibot, and arktype schemas all work with no dependency on any of them.\ntype StandardIssue = {\n\treadonly message: string;\n\treadonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined;\n};\ntype StandardResult<Output> =\n\t| { readonly value: Output; readonly issues?: undefined }\n\t| { readonly issues: ReadonlyArray<StandardIssue> };\n\n/** A schema that follows the Standard Schema interface, such as a zod object. */\nexport type StandardSchemaV1<Input = unknown, Output = Input> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: string;\n\t\treadonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;\n\t\treadonly types?: { readonly input: Input; readonly output: Output } | undefined;\n\t};\n};\n\n/** The parsed type of a Standard Schema. */\nexport type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n\tSchema[\"~standard\"][\"types\"]\n>[\"output\"];\n\n/** The `id` of the JSON `<script>` that carries the public values into each HTML document. */\nexport const PUBLIC_ENV_SCRIPT_ID = \"app-server-public-env\";\n\n/** Stops the search for `</head>` after this many characters, so a page with none still streams. */\nconst HEAD_SEARCH_LIMIT = 1_048_576;\n\n/** Options for {@link runtimeEnv}. */\nexport type RuntimeEnvOptions = {\n\t/** @default process.env */\n\tsource?: Readonly<Record<string, string | undefined>>;\n\t/**\n\t * Values whose names start with this prefix reach the browser.\n\t * @default \"PUBLIC_\"\n\t */\n\tpublicPrefix?: string;\n};\n\n/** The plugin that {@link runtimeEnv} returns, with the parsed values. */\nexport type RuntimeEnv<Values> = Plugin & {\n\t/** The parsed values. The first read parses, and a bad value throws. */\n\treadonly values: Values;\n\t/** The parsed values whose names start with the public prefix. */\n\treadonly publicValues: Readonly<Record<string, unknown>>;\n};\n\nfunction formatIssue(issue: StandardIssue): string {\n\tconst path = (issue.path ?? [])\n\t\t.map((segment) => String(typeof segment === \"object\" ? segment.key : segment))\n\t\t.join(\".\");\n\treturn ` ${path === \"\" ? \"(root)\" : path}: ${issue.message}`;\n}\n\n/** A JSON data block. Escaping `<` keeps a value from closing the `<script>`. */\nfunction publicEnvScript(values: Readonly<Record<string, unknown>>): string {\n\tconst json = JSON.stringify(values).replaceAll(\"<\", \"\\\\u003c\");\n\treturn `<script id=\"${PUBLIC_ENV_SCRIPT_ID}\" type=\"application/json\">${json}</script>`;\n}\n\n/** Inserts `html` before the first `</head>` of a streamed document. The rest streams as is. */\nfunction injectBeforeHeadEnd(\n\tbody: ReadableStream<Uint8Array>,\n\thtml: string,\n): ReadableStream<Uint8Array> {\n\t// Why decode every chunk: a chunk can end inside a multi-byte character.\n\tconst decoder = new TextDecoder();\n\tconst encoder = new TextEncoder();\n\tlet pending: string | undefined = \"\";\n\treturn body.pipeThrough(\n\t\tnew TransformStream<Uint8Array, Uint8Array>({\n\t\t\ttransform(chunk, controller) {\n\t\t\t\tconst text = decoder.decode(chunk, { stream: true });\n\t\t\t\tif (pending == null) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpending += text;\n\t\t\t\tconst index = pending.search(/<\\/head>/i);\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\tencoder.encode(`${pending.slice(0, index)}${html}${pending.slice(index)}`),\n\t\t\t\t\t);\n\t\t\t\t\tpending = undefined;\n\t\t\t\t} else if (pending.length > HEAD_SEARCH_LIMIT) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(pending));\n\t\t\t\t\tpending = undefined;\n\t\t\t\t}\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tconst rest = `${pending ?? \"\"}${decoder.decode()}`;\n\t\t\t\tif (rest !== \"\") {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(rest));\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t);\n}\n\n/**\n * Validates the environment once, at startup, against a schema. A missing or\n * bad value stops the server with a message that names it. The typed values\n * are on `.values`.\n *\n * The values whose names start with `PUBLIC_` go into each HTML document,\n * prerendered or rendered, as a JSON `<script id=\"app-server-public-env\">`.\n * So one image serves every environment, and a prerendered page never keeps\n * the values of the build. Put this plugin before the static stages, so it\n * sees the prerendered pages.\n *\n * @example\n * export const env = runtimeEnv(\n * \tz.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),\n * );\n * env.values.SESSION_KEY; // => string\n *\n * // In the browser:\n * const publicEnv = JSON.parse(document.getElementById(\"app-server-public-env\")?.textContent ?? \"{}\");\n */\nexport function runtimeEnv<Schema extends StandardSchemaV1>(\n\tschema: Schema,\n\t{ source = process.env, publicPrefix = \"PUBLIC_\" }: RuntimeEnvOptions = {},\n): RuntimeEnv<InferOutput<Schema>> {\n\tlet parsed:\n\t\t| {\n\t\t\t\tvalues: InferOutput<Schema>;\n\t\t\t\tpublicValues: Readonly<Record<string, unknown>>;\n\t\t\t\tscript: string | undefined;\n\t\t }\n\t\t| undefined;\n\n\tconst parse = () => {\n\t\tif (parsed != null) {\n\t\t\treturn parsed;\n\t\t}\n\t\tconst result = schema[\"~standard\"].validate({ ...source });\n\t\tif (result instanceof Promise) {\n\t\t\tthrow new TypeError(\"runtimeEnv needs a schema that validates synchronously.\");\n\t\t}\n\t\tif (result.issues != null) {\n\t\t\tthrow new Error(\n\t\t\t\t`The environment is not valid:\\n${result.issues.map(formatIssue).join(\"\\n\")}`,\n\t\t\t);\n\t\t}\n\t\tconst values: InferOutput<Schema> = result.value;\n\t\tconst publicValues =\n\t\t\ttypeof values === \"object\" && values != null\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(values).filter(([name]) => name.startsWith(publicPrefix)),\n\t\t\t\t\t)\n\t\t\t\t: {};\n\t\tparsed = {\n\t\t\tvalues,\n\t\t\tpublicValues,\n\t\t\tscript: Object.keys(publicValues).length > 0 ? publicEnvScript(publicValues) : undefined,\n\t\t};\n\t\treturn parsed;\n\t};\n\n\treturn {\n\t\tname: \"runtime-env\",\n\t\tget values() {\n\t\t\treturn parse().values;\n\t\t},\n\t\tget publicValues() {\n\t\t\treturn parse().publicValues;\n\t\t},\n\t\tsetup: () => {\n\t\t\tparse();\n\t\t},\n\t\tetagPart: () => parse().script,\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\tconst { script } = parse();\n\t\t\tconst response = context.res;\n\t\t\tif (\n\t\t\t\tscript == null ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: the script changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\t!(response.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false)\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.body != null) {\n\t\t\t\tcontext.res = new Response(injectBeforeHeadEnd(response.body, script), response);\n\t\t\t}\n\t\t\t// Why for HEAD too: it gets the headers that GET gets. The script changes the length, and a\n\t\t\t// rendered document's ETag does not cover the values, so a 304 could keep old ones.\n\t\t\tcontext.header(\"Content-Length\", undefined);\n\t\t\tcontext.header(\"ETag\", undefined);\n\t\t},\n\t};\n}\n"],"mappings":";;;AA6BA,SAAS,YAAY,EAAE,MAAM,OAAO,MAA+B;CAElE,IAAI,SAAS,KAAK,GAAG,SAAS,KAAK,MAAM,IAAI,GAC5C,MAAM,IAAI,UAAU,0DAA0D;CAQ/E,OAAO,GAAG;EALT,GAAI,SAAS,OAAO,CAAC,IAAI,CAAC,UAAU,OAAO;EAC3C,GAAI,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI;EAElC,GAAG,KAAK,MAAM,YAAY,CAAC,CAAC,KAAK,SAAS,SAAS,MAAM;CAE5C,CAAC,CAAC,KAAK,IAAI,EAAE;AAC5B;;;;;;;;;;;;;;;;AAiBA,SAAgB,YACf,EAAE,QAAQ,cAAc,MAAQ,WAChC,SACW;CACX,MAAM,UAAU,IAAI,YAAY;CAChC,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,aAAa,YAAY,IAAI;EAClC,QAAQ;EACR,eAAe;EACf,GAAI,UAAU,OAAO,CAAC,IAAI,CAAC,MAAM;CAClC,CAAC;CACD,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,OAAO,IAAI,eAA2B;EAC3C,MAAM,YAAY;GACjB,MAAM,cAAc;IACnB,IAAI,QACH;IAED,SAAS;IACT,cAAc,SAAS;IAEvB,WAAW,oBAAoB,SAAS,KAAK;IAC7C,WAAW,MAAM;GAClB;GACA,MAAM,SAAS,SAAiB;IAC/B,IAAI,CAAC,QACJ,WAAW,QAAQ,QAAQ,OAAO,IAAI,CAAC;GAEzC;GACA,YAAY,kBAAkB;IAC7B,MAAM,YAAY;GACnB,GAAG,WAAW;GACd,WAAW,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;GAC1D,IAAI,WAAW,SAAS;IACvB,MAAM;IACN;GACD;GACA,QAAQ,QAAQ,CAAC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AC,CAAC,QAAQ,CAAC,UAAU,KAAK,WAAW,YAAY,CAAC,CACxE,IACC,CAAC;EACL,SAAS;GACR;GACA;GACA,QAAQ,OAAO,KAAK,YAAY,CAAC,CAAC,SAAS,IAAI,gBAAgB,YAAY,IAAI;EAChF;EACA,OAAO;CACR;CAEA,OAAO;EACN,MAAM;EACN,IAAI,SAAS;GACZ,OAAO,MAAM,CAAC,CAAC;EAChB;EACA,IAAI,eAAe;GAClB,OAAO,MAAM,CAAC,CAAC;EAChB;EACA,aAAa;GACZ,MAAM;EACP;EACA,gBAAgB,MAAM,CAAC,CAAC;EACxB,YAAY,OAAO,SAAS,SAAS;GACpC,MAAM,KAAK;GACX,MAAM,EAAE,WAAW,MAAM;GACzB,MAAM,WAAW,QAAQ;GACzB,IACC,UAAU,QACV,SAAS,QAAQ,IAAI,kBAAkB,KAEvC,SAAS,QAAQ,IAAI,eAAe,KACpC,EAAE,SAAS,QAAQ,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,QAEnE;GAED,IAAI,SAAS,QAAQ,MACpB,QAAQ,MAAM,IAAI,SAAS,oBAAoB,SAAS,MAAM,MAAM,GAAG,QAAQ;GAIhF,QAAQ,OAAO,kBAAkB,MAAS;GAC1C,QAAQ,OAAO,QAAQ,MAAS;EACjC;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/event-stream.ts","../src/plugins/build-id.ts","../src/plugins/runtime-env.ts"],"sourcesContent":["import { shutdownSignal } from \"./shutdown.js\";\n\n/** One server-sent event. */\nexport type ServerSentEvent = {\n\tdata: string;\n\tevent?: string;\n\tid?: string;\n};\n\n/** What {@link eventStream} passes to its producer. */\nexport type EventStreamSink = {\n\tsend: (event: ServerSentEvent) => void;\n\t/** Aborts when the client disconnects or the server shuts down. Stop the work on it. */\n\tsignal: AbortSignal;\n};\n\n/** Options for {@link eventStream}. */\nexport type EventStreamOptions = {\n\t/** The request's signal, so a client disconnect stops the stream. */\n\tsignal?: AbortSignal;\n\t/**\n\t * How often a `: ping` comment goes out, so that a proxy keeps a quiet stream open.\n\t * @default 15000\n\t */\n\theartbeatMs?: number;\n\t/** Extra response headers. */\n\theaders?: HeadersInit;\n};\n\nfunction formatEvent({ data, event, id }: ServerSentEvent): string {\n\t// Why: a line break in `event` or `id` would start another field or event.\n\tif (/[\\r\\n]/.test(`${event ?? \"\"}${id ?? \"\"}`)) {\n\t\tthrow new TypeError(\"An event's `event` and `id` cannot contain a line break.\");\n\t}\n\tconst lines = [\n\t\t...(event == null ? [] : [`event: ${event}`]),\n\t\t...(id == null ? [] : [`id: ${id}`]),\n\t\t// Why `\\r` too: a client reads a lone carriage return as a line end.\n\t\t...data.split(/\\r\\n|\\r|\\n/).map((line) => `data: ${line}`),\n\t];\n\treturn `${lines.join(\"\\n\")}\\n\\n`;\n}\n\n/**\n * A `text/event-stream` response that stays correct for its whole life: it\n * sends a heartbeat comment, it stops when the client disconnects, and it\n * closes at server shutdown so the drain does not wait for the deadline. The\n * stream closes when `produce` resolves.\n *\n * @example\n * export async function loader({ request }: Route.LoaderArgs) {\n * \treturn eventStream({ signal: request.signal }, async ({ send, signal }) => {\n * \t\tfor await (const update of watchUpdates({ signal })) {\n * \t\t\tsend({ event: \"update\", data: JSON.stringify(update) });\n * \t\t}\n * \t});\n * }\n */\nexport function eventStream(\n\t{ signal, heartbeatMs = 15_000, headers }: EventStreamOptions,\n\tproduce: (sink: EventStreamSink) => void | Promise<void>,\n): Response {\n\tconst encoder = new TextEncoder();\n\tconst stopped = new AbortController();\n\tconst stopSignal = AbortSignal.any([\n\t\tstopped.signal,\n\t\tshutdownSignal(),\n\t\t...(signal == null ? [] : [signal]),\n\t]);\n\tlet heartbeat: ReturnType<typeof setInterval> | undefined;\n\tlet closed = false;\n\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst close = () => {\n\t\t\t\tif (closed) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclosed = true;\n\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t// Why: the listener lives on `shutdownSignal()`, which lasts the life of the process.\n\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\tcontroller.close();\n\t\t\t};\n\t\t\tconst write = (text: string) => {\n\t\t\t\tif (!closed) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t}\n\t\t\t};\n\t\t\theartbeat = setInterval(() => {\n\t\t\t\twrite(\": ping\\n\\n\");\n\t\t\t}, heartbeatMs);\n\t\t\tstopSignal.addEventListener(\"abort\", close, { once: true });\n\t\t\tif (stopSignal.aborted) {\n\t\t\t\tclose();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() => produce({ send: (event) => write(formatEvent(event)), signal: stopSignal }))\n\t\t\t\t.then(close, (error: unknown) => {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true;\n\t\t\tclearInterval(heartbeat);\n\t\t\tstopped.abort();\n\t\t},\n\t});\n\n\tconst responseHeaders = new Headers(headers);\n\tresponseHeaders.set(\"Content-Type\", \"text/event-stream; charset=utf-8\");\n\tresponseHeaders.set(\"Cache-Control\", \"no-cache\");\n\treturn new Response(body, { headers: responseHeaders });\n}\n","import type { Plugin } from \"../types.js\";\n\n/** Options for {@link buildId}. */\nexport type BuildIdOptions = {\n\t/** @default \"X-Build-Id\" */\n\theader?: string;\n\t/** The deployed build, such as the image tag. Read it from the runtime env, not the build. */\n\tvalue: string;\n};\n\n/**\n * Sets a build ID header on documents and React Router `.data` responses, so\n * a client can see that a deploy happened under it.\n *\n * @example\n * buildId({ value: env.values.PUBLIC_APP_VERSION });\n */\nexport function buildId({ header = \"X-Build-Id\", value }: BuildIdOptions): Plugin {\n\treturn {\n\t\tname: \"build-id\",\n\t\t// Why: a 304 has no `Content-Type`, so a document that did not change on disk must still\n\t\t// answer 200 when the build ID changes.\n\t\tetagPart: () => value,\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\tconst isDocument = context.res.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false;\n\t\t\tif (isDocument || context.req.path.endsWith(\".data\")) {\n\t\t\t\tcontext.header(header, value);\n\t\t\t}\n\t\t},\n\t};\n}\n","import type { Plugin } from \"../types.js\";\n\n// The Standard Schema interface (https://standardschema.dev), copied as its spec asks, so that\n// zod, valibot, and arktype schemas all work with no dependency on any of them.\ntype StandardIssue = {\n\treadonly message: string;\n\treadonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined;\n};\ntype StandardResult<Output> =\n\t| { readonly value: Output; readonly issues?: undefined }\n\t| { readonly issues: ReadonlyArray<StandardIssue> };\n\n/** A schema that follows the Standard Schema interface, such as a zod object. */\nexport type StandardSchemaV1<Input = unknown, Output = Input> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: string;\n\t\treadonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;\n\t\treadonly types?: { readonly input: Input; readonly output: Output } | undefined;\n\t};\n};\n\n/** The parsed type of a Standard Schema. */\nexport type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n\tSchema[\"~standard\"][\"types\"]\n>[\"output\"];\n\n/** The `id` of the JSON `<script>` that carries the public values into each HTML document. */\nexport const PUBLIC_ENV_SCRIPT_ID = \"app-server-public-env\";\n\n/** Stops the search for `</head>` after this many characters, so a page with none still streams. */\nconst HEAD_SEARCH_LIMIT = 1_048_576;\n\n/** Options for {@link runtimeEnv}. */\nexport type RuntimeEnvOptions = {\n\t/** @default process.env */\n\tsource?: Readonly<Record<string, string | undefined>>;\n\t/**\n\t * Values whose names start with this prefix reach the browser.\n\t * @default \"PUBLIC_\"\n\t */\n\tpublicPrefix?: string;\n};\n\n/** The plugin that {@link runtimeEnv} returns, with the parsed values. */\nexport type RuntimeEnv<Values> = Plugin & {\n\t/** The parsed values. The first read parses, and a bad value throws. */\n\treadonly values: Values;\n\t/** The parsed values whose names start with the public prefix. */\n\treadonly publicValues: Readonly<Record<string, unknown>>;\n};\n\nfunction formatIssue(issue: StandardIssue): string {\n\tconst path = (issue.path ?? [])\n\t\t.map((segment) => String(typeof segment === \"object\" ? segment.key : segment))\n\t\t.join(\".\");\n\treturn ` ${path === \"\" ? \"(root)\" : path}: ${issue.message}`;\n}\n\n/** A JSON data block. Escaping `<` keeps a value from closing the `<script>`. */\nfunction publicEnvScript(values: Readonly<Record<string, unknown>>): string {\n\tconst json = JSON.stringify(values).replaceAll(\"<\", \"\\\\u003c\");\n\treturn `<script id=\"${PUBLIC_ENV_SCRIPT_ID}\" type=\"application/json\">${json}</script>`;\n}\n\n/** Inserts `html` before the first `</head>` of a streamed document. The rest streams as is. */\nfunction injectBeforeHeadEnd(\n\tbody: ReadableStream<Uint8Array>,\n\thtml: string,\n): ReadableStream<Uint8Array> {\n\t// Why decode every chunk: a chunk can end inside a multi-byte character.\n\tconst decoder = new TextDecoder();\n\tconst encoder = new TextEncoder();\n\tlet pending: string | undefined = \"\";\n\treturn body.pipeThrough(\n\t\tnew TransformStream<Uint8Array, Uint8Array>({\n\t\t\ttransform(chunk, controller) {\n\t\t\t\tconst text = decoder.decode(chunk, { stream: true });\n\t\t\t\tif (pending == null) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpending += text;\n\t\t\t\tconst index = pending.search(/<\\/head>/i);\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\tencoder.encode(`${pending.slice(0, index)}${html}${pending.slice(index)}`),\n\t\t\t\t\t);\n\t\t\t\t\tpending = undefined;\n\t\t\t\t} else if (pending.length > HEAD_SEARCH_LIMIT) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(pending));\n\t\t\t\t\tpending = undefined;\n\t\t\t\t}\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tconst rest = `${pending ?? \"\"}${decoder.decode()}`;\n\t\t\t\tif (rest !== \"\") {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(rest));\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t);\n}\n\n/**\n * Validates the environment once, at startup, against a schema. A missing or\n * bad value stops the server with a message that names it. The typed values\n * are on `.values`.\n *\n * The values whose names start with `PUBLIC_` go into each HTML document,\n * prerendered or rendered, as a JSON `<script id=\"app-server-public-env\">`.\n * So one image serves every environment, and a prerendered page never keeps\n * the values of the build. Put this plugin before the static stages, so it\n * sees the prerendered pages.\n *\n * @example\n * export const env = runtimeEnv(\n * \tz.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),\n * );\n * env.values.SESSION_KEY; // => string\n *\n * // In the browser:\n * const publicEnv = JSON.parse(document.getElementById(\"app-server-public-env\")?.textContent ?? \"{}\");\n */\nexport function runtimeEnv<Schema extends StandardSchemaV1>(\n\tschema: Schema,\n\t{ source = process.env, publicPrefix = \"PUBLIC_\" }: RuntimeEnvOptions = {},\n): RuntimeEnv<InferOutput<Schema>> {\n\tlet parsed:\n\t\t| {\n\t\t\t\tvalues: InferOutput<Schema>;\n\t\t\t\tpublicValues: Readonly<Record<string, unknown>>;\n\t\t\t\tscript: string | undefined;\n\t\t }\n\t\t| undefined;\n\n\tconst parse = () => {\n\t\tif (parsed != null) {\n\t\t\treturn parsed;\n\t\t}\n\t\tconst result = schema[\"~standard\"].validate({ ...source });\n\t\tif (result instanceof Promise) {\n\t\t\tthrow new TypeError(\"runtimeEnv needs a schema that validates synchronously.\");\n\t\t}\n\t\tif (result.issues != null) {\n\t\t\tthrow new Error(\n\t\t\t\t`The environment is not valid:\\n${result.issues.map(formatIssue).join(\"\\n\")}`,\n\t\t\t);\n\t\t}\n\t\tconst values: InferOutput<Schema> = result.value;\n\t\tconst publicValues =\n\t\t\ttypeof values === \"object\" && values != null\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(values).filter(([name]) => name.startsWith(publicPrefix)),\n\t\t\t\t\t)\n\t\t\t\t: {};\n\t\tparsed = {\n\t\t\tvalues,\n\t\t\tpublicValues,\n\t\t\tscript: Object.keys(publicValues).length > 0 ? publicEnvScript(publicValues) : undefined,\n\t\t};\n\t\treturn parsed;\n\t};\n\n\treturn {\n\t\tname: \"runtime-env\",\n\t\tget values() {\n\t\t\treturn parse().values;\n\t\t},\n\t\tget publicValues() {\n\t\t\treturn parse().publicValues;\n\t\t},\n\t\tsetup: () => {\n\t\t\tparse();\n\t\t},\n\t\tetagPart: () => parse().script,\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\tconst { script } = parse();\n\t\t\tconst response = context.res;\n\t\t\tif (\n\t\t\t\tscript == null ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: the script changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\t!(response.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false)\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.body != null) {\n\t\t\t\tcontext.res = new Response(injectBeforeHeadEnd(response.body, script), response);\n\t\t\t}\n\t\t\t// Why for HEAD too: it gets the headers that GET gets. The script changes the length, and a\n\t\t\t// rendered document's ETag does not cover the values, so a 304 could keep old ones.\n\t\t\tcontext.header(\"Content-Length\", undefined);\n\t\t\tcontext.header(\"ETag\", undefined);\n\t\t},\n\t};\n}\n"],"mappings":";;;;AA6BA,SAAS,YAAY,EAAE,MAAM,OAAO,MAA+B;CAElE,IAAI,SAAS,KAAK,GAAG,SAAS,KAAK,MAAM,IAAI,GAC5C,MAAM,IAAI,UAAU,0DAA0D;CAQ/E,OAAO,GAAG;EALT,GAAI,SAAS,OAAO,CAAC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B;EACA,aAAa;GACZ,MAAM;EACP;EACA,gBAAgB,MAAM,CAAC,CAAC;EACxB,YAAY,OAAO,SAAS,SAAS;GACpC,MAAM,KAAK;GACX,MAAM,EAAE,WAAW,MAAM;GACzB,MAAM,WAAW,QAAQ;GACzB,IACC,UAAU,QACV,SAAS,QAAQ,IAAI,kBAAkB,KAEvC,SAAS,QAAQ,IAAI,eAAe,KACpC,EAAE,SAAS,QAAQ,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,QAEnE;GAED,IAAI,SAAS,QAAQ,MACpB,QAAQ,MAAM,IAAI,SAAS,oBAAoB,SAAS,MAAM,MAAM,GAAG,QAAQ;GAIhF,QAAQ,OAAO,kBAAkB,MAAS;GAC1C,QAAQ,OAAO,QAAQ,MAAS;EACjC;CACD;AACD"}
|
package/dist/react-router.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { f as jsonSink, p as sinkLogger, r as createServer, t as createEntry } from "./entry-ChjmFwX5.js";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
3
|
import { RouterContextProvider, createContext, createRequestHandler } from "react-router";
|
|
4
4
|
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import { n as loadEntry } from "./entry-
|
|
1
|
+
import { n as loadEntry } from "./entry-ChjmFwX5.js";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
3
|
import { pathToFileURL } from "node:url";
|
|
4
4
|
|
|
5
|
-
// src/
|
|
5
|
+
// src/serve.ts
|
|
6
6
|
/**
|
|
7
7
|
* Loads a production server build and starts it. The copy of this package in
|
|
8
8
|
* the build runs the server when the build has one: see `loadEntry`.
|
|
9
9
|
*/
|
|
10
|
-
async function
|
|
10
|
+
async function serve({ buildPath }) {
|
|
11
11
|
const build = await import(pathToFileURL(resolve(buildPath)).href);
|
|
12
12
|
await (await loadEntry(build)).start();
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
export {
|
|
16
|
-
//# sourceMappingURL=
|
|
15
|
+
export { serve };
|
|
16
|
+
//# sourceMappingURL=serve-ByeedcRB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"
|
|
1
|
+
{"version":3,"file":"serve-ByeedcRB.js","names":[],"sources":["../src/serve.ts"],"sourcesContent":["import { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./entry.js\";\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 }): Promise<void> {\n\tconst build: unknown = await import(pathToFileURL(resolve(buildPath)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;AAQA,eAAsB,MAAM,EAAE,aAAmD;CAChF,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,SAAS,CAAC,CAAC,CAAC;CACtE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
|
|
@@ -1,13 +1,83 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as parsePort } from "./tcp-Dau_IONd.js";
|
|
2
|
+
import { d as errorAttributes, f as jsonSink, n as loadEntry } from "./entry-ChjmFwX5.js";
|
|
2
3
|
import { t as SERVER_ENTRY_ID } from "./vite-CrNqpoeK.js";
|
|
3
4
|
import { t as listenerUrl } from "./listen-options-DHWmSWGi.js";
|
|
4
5
|
import { t as cancelIfClosed } from "./node-79my3Uix.js";
|
|
5
6
|
import { IncomingMessage, ServerResponse, createServer } from "node:http";
|
|
6
7
|
import { getRequestListener } from "@hono/node-server";
|
|
8
|
+
import { createServer as createServer$1 } from "node:net";
|
|
9
|
+
|
|
10
|
+
// src/start-port.ts
|
|
11
|
+
const MAX_PORT = 65535;
|
|
12
|
+
/**
|
|
13
|
+
* Starts `server` on `port`. When the port is in use, it tries each next port
|
|
14
|
+
* up to 65535, like Vite and `react-router-serve` do in development.
|
|
15
|
+
*
|
|
16
|
+
* @returns the port that the server listens on
|
|
17
|
+
*/
|
|
18
|
+
async function listenFromPort(server, { port, hostname, strictPort, onPortInUse, onWildcardInUse }) {
|
|
19
|
+
if (port === 0) {
|
|
20
|
+
await bind(server, port, hostname);
|
|
21
|
+
return boundPort(server, port);
|
|
22
|
+
}
|
|
23
|
+
if (strictPort) {
|
|
24
|
+
const freeOnWildcard = hostname == null || await isFreeOnWildcard(port);
|
|
25
|
+
await bind(server, port, hostname);
|
|
26
|
+
if (!freeOnWildcard) onWildcardInUse?.(port);
|
|
27
|
+
return port;
|
|
28
|
+
}
|
|
29
|
+
for (let candidate = port; candidate <= MAX_PORT; candidate++) {
|
|
30
|
+
if (hostname == null || await isFreeOnWildcard(candidate)) try {
|
|
31
|
+
await bind(server, candidate, hostname);
|
|
32
|
+
return candidate;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (!isAddressInUse(error)) throw error;
|
|
35
|
+
}
|
|
36
|
+
onPortInUse?.(candidate);
|
|
37
|
+
}
|
|
38
|
+
throw new Error(`No open port from ${port} to ${MAX_PORT}.`);
|
|
39
|
+
}
|
|
40
|
+
function bind(server, port, hostname) {
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
const onError = (error) => {
|
|
43
|
+
server.off("listening", onListening);
|
|
44
|
+
reject(error);
|
|
45
|
+
};
|
|
46
|
+
const onListening = () => {
|
|
47
|
+
server.off("error", onError);
|
|
48
|
+
resolve();
|
|
49
|
+
};
|
|
50
|
+
server.once("error", onError);
|
|
51
|
+
server.once("listening", onListening);
|
|
52
|
+
server.listen(port, hostname);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
async function isFreeOnWildcard(port) {
|
|
56
|
+
const probe = createServer$1();
|
|
57
|
+
try {
|
|
58
|
+
await bind(probe, port, void 0);
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (isAddressInUse(error)) return false;
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
await new Promise((resolve) => {
|
|
64
|
+
probe.close(() => {
|
|
65
|
+
resolve();
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
function boundPort(server, fallback) {
|
|
71
|
+
const address = server.address();
|
|
72
|
+
return typeof address === "object" && address != null ? address.port : fallback;
|
|
73
|
+
}
|
|
74
|
+
function isAddressInUse(error) {
|
|
75
|
+
return error instanceof Error && "code" in error && error.code === "EADDRINUSE";
|
|
76
|
+
}
|
|
7
77
|
|
|
8
78
|
// src/served-apps.ts
|
|
9
79
|
/**
|
|
10
|
-
* Tracks the apps that `app-server
|
|
80
|
+
* Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a
|
|
11
81
|
* new app, and the old app's plugins still hold what their `setup` opened.
|
|
12
82
|
* When the last request that the old app took returns, its `onShutdown` hooks
|
|
13
83
|
* run, and the tracker lets go of it. A route edit makes a new entry with the
|
|
@@ -55,17 +125,18 @@ function servedApps() {
|
|
|
55
125
|
};
|
|
56
126
|
}
|
|
57
127
|
|
|
58
|
-
// src/
|
|
128
|
+
// src/start.ts
|
|
59
129
|
/**
|
|
60
130
|
* Runs the app in development: the same pipeline as production, with Vite in
|
|
61
131
|
* middleware mode inside it. Each request loads the server entry through
|
|
62
132
|
* Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies
|
|
63
133
|
* at once. HMR shares the port.
|
|
64
134
|
*
|
|
65
|
-
* The port is `PORT`, else Vite's `server.port`.
|
|
66
|
-
* Vite's `server.
|
|
135
|
+
* The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the
|
|
136
|
+
* server tries each next port, unless Vite's `server.strictPort` is true. The
|
|
137
|
+
* host is `HOST`, else Vite's `server.host`.
|
|
67
138
|
*/
|
|
68
|
-
async function
|
|
139
|
+
async function start() {
|
|
69
140
|
const vite = await import("vite");
|
|
70
141
|
const httpServer = createServer();
|
|
71
142
|
const viteServer = await vite.createServer({
|
|
@@ -109,14 +180,21 @@ async function dev() {
|
|
|
109
180
|
const port = process.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);
|
|
110
181
|
const configuredHost = viteServer.config.server.host;
|
|
111
182
|
const hostname = process.env.HOST || (configuredHost === true ? void 0 : configuredHost || "localhost");
|
|
112
|
-
await
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
183
|
+
const boundPort = await listenFromPort(httpServer, {
|
|
184
|
+
port,
|
|
185
|
+
hostname,
|
|
186
|
+
strictPort: viteServer.config.server.strictPort,
|
|
187
|
+
onPortInUse: (inUse) => {
|
|
188
|
+
sink.log("info", "port in use, trying the next port", { "server.port": inUse });
|
|
189
|
+
},
|
|
190
|
+
onWildcardInUse: (inUse) => {
|
|
191
|
+
sink.log("warn", "port in use on a wildcard address", {
|
|
192
|
+
"server.port": inUse,
|
|
193
|
+
"server.address": hostname
|
|
194
|
+
});
|
|
195
|
+
}
|
|
118
196
|
});
|
|
119
|
-
sink.log("info", "listening", { "app_server.urls": [listenerUrl(hostname,
|
|
197
|
+
sink.log("info", "listening", { "app_server.urls": [listenerUrl(hostname, boundPort)] });
|
|
120
198
|
for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
|
|
121
199
|
apps.stopAll();
|
|
122
200
|
httpServer.closeAllConnections();
|
|
@@ -128,5 +206,5 @@ async function dev() {
|
|
|
128
206
|
});
|
|
129
207
|
}
|
|
130
208
|
|
|
131
|
-
export {
|
|
132
|
-
//# sourceMappingURL=
|
|
209
|
+
export { start };
|
|
210
|
+
//# sourceMappingURL=start-BVMb8Pyt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"start-BVMb8Pyt.js","names":["createServer","createHttpServer"],"sources":["../src/start-port.ts","../src/served-apps.ts","../src/start.ts"],"sourcesContent":["import { createServer, type Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nfunction bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst onError = (error: Error) => {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t};\n\t\tconst onListening = () => {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t};\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import type { AppServerEntry } from \"./entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps() {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\tconst retire = (app: ServedApp) => {\n\t\tserved.delete(app);\n\t\tvoid app.entry.stopPlugins();\n\t};\n\treturn {\n\t\t/** Runs `handle` for a request that `entry` serves. */\n\t\tserve: async <Result>(\n\t\t\tentry: AppServerEntry,\n\t\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t\t): Promise<Result> => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tretire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tretire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t/** At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each app still held. */\n\t\tstopAll: () => {\n\t\t\tfor (const app of served) {\n\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\tretire(app);\n\t\t\t}\n\t\t},\n\t};\n}\n","import { createServer as createHttpServer, IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { loadEntry } from \"./entry.js\";\nimport { listenFromPort } from \"./start-port.js\";\nimport { errorAttributes, jsonSink } from \"./log.js\";\nimport { listenerUrl } from \"./runtimes/listen-options.js\";\nimport { cancelIfClosed } from \"./runtimes/node.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { parsePort } from \"./tcp.js\";\nimport { SERVER_ENTRY_ID } from \"./vite.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst ssr = viteServer.environments.ssr;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tconst entryId = viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")\n\t\t? SERVER_ENTRY_ID\n\t\t: \"virtual:react-router/server-build\";\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = getRequestListener(async (request, { incoming, outgoing }) => {\n\t\ttry {\n\t\t\tconst response = await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(entryId)),\n\t\t\t\t(entry) =>\n\t\t\t\t\tentry.fetchDev(\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tremoteAddress: incoming.socket.remoteAddress,\n\t\t\t\t\t\t\t// Why the check: the listener is plain `node:http`, so these are always HTTP/1 objects.\n\t\t\t\t\t\t\t...(incoming instanceof IncomingMessage && outgoing instanceof ServerResponse\n\t\t\t\t\t\t\t\t? { incoming, outgoing }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tviteServer.middlewares,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\treturn await cancelIfClosed(response, outgoing);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst configuredHost = viteServer.config.server.host;\n\tconst hostname =\n\t\tprocess.env.HOST || (configuredHost === true ? undefined : configuredHost || \"localhost\");\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tapps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\thttpServer.close();\n\t\t\tviteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;AAEA,MAAM,WAAW;;;;;;;AAyBjB,eAAsB,eACrB,QACA,EAAE,MAAM,UAAU,YAAY,aAAa,mBACzB;CAClB,IAAI,SAAS,GAAG;EACf,MAAM,KAAK,QAAQ,MAAM,QAAQ;EACjC,OAAO,UAAU,QAAQ,IAAI;CAC9B;CACA,IAAI,YAAY;EAGf,MAAM,iBAAiB,YAAY,QAAS,MAAM,iBAAiB,IAAI;EACvE,MAAM,KAAK,QAAQ,MAAM,QAAQ;EACjC,IAAI,CAAC,gBACJ,kBAAkB,IAAI;EAEvB,OAAO;CACR;CACA,KAAK,IAAI,YAAY,MAAM,aAAa,UAAU,aAAa;EAG9D,IAAI,YAAY,QAAS,MAAM,iBAAiB,SAAS,GACxD,IAAI;GACH,MAAM,KAAK,QAAQ,WAAW,QAAQ;GACtC,OAAO;EACR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;CACF,CAAC;AAEH"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// src/tcp.ts
|
|
2
|
+
/** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */
|
|
3
|
+
const DEFAULT_IDLE_TIMEOUT_MS = 95e3;
|
|
4
|
+
/**
|
|
5
|
+
* Reads a port number. A value that is not an integer from 0 to 65535 throws,
|
|
6
|
+
* so a bad `PORT` stops startup.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* parsePort("8080"); // => 8080
|
|
10
|
+
*/
|
|
11
|
+
function parsePort(value) {
|
|
12
|
+
const port = Number(value);
|
|
13
|
+
if (value.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`PORT must be an integer from 0 to 65535, not "${value}".`);
|
|
14
|
+
return port;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The default listener: a TCP port, served by the runtime's own HTTP server
|
|
18
|
+
* (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
|
|
19
|
+
* `PORT` and `HOST` when it starts.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* createServer({ listeners: [tcp({ port: 8080 })] });
|
|
23
|
+
*/
|
|
24
|
+
function tcp({ port, host, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
|
|
25
|
+
return {
|
|
26
|
+
name: "tcp",
|
|
27
|
+
start: async (fetch) => {
|
|
28
|
+
const options = {
|
|
29
|
+
port: port ?? (process.env.PORT == null ? 3e3 : parsePort(process.env.PORT)),
|
|
30
|
+
hostname: host ?? (process.env.HOST || void 0),
|
|
31
|
+
idleTimeoutMs
|
|
32
|
+
};
|
|
33
|
+
if ("Bun" in globalThis) return (await import("./bun-DCGnDEPn.js")).listen(fetch, options);
|
|
34
|
+
if ("Deno" in globalThis) return (await import("./deno-BnMfk2n1.js")).listen(fetch, options);
|
|
35
|
+
return (await import("./node-2wWBMFeO.js")).listen(fetch, options);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export { tcp as n, parsePort as t };
|
|
41
|
+
//# sourceMappingURL=tcp-Dau_IONd.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tcp-Dau_IONd.js","names":[],"sources":["../src/tcp.ts"],"sourcesContent":["import type { Listener } from \"./types.js\";\n\n/** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */\nconst DEFAULT_IDLE_TIMEOUT_MS = 95_000;\n\n/** Options for {@link tcp}. */\nexport type TcpOptions = {\n\t/** @default the `PORT` environment variable, else 3000 */\n\tport?: number;\n\t/** @default the `HOST` environment variable, else every interface */\n\thost?: string;\n\t/** @default 95000 */\n\tidleTimeoutMs?: number;\n};\n\n/**\n * Reads a port number. A value that is not an integer from 0 to 65535 throws,\n * so a bad `PORT` stops startup.\n *\n * @example\n * parsePort(\"8080\"); // => 8080\n */\nexport function parsePort(value: string): number {\n\tconst port = Number(value);\n\tif (value.trim() === \"\" || !Number.isInteger(port) || port < 0 || port > 65_535) {\n\t\tthrow new Error(`PORT must be an integer from 0 to 65535, not \"${value}\".`);\n\t}\n\treturn port;\n}\n\n/**\n * The default listener: a TCP port, served by the runtime's own HTTP server\n * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads\n * `PORT` and `HOST` when it starts.\n *\n * @example\n * createServer({ listeners: [tcp({ port: 8080 })] });\n */\nexport function tcp({\n\tport,\n\thost,\n\tidleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,\n}: TcpOptions = {}): Listener {\n\treturn {\n\t\tname: \"tcp\",\n\t\tstart: async (fetch) => {\n\t\t\tconst options = {\n\t\t\t\tport: port ?? (process.env.PORT == null ? 3000 : parsePort(process.env.PORT)),\n\t\t\t\thostname: host ?? (process.env.HOST || undefined),\n\t\t\t\tidleTimeoutMs,\n\t\t\t};\n\t\t\tif (\"Bun\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/bun.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\tif (\"Deno\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/deno.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\treturn (await import(\"./runtimes/node.js\")).listen(fetch, options);\n\t\t},\n\t};\n}\n"],"mappings":";;AAGA,MAAM,0BAA0B;;;;;;;;AAmBhC,SAAgB,UAAU,OAAuB;CAChD,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,MAAM,KAAK,MAAM,MAAM,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OACxE,MAAM,IAAI,MAAM,iDAAiD,MAAM,GAAG;CAE3E,OAAO;AACR;;;;;;;;;AAUA,SAAgB,IAAI,EACnB,MACA,MACA,gBAAgB,4BACD,CAAC,GAAa;CAC7B,OAAO;EACN,MAAM;EACN,OAAO,OAAO,UAAU;GACvB,MAAM,UAAU;IACf,MAAM,SAAS,QAAQ,IAAI,QAAQ,OAAO,MAAO,UAAU,QAAQ,IAAI,IAAI;IAC3E,UAAU,SAAS,QAAQ,IAAI,QAAQ;IACvC;GACD;GACA,IAAI,SAAS,YACZ,QAAQ,MAAM,OAAO,qBAAoB,CAAE,OAAO,OAAO,OAAO;GAEjE,IAAI,UAAU,YACb,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;GAElE,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;EAClE;CACD;AACD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ngrok/app-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "A composable Hono app server for React Router: prerendered pages, streamed compression, structured logs, and clean shutdown on Node, Bun, and Deno.",
|
|
5
5
|
"homepage": "https://github.com/ngrok/app-server#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -35,19 +35,6 @@
|
|
|
35
35
|
},
|
|
36
36
|
"./package.json": "./package.json"
|
|
37
37
|
},
|
|
38
|
-
"scripts": {
|
|
39
|
-
"build": "tsdown",
|
|
40
|
-
"changeset": "changeset",
|
|
41
|
-
"fmt": "oxfmt --write .",
|
|
42
|
-
"fmt:check": "oxfmt --check .",
|
|
43
|
-
"lint": "oxlint --type-aware --deny-warnings",
|
|
44
|
-
"lint:fix": "oxlint --type-aware --fix",
|
|
45
|
-
"prepublishOnly": "pnpm run build",
|
|
46
|
-
"test": "vitest run",
|
|
47
|
-
"test:runtimes": "node ./test/runtimes.ts",
|
|
48
|
-
"test:watch": "vitest watch",
|
|
49
|
-
"typecheck": "tsc --noEmit"
|
|
50
|
-
},
|
|
51
38
|
"dependencies": {
|
|
52
39
|
"@hono/node-server": "2.1.5",
|
|
53
40
|
"hono": "4.13.14"
|
|
@@ -81,5 +68,16 @@
|
|
|
81
68
|
"engines": {
|
|
82
69
|
"node": "^24.0.0"
|
|
83
70
|
},
|
|
84
|
-
"
|
|
85
|
-
|
|
71
|
+
"scripts": {
|
|
72
|
+
"build": "tsdown",
|
|
73
|
+
"changeset": "changeset",
|
|
74
|
+
"fmt": "oxfmt --write .",
|
|
75
|
+
"fmt:check": "oxfmt --check .",
|
|
76
|
+
"lint": "oxlint --type-aware --deny-warnings",
|
|
77
|
+
"lint:fix": "oxlint --type-aware --fix",
|
|
78
|
+
"test": "vitest run",
|
|
79
|
+
"test:runtimes": "node ./test/runtimes.ts",
|
|
80
|
+
"test:watch": "vitest watch",
|
|
81
|
+
"typecheck": "tsc --noEmit"
|
|
82
|
+
}
|
|
83
|
+
}
|
package/dist/dev-DCytOhpM.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dev-DCytOhpM.js","names":["createHttpServer"],"sources":["../src/served-apps.ts","../src/dev.ts"],"sourcesContent":["import type { AppServerEntry } from \"./entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/**\n * Tracks the apps that `app-server dev` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps() {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\tconst retire = (app: ServedApp) => {\n\t\tserved.delete(app);\n\t\tvoid app.entry.stopPlugins();\n\t};\n\treturn {\n\t\t/** Runs `handle` for a request that `entry` serves. */\n\t\tserve: async <Result>(\n\t\t\tentry: AppServerEntry,\n\t\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t\t): Promise<Result> => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tretire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tretire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t/** At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each app still held. */\n\t\tstopAll: () => {\n\t\t\tfor (const app of served) {\n\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\tretire(app);\n\t\t\t}\n\t\t},\n\t};\n}\n","import { createServer as createHttpServer, IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { loadEntry } from \"./entry.js\";\nimport { errorAttributes, jsonSink } from \"./log.js\";\nimport { listenerUrl } from \"./runtimes/listen-options.js\";\nimport { cancelIfClosed } from \"./runtimes/node.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { parsePort } from \"./tcp.js\";\nimport { SERVER_ENTRY_ID } from \"./vite.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port.\n *\n * The port is `PORT`, else Vite's `server.port`. The host is `HOST`, else\n * Vite's `server.host`.\n */\nexport async function dev(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst ssr = viteServer.environments.ssr;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tconst entryId = viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")\n\t\t? SERVER_ENTRY_ID\n\t\t: \"virtual:react-router/server-build\";\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = getRequestListener(async (request, { incoming, outgoing }) => {\n\t\ttry {\n\t\t\tconst response = await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(entryId)),\n\t\t\t\t(entry) =>\n\t\t\t\t\tentry.fetchDev(\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tremoteAddress: incoming.socket.remoteAddress,\n\t\t\t\t\t\t\t// Why the check: the listener is plain `node:http`, so these are always HTTP/1 objects.\n\t\t\t\t\t\t\t...(incoming instanceof IncomingMessage && outgoing instanceof ServerResponse\n\t\t\t\t\t\t\t\t? { incoming, outgoing }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tviteServer.middlewares,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\treturn await cancelIfClosed(response, outgoing);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst configuredHost = viteServer.config.server.host;\n\tconst hostname =\n\t\tprocess.env.HOST || (configuredHost === true ? undefined : configuredHost || \"localhost\");\n\tawait new Promise<void>((resolve, reject) => {\n\t\thttpServer.once(\"error\", reject);\n\t\thttpServer.listen(port, hostname, () => {\n\t\t\thttpServer.off(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, port)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tapps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\thttpServer.close();\n\t\t\tviteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,SAAgB,aAAa;CAC5B,IAAI;CACJ,MAAM,yBAAS,IAAI,IAAe;CAClC,MAAM,UAAU,QAAmB;EAClC,OAAO,OAAO,GAAG;EACjB,AAAK,IAAI,MAAM,YAAY;CAC5B;CACA,OAA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B,CAAC;CACF,CAAC;AAEH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"entry-2XXp2Ukh.js","names":["requestId","honoRequestId","requestId"],"sources":["../src/log.ts","../src/plugins/access-log.ts","../src/plugins/request-id.ts","../src/static-files.ts","../src/plugins/static.ts","../src/plugins/streaming-compress.ts","../src/shutdown.ts","../src/tcp.ts","../src/create-server.ts","../src/entry.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogSink, RequestLogger } from \"./types.js\";\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.\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(\n\twrite: (line: string) => void = (line) => {\n\t\tprocess.stdout.write(line);\n\t},\n): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\twrite(\n\t\t\t\t`${JSON.stringify({ time: new Date().toISOString(), level, message, ...attributes })}\\n`,\n\t\t\t);\n\t\t},\n\t};\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\n/** A logger that writes to `sink`, with the attributes from `base` first on each line. */\nexport function sinkLogger(\n\tsink: LogSink,\n\tbase: () => Readonly<Record<string, unknown>> = () => ({}),\n): RequestLogger {\n\tconst line =\n\t\t(level: \"debug\" | \"info\" | \"warn\" | \"error\") =>\n\t\t(message: string, attributes: Readonly<Record<string, unknown>> = {}) => {\n\t\t\tsink.log(level, message, { ...base(), ...attributes });\n\t\t};\n\treturn { debug: line(\"debug\"), info: line(\"info\"), warn: line(\"warn\"), error: line(\"error\") };\n}\n\n/** A logger whose lines carry the request's ID, method, and path. */\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.\n\treturn sinkLogger(sink, () => ({\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}));\n}\n","import type { Context } from \"hono\";\nimport type { AppServerEnv, Plugin } from \"../types.js\";\n\n/** Options for {@link accessLog}. */\nexport type AccessLogOptions = {\n\t/**\n\t * Replace each query value with `REDACTED`, so a single-use code in a URL\n\t * never reaches a log.\n\t * @default true\n\t */\n\tredactQuery?: boolean;\n};\n\n/**\n * A URL's path and query, with each query value replaced when `redact` is set.\n *\n * @example\n * loggedUrl(new URL(\"https://example.com/verify?code=123\"), { redact: true }); // => \"/verify?code=REDACTED\"\n */\nexport function loggedUrl(url: URL, { redact }: { redact: boolean }): string {\n\tif (!redact || url.search === \"\") {\n\t\treturn `${url.pathname}${url.search}`;\n\t}\n\tconst query = Array.from(url.searchParams.keys())\n\t\t.map((key) => `${encodeURIComponent(key)}=REDACTED`)\n\t\t.join(\"&\");\n\treturn `${url.pathname}?${query}`;\n}\n\n/** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */\nfunction loggedReferer(referer: string | undefined, { redact }: { redact: boolean }) {\n\tif (referer == null || !redact) {\n\t\treturn referer;\n\t}\n\tconst url = URL.parse(referer);\n\treturn url == null ? undefined : `${url.origin}${loggedUrl(url, { redact })}`;\n}\n\n/**\n * One log line per request, static hits included, with Datadog standard\n * attribute names. The line goes out when the body ends or the client\n * disconnects, so a streamed response logs its full duration and size.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });\n * // {\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200,\"network.bytes_written\":5120,\"duration\":1830000,...}\n */\nexport function accessLog({ redactQuery = true }: AccessLogOptions = {}): Plugin {\n\treturn {\n\t\tname: \"access-log\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst started = performance.now();\n\t\t\tawait next();\n\t\t\tconst write = ({ bytes, aborted }: { bytes: number; aborted: boolean }) => {\n\t\t\t\tcontext.var.logger.info(\"request\", lineAttributes(context, { bytes, aborted, started }));\n\t\t\t};\n\t\t\tconst response = context.res;\n\t\t\t// Why HEAD: Hono drops the body of a HEAD response, so no one reads it to its end.\n\t\t\tif (context.req.method === \"HEAD\") {\n\t\t\t\twrite({ bytes: 0, aborted: false });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Why `Content-Length`: a stage that answers through Node's response, such as Vite in\n\t\t\t// development, gives a response with no body and the length it sent.\n\t\t\tif (response.body == null) {\n\t\t\t\twrite({ bytes: Number(response.headers.get(\"Content-Length\") ?? 0), aborted: false });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst reader = response.body.getReader();\n\t\t\tlet bytes = 0;\n\t\t\tconst counted = new ReadableStream<Uint8Array>({\n\t\t\t\tasync pull(controller) {\n\t\t\t\t\tlet result: ReadableStreamReadResult<Uint8Array>;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresult = await reader.read();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// Why here: `cancel` does not run for a stream that failed.\n\t\t\t\t\t\twrite({ bytes, aborted: true });\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tconst { done, value } = result;\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\twrite({ bytes, aborted: false });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tbytes += value.byteLength;\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t},\n\t\t\t\tasync cancel(reason) {\n\t\t\t\t\twrite({ bytes, aborted: true });\n\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t},\n\t\t\t});\n\t\t\tcontext.res = new Response(counted, response);\n\t\t},\n\t};\n\n\tfunction lineAttributes(\n\t\tcontext: Context<AppServerEnv>,\n\t\t{ bytes, aborted, started }: { bytes: number; aborted: boolean; started: number },\n\t): Record<string, unknown> {\n\t\treturn {\n\t\t\t\"http.url\": loggedUrl(new URL(context.req.url), { redact: redactQuery }),\n\t\t\t\"http.status_code\": context.res.status,\n\t\t\t\"http.useragent\": context.req.header(\"User-Agent\"),\n\t\t\t\"http.referer\": loggedReferer(context.req.header(\"Referer\"), { redact: redactQuery }),\n\t\t\t\"network.client.ip\": context.env.remoteAddress,\n\t\t\t\"network.bytes_written\": bytes,\n\t\t\t// Why nanoseconds: Datadog's standard `duration` attribute is in nanoseconds.\n\t\t\tduration: Math.round((performance.now() - started) * 1_000_000),\n\t\t\t...(aborted ? { \"http.client_aborted\": true } : {}),\n\t\t};\n\t}\n}\n","import { requestId as honoRequestId } from \"hono/request-id\";\nimport type { Plugin } from \"../types.js\";\n\n/** Options for {@link requestId}. */\nexport type RequestIdOptions = {\n\t/** @default \"X-Request-Id\" */\n\theaderName?: string;\n};\n\n/**\n * Gives each request an ID: a valid incoming header (up to 255 word\n * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on\n * every log line, and into the framework's context.\n *\n * @example\n * const app = createServer({ plugins: [requestId()] });\n * const response = await app.request(\"/\", { headers: { \"X-Request-Id\": \"abc-123\" } });\n * response.headers.get(\"X-Request-Id\"); // => \"abc-123\"\n */\nexport function requestId({ headerName = \"X-Request-Id\" }: RequestIdOptions = {}): Plugin {\n\tconst assign = honoRequestId({ headerName });\n\treturn {\n\t\tname: \"request-id\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait assign(context, next);\n\t\t\t// Why set it again: a `Response` that the framework returns replaces the headers set before `next`.\n\t\t\t// `context.header` also copies a response whose headers are immutable.\n\t\t\tconst id = context.get(\"requestId\");\n\t\t\tif (id != null) {\n\t\t\t\tcontext.header(headerName, id);\n\t\t\t}\n\t\t},\n\t};\n}\n","import { createHash } from \"node:crypto\";\nimport { open, stat, type FileHandle } from \"node:fs/promises\";\nimport { join, sep } from \"node:path\";\nimport type { Context } from \"hono\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport type { AppServerEnv } from \"./types.js\";\n\n/** A file under the client build that answers a request. */\nexport type StaticFile = {\n\t/** The absolute file path. */\n\tpath: string;\n\tsize: number;\n\tmtimeMs: number;\n};\n\n/**\n * Whether a URL path names a dotfile or goes through a dot directory.\n * `/.well-known/` stays reachable.\n */\nfunction hasDotSegment(path: string): boolean {\n\treturn path\n\t\t.split(\"/\")\n\t\t.some(\n\t\t\t(segment, index) => segment.startsWith(\".\") && !(index === 1 && segment === \".well-known\"),\n\t\t);\n}\n\nasync function fileStats(path: string) {\n\ttry {\n\t\treturn await stat(path);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Finds the file under `root` that answers a decoded URL path, such as\n * Hono's `context.req.path`. A directory answers with its `index.html` and no\n * redirect, so a prerendered page keeps its URL. Dotfiles and paths outside\n * `root` find nothing.\n *\n * Each file has one URL, because the headers for a file are keyed by that\n * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes\n * the path but keeps an encoded `/` as `%2F`, so this function does not\n * decode it again.\n *\n * @example\n * await findStaticFile(\"/app/build/client\", \"/components/button\");\n * // => { path: \"/app/build/client/components/button/index.html\", size: 5120, mtimeMs: 1761652800000 }\n */\nexport async function findStaticFile(root: string, path: string): Promise<StaticFile | undefined> {\n\tif (\n\t\tpath.includes(\"\\0\") ||\n\t\tpath.includes(\"\\\\\") ||\n\t\tpath.split(\"/\").includes(\"..\") ||\n\t\tpath.includes(\"//\") ||\n\t\tpath.endsWith(\"/index.html\") ||\n\t\thasDotSegment(path)\n\t) {\n\t\treturn undefined;\n\t}\n\tconst candidate = join(root, path);\n\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\treturn undefined;\n\t}\n\tconst stats = await fileStats(candidate);\n\tif (stats?.isFile()) {\n\t\treturn { path: candidate, size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\tif (stats?.isDirectory()) {\n\t\tconst index = join(candidate, \"index.html\");\n\t\tconst indexStats = await fileStats(index);\n\t\tif (indexStats?.isFile()) {\n\t\t\treturn { path: index, size: indexStats.size, mtimeMs: indexStats.mtimeMs };\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * A file's bytes, one chunk for each pull, so a slow client holds one chunk,\n * not the whole file. The handle closes at the end, on an error, or on cancel.\n */\nfunction fileStream(handle: FileHandle): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { bytesRead, buffer } = await handle.read({ buffer: new Uint8Array(65_536) });\n\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\tawait handle.close();\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tawait handle.close();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tcancel: () => handle.close(),\n\t});\n}\n\n/** The content type of a file, with the React Router and markdown types that `mime` lacks. */\nfunction contentType(path: string): string {\n\tif (path.endsWith(\".md\")) {\n\t\treturn \"text/markdown; charset=utf-8\";\n\t}\n\tif (path.endsWith(\".data\")) {\n\t\treturn \"text/x-script\";\n\t}\n\treturn getMimeType(path) ?? \"application/octet-stream\";\n}\n\n/** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */\nfunction opaqueTag(etag: string): string {\n\treturn etag.trim().replace(/^W\\//, \"\");\n}\n\n/** Whether an `If-None-Match` header lists an ETag. */\nfunction matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean {\n\treturn (\n\t\tifNoneMatch?.split(\",\").some((candidate) => {\n\t\t\tconst trimmed = candidate.trim();\n\t\t\treturn trimmed === \"*\" || opaqueTag(trimmed) === opaqueTag(etag);\n\t\t}) ?? false\n\t);\n}\n\n/** A weak ETag from a file's size, its modification time, and the request's `etagParts`. */\nfunction fileEtag(file: StaticFile, parts: readonly string[]): string {\n\tconst base = `${file.size.toString(16)}-${Math.trunc(file.mtimeMs).toString(16)}`;\n\tif (parts.length === 0) {\n\t\treturn `W/\"${base}\"`;\n\t}\n\tconst hash = createHash(\"sha256\").update(parts.join(\"\\0\")).digest(\"base64url\").slice(0, 16);\n\treturn `W/\"${base}-${hash}\"`;\n}\n\n/**\n * The response for a static file, with a weak ETag from its size,\n * modification time, and the request's `etagParts`. A matching\n * `If-None-Match` gets a 304, and `HEAD` gets the headers only. `headers`\n * replace the defaults, so a captured `Content-Type` wins over the one from\n * the file name.\n */\nexport async function staticResponse(\n\tcontext: Context<AppServerEnv>,\n\tfile: StaticFile,\n\theaders: Readonly<Record<string, string>>,\n): Promise<Response> {\n\tconst etag = fileEtag(file, context.get(\"etagParts\") ?? []);\n\tconst responseHeaders = new Headers({ \"Content-Type\": contentType(file.path), ETag: etag });\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tresponseHeaders.set(name, value);\n\t}\n\t// Why the final header: `headers` can replace the ETag.\n\tif (matchesEtag(context.req.header(\"If-None-Match\"), responseHeaders.get(\"ETag\") ?? etag)) {\n\t\tresponseHeaders.delete(\"Content-Type\");\n\t\treturn new Response(null, { status: 304, headers: responseHeaders });\n\t}\n\tif (context.req.method === \"HEAD\") {\n\t\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\t\treturn new Response(null, { headers: responseHeaders });\n\t}\n\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\treturn new Response(fileStream(await open(file.path)), { headers: responseHeaders });\n}\n","import { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport { capturedHeadersKey, readCapturedHeaders } from \"../captured-headers.js\";\nimport { findStaticFile, staticResponse } from \"../static-files.js\";\nimport type { AppServerEnv, NodeMiddleware, Plugin } from \"../types.js\";\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/** Runs Vite's middleware inside the pipeline. Vite answers or calls `next`. */\nfunction viteStage(viteMiddleware: NodeMiddleware): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (incoming == null || outgoing == null) {\n\t\t\treturn next();\n\t\t}\n\t\t// Why before Vite: it sends the headers itself, so the headers the earlier stages set, such\n\t\t// 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 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\tviteMiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\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(\"Vite 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 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 length\n\t\t\t// are Vite's, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tconst length = outgoing.getHeader(\"Content-Length\");\n\t\t\tif (length != null) {\n\t\t\t\theaders.set(\"Content-Length\", String(length));\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\n/**\n * Serves the hashed files under `/assets/` with a one-year immutable cache.\n * A missing asset gets a plain 404, not a rendered page. In development,\n * Vite serves the source modules, the HMR client, and the CSS here instead.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });\n */\nexport function assets(): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"assets\",\n\t\tsetup: (info) => {\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\tstage = viteStage(info.viteMiddleware);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst root = info.clientDirectory;\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method, path } = context.req;\n\t\t\t\tif (!path.startsWith(\"/assets/\") || (method !== \"GET\" && method !== \"HEAD\")) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst file = await findStaticFile(root, path);\n\t\t\t\tif (file == null) {\n\t\t\t\t\treturn context.text(\"Not Found\", 404);\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, file, { \"Cache-Control\": IMMUTABLE });\n\t\t\t};\n\t\t},\n\t\tmiddleware: (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n\n/** Options for {@link prerendered}. */\nexport type PrerenderedOptions = {\n\t/**\n\t * Extra headers for a served file, by its URL path. They replace the\n\t * headers captured at build time.\n\t */\n\theaders?: (\n\t\tpath: string,\n\t\tcontext: Context<AppServerEnv>,\n\t) => Readonly<Record<string, string>> | undefined;\n\t/**\n\t * Maps a request path to the URL path of the file to serve, for content\n\t * negotiation. Return the path unchanged to serve the usual file. The\n\t * returned path follows the rules of a request path: one URL for each\n\t * file, no dotfiles, and nothing outside the client build. When the\n\t * answer depends on a request header, add a `Vary` for it in a plugin.\n\t */\n\trewrite?: (path: string, context: Context<AppServerEnv>) => string;\n};\n\n/**\n * Serves the client build: prerendered pages at their own URL with a 200 and\n * no trailing-slash redirect, plus every other file in it. Each response gets\n * the headers its loader sent at build time (the `serverEntry` Vite plugin\n * captures them), an ETag, and a 304 for a matching `If-None-Match`. A path\n * with no file goes on to the framework. Off in development.\n *\n * At startup, it warns about each prerendered path that has no file.\n *\n * @example\n * prerendered({\n * \theaders: (path) => (path.startsWith(\"/api/\") ? { \"Access-Control-Allow-Origin\": \"*\" } : undefined),\n * });\n */\nexport function prerendered(options: PrerenderedOptions = {}): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"prerendered\",\n\t\tsetup: async (info) => {\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst root = info.clientDirectory;\n\t\t\tconst captured = await readCapturedHeaders(root);\n\t\t\tconst missing: string[] = [];\n\t\t\tfor (const path of info.prerenderedPaths) {\n\t\t\t\tif ((await findStaticFile(root, path)) == null) {\n\t\t\t\t\tmissing.push(path);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (missing.length > 0) {\n\t\t\t\t// Why a warning: a path with no file falls through to the framework, which still answers.\n\t\t\t\tinfo.logger.log(\"warn\", \"prerendered paths with no file\", {\n\t\t\t\t\t\"app_server.missing_paths\": missing,\n\t\t\t\t});\n\t\t\t}\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method } = context.req;\n\t\t\t\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst path = options.rewrite?.(context.req.path, context) ?? context.req.path;\n\t\t\t\tconst file = await findStaticFile(root, path);\n\t\t\t\tif (file == null) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, file, {\n\t\t\t\t\t...captured.get(capturedHeadersKey(path)),\n\t\t\t\t\t...options.headers?.(path, context),\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t\tmiddleware: (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import { accepts } from \"hono/accepts\";\nimport { constants, createGzip } from \"node:zlib\";\nimport type { Plugin } from \"../types.js\";\n\nconst COMPRESSIBLE =\n\t/^(text\\/|application\\/(json|javascript|xml|schema\\+json|manifest\\+json|x-ndjson|connect\\+json)|image\\/svg\\+xml)/;\n\n/**\n * Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at\n * once. It reads the next source chunk only when the consumer pulls, so a slow\n * client holds back the source.\n */\nfunction gzipStream(source: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n\tconst gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });\n\tconst reader = source.getReader();\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tgzip.on(\"data\", (chunk: Buffer) => {\n\t\t\t\tcontroller.enqueue(new Uint8Array(chunk));\n\t\t\t});\n\t\t\tgzip.on(\"end\", () => {\n\t\t\t\tcontroller.close();\n\t\t\t});\n\t\t\tgzip.on(\"error\", (error) => {\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\t\t},\n\t\tasync pull() {\n\t\t\ttry {\n\t\t\t\tlet chunk = await reader.read();\n\t\t\t\t// Why skip empty chunks: gzip writes nothing for one, and a pull that enqueues nothing\n\t\t\t\t// is not called again.\n\t\t\t\twhile (!chunk.done && chunk.value.byteLength === 0) {\n\t\t\t\t\tchunk = await reader.read();\n\t\t\t\t}\n\t\t\t\tif (chunk.done) {\n\t\t\t\t\tgzip.end();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst { value } = chunk;\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tgzip.write(value, (error) => {\n\t\t\t\t\t\tif (error == null) {\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tgzip.destroy();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\t// Why cancel the source: a client disconnect must reach the handler, so it stops its work.\n\t\tcancel(reason) {\n\t\t\tgzip.destroy();\n\t\t\treturn reader.cancel(reason);\n\t\t},\n\t});\n}\n\n/**\n * Gzips text responses and flushes after each chunk, so a streamed page shell\n * or a server-sent event reaches the client at once. `hono/compress` holds a\n * stream until it ends. Skips a response that is already encoded, a partial\n * response, and one marked `no-transform`. Always sets `Vary: Accept-Encoding`.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });\n */\nexport function streamingCompress(): Plugin {\n\treturn {\n\t\tname: \"streaming-compress\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\t// Why `context.header`: it copies a response whose headers are immutable, such as one from `fetch`.\n\t\t\tcontext.header(\"Vary\", \"Accept-Encoding\", { append: true });\n\t\t\tconst response = context.res;\n\t\t\tif (\n\t\t\t\tresponse.body == null ||\n\t\t\t\tcontext.req.method === \"HEAD\" ||\n\t\t\t\taccepts(context, { header: \"Accept-Encoding\", supports: [\"gzip\"], default: \"identity\" }) !==\n\t\t\t\t\t\"gzip\" ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: gzip changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\t/\\bno-transform\\b/.test(response.headers.get(\"Cache-Control\") ?? \"\") ||\n\t\t\t\t!COMPRESSIBLE.test(response.headers.get(\"Content-Type\") ?? \"\")\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontext.res = new Response(gzipStream(response.body), response);\n\t\t\t// Why after the assignment: Hono copies the old response's headers onto the new one.\n\t\t\tcontext.res.headers.set(\"Content-Encoding\", \"gzip\");\n\t\t\tcontext.res.headers.delete(\"Content-Length\");\n\t\t},\n\t};\n}\n","let controller = new AbortController();\n\n/**\n * A signal that aborts when the server starts to shut down. Read it for each\n * request: each start of a server makes a new one. A handler that\n * holds a response open, such as an event stream, stops on it so that the\n * drain does not wait for the deadline.\n *\n * @example\n * const timer = setInterval(sendUpdate, 1_000);\n * shutdownSignal().addEventListener(\"abort\", () => clearInterval(timer), { once: true });\n */\nexport function shutdownSignal(): AbortSignal {\n\treturn controller.signal;\n}\n\n/** Replaces {@link shutdownSignal} with a new one that has not aborted. */\nexport function renewShutdownSignal(): void {\n\tcontroller = new AbortController();\n}\n\n/** Aborts {@link shutdownSignal}. */\nexport function abortShutdownSignal(): void {\n\tcontroller.abort();\n}\n","import type { Listener } from \"./types.js\";\n\n/** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */\nconst DEFAULT_IDLE_TIMEOUT_MS = 95_000;\n\n/** Options for {@link tcp}. */\nexport type TcpOptions = {\n\t/** @default the `PORT` environment variable, else 3000 */\n\tport?: number;\n\t/** @default the `HOST` environment variable, else every interface */\n\thost?: string;\n\t/** @default 95000 */\n\tidleTimeoutMs?: number;\n};\n\n/**\n * Reads a port number. A value that is not an integer from 0 to 65535 throws,\n * so a bad `PORT` stops startup.\n *\n * @example\n * parsePort(\"8080\"); // => 8080\n */\nexport function parsePort(value: string): number {\n\tconst port = Number(value);\n\tif (value.trim() === \"\" || !Number.isInteger(port) || port < 0 || port > 65_535) {\n\t\tthrow new Error(`PORT must be an integer from 0 to 65535, not \"${value}\".`);\n\t}\n\treturn port;\n}\n\n/**\n * The default listener: a TCP port, served by the runtime's own HTTP server\n * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads\n * `PORT` and `HOST` when it starts.\n *\n * @example\n * createServer({ listeners: [tcp({ port: 8080 })] });\n */\nexport function tcp({\n\tport,\n\thost,\n\tidleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,\n}: TcpOptions = {}): Listener {\n\treturn {\n\t\tname: \"tcp\",\n\t\tstart: async (fetch) => {\n\t\t\tconst options = {\n\t\t\t\tport: port ?? (process.env.PORT == null ? 3000 : parsePort(process.env.PORT)),\n\t\t\t\thostname: host ?? (process.env.HOST || undefined),\n\t\t\t\tidleTimeoutMs,\n\t\t\t};\n\t\t\tif (\"Bun\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/bun.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\tif (\"Deno\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/deno.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\treturn (await import(\"./runtimes/node.js\")).listen(fetch, options);\n\t\t},\n\t};\n}\n","import { Hono } from \"hono\";\nimport { errorAttributes, jsonSink, requestLogger } from \"./log.js\";\nimport { accessLog, type AccessLogOptions } from \"./plugins/access-log.js\";\nimport { requestId, type RequestIdOptions } from \"./plugins/request-id.js\";\nimport { assets, prerendered, type PrerenderedOptions } from \"./plugins/static.js\";\nimport { streamingCompress } from \"./plugins/streaming-compress.js\";\nimport { abortShutdownSignal, renewShutdownSignal } from \"./shutdown.js\";\nimport { tcp } from \"./tcp.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkAdapter,\n\tListener,\n\tLogSink,\n\tPlugin,\n\tSetupInfo,\n} from \"./types.js\";\n\n// Why a WeakMap: only this copy of the package reads an app's internals, through `createEntry`.\nconst appInternals = new WeakMap<AppServer, ServerInternals>();\n\n/** A Hono app from {@link createServer}. Add routes to it before you export it. */\nexport type AppServer = Hono<AppServerEnv>;\n\n/** A server that listens. */\nexport type RunningServer = {\n\t/** The URL of each listener. */\n\turls: readonly string[];\n\t/**\n\t * Aborts `shutdownSignal()`, then runs each plugin's `onShutdown` while the\n\t * listeners stop and drain open requests. Both stop at the deadline.\n\t */\n\tshutdown: () => Promise<void>;\n};\n\n/** What `createEntry` calls on an app. */\nexport type ServerInternals = {\n\tlogger: LogSink;\n\t/** Runs each plugin's `setup` once and adds the framework handler after the app's routes. */\n\tprepare: (info: SetupInfo) => Promise<void>;\n\t/** Starts the listeners. Call `prepare` first. */\n\tlisten: (framework: FrameworkAdapter) => Promise<RunningServer>;\n\t/** Runs each plugin's `onShutdown` once, and stops waiting for them at the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n};\n\n/** Options for {@link defaultPlugins}. */\nexport type DefaultPluginsOptions = {\n\trequestId?: RequestIdOptions;\n\taccessLog?: AccessLogOptions;\n\tprerendered?: PrerenderedOptions;\n\t/**\n\t * Plugins that go after compression and before the static stages, so they\n\t * see every response, prerendered pages included. `runtimeEnv` and\n\t * `buildId` go here.\n\t */\n\tbeforeStatic?: readonly Plugin[];\n};\n\n/**\n * The default pipeline, in order: `requestId`, `accessLog`,\n * `streamingCompress`, the `beforeStatic` plugins, `assets`, and\n * `prerendered`. It is a plain array, so an app can filter it or splice into it.\n *\n * @example\n * createServer({ plugins: defaultPlugins({ accessLog: { redactQuery: false }, beforeStatic: [env] }) });\n */\nexport function defaultPlugins(options: DefaultPluginsOptions = {}): Plugin[] {\n\treturn [\n\t\trequestId(options.requestId),\n\t\taccessLog(options.accessLog),\n\t\tstreamingCompress(),\n\t\t...(options.beforeStatic ?? []),\n\t\tassets(),\n\t\tprerendered(options.prerendered),\n\t];\n}\n\n/** Options for {@link createServer}. */\nexport type CreateServerOptions = {\n\t/** @default defaultPlugins() */\n\tplugins?: readonly Plugin[];\n\t/** @default jsonSink() */\n\tlogger?: LogSink;\n\t/** @default [tcp()] */\n\tlisteners?: readonly Listener[];\n\t/**\n\t * Read the request scheme from `X-Forwarded-Proto`. Set it only behind a\n\t * proxy that overwrites that header, else a client can spoof it.\n\t * @default false\n\t */\n\ttrustForwardedProto?: boolean;\n\t/**\n\t * How long open requests get to finish after a stop signal.\n\t * @default 10000\n\t */\n\tshutdownDeadlineMs?: number;\n};\n\n/** The request with the scheme from `X-Forwarded-Proto`, when that header holds one. */\nfunction withForwardedProto(request: Request): Request {\n\tconst proto = request.headers.get(\"X-Forwarded-Proto\");\n\tif (proto !== \"http\" && proto !== \"https\") {\n\t\treturn request;\n\t}\n\tconst url = new URL(request.url);\n\turl.protocol = `${proto}:`;\n\treturn new Request(url, request);\n}\n\n/**\n * Runs `step`, and rethrows a thrown value that is not an `Error` as one.\n * Hono sends only an `Error` to `onError`, and rethrows any other value.\n */\nasync function asError<Result>(step: () => Promise<Result>): Promise<Result> {\n\ttry {\n\t\treturn await step();\n\t} catch (error) {\n\t\tthrow error instanceof Error\n\t\t\t? error\n\t\t\t: new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });\n\t}\n}\n\n/** Whether `work` settles before `ms` pass. */\nasync function settlesWithin(work: Promise<void>, ms: number): Promise<boolean> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst settled = await Promise.race([\n\t\twork.then(() => true),\n\t\tnew Promise<boolean>((resolve) => {\n\t\t\ttimer = setTimeout(resolve, ms, false);\n\t\t}),\n\t]);\n\tclearTimeout(timer);\n\treturn settled;\n}\n\n/**\n * Builds an app server: a Hono app that runs the plugins in list order, then\n * the app's own routes, then the framework. It does not listen; the\n * `app-server` CLI starts it.\n *\n * @example\n * // server.ts\n * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ beforeStatic: [env] }) });\n * app.get(\"/livez\", (c) => c.text(\"ok\"));\n * export default app;\n */\nexport function createServer({\n\tplugins = defaultPlugins(),\n\tlogger = jsonSink(),\n\tlisteners = [tcp()],\n\ttrustForwardedProto = false,\n\tshutdownDeadlineMs = 10_000,\n}: CreateServerOptions = {}): AppServer {\n\tconst app = new Hono<AppServerEnv>();\n\tif (trustForwardedProto) {\n\t\t// Why wrap `fetch`: every plugin and route, not only the framework, must see the trusted scheme.\n\t\tconst dispatch = app.fetch;\n\t\tapp.fetch = (request, ...rest) => dispatch(withForwardedProto(request), ...rest);\n\t}\n\tapp.use(async (context, next) => {\n\t\tcontext.set(\"logger\", requestLogger(logger, context));\n\t\tawait next();\n\t\t// Why cancel: Hono drops the body of a HEAD response without a cancel, so a stream would run on.\n\t\tif (context.req.method === \"HEAD\") {\n\t\t\tawait context.res.body?.cancel();\n\t\t}\n\t});\n\t// Why `asError` at each step: a value that is not an `Error` becomes one where it is thrown,\n\t// so `onError` answers at once and each earlier plugin still sees the 500 after its `next`.\n\tfor (const { middleware, etagPart } of plugins) {\n\t\tapp.use((context, next) => {\n\t\t\tconst part = etagPart?.();\n\t\t\tif (part != null) {\n\t\t\t\tcontext.set(\"etagParts\", [...(context.get(\"etagParts\") ?? []), part]);\n\t\t\t}\n\t\t\treturn asError(async () => (middleware == null ? next() : middleware(context, next)));\n\t\t});\n\t}\n\tapp.use((_, next) => asError(next));\n\tapp.onError((error, context) => {\n\t\t// Why no `instanceof`: the app's routes can throw an `HTTPException` from another copy of Hono.\n\t\tif (\"getResponse\" in error && typeof error.getResponse === \"function\") {\n\t\t\tconst response: unknown = error.getResponse();\n\t\t\tif (response instanceof Response) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t}\n\t\tcontext.var.logger.error(\"unhandled error\", errorAttributes(error));\n\t\treturn context.text(\"Internal Server Error\", 500);\n\t});\n\n\tlet prepared: Promise<void> | undefined;\n\tlet running: RunningServer | undefined;\n\tlet stoppingPlugins: Promise<void> | undefined;\n\tconst internals: ServerInternals = {\n\t\tlogger,\n\t\tprepare: (info) => {\n\t\t\tprepared ??= (async () => {\n\t\t\t\tfor (const plugin of plugins) {\n\t\t\t\t\tawait plugin.setup?.(info);\n\t\t\t\t}\n\t\t\t\tapp.all(\"*\", (context) => context.env.framework.fetch(context.req.raw, context));\n\t\t\t})();\n\t\t\treturn prepared;\n\t\t},\n\t\tlisten: async (framework) => {\n\t\t\tif (running != null) {\n\t\t\t\tthrow new Error(\"This app server is already listening.\");\n\t\t\t}\n\t\t\trenewShutdownSignal();\n\t\t\tlet deadlinePassed = false;\n\t\t\tconst fetch: FetchHandler = async (request, bindings) => {\n\t\t\t\tconst response = await app.fetch(request, { ...bindings, framework });\n\t\t\t\t// Why: after the drain deadline, the listener closed the connection, so no one reads this\n\t\t\t\t// body. A cancel stops its producer, which can otherwise keep the process alive.\n\t\t\t\tif (deadlinePassed) {\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 starts = await Promise.allSettled(listeners.map((listener) => listener.start(fetch)));\n\t\t\tconst started = starts.flatMap((start) =>\n\t\t\t\tstart.status === \"fulfilled\" ? [start.value] : [],\n\t\t\t);\n\t\t\tconst failed = starts.find((start) => start.status === \"rejected\");\n\t\t\tif (failed != null) {\n\t\t\t\t// Why stop the others: the caller gets no handle to stop them.\n\t\t\t\tawait Promise.all(started.map((listener) => listener.stop({ deadlineMs: 0 })));\n\t\t\t\tthrow failed.reason;\n\t\t\t}\n\t\t\tconst urls = started.map((listener) => listener.url);\n\t\t\tlogger.log(\"info\", \"listening\", { \"app_server.urls\": urls });\n\t\t\tlet stopping: Promise<void> | undefined;\n\t\t\trunning = {\n\t\t\t\turls,\n\t\t\t\tshutdown: () => {\n\t\t\t\t\tstopping ??= (async () => {\n\t\t\t\t\t\tlogger.log(\"info\", \"draining\", { \"app_server.deadline_ms\": shutdownDeadlineMs });\n\t\t\t\t\t\tabortShutdownSignal();\n\t\t\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\t\t\tdeadlinePassed = true;\n\t\t\t\t\t\t}, shutdownDeadlineMs);\n\t\t\t\t\t\t// Why at the same time: a plugin that hangs must not keep the listeners open.\n\t\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\t\tinternals.stopPlugins(),\n\t\t\t\t\t\t\t...started.map((listener) => listener.stop({ deadlineMs: shutdownDeadlineMs })),\n\t\t\t\t\t\t]);\n\t\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\t\tlogger.log(\"info\", \"stopped\", {});\n\t\t\t\t\t})();\n\t\t\t\t\treturn stopping;\n\t\t\t\t},\n\t\t\t};\n\t\t\treturn running;\n\t\t},\n\t\tstopPlugins: () => {\n\t\t\tstoppingPlugins ??= (async () => {\n\t\t\t\tconst hooks = (async () => {\n\t\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\t\tplugins.map(async (plugin) => plugin.onShutdown?.()),\n\t\t\t\t\t);\n\t\t\t\t\tfor (const result of results) {\n\t\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\t\tlogger.log(\"error\", \"plugin shutdown failed\", errorAttributes(result.reason));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\tif (!(await settlesWithin(hooks, shutdownDeadlineMs))) {\n\t\t\t\t\tlogger.log(\"warn\", \"plugin shutdown passed the deadline\", {\n\t\t\t\t\t\t\"app_server.deadline_ms\": shutdownDeadlineMs,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn stoppingPlugins;\n\t\t},\n\t};\n\tappInternals.set(app, internals);\n\treturn app;\n}\n\n/** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */\nexport function serverInternals(app: AppServer): ServerInternals | undefined {\n\treturn appInternals.get(app);\n}\n","import { serverInternals, type AppServer } from \"./create-server.js\";\nimport { errorAttributes } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport type { FrameworkAdapter, ListenerBindings, NodeMiddleware, SetupInfo } from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 1;\n\n/**\n * What a server build exports as `appServer`. The CLI calls it, so the copy\n * of this package in the build runs the server, and the CLI's copy runs\n * nothing.\n */\nexport type AppServerEntry = {\n\t/** The CLI refuses an entry with another version. */\n\tprotocol: typeof ENTRY_PROTOCOL;\n\t/** The app. Two entries with the same app share its plugins. */\n\tapp: AppServer;\n\t/** Production: runs each plugin's `setup`, listens, and shuts down on `SIGTERM` or `SIGINT`. */\n\tstart: () => Promise<void>;\n\t/** Development: answers one request with Vite's middleware inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tviteMiddleware: NodeMiddleware,\n\t) => Promise<Response>;\n\t/** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Aborts `shutdownSignal()` of this copy of the package. */\n\tabortShutdownSignal: () => void;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer` and\n * the framework adapter for each mode. The `serverEntry` Vite plugin makes\n * this export for a React Router build. Call this for another framework.\n *\n * @example\n * export const appServer = createEntry({ app, framework: (mode) => myAdapter(build, mode) });\n */\nexport function createEntry({\n\tapp,\n\tframework,\n}: {\n\tapp: AppServer;\n\tframework: (mode: SetupInfo[\"mode\"]) => FrameworkAdapter;\n}): AppServerEntry {\n\tconst internals = serverInternals(app);\n\tif (internals == null) {\n\t\tthrow new Error(\n\t\t\t\"The app is not from `createServer()` of the copy of @ngrok/app-server in this build.\",\n\t\t);\n\t}\n\tlet development: FrameworkAdapter | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst adapter = framework(\"production\");\n\t\t\tawait internals.prepare({\n\t\t\t\tmode: \"production\",\n\t\t\t\tclientDirectory: adapter.clientDirectory,\n\t\t\t\tprerenderedPaths: adapter.prerenderedPaths,\n\t\t\t\tlogger: internals.logger,\n\t\t\t});\n\t\t\tconst server = await internals.listen(adapter);\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\t\tinternals.logger.log(\"error\", \"shutdown failed\", errorAttributes(error));\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\tfetchDev: async (request, bindings, viteMiddleware) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\tmode: \"development\",\n\t\t\t\tviteMiddleware,\n\t\t\t\tclientDirectory: development.clientDirectory,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tlogger: internals.logger,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\nfunction isAppServerEntry(value: unknown): value is AppServerEntry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"protocol\" in value &&\n\t\tvalue.protocol === ENTRY_PROTOCOL\n\t);\n}\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `serverEntry` Vite plugin made it, else this copy of the package over a\n * plain React Router build with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { appServerEntry, isServerBuild } = await import(\"./react-router.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = appServerEntry(build);\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAgB,SACf,SAAiC,SAAS;CACzC,QAAQ,OAAO,MAAM,IAAI;AAC1B,GACU;CACV,OAAO,EACN,MAAM,OAAO,SAAS,eAAe;EACpC,MACC,GAAG,KAAK,UAAU;GAAE,uBAAM,IAAI,KAAK,EAAC,CAAC,YAAY;GAAG;GAAO;GAAS,GAAG;EAAW,CAAC,EAAE,GACtF;CACD,EACD;AACD;;AAGA,SAAgB,gBAAgB,OAAyC;CACxE,IAAI,iBAAiB,OACpB,OAAO;EAAE,cAAc,MAAM;EAAM,iBAAiB,MAAM;EAAS,eAAe,MAAM;CAAM;CAE/F,OAAO,EAAE,iBAAiB,OAAO,KAAK,EAAE;AACzC;;AAGA,SAAgB,WACf,MACA,cAAuD,CAAC,IACxC;CAChB,MAAM,QACJ,WACA,SAAiB,aAAgD,CAAC,MAAM;EACxE,KAAK,IAAI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