@ngrok/app-server 0.4.0 → 0.4.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 +3 -3
- package/dist/cli.js +3 -3
- package/dist/client.js +1 -1
- package/dist/{create-server-C63luLkn.js → create-server-Bp1yILQk.js} +4 -4
- package/dist/{create-server-C63luLkn.js.map → create-server-Bp1yILQk.js.map} +1 -1
- package/dist/{create-server-DKJ0wASH.d.ts → create-server-X2GR-U6t.d.ts} +3 -3
- package/dist/{entry-BSbsQ_kq.js → entry-BoxCqc6w.js} +3 -3
- package/dist/{entry-BSbsQ_kq.js.map → entry-BoxCqc6w.js.map} +1 -1
- package/dist/{entry-C9bBcYeP.d.ts → entry-DZTCaL3d.d.ts} +3 -3
- package/dist/index.d.ts +4 -4
- package/dist/index.js +5 -5
- package/dist/{load-entry-DgZyPtoD.js → load-entry-CCPWbsrj.js} +4 -4
- package/dist/{load-entry-DgZyPtoD.js.map → load-entry-CCPWbsrj.js.map} +1 -1
- package/dist/{log-CW_g1pWk.js → log-DQAS5gGT.js} +14 -4
- package/dist/{log-CW_g1pWk.js.map → log-DQAS5gGT.js.map} +1 -1
- package/dist/{node-DiMwdTOC.js → node-CVVdk2N6.js} +3 -3
- package/dist/{node-DiMwdTOC.js.map → node-CVVdk2N6.js.map} +1 -1
- package/dist/{node-DBwgrye_.js → node-D6m6e6EI.js} +2 -2
- package/dist/{node-DBwgrye_.js.map → node-D6m6e6EI.js.map} +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +2 -2
- package/dist/react-router.d.ts +1 -1
- package/dist/react-router.js +1 -1
- package/dist/{request-context-BdAH1D-2.js → request-context-Bxdbk5P1.js} +2 -2
- package/dist/{request-context-BdAH1D-2.js.map → request-context-Bxdbk5P1.js.map} +1 -1
- package/dist/{response-edge-7eUl2ewl.js → response-edge-CU8ZvL_F.js} +2 -2
- package/dist/{response-edge-7eUl2ewl.js.map → response-edge-CU8ZvL_F.js.map} +1 -1
- package/dist/{response-writer-CLtCseu5.js → response-writer-D7KHfr8n.js} +2 -2
- package/dist/{response-writer-CLtCseu5.js.map → response-writer-D7KHfr8n.js.map} +1 -1
- package/dist/{serve-DCaIBTM-.js → serve-W4WacdOw.js} +2 -2
- package/dist/{serve-DCaIBTM-.js.map → serve-W4WacdOw.js.map} +1 -1
- package/dist/{start-D2IVWkow.js → start-j0VlxeiI.js} +6 -6
- package/dist/{start-D2IVWkow.js.map → start-j0VlxeiI.js.map} +1 -1
- package/dist/tanstack-start.d.ts +2 -2
- package/dist/tanstack-start.js +1 -1
- package/dist/{tcp-B8aFGQRB.js → tcp-BgDXbjOG.js} +2 -2
- package/dist/{tcp-B8aFGQRB.js.map → tcp-BgDXbjOG.js.map} +1 -1
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +4 -4
- package/dist/{trailing-slash-D_52DJaQ.d.ts → trailing-slash-D2QWKWEu.d.ts} +2 -2
- package/dist/{types-C_I3i62n.d.ts → types-MgFtkNQW.d.ts} +6 -3
- package/dist/vercel.d.ts +2 -2
- package/dist/vercel.js +4 -4
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as SentResponse, g as LogSink, h as LogOptions, t as AppServerEnv, u as Listener, v as Plugin } from "./types-
|
|
2
|
-
import { t as TrailingSlash } from "./trailing-slash-
|
|
1
|
+
import { C as SentResponse, g as LogSink, h as LogOptions, t as AppServerEnv, u as Listener, v as Plugin } from "./types-MgFtkNQW.js";
|
|
2
|
+
import { t as TrailingSlash } from "./trailing-slash-D2QWKWEu.js";
|
|
3
3
|
import { Context, Hono } from "hono";
|
|
4
4
|
/** Options for {@link accessLog}. */
|
|
5
5
|
type AccessLogOptions = {
|
|
@@ -629,4 +629,4 @@ type CreateServerOptions = {
|
|
|
629
629
|
*/
|
|
630
630
|
declare function createServer({ plugins, logger: sink, log, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
|
|
631
631
|
export { buildId as A, RedirectRule as C, HealthOptions as D, noindex as E, accessLog as M, health as O, securityHeaders as S, NoindexOptions as T, requestId as _, createServer as a, SecurityHeadersOptions as b, assets as c, PUBLIC_ENV_SCRIPT_ID as d, RuntimeEnv as f, RequestIdOptions as g, runtimeEnv as h, RunningServer as i, AccessLogOptions as j, BuildIdOptions as k, prerendered as l, StandardSchemaV1 as m, CreateServerOptions as n, defaultPlugins as o, RuntimeEnvOptions as p, DefaultPluginsOptions as r, PrerenderedOptions as s, AppServer as t, InferOutput as u, ContentSecurityPolicyOptions as v, redirects as w, contentSecurityPolicy as x, SecurityHeaderValues as y };
|
|
632
|
-
//# sourceMappingURL=create-server-
|
|
632
|
+
//# sourceMappingURL=create-server-X2GR-U6t.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as asError } from "./log-
|
|
1
|
+
import { t as asError } from "./log-DQAS5gGT.js";
|
|
2
2
|
import { i as readBuildManifest, n as DEFAULT_ASSETS_PATH } from "./build-manifest-DBMWe3Lx.js";
|
|
3
|
-
import { p as abortShutdownSignal, r as serverInternals } from "./create-server-
|
|
3
|
+
import { p as abortShutdownSignal, r as serverInternals } from "./create-server-Bp1yILQk.js";
|
|
4
4
|
import { a as keptFiles } from "./static-files-C2ea8KQ6.js";
|
|
5
5
|
|
|
6
6
|
// src/core/static-pages.ts
|
|
@@ -357,4 +357,4 @@ function isAppServerEntry(value) {
|
|
|
357
357
|
}
|
|
358
358
|
|
|
359
359
|
export { isAppServerEntry as n, createEntry as t };
|
|
360
|
-
//# sourceMappingURL=entry-
|
|
360
|
+
//# sourceMappingURL=entry-BoxCqc6w.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entry-BSbsQ_kq.js","names":[],"sources":["../src/core/static-pages.ts","../src/core/entry.ts"],"sourcesContent":["/** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */\nexport type CdnPage = {\n\t/** The URL path of the client build's file that the answer comes from, such as `/about/index.html`. */\n\tfile: string;\n\t/** The body that the pipeline sent. It can differ from the file, such as with `runtimeEnv` values. */\n\tbody: Uint8Array;\n\t/**\n\t * The response headers for each case of the presence headers. `present`\n\t * lists the headers that the request has. With no presence headers, there\n\t * is one case.\n\t */\n\tanswers: { present: readonly string[]; headers: Readonly<Record<string, string>> }[];\n\t/**\n\t * The path of the page's markdown twin. A request whose `Accept` names\n\t * `text/markdown` must reach the server, which negotiates the answer.\n\t */\n\ttwin?: string;\n};\n\n/** A prerendered path, with its CDN answer, or with the reason that the server must answer it. */\nexport type StaticPage = { path: string } & ({ cdn: CdnPage } | { reason: string });\n\n/**\n * Sends a request through the pipeline as a client at `remoteAddress`. The\n * pipeline calls `onServedFile` with the URL path of the client build's file\n * that `prerendered()` sends, if it sends one.\n */\nexport type PipelineFetch = (\n\trequest: Request,\n\tbindings: { remoteAddress: string; onServedFile: (path: string) => void },\n) => Promise<Response>;\n\n/** The headers that change with each request, such as the request ID. A CDN answer drops them. */\nconst PER_REQUEST = new Set([\"x-request-id\", \"date\"]);\n\n/** The headers that the CDN sets for each file itself. */\nconst CDN_OWN = new Set([\n\t\"content-length\",\n\t\"etag\",\n\t\"last-modified\",\n\t\"accept-ranges\",\n\t\"transfer-encoding\",\n\t\"connection\",\n\t\"keep-alive\",\n]);\n\n/** A browser's `Accept`. A browser never names `text/markdown`, so it gets the HTML. */\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\n/**\n * A URL path that a CDN route matches as it is. Why only these characters: a\n * CDN can match a path before or after it decodes it, and these two forms\n * are the same. Why a slash after each segment but the last: the match then\n * takes linear time.\n */\nconst PLAIN_PATH = /^\\/(?:[\\w.~-]+\\/)*[\\w.~-]*$/u;\n\n/** The most presence headers. Why: each one doubles the requests and the CDN routes. */\nconst MAX_PRESENCE_HEADERS = 3;\n\n/** One answer of the pipeline. */\ntype Answer = {\n\tstatus: number;\n\theaders: Headers;\n\tbody: Uint8Array;\n\tfile: string | undefined;\n};\n\n/**\n * The two clients of each check. The first is an anonymous browser. The\n * second differs in each value that a CDN route does not match on: the host,\n * the address, the query, the value of a presence header, and the request\n * headers that a plugin reads most often to choose an answer. Why a cookie\n * and `Authorization`: a plugin that sends a signed-in visitor to another\n * page must keep its pages on the server. Why the geo headers: Vercel adds\n * them, and a plugin can redirect by country.\n */\nconst CLIENTS = [\n\t{\n\t\torigin: \"https://localhost\",\n\t\tquery: \"\",\n\t\taddress: \"203.0.113.1\",\n\t\tpresentValue: \"1\",\n\t\theaders: { Accept: BROWSER_ACCEPT, \"User-Agent\": \"app-server-build\" },\n\t},\n\t{\n\t\torigin: \"https://app-server-check.example\",\n\t\tquery: \"?app-server-check=1\",\n\t\taddress: \"198.51.100.2\",\n\t\tpresentValue: \"2\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\t\"Accept-Language\": \"de-DE\",\n\t\t\tAuthorization: \"Bearer app-server-check\",\n\t\t\tCookie: \"session=app-server-check\",\n\t\t\tReferer: \"https://app-server-check.example/\",\n\t\t\t\"User-Agent\": \"app-server-build-check\",\n\t\t\t\"X-Vercel-IP-City\": \"Berlin\",\n\t\t\t\"X-Vercel-IP-Country\": \"DE\",\n\t\t\t\"X-Vercel-IP-Country-Region\": \"BE\",\n\t\t},\n\t},\n] as const;\n\n/**\n * The answer of the pipeline for `path`. The request has each of `presence`\n * that is in `present`, and no other of `presence`.\n */\nasync function answer(\n\tfetch: PipelineFetch,\n\tpath: string,\n\t{\n\t\tclient,\n\t\tpresence,\n\t\tpresent,\n\t}: {\n\t\tclient: (typeof CLIENTS)[number];\n\t\tpresence: readonly string[];\n\t\tpresent: readonly string[];\n\t},\n): Promise<Answer> {\n\t// Why `Host`: a listener gives it to each request, and a plugin can read it.\n\tconst headers = new Headers({ ...client.headers, Host: new URL(client.origin).host });\n\tfor (const name of presence) {\n\t\tif (present.includes(name)) {\n\t\t\theaders.set(name, client.presentValue);\n\t\t} else {\n\t\t\theaders.delete(name);\n\t\t}\n\t}\n\tconst request = new Request(`${client.origin}${path}${client.query}`, { headers });\n\tlet file: string | undefined;\n\tconst response = await fetch(request, {\n\t\tremoteAddress: client.address,\n\t\tonServedFile: (served) => {\n\t\t\tfile = served;\n\t\t},\n\t});\n\tif (file == null) {\n\t\t// Why cancel: only the answer of a file can go on a CDN, and another body can stream with no end.\n\t\tawait response.body?.cancel();\n\t}\n\treturn {\n\t\tstatus: response.status,\n\t\theaders: response.headers,\n\t\tbody: file == null ? new Uint8Array() : new Uint8Array(await response.arrayBuffer()),\n\t\tfile,\n\t};\n}\n\nfunction sameBytes(first: Uint8Array, second: Uint8Array): boolean {\n\treturn first.length === second.length && first.every((byte, index) => byte === second[index]);\n}\n\n/** The headers of `headers` that a CDN answer keeps, sorted by name. */\nfunction keptHeaders(headers: Headers): [string, string][] {\n\treturn [...headers]\n\t\t.filter(([name]) => !PER_REQUEST.has(name) && !CDN_OWN.has(name))\n\t\t.toSorted(([first], [second]) => (first < second ? -1 : 1));\n}\n\n/** The path of the markdown twin in a `Link` header, if any. */\nfunction twinIn(link: string | null): string | undefined {\n\treturn /<(?<path>[^>]+)>;\\s*rel=\"alternate\";\\s*type=\"text\\/markdown\"/u.exec(link ?? \"\")?.groups\n\t\t?.path;\n}\n\n/** Why a CDN cannot keep `first`, or `undefined` when it can. */\nfunction uncacheable(first: Answer, allowedVary: ReadonlySet<string>): string | undefined {\n\tif (first.status !== 200) {\n\t\treturn `the status is ${first.status}`;\n\t}\n\tif (first.file == null) {\n\t\treturn \"the answer does not come from a prerendered file\";\n\t}\n\tif (!PLAIN_PATH.test(first.file)) {\n\t\treturn \"the file path has a character that a CDN route can match two ways\";\n\t}\n\tif (first.headers.has(\"set-cookie\")) {\n\t\treturn \"the answer sets a cookie\";\n\t}\n\t// Why each `CDN-Cache-Control` field: a CDN obeys it before `Cache-Control` (RFC 9213).\n\tfor (const [name, value] of first.headers) {\n\t\t// Why `i`: cache directives are case-insensitive.\n\t\tconst blocked = /\\b(?:private|no-store|no-cache)\\b/iu.exec(value);\n\t\tif (blocked != null && (name === \"cache-control\" || name.endsWith(\"cdn-cache-control\"))) {\n\t\t\treturn `the ${name} header has ${blocked[0]}`;\n\t\t}\n\t}\n\tif (first.headers.has(\"content-encoding\")) {\n\t\treturn \"the answer has a Content-Encoding\";\n\t}\n\tconst vary = (first.headers.get(\"vary\") ?? \"\")\n\t\t.split(\",\")\n\t\t.map((name) => name.trim().toLowerCase())\n\t\t.find((name) => name !== \"\" && !allowedVary.has(name));\n\treturn vary == null ? undefined : `the answer varies on ${vary}`;\n}\n\n/** Why `second` differs from `first`, or `undefined` when they match. */\nfunction difference(first: Answer, second: Answer): string | undefined {\n\tif (first.status !== second.status || first.file !== second.file) {\n\t\treturn \"the status or the file changes with the request\";\n\t}\n\tconst names = new Set(\n\t\t[...keptHeaders(first.headers), ...keptHeaders(second.headers)].map(([name]) => name),\n\t);\n\tconst changed = [...names].find((name) => first.headers.get(name) !== second.headers.get(name));\n\tif (changed != null) {\n\t\treturn `the ${changed} header changes with the request`;\n\t}\n\treturn sameBytes(first.body, second.body) ? undefined : \"the body changes with the request\";\n}\n\n/** Each subset of `names`, the empty one first. */\nfunction subsets(names: readonly string[]): string[][] {\n\tconst all: string[][] = [[]];\n\tfor (const name of names) {\n\t\tall.push(...all.map((subset) => [...subset, name]));\n\t}\n\treturn all;\n}\n\n/** The CDN answer of one path, or the reason that the server must answer it. */\nasync function staticPage(\n\tfetch: PipelineFetch,\n\tpath: string,\n\tpresence: readonly string[],\n): Promise<StaticPage> {\n\tif (!PLAIN_PATH.test(path)) {\n\t\treturn { path, reason: \"the path has a character that a CDN route can match two ways\" };\n\t}\n\t// Why: the build records a path with no trailing slash, and `trailingSlash: \"always\"` sends it on.\n\tconst probe = await answer(fetch, path, { client: CLIENTS[0], presence, present: [] });\n\tif (probe.status === 308 && probe.headers.get(\"location\") === `${path}/`) {\n\t\treturn staticPage(fetch, `${path}/`, presence);\n\t}\n\tif (presence.length > MAX_PRESENCE_HEADERS) {\n\t\treturn { path, reason: `more than ${MAX_PRESENCE_HEADERS} presence headers` };\n\t}\n\t// Why reuse the probe: it is the first client's answer with no presence header.\n\tconst firstAnswer = async (present: readonly string[]): Promise<Answer> =>\n\t\tpresent.length === 0 ? probe : answer(fetch, path, { client: CLIENTS[0], presence, present });\n\tconst answers: CdnPage[\"answers\"] = [];\n\tlet base: Answer | undefined;\n\tlet twin: string | undefined;\n\tfor (const present of subsets(presence)) {\n\t\tconst [first, second] = [\n\t\t\tawait firstAnswer(present),\n\t\t\tawait answer(fetch, path, { client: CLIENTS[1], presence, present }),\n\t\t];\n\t\tconst caseTwin = twinIn(first.headers.get(\"link\"));\n\t\tconst allowedVary = new Set([\n\t\t\t\"accept-encoding\",\n\t\t\t...presence,\n\t\t\t...(caseTwin == null ? [] : [\"accept\"]),\n\t\t]);\n\t\tconst reason = uncacheable(first, allowedVary) ?? difference(first, second);\n\t\tif (reason != null) {\n\t\t\treturn { path, reason };\n\t\t}\n\t\tif (base != null && (base.file !== first.file || !sameBytes(base.body, first.body))) {\n\t\t\treturn { path, reason: \"the body changes with a presence header\" };\n\t\t}\n\t\t// Why: the CDN routes send each markdown request of a page to the server, or none.\n\t\tif (base != null && caseTwin !== twin) {\n\t\t\treturn { path, reason: \"the markdown twin changes with a presence header\" };\n\t\t}\n\t\tbase ??= first;\n\t\ttwin = caseTwin;\n\t\tanswers.push({ present, headers: Object.fromEntries(keptHeaders(first.headers)) });\n\t}\n\tif (base?.file == null) {\n\t\treturn { path, reason: \"the answer does not come from a prerendered file\" };\n\t}\n\tif (twin != null && !PLAIN_PATH.test(twin)) {\n\t\treturn { path, reason: \"the twin path has a character that a CDN route can match two ways\" };\n\t}\n\treturn {\n\t\tpath,\n\t\tcdn: { file: base.file, body: base.body, answers, ...(twin == null ? {} : { twin }) },\n\t};\n}\n\n/**\n * Sends each prerendered path through the pipeline, and gives the paths that\n * a CDN can serve with no server. A path qualifies when its answer:\n *\n * - is a 200 from a prerendered file, with no cookie and no `private`,\n * `no-store`, or `no-cache`\n * - is the same, except for the request ID, for a second client with another\n * host, client address, query, and value of each presence header, and with\n * a cookie, `Authorization`, `Accept-Language`, and geo headers. Why: a CDN\n * route matches only the path, a markdown `Accept`, and the presence of\n * each presence header.\n * - varies only on `Accept-Encoding`, on `Accept` for a markdown twin, and on\n * the presence headers. Each case of the presence headers gets its own\n * headers, and all cases must send the same body.\n *\n * An auth check that refuses an anonymous request keeps its pages on the\n * server. Why: the first client sends no cookie and no `Authorization`.\n *\n * @yields Each path with its CDN answer, or with the reason that the server must answer it, in the order of `paths`.\n * @example\n * for await (const page of staticPages(fetch, [\"/\", \"/about\"], { presence: [\"x-ngrok-edge\"] })) {\n * \tconsole.log(page.path, \"cdn\" in page ? \"CDN\" : page.reason);\n * }\n */\nexport async function* staticPages(\n\tfetch: PipelineFetch,\n\tpaths: readonly string[],\n\t{ presence }: { presence: readonly string[] },\n): AsyncGenerator<StaticPage> {\n\tfor (const path of paths) {\n\t\tyield await staticPage(fetch, path, presence);\n\t}\n}\n","import type { MiddlewareHandler } from \"hono\";\nimport { DEFAULT_ASSETS_PATH, readBuildManifest } from \"./build-manifest.js\";\nimport { serverInternals } from \"./create-server.js\";\nimport type { AppServer } from \"./create-server.js\";\nimport { asError } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport { staticPages } from \"./static-pages.js\";\nimport type { StaticPage } from \"./static-pages.js\";\nimport { keptFiles } from \"./static-files.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHostRuntime,\n\tListenerBindings,\n\tMode,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 2;\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/**\n\t * Production: runs each plugin's `setup` and listens. When the host's\n\t * lifecycle stops, such as on `SIGTERM`, it shuts down.\n\t */\n\tstart: () => Promise<void>;\n\t/**\n\t * Production, for a serverless host: answers one request, and does not\n\t * listen. The first call runs each plugin's `setup`.\n\t */\n\tfetch: FetchHandler;\n\t/** Development: answers one request with the dev server inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tdevServer: MiddlewareHandler<AppServerEnv>,\n\t) => Promise<Response>;\n\t/**\n\t * Production, for a build step: each prerendered path, with the answer\n\t * that a content delivery network (CDN) can send with no server, or the\n\t * reason that the server must answer it. The first call runs each\n\t * plugin's `setup`. See `staticPages`.\n\t */\n\tstaticPages: () => AsyncGenerator<StaticPage>;\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/** Options for {@link createEntry}. */\nexport type CreateEntryOptions = {\n\t/** The app from `createServer`. */\n\tapp: AppServer;\n\t/** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */\n\thost: HostRuntime;\n\t/** Makes the run side of the framework adapter for a mode. */\n\tframework: (mode: Mode) => FrameworkRuntime;\n\t/**\n\t * The client build, as a file path or a `file:` URL. The entry that the\n\t * Vite plugin generates sets it.\n\t * @default the framework's `clientDirectory`\n\t */\n\tclientDirectory?: string;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer`, the\n * host, and the framework adapter for each mode. The `appServer` Vite plugin\n * generates this export. Call this for a build without the plugin.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport function createEntry({\n\tapp,\n\thost,\n\tframework,\n\tclientDirectory,\n}: CreateEntryOptions): 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\tinternals.setRequestStore(host.storage);\n\tconst setupInfo = async (runtime: FrameworkRuntime) => {\n\t\tconst directory = clientDirectory ?? runtime.clientDirectory;\n\t\tif (directory == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`,\n\t\t\t);\n\t\t}\n\t\tconst files = host.files(directory);\n\t\treturn {\n\t\t\tfiles,\n\t\t\tisDataRequest: runtime.isDataRequest ?? (() => false),\n\t\t\tcontentTypes: runtime.contentTypes ?? {},\n\t\t\tgzip: host.gzip,\n\t\t\tbrotli: host.brotli,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\tlet prerenderedPaths: readonly string[] = [];\n\t/** Runs each plugin's `setup` for production, and gives the framework's run side. */\n\tconst prepareProduction = async (): Promise<FrameworkRuntime> => {\n\t\tconst runtime = framework(\"production\");\n\t\tconst shared = await setupInfo(runtime);\n\t\tconst snapshot = await shared.files.snapshot?.();\n\t\t// Why only with a snapshot: it promises that the client build does not change while the server runs.\n\t\tconst files = snapshot == null ? shared.files : keptFiles(snapshot);\n\t\tconst manifest = await readBuildManifest(files);\n\t\tconst info: SetupInfo = {\n\t\t\t...shared,\n\t\t\tfiles,\n\t\t\tmode: \"production\",\n\t\t\tprerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,\n\t\t\tcapturedHeaders: new Map(Object.entries(manifest.headers)),\n\t\t\tscriptHashes: new Map(Object.entries(manifest.scriptHashes)),\n\t\t\tbuildId: manifest.buildId,\n\t\t\tassetsPath: manifest.assetsPath ?? DEFAULT_ASSETS_PATH,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\t({ prerenderedPaths } = info);\n\t\treturn runtime;\n\t};\n\tlet preparing: Promise<FrameworkRuntime> | undefined;\n\t/**\n\t * The production run side, set up once. Why forget a failure: a serverless\n\t * instance stays up, so the next request runs each `setup` again.\n\t */\n\tconst production = async (): Promise<FrameworkRuntime> => {\n\t\tpreparing ??= prepareProduction().catch((error: unknown) => {\n\t\t\tpreparing = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\treturn preparing;\n\t};\n\tlet development: FrameworkRuntime | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst runtime = await production();\n\t\t\tconst server = await internals.listen(runtime, host.listeners?.());\n\t\t\thost.lifecycle?.onStop(async () =>\n\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\tinternals.logger.log({\n\t\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\t\tmessage: \"shutdown failed\",\n\t\t\t\t\t\tattributes: { error: asError(error) },\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tfetch: async (request, bindings) => {\n\t\t\t// Why log it: the host sends a 500 with no log, and no app handler runs before setup ends.\n\t\t\tconst runtime = await production().catch((error: unknown) => {\n\t\t\t\tinternals.logger.log({\n\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\tmessage: \"setup failed\",\n\t\t\t\t\tattributes: { error: asError(error) },\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: runtime });\n\t\t},\n\t\tfetchDev: async (request, bindings, devServer) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\t...(await setupInfo(development)),\n\t\t\t\tmode: \"development\",\n\t\t\t\tdevServer,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tcapturedHeaders: new Map(),\n\t\t\t\tscriptHashes: new Map(),\n\t\t\t\t// Why none: development has no client build, and Vite's HMR updates an open tab after each edit.\n\t\t\t\tbuildId: undefined,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tasync *staticPages() {\n\t\t\tconst runtime = await production();\n\t\t\tyield* staticPages(\n\t\t\t\tasync (request, bindings) => app.fetch(request, { ...bindings, framework: runtime }),\n\t\t\t\tprerenderedPaths,\n\t\t\t\t{ presence: internals.presenceHeaders },\n\t\t\t);\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\n/**\n * Whether a value is an entry of this protocol version.\n *\n * @example\n * isAppServerEntry((await import(\"./build/server/app-server.js\")).appServer); // => true\n */\nexport function 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"],"mappings":";;;;;;;AAiCA,MAAM,8BAAc,IAAI,IAAI,CAAC,gBAAgB,MAAM,CAAC;;AAGpD,MAAM,0BAAU,IAAI,IAAI;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,aAAa;;AAGnB,MAAM,uBAAuB;;;;;;;;;;AAmB7B,MAAM,UAAU,CACf;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EAAE,QAAQ;EAAgB,cAAc;CAAmB;AACrE,GACA;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EACR,QAAQ;EACR,mBAAmB;EACnB,eAAe;EACf,QAAQ;EACR,SAAS;EACT,cAAc;EACd,oBAAoB;EACpB,uBAAuB;EACvB,8BAA8B;CAC/B;AACD,CACD;;;;;AAMA,eAAe,OACd,OACA,MACA,EACC,QACA,UACA,WAMiB;CAElB,MAAM,UAAU,IAAI,QAAQ;EAAE,GAAG,OAAO;EAAS,MAAM,IAAI,IAAI,OAAO,MAAM,CAAC,CAAC;CAAK,CAAC;CACpF,KAAK,MAAM,QAAQ,UAClB,IAAI,QA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CAAC;EAClE;EACA,OAAO,cAAc;GACpB,MAAM,UAAU,MAAM,WAAW;GACjC,OAAO,YACN,OAAO,SAAS,aAAa,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAQ,CAAC,GACnF,kBACA,EAAE,UAAU,UAAU,gBAAgB,CACvC;EACD;EACA,aAAa,UAAU;EACvB;CACD;AACD;;;;;;;AAQA,SAAgB,iBAAiB,OAAyC;CACzE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER"}
|
|
1
|
+
{"version":3,"file":"entry-BoxCqc6w.js","names":[],"sources":["../src/core/static-pages.ts","../src/core/entry.ts"],"sourcesContent":["/** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */\nexport type CdnPage = {\n\t/** The URL path of the client build's file that the answer comes from, such as `/about/index.html`. */\n\tfile: string;\n\t/** The body that the pipeline sent. It can differ from the file, such as with `runtimeEnv` values. */\n\tbody: Uint8Array;\n\t/**\n\t * The response headers for each case of the presence headers. `present`\n\t * lists the headers that the request has. With no presence headers, there\n\t * is one case.\n\t */\n\tanswers: { present: readonly string[]; headers: Readonly<Record<string, string>> }[];\n\t/**\n\t * The path of the page's markdown twin. A request whose `Accept` names\n\t * `text/markdown` must reach the server, which negotiates the answer.\n\t */\n\ttwin?: string;\n};\n\n/** A prerendered path, with its CDN answer, or with the reason that the server must answer it. */\nexport type StaticPage = { path: string } & ({ cdn: CdnPage } | { reason: string });\n\n/**\n * Sends a request through the pipeline as a client at `remoteAddress`. The\n * pipeline calls `onServedFile` with the URL path of the client build's file\n * that `prerendered()` sends, if it sends one.\n */\nexport type PipelineFetch = (\n\trequest: Request,\n\tbindings: { remoteAddress: string; onServedFile: (path: string) => void },\n) => Promise<Response>;\n\n/** The headers that change with each request, such as the request ID. A CDN answer drops them. */\nconst PER_REQUEST = new Set([\"x-request-id\", \"date\"]);\n\n/** The headers that the CDN sets for each file itself. */\nconst CDN_OWN = new Set([\n\t\"content-length\",\n\t\"etag\",\n\t\"last-modified\",\n\t\"accept-ranges\",\n\t\"transfer-encoding\",\n\t\"connection\",\n\t\"keep-alive\",\n]);\n\n/** A browser's `Accept`. A browser never names `text/markdown`, so it gets the HTML. */\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\n/**\n * A URL path that a CDN route matches as it is. Why only these characters: a\n * CDN can match a path before or after it decodes it, and these two forms\n * are the same. Why a slash after each segment but the last: the match then\n * takes linear time.\n */\nconst PLAIN_PATH = /^\\/(?:[\\w.~-]+\\/)*[\\w.~-]*$/u;\n\n/** The most presence headers. Why: each one doubles the requests and the CDN routes. */\nconst MAX_PRESENCE_HEADERS = 3;\n\n/** One answer of the pipeline. */\ntype Answer = {\n\tstatus: number;\n\theaders: Headers;\n\tbody: Uint8Array;\n\tfile: string | undefined;\n};\n\n/**\n * The two clients of each check. The first is an anonymous browser. The\n * second differs in each value that a CDN route does not match on: the host,\n * the address, the query, the value of a presence header, and the request\n * headers that a plugin reads most often to choose an answer. Why a cookie\n * and `Authorization`: a plugin that sends a signed-in visitor to another\n * page must keep its pages on the server. Why the geo headers: Vercel adds\n * them, and a plugin can redirect by country.\n */\nconst CLIENTS = [\n\t{\n\t\torigin: \"https://localhost\",\n\t\tquery: \"\",\n\t\taddress: \"203.0.113.1\",\n\t\tpresentValue: \"1\",\n\t\theaders: { Accept: BROWSER_ACCEPT, \"User-Agent\": \"app-server-build\" },\n\t},\n\t{\n\t\torigin: \"https://app-server-check.example\",\n\t\tquery: \"?app-server-check=1\",\n\t\taddress: \"198.51.100.2\",\n\t\tpresentValue: \"2\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\t\"Accept-Language\": \"de-DE\",\n\t\t\tAuthorization: \"Bearer app-server-check\",\n\t\t\tCookie: \"session=app-server-check\",\n\t\t\tReferer: \"https://app-server-check.example/\",\n\t\t\t\"User-Agent\": \"app-server-build-check\",\n\t\t\t\"X-Vercel-IP-City\": \"Berlin\",\n\t\t\t\"X-Vercel-IP-Country\": \"DE\",\n\t\t\t\"X-Vercel-IP-Country-Region\": \"BE\",\n\t\t},\n\t},\n] as const;\n\n/**\n * The answer of the pipeline for `path`. The request has each of `presence`\n * that is in `present`, and no other of `presence`.\n */\nasync function answer(\n\tfetch: PipelineFetch,\n\tpath: string,\n\t{\n\t\tclient,\n\t\tpresence,\n\t\tpresent,\n\t}: {\n\t\tclient: (typeof CLIENTS)[number];\n\t\tpresence: readonly string[];\n\t\tpresent: readonly string[];\n\t},\n): Promise<Answer> {\n\t// Why `Host`: a listener gives it to each request, and a plugin can read it.\n\tconst headers = new Headers({ ...client.headers, Host: new URL(client.origin).host });\n\tfor (const name of presence) {\n\t\tif (present.includes(name)) {\n\t\t\theaders.set(name, client.presentValue);\n\t\t} else {\n\t\t\theaders.delete(name);\n\t\t}\n\t}\n\tconst request = new Request(`${client.origin}${path}${client.query}`, { headers });\n\tlet file: string | undefined;\n\tconst response = await fetch(request, {\n\t\tremoteAddress: client.address,\n\t\tonServedFile: (served) => {\n\t\t\tfile = served;\n\t\t},\n\t});\n\tif (file == null) {\n\t\t// Why cancel: only the answer of a file can go on a CDN, and another body can stream with no end.\n\t\tawait response.body?.cancel();\n\t}\n\treturn {\n\t\tstatus: response.status,\n\t\theaders: response.headers,\n\t\tbody: file == null ? new Uint8Array() : new Uint8Array(await response.arrayBuffer()),\n\t\tfile,\n\t};\n}\n\nfunction sameBytes(first: Uint8Array, second: Uint8Array): boolean {\n\treturn first.length === second.length && first.every((byte, index) => byte === second[index]);\n}\n\n/** The headers of `headers` that a CDN answer keeps, sorted by name. */\nfunction keptHeaders(headers: Headers): [string, string][] {\n\treturn [...headers]\n\t\t.filter(([name]) => !PER_REQUEST.has(name) && !CDN_OWN.has(name))\n\t\t.toSorted(([first], [second]) => (first < second ? -1 : 1));\n}\n\n/** The path of the markdown twin in a `Link` header, if any. */\nfunction twinIn(link: string | null): string | undefined {\n\treturn /<(?<path>[^>]+)>;\\s*rel=\"alternate\";\\s*type=\"text\\/markdown\"/u.exec(link ?? \"\")?.groups\n\t\t?.path;\n}\n\n/** Why a CDN cannot keep `first`, or `undefined` when it can. */\nfunction uncacheable(first: Answer, allowedVary: ReadonlySet<string>): string | undefined {\n\tif (first.status !== 200) {\n\t\treturn `the status is ${first.status}`;\n\t}\n\tif (first.file == null) {\n\t\treturn \"the answer does not come from a prerendered file\";\n\t}\n\tif (!PLAIN_PATH.test(first.file)) {\n\t\treturn \"the file path has a character that a CDN route can match two ways\";\n\t}\n\tif (first.headers.has(\"set-cookie\")) {\n\t\treturn \"the answer sets a cookie\";\n\t}\n\t// Why each `CDN-Cache-Control` field: a CDN obeys it before `Cache-Control` (RFC 9213).\n\tfor (const [name, value] of first.headers) {\n\t\t// Why `i`: cache directives are case-insensitive.\n\t\tconst blocked = /\\b(?:private|no-store|no-cache)\\b/iu.exec(value);\n\t\tif (blocked != null && (name === \"cache-control\" || name.endsWith(\"cdn-cache-control\"))) {\n\t\t\treturn `the ${name} header has ${blocked[0]}`;\n\t\t}\n\t}\n\tif (first.headers.has(\"content-encoding\")) {\n\t\treturn \"the answer has a Content-Encoding\";\n\t}\n\tconst vary = (first.headers.get(\"vary\") ?? \"\")\n\t\t.split(\",\")\n\t\t.map((name) => name.trim().toLowerCase())\n\t\t.find((name) => name !== \"\" && !allowedVary.has(name));\n\treturn vary == null ? undefined : `the answer varies on ${vary}`;\n}\n\n/** Why `second` differs from `first`, or `undefined` when they match. */\nfunction difference(first: Answer, second: Answer): string | undefined {\n\tif (first.status !== second.status || first.file !== second.file) {\n\t\treturn \"the status or the file changes with the request\";\n\t}\n\tconst names = new Set(\n\t\t[...keptHeaders(first.headers), ...keptHeaders(second.headers)].map(([name]) => name),\n\t);\n\tconst changed = [...names].find((name) => first.headers.get(name) !== second.headers.get(name));\n\tif (changed != null) {\n\t\treturn `the ${changed} header changes with the request`;\n\t}\n\treturn sameBytes(first.body, second.body) ? undefined : \"the body changes with the request\";\n}\n\n/** Each subset of `names`, the empty one first. */\nfunction subsets(names: readonly string[]): string[][] {\n\tconst all: string[][] = [[]];\n\tfor (const name of names) {\n\t\tall.push(...all.map((subset) => [...subset, name]));\n\t}\n\treturn all;\n}\n\n/** The CDN answer of one path, or the reason that the server must answer it. */\nasync function staticPage(\n\tfetch: PipelineFetch,\n\tpath: string,\n\tpresence: readonly string[],\n): Promise<StaticPage> {\n\tif (!PLAIN_PATH.test(path)) {\n\t\treturn { path, reason: \"the path has a character that a CDN route can match two ways\" };\n\t}\n\t// Why: the build records a path with no trailing slash, and `trailingSlash: \"always\"` sends it on.\n\tconst probe = await answer(fetch, path, { client: CLIENTS[0], presence, present: [] });\n\tif (probe.status === 308 && probe.headers.get(\"location\") === `${path}/`) {\n\t\treturn staticPage(fetch, `${path}/`, presence);\n\t}\n\tif (presence.length > MAX_PRESENCE_HEADERS) {\n\t\treturn { path, reason: `more than ${MAX_PRESENCE_HEADERS} presence headers` };\n\t}\n\t// Why reuse the probe: it is the first client's answer with no presence header.\n\tconst firstAnswer = async (present: readonly string[]): Promise<Answer> =>\n\t\tpresent.length === 0 ? probe : answer(fetch, path, { client: CLIENTS[0], presence, present });\n\tconst answers: CdnPage[\"answers\"] = [];\n\tlet base: Answer | undefined;\n\tlet twin: string | undefined;\n\tfor (const present of subsets(presence)) {\n\t\tconst [first, second] = [\n\t\t\tawait firstAnswer(present),\n\t\t\tawait answer(fetch, path, { client: CLIENTS[1], presence, present }),\n\t\t];\n\t\tconst caseTwin = twinIn(first.headers.get(\"link\"));\n\t\tconst allowedVary = new Set([\n\t\t\t\"accept-encoding\",\n\t\t\t...presence,\n\t\t\t...(caseTwin == null ? [] : [\"accept\"]),\n\t\t]);\n\t\tconst reason = uncacheable(first, allowedVary) ?? difference(first, second);\n\t\tif (reason != null) {\n\t\t\treturn { path, reason };\n\t\t}\n\t\tif (base != null && (base.file !== first.file || !sameBytes(base.body, first.body))) {\n\t\t\treturn { path, reason: \"the body changes with a presence header\" };\n\t\t}\n\t\t// Why: the CDN routes send each markdown request of a page to the server, or none.\n\t\tif (base != null && caseTwin !== twin) {\n\t\t\treturn { path, reason: \"the markdown twin changes with a presence header\" };\n\t\t}\n\t\tbase ??= first;\n\t\ttwin = caseTwin;\n\t\tanswers.push({ present, headers: Object.fromEntries(keptHeaders(first.headers)) });\n\t}\n\tif (base?.file == null) {\n\t\treturn { path, reason: \"the answer does not come from a prerendered file\" };\n\t}\n\tif (twin != null && !PLAIN_PATH.test(twin)) {\n\t\treturn { path, reason: \"the twin path has a character that a CDN route can match two ways\" };\n\t}\n\treturn {\n\t\tpath,\n\t\tcdn: { file: base.file, body: base.body, answers, ...(twin == null ? {} : { twin }) },\n\t};\n}\n\n/**\n * Sends each prerendered path through the pipeline, and gives the paths that\n * a CDN can serve with no server. A path qualifies when its answer:\n *\n * - is a 200 from a prerendered file, with no cookie and no `private`,\n * `no-store`, or `no-cache`\n * - is the same, except for the request ID, for a second client with another\n * host, client address, query, and value of each presence header, and with\n * a cookie, `Authorization`, `Accept-Language`, and geo headers. Why: a CDN\n * route matches only the path, a markdown `Accept`, and the presence of\n * each presence header.\n * - varies only on `Accept-Encoding`, on `Accept` for a markdown twin, and on\n * the presence headers. Each case of the presence headers gets its own\n * headers, and all cases must send the same body.\n *\n * An auth check that refuses an anonymous request keeps its pages on the\n * server. Why: the first client sends no cookie and no `Authorization`.\n *\n * @yields Each path with its CDN answer, or with the reason that the server must answer it, in the order of `paths`.\n * @example\n * for await (const page of staticPages(fetch, [\"/\", \"/about\"], { presence: [\"x-ngrok-edge\"] })) {\n * \tconsole.log(page.path, \"cdn\" in page ? \"CDN\" : page.reason);\n * }\n */\nexport async function* staticPages(\n\tfetch: PipelineFetch,\n\tpaths: readonly string[],\n\t{ presence }: { presence: readonly string[] },\n): AsyncGenerator<StaticPage> {\n\tfor (const path of paths) {\n\t\tyield await staticPage(fetch, path, presence);\n\t}\n}\n","import type { MiddlewareHandler } from \"hono\";\nimport { DEFAULT_ASSETS_PATH, readBuildManifest } from \"./build-manifest.js\";\nimport { serverInternals } from \"./create-server.js\";\nimport type { AppServer } from \"./create-server.js\";\nimport { asError } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport { staticPages } from \"./static-pages.js\";\nimport type { StaticPage } from \"./static-pages.js\";\nimport { keptFiles } from \"./static-files.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHostRuntime,\n\tListenerBindings,\n\tMode,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 2;\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/**\n\t * Production: runs each plugin's `setup` and listens. When the host's\n\t * lifecycle stops, such as on `SIGTERM`, it shuts down.\n\t */\n\tstart: () => Promise<void>;\n\t/**\n\t * Production, for a serverless host: answers one request, and does not\n\t * listen. The first call runs each plugin's `setup`.\n\t */\n\tfetch: FetchHandler;\n\t/** Development: answers one request with the dev server inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tdevServer: MiddlewareHandler<AppServerEnv>,\n\t) => Promise<Response>;\n\t/**\n\t * Production, for a build step: each prerendered path, with the answer\n\t * that a content delivery network (CDN) can send with no server, or the\n\t * reason that the server must answer it. The first call runs each\n\t * plugin's `setup`. See `staticPages`.\n\t */\n\tstaticPages: () => AsyncGenerator<StaticPage>;\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/** Options for {@link createEntry}. */\nexport type CreateEntryOptions = {\n\t/** The app from `createServer`. */\n\tapp: AppServer;\n\t/** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */\n\thost: HostRuntime;\n\t/** Makes the run side of the framework adapter for a mode. */\n\tframework: (mode: Mode) => FrameworkRuntime;\n\t/**\n\t * The client build, as a file path or a `file:` URL. The entry that the\n\t * Vite plugin generates sets it.\n\t * @default the framework's `clientDirectory`\n\t */\n\tclientDirectory?: string;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer`, the\n * host, and the framework adapter for each mode. The `appServer` Vite plugin\n * generates this export. Call this for a build without the plugin.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport function createEntry({\n\tapp,\n\thost,\n\tframework,\n\tclientDirectory,\n}: CreateEntryOptions): 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\tinternals.setRequestStore(host.storage);\n\tconst setupInfo = async (runtime: FrameworkRuntime) => {\n\t\tconst directory = clientDirectory ?? runtime.clientDirectory;\n\t\tif (directory == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`,\n\t\t\t);\n\t\t}\n\t\tconst files = host.files(directory);\n\t\treturn {\n\t\t\tfiles,\n\t\t\tisDataRequest: runtime.isDataRequest ?? (() => false),\n\t\t\tcontentTypes: runtime.contentTypes ?? {},\n\t\t\tgzip: host.gzip,\n\t\t\tbrotli: host.brotli,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\tlet prerenderedPaths: readonly string[] = [];\n\t/** Runs each plugin's `setup` for production, and gives the framework's run side. */\n\tconst prepareProduction = async (): Promise<FrameworkRuntime> => {\n\t\tconst runtime = framework(\"production\");\n\t\tconst shared = await setupInfo(runtime);\n\t\tconst snapshot = await shared.files.snapshot?.();\n\t\t// Why only with a snapshot: it promises that the client build does not change while the server runs.\n\t\tconst files = snapshot == null ? shared.files : keptFiles(snapshot);\n\t\tconst manifest = await readBuildManifest(files);\n\t\tconst info: SetupInfo = {\n\t\t\t...shared,\n\t\t\tfiles,\n\t\t\tmode: \"production\",\n\t\t\tprerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,\n\t\t\tcapturedHeaders: new Map(Object.entries(manifest.headers)),\n\t\t\tscriptHashes: new Map(Object.entries(manifest.scriptHashes)),\n\t\t\tbuildId: manifest.buildId,\n\t\t\tassetsPath: manifest.assetsPath ?? DEFAULT_ASSETS_PATH,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\t({ prerenderedPaths } = info);\n\t\treturn runtime;\n\t};\n\tlet preparing: Promise<FrameworkRuntime> | undefined;\n\t/**\n\t * The production run side, set up once. Why forget a failure: a serverless\n\t * instance stays up, so the next request runs each `setup` again.\n\t */\n\tconst production = async (): Promise<FrameworkRuntime> => {\n\t\tpreparing ??= prepareProduction().catch((error: unknown) => {\n\t\t\tpreparing = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\treturn preparing;\n\t};\n\tlet development: FrameworkRuntime | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst runtime = await production();\n\t\t\tconst server = await internals.listen(runtime, host.listeners?.());\n\t\t\thost.lifecycle?.onStop(async () =>\n\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\tinternals.logger.log({\n\t\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\t\tmessage: \"shutdown failed\",\n\t\t\t\t\t\tattributes: { error: asError(error) },\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tfetch: async (request, bindings) => {\n\t\t\t// Why log it: the host sends a 500 with no log, and no app handler runs before setup ends.\n\t\t\tconst runtime = await production().catch((error: unknown) => {\n\t\t\t\tinternals.logger.log({\n\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\tmessage: \"setup failed\",\n\t\t\t\t\tattributes: { error: asError(error) },\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: runtime });\n\t\t},\n\t\tfetchDev: async (request, bindings, devServer) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\t...(await setupInfo(development)),\n\t\t\t\tmode: \"development\",\n\t\t\t\tdevServer,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tcapturedHeaders: new Map(),\n\t\t\t\tscriptHashes: new Map(),\n\t\t\t\t// Why none: development has no client build, and Vite's HMR updates an open tab after each edit.\n\t\t\t\tbuildId: undefined,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tasync *staticPages() {\n\t\t\tconst runtime = await production();\n\t\t\tyield* staticPages(\n\t\t\t\tasync (request, bindings) => app.fetch(request, { ...bindings, framework: runtime }),\n\t\t\t\tprerenderedPaths,\n\t\t\t\t{ presence: internals.presenceHeaders },\n\t\t\t);\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\n/**\n * Whether a value is an entry of this protocol version.\n *\n * @example\n * isAppServerEntry((await import(\"./build/server/app-server.js\")).appServer); // => true\n */\nexport function 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"],"mappings":";;;;;;;AAiCA,MAAM,8BAAc,IAAI,IAAI,CAAC,gBAAgB,MAAM,CAAC;;AAGpD,MAAM,0BAAU,IAAI,IAAI;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,aAAa;;AAGnB,MAAM,uBAAuB;;;;;;;;;;AAmB7B,MAA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OAAO,UAAmB;IAC5D,UAAU,OAAO,IAAI;KACpB,OAAO;KACP,SAAS;KACT,YAAY,EAAE,OAAO,QAAQ,KAAK,EAAE;IACrC,CAAC;IACD,MAAM;GACP,CAAC;GACD,OAAO,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAQ,CAAC;EAC9D;EACA,UAAU,OAAO,SAAS,UAAU,cAAc;GACjD,gBAAgB,UAAU,aAAa;GACvC,MAAM,UAAU,QAAQ;IACvB,GAAI,MAAM,UAAU,WAAW;IAC/B,MAAM;IACN;IACA,kBAAkB,YAAY;IAC9B,iCAAiB,IAAI,IAAI;IACzB,8BAAc,IAAI,IAAI;IAEtB,SAAS;GACV,CAAC;GACD,OAAO,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAY,CAAC;EAClE;EACA,OAAO,cAAc;GACpB,MAAM,UAAU,MAAM,WAAW;GACjC,OAAO,YACN,OAAO,SAAS,aAAa,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAQ,CAAC,GACnF,kBACA,EAAE,UAAU,UAAU,gBAAgB,CACvC;EACD;EACA,aAAa,UAAU;EACvB;CACD;AACD;;;;;;;AAQA,SAAgB,iBAAiB,OAAyC;CACzE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { _ as Mode, a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, r as FetchHandler, t as AppServerEnv } from "./types-
|
|
2
|
-
import { t as AppServer } from "./create-server-
|
|
1
|
+
import { _ as Mode, a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, r as FetchHandler, t as AppServerEnv } from "./types-MgFtkNQW.js";
|
|
2
|
+
import { t as AppServer } from "./create-server-X2GR-U6t.js";
|
|
3
3
|
import { MiddlewareHandler } from "hono";
|
|
4
4
|
/** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */
|
|
5
5
|
type CdnPage = {
|
|
@@ -91,4 +91,4 @@ type CreateEntryOptions = {
|
|
|
91
91
|
*/
|
|
92
92
|
declare function createEntry({ app, host, framework, clientDirectory }: CreateEntryOptions): AppServerEntry;
|
|
93
93
|
export { CreateEntryOptions as n, createEntry as r, AppServerEntry as t };
|
|
94
|
-
//# sourceMappingURL=entry-
|
|
94
|
+
//# sourceMappingURL=entry-DZTCaL3d.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as SentResponse, D as StaticFiles, E as StartedListener, O as ResponseEdge, S as ResponseHeaders, T as SetupInfo, _ as Mode, a as FrameworkRuntime, b as RequestLogger, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as LogSink, h as LogOptions, i as FileInfo, l as Lifecycle, m as LogLine, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as Plugin, w as ServerBindings, x as RequestStore, y as RequestContext } from "./types-
|
|
2
|
-
import { A as buildId, C as RedirectRule, D as HealthOptions, E as noindex, M as accessLog, O as health, S as securityHeaders, T as NoindexOptions, _ as requestId, a as createServer, b as SecurityHeadersOptions, c as assets, d as PUBLIC_ENV_SCRIPT_ID, f as RuntimeEnv, g as RequestIdOptions, h as runtimeEnv, i as RunningServer, j as AccessLogOptions, k as BuildIdOptions, l as prerendered, m as StandardSchemaV1, n as CreateServerOptions, o as defaultPlugins, p as RuntimeEnvOptions, r as DefaultPluginsOptions, s as PrerenderedOptions, t as AppServer, u as InferOutput, v as ContentSecurityPolicyOptions, w as redirects, x as contentSecurityPolicy, y as SecurityHeaderValues } from "./create-server-
|
|
3
|
-
import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-
|
|
4
|
-
import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-
|
|
1
|
+
import { C as SentResponse, D as StaticFiles, E as StartedListener, O as ResponseEdge, S as ResponseHeaders, T as SetupInfo, _ as Mode, a as FrameworkRuntime, b as RequestLogger, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as LogSink, h as LogOptions, i as FileInfo, l as Lifecycle, m as LogLine, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as Plugin, w as ServerBindings, x as RequestStore, y as RequestContext } from "./types-MgFtkNQW.js";
|
|
2
|
+
import { A as buildId, C as RedirectRule, D as HealthOptions, E as noindex, M as accessLog, O as health, S as securityHeaders, T as NoindexOptions, _ as requestId, a as createServer, b as SecurityHeadersOptions, c as assets, d as PUBLIC_ENV_SCRIPT_ID, f as RuntimeEnv, g as RequestIdOptions, h as runtimeEnv, i as RunningServer, j as AccessLogOptions, k as BuildIdOptions, l as prerendered, m as StandardSchemaV1, n as CreateServerOptions, o as defaultPlugins, p as RuntimeEnvOptions, r as DefaultPluginsOptions, s as PrerenderedOptions, t as AppServer, u as InferOutput, v as ContentSecurityPolicyOptions, w as redirects, x as contentSecurityPolicy, y as SecurityHeaderValues } from "./create-server-X2GR-U6t.js";
|
|
3
|
+
import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-D2QWKWEu.js";
|
|
4
|
+
import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-DZTCaL3d.js";
|
|
5
5
|
import { Context, Next } from "hono";
|
|
6
6
|
/** One server-sent event. */
|
|
7
7
|
type ServerSentEvent = {
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { i as jsonSink } from "./log-
|
|
2
|
-
import { r as requestContext, t as logger } from "./request-context-
|
|
1
|
+
import { i as jsonSink } from "./log-DQAS5gGT.js";
|
|
2
|
+
import { r as requestContext, t as logger } from "./request-context-Bxdbk5P1.js";
|
|
3
3
|
import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
|
|
4
4
|
import { r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
|
|
5
|
-
import { t as ResponseEdge } from "./response-edge-
|
|
6
|
-
import { _ as assets, a as streamingCompress, b as prefersMarkdown, c as securityHeaders, d as noindex, f as health, g as accessLog, h as bodyLimit, l as redirects, m as shutdownSignal, n as defaultPlugins, o as requestId, s as contentSecurityPolicy, t as createServer, u as privateDocuments, v as prerendered, y as trailingSlash } from "./create-server-
|
|
7
|
-
import { t as createEntry } from "./entry-
|
|
5
|
+
import { t as ResponseEdge } from "./response-edge-CU8ZvL_F.js";
|
|
6
|
+
import { _ as assets, a as streamingCompress, b as prefersMarkdown, c as securityHeaders, d as noindex, f as health, g as accessLog, h as bodyLimit, l as redirects, m as shutdownSignal, n as defaultPlugins, o as requestId, s as contentSecurityPolicy, t as createServer, u as privateDocuments, v as prerendered, y as trailingSlash } from "./create-server-Bp1yILQk.js";
|
|
7
|
+
import { t as createEntry } from "./entry-BoxCqc6w.js";
|
|
8
8
|
|
|
9
9
|
// src/core/event-stream.ts
|
|
10
10
|
function formatEvent({ data, event, id }) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as createServer } from "./create-server-
|
|
2
|
-
import { n as isAppServerEntry, t as createEntry } from "./entry-
|
|
3
|
-
import { t as host } from "./node-
|
|
1
|
+
import { t as createServer } from "./create-server-Bp1yILQk.js";
|
|
2
|
+
import { n as isAppServerEntry, t as createEntry } from "./entry-BoxCqc6w.js";
|
|
3
|
+
import { t as host } from "./node-CVVdk2N6.js";
|
|
4
4
|
|
|
5
5
|
// src/cli/load-entry.ts
|
|
6
6
|
/** Entries that this copy made for plain React Router builds, by build module. */
|
|
@@ -34,4 +34,4 @@ async function loadEntry(build) {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
export { loadEntry as t };
|
|
37
|
-
//# sourceMappingURL=load-entry-
|
|
37
|
+
//# sourceMappingURL=load-entry-CCPWbsrj.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-entry-
|
|
1
|
+
{"version":3,"file":"load-entry-CCPWbsrj.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\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 * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, 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 { isServerBuild, runtime } = await import(\"../react-router/index.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 = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,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,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
|
|
@@ -150,9 +150,13 @@ function isoNow() {
|
|
|
150
150
|
function asError(error) {
|
|
151
151
|
return error instanceof Error ? error : new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });
|
|
152
152
|
}
|
|
153
|
-
/**
|
|
153
|
+
/**
|
|
154
|
+
* The fields of an error that {@link errorFields} writes on its own, not as an
|
|
155
|
+
* own field. Why `kind`: an own `kind` must not replace the error's name.
|
|
156
|
+
*/
|
|
154
157
|
const ERROR_KEYS = /* @__PURE__ */ new Set([
|
|
155
158
|
"name",
|
|
159
|
+
"kind",
|
|
156
160
|
"message",
|
|
157
161
|
"stack",
|
|
158
162
|
"cause"
|
|
@@ -200,7 +204,11 @@ function errorFields(error, prefix) {
|
|
|
200
204
|
addError(fields, prefix, error);
|
|
201
205
|
return fields;
|
|
202
206
|
}
|
|
203
|
-
/**
|
|
207
|
+
/**
|
|
208
|
+
* `attributes` with each `Error` value replaced by its fields, after the
|
|
209
|
+
* `change` hook. Each other attribute, such as `http.method`, wins over an
|
|
210
|
+
* error field of the same name.
|
|
211
|
+
*/
|
|
204
212
|
function flattenErrors(attributes, change) {
|
|
205
213
|
let hasError = false;
|
|
206
214
|
for (const key in attributes) if (attributes[key] instanceof Error) {
|
|
@@ -209,7 +217,8 @@ function flattenErrors(attributes, change) {
|
|
|
209
217
|
}
|
|
210
218
|
if (!hasError) return attributes;
|
|
211
219
|
const flat = {};
|
|
212
|
-
|
|
220
|
+
const entries = Object.entries(attributes);
|
|
221
|
+
for (const [key, value] of entries) if (value instanceof Error) {
|
|
213
222
|
const fields = errorFields(value, key);
|
|
214
223
|
Object.assign(flat, change == null ? fields : change({
|
|
215
224
|
error: value,
|
|
@@ -217,6 +226,7 @@ function flattenErrors(attributes, change) {
|
|
|
217
226
|
fields
|
|
218
227
|
}));
|
|
219
228
|
} else flat[key] = value;
|
|
229
|
+
for (const [key, value] of entries) if (!(value instanceof Error)) flat[key] = value;
|
|
220
230
|
return flat;
|
|
221
231
|
}
|
|
222
232
|
/**
|
|
@@ -301,4 +311,4 @@ function requestLogger(sink, context) {
|
|
|
301
311
|
}
|
|
302
312
|
|
|
303
313
|
export { requestLogger as a, jsonSink as i, flushLogs as n, sinkLogger as o, hookSink as r, textSink as s, asError as t };
|
|
304
|
-
//# sourceMappingURL=log-
|
|
314
|
+
//# sourceMappingURL=log-DQAS5gGT.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log-CW_g1pWk.js","names":[],"sources":["../src/core/log.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogOptions, LogSink, RequestLogger } from \"./types.js\";\n\n/** The standard output (stdout) lines that wait for {@link flushLogs}. */\nlet pending = \"\";\n/** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */\nlet exiting = false;\n\n/** The libuv handle of stdout on Node.js. Bun and Deno have none. */\ntype StdoutHandle = { _handle?: { setBlocking?: (blocking: boolean) => number } };\n\n// Why: a process that crashes or calls `process.exit()` before the next turn keeps its last lines.\nprocess.on(\"exit\", () => {\n\texiting = true;\n\t// Why block: the exit drops a write that waits for a full pipe. On POSIX, a write to a file or\n\t// a terminal already blocks.\n\t// oxlint-disable-next-line no-underscore-dangle -- Node.js has no public way to block stdout.\n\t(process.stdout as NodeJS.WriteStream & StdoutHandle)._handle?.setBlocking?.(true);\n\t// Why one write for each line: Bun cannot block. Between small writes, the reader can empty the pipe.\n\tfor (const line of pending.match(/[^\\n]*\\n/gu) ?? []) {\n\t\tprocess.stdout.write(line);\n\t}\n\tpending = \"\";\n});\n\n/**\n * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it\n * before the process exits.\n */\nexport function flushLogs(): void {\n\tif (pending === \"\") {\n\t\treturn;\n\t}\n\tconst lines = pending;\n\tpending = \"\";\n\tprocess.stdout.write(lines);\n}\n\n/**\n * Adds `line` to the next stdout write. Why one write for each turn of the\n * event loop: a write to a pipe, such as stdout in Docker, is a system call,\n * and under load many requests end in one turn.\n */\nfunction writeStdout(line: string): void {\n\tif (exiting) {\n\t\tprocess.stdout.write(line);\n\t\treturn;\n\t}\n\tif (pending === \"\") {\n\t\tsetImmediate(flushLogs);\n\t}\n\tpending += line;\n}\n\n/** The end of a {@link jsonSink} line whose attributes have no JSON. */\nconst NO_JSON = '\"log.error\":\"attributes not written as JSON\"}';\n\n/**\n * A log sink that writes one JSON object per line. Each line has `time`,\n * `level`, `message`, and the flat attributes, which Datadog reads as its\n * standard attributes. The default writes the lines of one event-loop turn\n * to stdout at the end of the turn.\n *\n * @param write - Where each line goes. Defaults to stdout.\n *\n * @example\n * createServer({ logger: jsonSink() });\n * // {\"time\":\"2026-10-28T12:00:00.000Z\",\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200}\n */\nexport function jsonSink(write: (line: string) => void = writeStdout): LogSink {\n\treturn {\n\t\tlog: ({ level, message, attributes }) => {\n\t\t\tconst time = isoNow();\n\t\t\tconst head = `{\"time\":\"${time}\",\"level\":\"${level}\",\"message\":${JSON.stringify(message)}`;\n\t\t\t// Why the key check: a caller's `time`, `level`, or `message` replaces the sink's, as in a spread.\n\t\t\tconst ownKeys = \"time\" in attributes || \"level\" in attributes || \"message\" in attributes;\n\t\t\t// Why a splice, not one object: a copy of each attribute costs more than the rest of the line.\n\t\t\tconst json = toJson(ownKeys ? { time, level, message, ...attributes } : attributes);\n\t\t\tlet line = `${head},${NO_JSON}`;\n\t\t\tif (json != null) {\n\t\t\t\tline = ownKeys ? json : `${head}${json === \"{}\" ? \"}\" : `,${json.slice(1)}`}`;\n\t\t\t}\n\t\t\twrite(`${line}\\n`);\n\t\t},\n\t};\n}\n\n/**\n * A log sink that writes one line of `key=value` pairs per event, in the text\n * format of Go's `log/slog`. A value with a space, a quote, `=`, or a control\n * character is quoted, so an escape sequence cannot reach the terminal.\n * `app-server start` uses it, because a person reads those lines.\n *\n * @param write - Where each line goes. Defaults to stdout, at once. Why not\n * one write for each turn: the lines then keep their order with Vite's lines.\n *\n * @example\n * textSink().log({ level: \"info\", message: \"port in use, trying the next port\", attributes: { \"server.port\": 3000 } });\n * // time=2026-11-11T12:00:00.000Z level=INFO msg=\"port in use, trying the next port\" server.port=3000\n */\nexport function textSink(\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\tlet line = `time=${isoNow()} level=${level.toUpperCase()} msg=${textValue(message)}`;\n\t\t\tfor (const [key, value] of Object.entries(attributes)) {\n\t\t\t\tline += ` ${key}=${textValue(value)}`;\n\t\t\t}\n\t\t\twrite(`${line}\\n`);\n\t\t},\n\t};\n}\n\n/** A value of a {@link textSink} line. `JSON.stringify` escapes each control character. */\nfunction textValue(value: unknown): string {\n\tif (typeof value === \"bigint\") {\n\t\treturn `${value}n`;\n\t}\n\tconst text = typeof value === \"string\" ? value : (toJson(value) ?? String(value));\n\treturn /^[^\\s\"=\\p{Cc}]+$/u.test(text) ? text : JSON.stringify(text);\n}\n\n/**\n * `value` as JSON, with each bigint as a string such as `\"1n\"`, and each\n * cycle as `\"[Circular]\"`. Gives `undefined` for a value with no JSON, such\n * as a function, or one whose `toJSON` throws. Why try the plain call first:\n * the replacer runs for each value, and a log line seldom needs it.\n */\nfunction toJson(value: unknown): string | undefined {\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\ttry {\n\t\t\treturn JSON.stringify(value, safeReplacer());\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\n/** A `JSON.stringify` replacer for {@link toJson}. */\nfunction safeReplacer(): (this: unknown, key: string, value: unknown) => unknown {\n\t// Why the ancestors, not each object seen: an object that two fields share is not a cycle.\n\tconst ancestors: unknown[] = [];\n\treturn function replace(this: unknown, _key: string, value: unknown): unknown {\n\t\tif (typeof value === \"bigint\") {\n\t\t\treturn `${value}n`;\n\t\t}\n\t\tif (typeof value !== \"object\" || value == null) {\n\t\t\treturn value;\n\t\t}\n\t\t// Why `this`: it is the object that holds `value`, so each ancestor after it is done.\n\t\twhile (ancestors.length > 0 && ancestors.at(-1) !== this) {\n\t\t\tancestors.pop();\n\t\t}\n\t\tif (ancestors.includes(value)) {\n\t\t\treturn \"[Circular]\";\n\t\t}\n\t\tancestors.push(value);\n\t\treturn value;\n\t};\n}\n\n/** The millisecond of the last `time`, and its ISO string. */\nlet lastMs = Number.NaN;\nlet lastTime = \"\";\n/** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */\nlet lastSecond = Number.NaN;\nlet secondPrefix = \"\";\n\n/**\n * The time now, as `new Date().toISOString()` gives it. Why keep the last\n * time: under load, many lines share a millisecond. Why keep the prefix of\n * the second: `toISOString()` costs more than the rest of a line.\n */\nfunction isoNow(): string {\n\tconst now = Date.now();\n\tif (now !== lastMs) {\n\t\tlastMs = now;\n\t\tconst second = Math.floor(now / 1000);\n\t\tif (second !== lastSecond) {\n\t\t\tlastSecond = second;\n\t\t\tsecondPrefix = new Date(now).toISOString().slice(0, -4);\n\t\t}\n\t\tlastTime = `${secondPrefix}${String(now - second * 1000).padStart(3, \"0\")}Z`;\n\t}\n\treturn lastTime;\n}\n\ntype Attributes = Readonly<Record<string, unknown>>;\n\n/**\n * A thrown value as an `Error`, so a log line gives it the `error.*` fields.\n * Hono sends only an `Error` to `onError`, and rethrows any other value.\n */\nexport function asError(error: unknown): Error {\n\treturn error instanceof Error\n\t\t? error\n\t\t: new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });\n}\n\n/** The fields of an error that {@link errorFields} writes on its own, not as an own field. */\nconst ERROR_KEYS = new Set([\"name\", \"message\", \"stack\", \"cause\"]);\n\n/**\n * The dotted fields of `error` under `prefix`: `kind`, `message`, `stack`,\n * each own field, such as `code`, the `cause` chain, and the `errors` of an\n * `AggregateError`. An error with `toJSON` gives its own fields from it. An\n * error that is its own ancestor in the chain gives `\"[Circular]\"`.\n *\n * @example\n * errorFields(new Error(\"no row\", { cause: new RangeError(\"bad id\") }), \"error\");\n * // => { \"error.kind\": \"Error\", \"error.message\": \"no row\", \"error.stack\": \"…\",\n * // \"error.cause.kind\": \"RangeError\", \"error.cause.message\": \"bad id\", \"error.cause.stack\": \"…\" }\n */\nfunction errorFields(error: Error, prefix: string): Record<string, unknown> {\n\t// Why the ancestors, not each error seen: an error that two fields share is not a cycle.\n\tconst ancestors: Error[] = [];\n\tconst addError = (fields: Record<string, unknown>, base: string, current: Error): void => {\n\t\tconst at = (key: string) => (base === \"\" ? key : `${base}.${key}`);\n\t\tconst add = (key: string, value: unknown) => {\n\t\t\tif (!(value instanceof Error)) {\n\t\t\t\tfields[key] = value;\n\t\t\t} else if (ancestors.includes(value)) {\n\t\t\t\tfields[key] = \"[Circular]\";\n\t\t\t} else {\n\t\t\t\taddError(fields, key, value);\n\t\t\t}\n\t\t};\n\t\tancestors.push(current);\n\t\tfields[at(\"kind\")] = current.name;\n\t\tfields[at(\"message\")] = current.message;\n\t\tfields[at(\"stack\")] = current.stack;\n\t\tconst toJSON: unknown = \"toJSON\" in current ? current.toJSON : undefined;\n\t\tconst own: unknown =\n\t\t\ttypeof toJSON === \"function\" ? Reflect.apply(toJSON, current, []) : current;\n\t\tif (typeof own === \"object\" && own != null) {\n\t\t\tfor (const [key, value] of Object.entries(own)) {\n\t\t\t\tif (!ERROR_KEYS.has(key)) {\n\t\t\t\t\tadd(at(key), value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (current.cause != null) {\n\t\t\tadd(at(\"cause\"), current.cause);\n\t\t}\n\t\tif (current instanceof AggregateError) {\n\t\t\tfields[at(\"errors\")] = current.errors.map((member: unknown) => {\n\t\t\t\tif (!(member instanceof Error)) {\n\t\t\t\t\treturn member;\n\t\t\t\t}\n\t\t\t\tif (ancestors.includes(member)) {\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tconst memberFields: Record<string, unknown> = {};\n\t\t\t\taddError(memberFields, \"\", member);\n\t\t\t\treturn memberFields;\n\t\t\t});\n\t\t}\n\t\tancestors.pop();\n\t};\n\tconst fields: Record<string, unknown> = {};\n\taddError(fields, prefix, error);\n\treturn fields;\n}\n\n/** `attributes` with each `Error` value replaced by its fields, after the `change` hook. */\nfunction flattenErrors(attributes: Attributes, change: LogOptions[\"error\"]): Attributes {\n\t// Why look first: a line seldom holds an error, and then it needs no copy. Why `for...in`: it\n\t// makes no array, and costs about half of `Object.values(...).some(...)` for each line.\n\tlet hasError = false;\n\tfor (const key in attributes) {\n\t\tif (attributes[key] instanceof Error) {\n\t\t\thasError = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!hasError) {\n\t\treturn attributes;\n\t}\n\tconst flat: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(attributes)) {\n\t\tif (value instanceof Error) {\n\t\t\tconst fields = errorFields(value, key);\n\t\t\tObject.assign(flat, change == null ? fields : change({ error: value, prefix: key, fields }));\n\t\t} else {\n\t\t\tflat[key] = value;\n\t\t}\n\t}\n\treturn flat;\n}\n\n/**\n * A sink that writes each line to `sink`, after it replaces each `Error`\n * value with its fields, and then runs the `attributes` hook.\n *\n * @example\n * hookSink(jsonSink()).log({ level: \"error\", message: \"failed\", attributes: { error: new Error(\"boom\") } });\n * // {\"time\":\"…\",\"level\":\"error\",\"message\":\"failed\",\"error.kind\":\"Error\",\"error.message\":\"boom\",\"error.stack\":\"…\"}\n */\nexport function hookSink(\n\tsink: LogSink,\n\t{ attributes: changeAttributes, error: changeError }: LogOptions = {},\n): LogSink {\n\treturn {\n\t\tlog: (line) => {\n\t\t\tconst flat = flattenErrors(line.attributes, changeError);\n\t\t\t// Why keep `line` when nothing changes: a line seldom holds an error, and then it needs no copy.\n\t\t\tconst flatLine = flat === line.attributes ? line : { ...line, attributes: flat };\n\t\t\tsink.log(\n\t\t\t\tchangeAttributes == null\n\t\t\t\t\t? flatLine\n\t\t\t\t\t: { ...flatLine, attributes: changeAttributes(flatLine) },\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * A logger that writes to `sink`. `withBase` gives the attributes of each\n * line as a new object, from the attributes that the caller gives.\n */\nexport function sinkLogger(\n\tsink: LogSink,\n\twithBase: (attributes: Attributes) => Attributes = (attributes) => ({ ...attributes }),\n): RequestLogger {\n\t// Why four functions in one scope: a function that makes each one adds a scope for each, on each request.\n\treturn {\n\t\tdebug: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"debug\", message, attributes: withBase(attributes) });\n\t\t},\n\t\tinfo: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"info\", message, attributes: withBase(attributes) });\n\t\t},\n\t\twarn: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"warn\", message, attributes: withBase(attributes) });\n\t\t},\n\t\terror: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"error\", message, attributes: withBase(attributes) });\n\t\t},\n\t};\n}\n\n/**\n * A logger whose lines carry the request's ID, method, path, and\n * `logAttributes`. These fields win over a caller's field of the same name.\n */\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, (attributes) => {\n\t\tconst requestId = context.get(\"requestId\");\n\t\tconst { method, path } = context.req;\n\t\tconst logAttributes = context.get(\"logAttributes\");\n\t\tconst line: Record<string, unknown> = {\n\t\t\t\"http.request_id\": requestId,\n\t\t\t\"http.method\": method,\n\t\t\t\"http.url_details.path\": path,\n\t\t\t...logAttributes,\n\t\t\t...attributes,\n\t\t};\n\t\t// Why write them again, not merge a base object: a caller's field must not replace a request\n\t\t// field, and a merge copies each attribute two times. A key keeps its first place.\n\t\t// oxlint-disable-next-line unicorn/no-immediate-mutation -- the spread above must not win.\n\t\tline[\"http.request_id\"] = requestId;\n\t\tline[\"http.method\"] = method;\n\t\tline[\"http.url_details.path\"] = path;\n\t\tObject.assign(line, logAttributes);\n\t\treturn line;\n\t});\n}\n"],"mappings":";;AAIA,IAAI,UAAU;;AAEd,IAAI,UAAU;AAMd,QAAQ,GAAG,cAAc;CACxB,UAAU;CAIV,AAAC,QAAQ,OAA6C,SAAS,cAAc,IAAI;CAEjF,KAAK,MAAM,QAAQ,QAAQ,MAAM,YAAY,KAAK,CAAC,GAClD,QAAQ,OAAO,MAAM,IAAI;CAE1B,UAAU;AACX,CAAC;;;;;AAMD,SAAgB,YAAkB;CACjC,IAAI,YAAY,IACf;CAED,MAAM,QAAQ;CACd,UAAU;CACV,QAAQ,OAAO,MAAM,KAAK;AAC3B;;;;;;AAOA,SAAS,YAAY,MAAoB;CACxC,IAAI,SAAS;EACZ,QAAQ,OAAO,MAAM,IAAI;EACzB;CACD;CACA,IAAI,YAAY,IACf,aAAa,SAAS;CAEvB,WAAW;AACZ;;AAGA,MAAM,UAAU;;;;;;;;;;;;;AAchB,SAAgB,SAAS,QAAgC,aAAsB;CAC9E,OAAO,EACN,MAAM,EAAE,OAAO,SAAS,iBAAiB;EACxC,MAAM,OAAO,OAAO;EACpB,MAAM,OAAO,YAAY,KAAK,aAAa,MAAM,cAAc,KAA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O;CACR,CAAC;AACF"}
|
|
1
|
+
{"version":3,"file":"log-DQAS5gGT.js","names":[],"sources":["../src/core/log.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogOptions, LogSink, RequestLogger } from \"./types.js\";\n\n/** The standard output (stdout) lines that wait for {@link flushLogs}. */\nlet pending = \"\";\n/** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */\nlet exiting = false;\n\n/** The libuv handle of stdout on Node.js. Bun and Deno have none. */\ntype StdoutHandle = { _handle?: { setBlocking?: (blocking: boolean) => number } };\n\n// Why: a process that crashes or calls `process.exit()` before the next turn keeps its last lines.\nprocess.on(\"exit\", () => {\n\texiting = true;\n\t// Why block: the exit drops a write that waits for a full pipe. On POSIX, a write to a file or\n\t// a terminal already blocks.\n\t// oxlint-disable-next-line no-underscore-dangle -- Node.js has no public way to block stdout.\n\t(process.stdout as NodeJS.WriteStream & StdoutHandle)._handle?.setBlocking?.(true);\n\t// Why one write for each line: Bun cannot block. Between small writes, the reader can empty the pipe.\n\tfor (const line of pending.match(/[^\\n]*\\n/gu) ?? []) {\n\t\tprocess.stdout.write(line);\n\t}\n\tpending = \"\";\n});\n\n/**\n * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it\n * before the process exits.\n */\nexport function flushLogs(): void {\n\tif (pending === \"\") {\n\t\treturn;\n\t}\n\tconst lines = pending;\n\tpending = \"\";\n\tprocess.stdout.write(lines);\n}\n\n/**\n * Adds `line` to the next stdout write. Why one write for each turn of the\n * event loop: a write to a pipe, such as stdout in Docker, is a system call,\n * and under load many requests end in one turn.\n */\nfunction writeStdout(line: string): void {\n\tif (exiting) {\n\t\tprocess.stdout.write(line);\n\t\treturn;\n\t}\n\tif (pending === \"\") {\n\t\tsetImmediate(flushLogs);\n\t}\n\tpending += line;\n}\n\n/** The end of a {@link jsonSink} line whose attributes have no JSON. */\nconst NO_JSON = '\"log.error\":\"attributes not written as JSON\"}';\n\n/**\n * A log sink that writes one JSON object per line. Each line has `time`,\n * `level`, `message`, and the flat attributes, which Datadog reads as its\n * standard attributes. The default writes the lines of one event-loop turn\n * to stdout at the end of the turn.\n *\n * @param write - Where each line goes. Defaults to stdout.\n *\n * @example\n * createServer({ logger: jsonSink() });\n * // {\"time\":\"2026-10-28T12:00:00.000Z\",\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200}\n */\nexport function jsonSink(write: (line: string) => void = writeStdout): LogSink {\n\treturn {\n\t\tlog: ({ level, message, attributes }) => {\n\t\t\tconst time = isoNow();\n\t\t\tconst head = `{\"time\":\"${time}\",\"level\":\"${level}\",\"message\":${JSON.stringify(message)}`;\n\t\t\t// Why the key check: a caller's `time`, `level`, or `message` replaces the sink's, as in a spread.\n\t\t\tconst ownKeys = \"time\" in attributes || \"level\" in attributes || \"message\" in attributes;\n\t\t\t// Why a splice, not one object: a copy of each attribute costs more than the rest of the line.\n\t\t\tconst json = toJson(ownKeys ? { time, level, message, ...attributes } : attributes);\n\t\t\tlet line = `${head},${NO_JSON}`;\n\t\t\tif (json != null) {\n\t\t\t\tline = ownKeys ? json : `${head}${json === \"{}\" ? \"}\" : `,${json.slice(1)}`}`;\n\t\t\t}\n\t\t\twrite(`${line}\\n`);\n\t\t},\n\t};\n}\n\n/**\n * A log sink that writes one line of `key=value` pairs per event, in the text\n * format of Go's `log/slog`. A value with a space, a quote, `=`, or a control\n * character is quoted, so an escape sequence cannot reach the terminal.\n * `app-server start` uses it, because a person reads those lines.\n *\n * @param write - Where each line goes. Defaults to stdout, at once. Why not\n * one write for each turn: the lines then keep their order with Vite's lines.\n *\n * @example\n * textSink().log({ level: \"info\", message: \"port in use, trying the next port\", attributes: { \"server.port\": 3000 } });\n * // time=2026-11-11T12:00:00.000Z level=INFO msg=\"port in use, trying the next port\" server.port=3000\n */\nexport function textSink(\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\tlet line = `time=${isoNow()} level=${level.toUpperCase()} msg=${textValue(message)}`;\n\t\t\tfor (const [key, value] of Object.entries(attributes)) {\n\t\t\t\tline += ` ${key}=${textValue(value)}`;\n\t\t\t}\n\t\t\twrite(`${line}\\n`);\n\t\t},\n\t};\n}\n\n/** A value of a {@link textSink} line. `JSON.stringify` escapes each control character. */\nfunction textValue(value: unknown): string {\n\tif (typeof value === \"bigint\") {\n\t\treturn `${value}n`;\n\t}\n\tconst text = typeof value === \"string\" ? value : (toJson(value) ?? String(value));\n\treturn /^[^\\s\"=\\p{Cc}]+$/u.test(text) ? text : JSON.stringify(text);\n}\n\n/**\n * `value` as JSON, with each bigint as a string such as `\"1n\"`, and each\n * cycle as `\"[Circular]\"`. Gives `undefined` for a value with no JSON, such\n * as a function, or one whose `toJSON` throws. Why try the plain call first:\n * the replacer runs for each value, and a log line seldom needs it.\n */\nfunction toJson(value: unknown): string | undefined {\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\ttry {\n\t\t\treturn JSON.stringify(value, safeReplacer());\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\n/** A `JSON.stringify` replacer for {@link toJson}. */\nfunction safeReplacer(): (this: unknown, key: string, value: unknown) => unknown {\n\t// Why the ancestors, not each object seen: an object that two fields share is not a cycle.\n\tconst ancestors: unknown[] = [];\n\treturn function replace(this: unknown, _key: string, value: unknown): unknown {\n\t\tif (typeof value === \"bigint\") {\n\t\t\treturn `${value}n`;\n\t\t}\n\t\tif (typeof value !== \"object\" || value == null) {\n\t\t\treturn value;\n\t\t}\n\t\t// Why `this`: it is the object that holds `value`, so each ancestor after it is done.\n\t\twhile (ancestors.length > 0 && ancestors.at(-1) !== this) {\n\t\t\tancestors.pop();\n\t\t}\n\t\tif (ancestors.includes(value)) {\n\t\t\treturn \"[Circular]\";\n\t\t}\n\t\tancestors.push(value);\n\t\treturn value;\n\t};\n}\n\n/** The millisecond of the last `time`, and its ISO string. */\nlet lastMs = Number.NaN;\nlet lastTime = \"\";\n/** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */\nlet lastSecond = Number.NaN;\nlet secondPrefix = \"\";\n\n/**\n * The time now, as `new Date().toISOString()` gives it. Why keep the last\n * time: under load, many lines share a millisecond. Why keep the prefix of\n * the second: `toISOString()` costs more than the rest of a line.\n */\nfunction isoNow(): string {\n\tconst now = Date.now();\n\tif (now !== lastMs) {\n\t\tlastMs = now;\n\t\tconst second = Math.floor(now / 1000);\n\t\tif (second !== lastSecond) {\n\t\t\tlastSecond = second;\n\t\t\tsecondPrefix = new Date(now).toISOString().slice(0, -4);\n\t\t}\n\t\tlastTime = `${secondPrefix}${String(now - second * 1000).padStart(3, \"0\")}Z`;\n\t}\n\treturn lastTime;\n}\n\ntype Attributes = Readonly<Record<string, unknown>>;\n\n/**\n * A thrown value as an `Error`, so a log line gives it the `error.*` fields.\n * Hono sends only an `Error` to `onError`, and rethrows any other value.\n */\nexport function asError(error: unknown): Error {\n\treturn error instanceof Error\n\t\t? error\n\t\t: new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });\n}\n\n/**\n * The fields of an error that {@link errorFields} writes on its own, not as an\n * own field. Why `kind`: an own `kind` must not replace the error's name.\n */\nconst ERROR_KEYS = new Set([\"name\", \"kind\", \"message\", \"stack\", \"cause\"]);\n\n/**\n * The dotted fields of `error` under `prefix`: `kind`, `message`, `stack`,\n * each own field, such as `code`, the `cause` chain, and the `errors` of an\n * `AggregateError`. An error with `toJSON` gives its own fields from it. An\n * error that is its own ancestor in the chain gives `\"[Circular]\"`.\n *\n * @example\n * errorFields(new Error(\"no row\", { cause: new RangeError(\"bad id\") }), \"error\");\n * // => { \"error.kind\": \"Error\", \"error.message\": \"no row\", \"error.stack\": \"…\",\n * // \"error.cause.kind\": \"RangeError\", \"error.cause.message\": \"bad id\", \"error.cause.stack\": \"…\" }\n */\nfunction errorFields(error: Error, prefix: string): Record<string, unknown> {\n\t// Why the ancestors, not each error seen: an error that two fields share is not a cycle.\n\tconst ancestors: Error[] = [];\n\tconst addError = (fields: Record<string, unknown>, base: string, current: Error): void => {\n\t\tconst at = (key: string) => (base === \"\" ? key : `${base}.${key}`);\n\t\tconst add = (key: string, value: unknown) => {\n\t\t\tif (!(value instanceof Error)) {\n\t\t\t\tfields[key] = value;\n\t\t\t} else if (ancestors.includes(value)) {\n\t\t\t\tfields[key] = \"[Circular]\";\n\t\t\t} else {\n\t\t\t\taddError(fields, key, value);\n\t\t\t}\n\t\t};\n\t\tancestors.push(current);\n\t\tfields[at(\"kind\")] = current.name;\n\t\tfields[at(\"message\")] = current.message;\n\t\tfields[at(\"stack\")] = current.stack;\n\t\tconst toJSON: unknown = \"toJSON\" in current ? current.toJSON : undefined;\n\t\tconst own: unknown =\n\t\t\ttypeof toJSON === \"function\" ? Reflect.apply(toJSON, current, []) : current;\n\t\tif (typeof own === \"object\" && own != null) {\n\t\t\tfor (const [key, value] of Object.entries(own)) {\n\t\t\t\tif (!ERROR_KEYS.has(key)) {\n\t\t\t\t\tadd(at(key), value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (current.cause != null) {\n\t\t\tadd(at(\"cause\"), current.cause);\n\t\t}\n\t\tif (current instanceof AggregateError) {\n\t\t\tfields[at(\"errors\")] = current.errors.map((member: unknown) => {\n\t\t\t\tif (!(member instanceof Error)) {\n\t\t\t\t\treturn member;\n\t\t\t\t}\n\t\t\t\tif (ancestors.includes(member)) {\n\t\t\t\t\treturn \"[Circular]\";\n\t\t\t\t}\n\t\t\t\tconst memberFields: Record<string, unknown> = {};\n\t\t\t\taddError(memberFields, \"\", member);\n\t\t\t\treturn memberFields;\n\t\t\t});\n\t\t}\n\t\tancestors.pop();\n\t};\n\tconst fields: Record<string, unknown> = {};\n\taddError(fields, prefix, error);\n\treturn fields;\n}\n\n/**\n * `attributes` with each `Error` value replaced by its fields, after the\n * `change` hook. Each other attribute, such as `http.method`, wins over an\n * error field of the same name.\n */\nfunction flattenErrors(attributes: Attributes, change: LogOptions[\"error\"]): Attributes {\n\t// Why look first: a line seldom holds an error, and then it needs no copy. Why `for...in`: it\n\t// makes no array, and costs about half of `Object.values(...).some(...)` for each line.\n\tlet hasError = false;\n\tfor (const key in attributes) {\n\t\tif (attributes[key] instanceof Error) {\n\t\t\thasError = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!hasError) {\n\t\treturn attributes;\n\t}\n\tconst flat: Record<string, unknown> = {};\n\t// Why `Object.entries`: it gives only own fields, and both passes must read the same fields.\n\tconst entries = Object.entries(attributes);\n\tfor (const [key, value] of entries) {\n\t\tif (value instanceof Error) {\n\t\t\tconst fields = errorFields(value, key);\n\t\t\tObject.assign(flat, change == null ? fields : change({ error: value, prefix: key, fields }));\n\t\t} else {\n\t\t\tflat[key] = value;\n\t\t}\n\t}\n\t// Why write them again: an error field that comes later must not replace an attribute, such as\n\t// a request field. A key keeps its first place.\n\tfor (const [key, value] of entries) {\n\t\tif (!(value instanceof Error)) {\n\t\t\tflat[key] = value;\n\t\t}\n\t}\n\treturn flat;\n}\n\n/**\n * A sink that writes each line to `sink`, after it replaces each `Error`\n * value with its fields, and then runs the `attributes` hook.\n *\n * @example\n * hookSink(jsonSink()).log({ level: \"error\", message: \"failed\", attributes: { error: new Error(\"boom\") } });\n * // {\"time\":\"…\",\"level\":\"error\",\"message\":\"failed\",\"error.kind\":\"Error\",\"error.message\":\"boom\",\"error.stack\":\"…\"}\n */\nexport function hookSink(\n\tsink: LogSink,\n\t{ attributes: changeAttributes, error: changeError }: LogOptions = {},\n): LogSink {\n\treturn {\n\t\tlog: (line) => {\n\t\t\tconst flat = flattenErrors(line.attributes, changeError);\n\t\t\t// Why keep `line` when nothing changes: a line seldom holds an error, and then it needs no copy.\n\t\t\tconst flatLine = flat === line.attributes ? line : { ...line, attributes: flat };\n\t\t\tsink.log(\n\t\t\t\tchangeAttributes == null\n\t\t\t\t\t? flatLine\n\t\t\t\t\t: { ...flatLine, attributes: changeAttributes(flatLine) },\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * A logger that writes to `sink`. `withBase` gives the attributes of each\n * line as a new object, from the attributes that the caller gives.\n */\nexport function sinkLogger(\n\tsink: LogSink,\n\twithBase: (attributes: Attributes) => Attributes = (attributes) => ({ ...attributes }),\n): RequestLogger {\n\t// Why four functions in one scope: a function that makes each one adds a scope for each, on each request.\n\treturn {\n\t\tdebug: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"debug\", message, attributes: withBase(attributes) });\n\t\t},\n\t\tinfo: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"info\", message, attributes: withBase(attributes) });\n\t\t},\n\t\twarn: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"warn\", message, attributes: withBase(attributes) });\n\t\t},\n\t\terror: (message, attributes = {}) => {\n\t\t\tsink.log({ level: \"error\", message, attributes: withBase(attributes) });\n\t\t},\n\t};\n}\n\n/**\n * A logger whose lines carry the request's ID, method, path, and\n * `logAttributes`. These fields win over a caller's field of the same name.\n */\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, (attributes) => {\n\t\tconst requestId = context.get(\"requestId\");\n\t\tconst { method, path } = context.req;\n\t\tconst logAttributes = context.get(\"logAttributes\");\n\t\tconst line: Record<string, unknown> = {\n\t\t\t\"http.request_id\": requestId,\n\t\t\t\"http.method\": method,\n\t\t\t\"http.url_details.path\": path,\n\t\t\t...logAttributes,\n\t\t\t...attributes,\n\t\t};\n\t\t// Why write them again, not merge a base object: a caller's field must not replace a request\n\t\t// field, and a merge copies each attribute two times. A key keeps its first place.\n\t\t// oxlint-disable-next-line unicorn/no-immediate-mutation -- the spread above must not win.\n\t\tline[\"http.request_id\"] = requestId;\n\t\tline[\"http.method\"] = method;\n\t\tline[\"http.url_details.path\"] = path;\n\t\tObject.assign(line, logAttributes);\n\t\treturn line;\n\t});\n}\n"],"mappings":";;A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pC,KAAK,IAAI;IAAE,OAAO;IAAS;IAAS,YAAY,SAAS,UAAU;GAAE,CAAC;EACvE;EACA,OAAO,SAAS,aAAa,CAAC,MAAM;GACnC,KAAK,IAAI;IAAE,OAAO;IAAQ;IAAS,YAAY,SAAS,UAAU;GAAE,CAAC;EACtE;EACA,OAAO,SAAS,aAAa,CAAC,MAAM;GACnC,KAAK,IAAI;IAAE,OAAO;IAAQ;IAAS,YAAY,SAAS,UAAU;GAAE,CAAC;EACtE;EACA,QAAQ,SAAS,aAAa,CAAC,MAAM;GACpC,KAAK,IAAI;IAAE,OAAO;IAAS;IAAS,YAAY,SAAS,UAAU;GAAE,CAAC;EACvE;CACD;AACD;;;;;AAMA,SAAgB,cAAc,MAAe,SAA+C;CAE3F,OAAO,WAAW,OAAO,eAAe;EACvC,MAAM,YAAY,QAAQ,IAAI,WAAW;EACzC,MAAM,EAAE,QAAQ,SAAS,QAAQ;EACjC,MAAM,gBAAgB,QAAQ,IAAI,eAAe;EACjD,MAAM,OAAgC;GACrC,mBAAmB;GACnB,eAAe;GACf,yBAAyB;GACzB,GAAG;GACH,GAAG;EACJ;EAIA,KAAK,qBAAqB;EAC1B,KAAK,iBAAiB;EACtB,KAAK,2BAA2B;EAChC,OAAO,OAAO,MAAM,aAAa;EACjC,OAAO;CACR,CAAC;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as tcp } from "./tcp-
|
|
2
|
-
import { n as flushLogs } from "./log-
|
|
1
|
+
import { n as tcp } from "./tcp-BgDXbjOG.js";
|
|
2
|
+
import { n as flushLogs } from "./log-DQAS5gGT.js";
|
|
3
3
|
import { n as gzipStream, t as brotliStream } from "./compress-Cp5NfXCC.js";
|
|
4
4
|
import { t as publicScriptHashes } from "./script-hashes-CU7P9oZU.js";
|
|
5
5
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -331,4 +331,4 @@ const host = {
|
|
|
331
331
|
};
|
|
332
332
|
|
|
333
333
|
export { exitAfterFlush as i, devServerStage as n, nodeFiles as r, host as t };
|
|
334
|
-
//# sourceMappingURL=node-
|
|
334
|
+
//# sourceMappingURL=node-CVVdk2N6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-DiMwdTOC.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\nimport { flushLogs } from \"../core/log.js\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tflushLogs();\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { constants } from \"node:fs\";\nimport { access, open, readdir, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ByteRange, FileInfo, StaticFiles } from \"../core/types.js\";\n\n/** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */\nconst CHUNK_BYTES = 65_536;\n\n/**\n * A file's bytes, one chunk for each pull. With `range`, it reads only those\n * bytes. The file opens on the first pull and closes at the end, on an error,\n * or on cancel.\n *\n * Why open on the first pull: a stage can drop a response that no one reads,\n * such as when a later stage throws. Node.js 26 throws an uncaught error when\n * garbage collection closes an open `FileHandle`.\n */\nfunction fileStream(path: string, range: ByteRange | undefined): ReadableStream<Uint8Array> {\n\tlet handle: FileHandle | undefined;\n\tlet position = range?.start ?? 0;\n\tconst end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;\n\tconst close = async () => {\n\t\tconst opened = handle;\n\t\thandle = undefined;\n\t\tawait opened?.close();\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst length = Math.min(CHUNK_BYTES, end - position);\n\t\t\t\t\tif (length > 0) {\n\t\t\t\t\t\thandle ??= await open(path);\n\t\t\t\t\t}\n\t\t\t\t\tconst { bytesRead, buffer } =\n\t\t\t\t\t\tlength <= 0 || handle == null\n\t\t\t\t\t\t\t? { bytesRead: 0, buffer: new Uint8Array(0) }\n\t\t\t\t\t\t\t: await handle.read({ buffer: new Uint8Array(length), position });\n\t\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\t\tawait close();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition += bytesRead;\n\t\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: close,\n\t\t},\n\t\t// Why 0: the stream opens and reads nothing until the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** The bytes of `range` in the file at `path`, usually from one read. */\nasync function readRange(path: string, range: ByteRange): Promise<Uint8Array> {\n\tconst buffer = new Uint8Array(range.end - range.start + 1);\n\tconst handle = await open(path);\n\ttry {\n\t\tlet filled = 0;\n\t\t// Why a loop: a read can give fewer bytes than it asks for before the end of the file.\n\t\twhile (filled < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read({\n\t\t\t\tbuffer,\n\t\t\t\toffset: filled,\n\t\t\t\tposition: range.start + filled,\n\t\t\t});\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfilled += bytesRead;\n\t\t}\n\t\treturn buffer.subarray(0, filled);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\n/** A stream of one chunk. */\nfunction oneChunk(chunk: Uint8Array): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tif (chunk.byteLength > 0) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n}\n\n/** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */\nconst MISSING_CODES = new Set([\"ENOENT\", \"ENOTDIR\", \"ENAMETOOLONG\"]);\n\n/** The value of `promise`, or `undefined` when it fails because nothing is at its path. */\nasync function orMissing<T>(promise: Promise<T>): Promise<T | undefined> {\n\ttry {\n\t\treturn await promise;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && MISSING_CODES.has(String(error.code))) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The {@link FileInfo} of a file or a directory, else `undefined`. */\nfunction fileInfo(stats: Stats | undefined): FileInfo | undefined {\n\tif (stats?.isFile() === true) {\n\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\treturn stats?.isDirectory() === true\n\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t: undefined;\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * Its `snapshot` reads each file and directory once. It throws for an error\n * that does not mean a missing file, so the server does not start.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\tconst files: StaticFiles = {\n\t\tstat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),\n\t\topen: async (path, range) => {\n\t\t\tconst candidate = filePath(path);\n\t\t\tif (range != null && range.end - range.start < CHUNK_BYTES) {\n\t\t\t\treturn oneChunk(await readRange(candidate, range));\n\t\t\t}\n\t\t\t// Why: an unreadable file then gets a logged 500, not a 200 whose body fails. The check\n\t\t\t// holds no `FileHandle`, so a response that no one reads leaves nothing open.\n\t\t\tawait access(candidate, constants.R_OK);\n\t\t\treturn fileStream(candidate, range);\n\t\t},\n\t\tsnapshot: async () => {\n\t\t\tconst entries = new Map<string, FileInfo>();\n\t\t\t// Why the inodes of the parents: a symbolic link to a parent directory must not make the\n\t\t\t// walk endless. A link to another directory, such as a sibling, still lists its files.\n\t\t\tconst walk = async (\n\t\t\t\tpath: string,\n\t\t\t\tstats: Stats,\n\t\t\t\tparents: ReadonlySet<string>,\n\t\t\t): Promise<void> => {\n\t\t\t\tconst info = fileInfo(stats);\n\t\t\t\tif (info == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentries.set(path, info);\n\t\t\t\tconst inode = `${stats.dev}:${stats.ino}`;\n\t\t\t\tif (info.kind === \"file\" || parents.has(inode)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst inside = new Set(parents).add(inode);\n\t\t\t\tconst prefix = path === \"/\" ? \"\" : path;\n\t\t\t\t// Why: a deploy can remove a directory between its `stat` and this read.\n\t\t\t\tconst names = (await orMissing(readdir(filePath(path)))) ?? [];\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tnames.map(async (name) => {\n\t\t\t\t\t\tconst childPath = `${prefix}/${name}`;\n\t\t\t\t\t\tconst childStats = await orMissing(stat(filePath(childPath)));\n\t\t\t\t\t\tif (childStats != null) {\n\t\t\t\t\t\t\tawait walk(childPath, childStats, inside);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst rootStats = await orMissing(stat(root));\n\t\t\tif (rootStats != null) {\n\t\t\t\tawait walk(\"/\", rootStats, new Set());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstat: async (path) => {\n\t\t\t\t\tconst trimmed = path.length > 1 ? path.replace(/\\/$/u, \"\") : path;\n\t\t\t\t\tconst info = entries.get(trimmed);\n\t\t\t\t\t// Why only a directory after a `/`: as on the disk, `/docs/` finds `/docs`, and\n\t\t\t\t\t// `/llms.txt/` finds nothing.\n\t\t\t\t\treturn trimmed === path || info?.kind === \"directory\" ? info : undefined;\n\t\t\t\t},\n\t\t\t\topen: files.open,\n\t\t\t};\n\t\t},\n\t};\n\treturn files;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OutgoingHttpHeader, OutgoingHttpHeaders } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ListenerBindings, ResponseHeaders } from \"../core/types.js\";\nimport { publicScriptHashes } from \"./script-hashes.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Makes `outgoing` run `hooks` before it sends its head, and returns the\n * function that undoes it. Why `writeHead`: Node calls it for each\n * response, also from `write` and `end`.\n */\nfunction runHooksAtHead(outgoing: ServerResponse, hooks: readonly HeaderHook[]): () => void {\n\tconst headers: ResponseHeaders = {\n\t\tget: (name) => {\n\t\t\tconst value = outgoing.getHeader(name);\n\t\t\treturn value == null ? null : String(value);\n\t\t},\n\t\thas: (name) => outgoing.hasHeader(name),\n\t\tset: (name, value) => {\n\t\t\toutgoing.setHeader(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\toutgoing.removeHeader(name);\n\t\t},\n\t};\n\tconst writeHead = outgoing.writeHead.bind(outgoing);\n\toutgoing.writeHead = (\n\t\tstatusCode: number,\n\t\treason?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\tvalues?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t) => {\n\t\tconst [message, given] = typeof reason === \"string\" ? [reason, values] : [undefined, reason];\n\t\t// Why: the hooks must see the headers that `writeHead` gets, such as the content type of a file.\n\t\tif (Array.isArray(given)) {\n\t\t\t// Why remove, then append: Node reads a flat `[name, value, …]` list so. A name replaces the old value and can repeat.\n\t\t\tconst names = given.filter((_, index) => index % 2 === 0).map(String);\n\t\t\tfor (const name of names) {\n\t\t\t\toutgoing.removeHeader(name);\n\t\t\t}\n\t\t\tfor (const [index, name] of names.entries()) {\n\t\t\t\tconst value = given[index * 2 + 1];\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.appendHeader(name, typeof value === \"number\" ? String(value) : value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (given != null) {\n\t\t\tfor (const [name, value] of Object.entries(given)) {\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.setHeader(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Why reversed: in production, the hook of an inner stage runs first, so an outer stage has the last word.\n\t\tfor (const hook of hooks.toReversed()) {\n\t\t\thook(headers);\n\t\t}\n\t\treturn message == null ? writeHead(statusCode) : writeHead(statusCode, message);\n\t};\n\treturn () => {\n\t\toutgoing.writeHead = writeHead;\n\t};\n}\n\n/** Options for {@link devServerStage}. */\nexport type DevServerStageOptions = {\n\t/**\n\t * The directory that the middleware serves as it is, and the URL base that\n\t * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML\n\t * file from it gets the `contentSecurityPolicy` with the hashes of its\n\t * inline scripts, as it does in production. Why a function: a Vite restart\n\t * can change both.\n\t */\n\tpublicFiles?: () => { directory: string; base: string };\n};\n\n/** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */\nfunction publicFileHashes(\n\t{ directory, base }: { directory: string; base: string },\n\tpathname: string,\n): string[] | undefined {\n\tconst prefix = base.replace(/\\/$/u, \"\");\n\t// Why both forms: in middleware mode, Vite's base middleware passes a path with no base on as it is.\n\treturn publicScriptHashes(\n\t\tdirectory,\n\t\tpathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname,\n\t);\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {\n * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n * }));\n */\nexport function devServerStage(\n\tmiddleware: NodeMiddleware,\n\t{ publicFiles }: DevServerStageOptions = {},\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\tconst hashes =\n\t\t\tpublicFiles == null\n\t\t\t\t? undefined\n\t\t\t\t: publicFileHashes(publicFiles(), new URL(context.req.url).pathname);\n\t\tconst earlierHashes = context.get(\"documentScriptHashes\");\n\t\tif (hashes != null) {\n\t\t\tcontext.set(\"documentScriptHashes\", hashes);\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t\tconst undoHooks = runHooksAtHead(outgoing, hooks);\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\t// Why: the later stages answer, and each hook runs on their response.\n\t\t\t\tundoHooks();\n\t\t\t\t// Why: the middleware did not send the public file, so its hashes do not apply.\n\t\t\t\tif (hashes != null) {\n\t\t\t\t\tcontext.set(\"documentScriptHashes\", earlierHashes);\n\t\t\t\t}\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why empty the list: the hooks ran on the head that the middleware sent, so the server must\n\t\t\t// not run them again on the response below.\n\t\t\thooks.length = 0;\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and the\n\t\t\t// headers are the ones that the middleware sent, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\t\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\t\t\tif (each != null) {\n\t\t\t\t\t\theaders.append(name, String(each));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { brotliStream, gzipStream } from \"./compress.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tDevServerStageOptions,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tbrotli: brotliStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tstop()\n\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.finally(exitAfterFlush);\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t},\n};\n"],"mappings":";;;;;;;;;;;;;;;AAIA,MAAM,mBAAmB;;;;;;;;;AAUzB,SAAgB,iBAAuB;CACtC,UAAU;CACV,IAAI,UAAU;CACd,MAAM,aAAa;EAClB,WAAW;EACX,IAAI,YAAY,GACf,QAAQ,KAAK;CAEf;CACA,MAAM,QAAQ,QAAQ,IAAI;CAC1B,MAAM,QAAQ,QAAQ,IAAI;CAE1B,iBAAiB;EAChB,QAAQ,KAAK;CACd,GAAG,gBAAgB,CAAC,CAAC,MAAM;AAC5B;;AAGA,SAAS,MAAM,QAA4B,MAAwB;CAClE,IAAI,SAAS,YAAY;EAGxB,OAAO,IAAI,IAAI;EACf;CACD;CAGA,OAAO,MAAM,IAAI,IAAI;AACtB;;;;ACjCA,MAAM,cAAc;;;;;;;;;;AAWpB,SAAS,WAAW,MAAc,OAA0D;CAC3F,IAAI;CACJ,IAAI,WAAW,OAAO,SAAS;CAC/B,MAAM,MAAM,SAAS,OAAO,OAAO,oBAAoB,MAAM,MAAM;CACnE,MAAM,QAAQ,YAAY;EACzB,MAAM,SAAS;EACf,SAAS;EACT,MAAM,QAAQ,MAAM;CACrB;CACA,OAAO,IAAI,eACV;EACC,MAAM,KAAK,YAAY;GACtB,IAAI;IACH,MAAM,SAAS,KAAK,IAAI,aAAa,MAAM,QAAQ;IACnD,IAAI,SAAS,GACZ,WAAW,MAAM,KAAK,IAAI;IAE3B,MAAM,EAAE,WAAW,WAClB,UAAU,KAAK,UAAU,OACtB;KAAE,WAAW;KAAG,wBAAQ,IAAI,WAAW,CAAC;IAAE,IAC1C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AC,CAAC,CACD,QAAQ,cAAc;EACzB,CAAC;CAEH,EACD;AACD"}
|
|
1
|
+
{"version":3,"file":"node-CVVdk2N6.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\nimport { flushLogs } from \"../core/log.js\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tflushLogs();\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { constants } from \"node:fs\";\nimport { access, open, readdir, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ByteRange, FileInfo, StaticFiles } from \"../core/types.js\";\n\n/** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */\nconst CHUNK_BYTES = 65_536;\n\n/**\n * A file's bytes, one chunk for each pull. With `range`, it reads only those\n * bytes. The file opens on the first pull and closes at the end, on an error,\n * or on cancel.\n *\n * Why open on the first pull: a stage can drop a response that no one reads,\n * such as when a later stage throws. Node.js 26 throws an uncaught error when\n * garbage collection closes an open `FileHandle`.\n */\nfunction fileStream(path: string, range: ByteRange | undefined): ReadableStream<Uint8Array> {\n\tlet handle: FileHandle | undefined;\n\tlet position = range?.start ?? 0;\n\tconst end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;\n\tconst close = async () => {\n\t\tconst opened = handle;\n\t\thandle = undefined;\n\t\tawait opened?.close();\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst length = Math.min(CHUNK_BYTES, end - position);\n\t\t\t\t\tif (length > 0) {\n\t\t\t\t\t\thandle ??= await open(path);\n\t\t\t\t\t}\n\t\t\t\t\tconst { bytesRead, buffer } =\n\t\t\t\t\t\tlength <= 0 || handle == null\n\t\t\t\t\t\t\t? { bytesRead: 0, buffer: new Uint8Array(0) }\n\t\t\t\t\t\t\t: await handle.read({ buffer: new Uint8Array(length), position });\n\t\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\t\tawait close();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition += bytesRead;\n\t\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: close,\n\t\t},\n\t\t// Why 0: the stream opens and reads nothing until the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** The bytes of `range` in the file at `path`, usually from one read. */\nasync function readRange(path: string, range: ByteRange): Promise<Uint8Array> {\n\tconst buffer = new Uint8Array(range.end - range.start + 1);\n\tconst handle = await open(path);\n\ttry {\n\t\tlet filled = 0;\n\t\t// Why a loop: a read can give fewer bytes than it asks for before the end of the file.\n\t\twhile (filled < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read({\n\t\t\t\tbuffer,\n\t\t\t\toffset: filled,\n\t\t\t\tposition: range.start + filled,\n\t\t\t});\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfilled += bytesRead;\n\t\t}\n\t\treturn buffer.subarray(0, filled);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\n/** A stream of one chunk. */\nfunction oneChunk(chunk: Uint8Array): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tif (chunk.byteLength > 0) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n}\n\n/** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */\nconst MISSING_CODES = new Set([\"ENOENT\", \"ENOTDIR\", \"ENAMETOOLONG\"]);\n\n/** The value of `promise`, or `undefined` when it fails because nothing is at its path. */\nasync function orMissing<T>(promise: Promise<T>): Promise<T | undefined> {\n\ttry {\n\t\treturn await promise;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && MISSING_CODES.has(String(error.code))) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The {@link FileInfo} of a file or a directory, else `undefined`. */\nfunction fileInfo(stats: Stats | undefined): FileInfo | undefined {\n\tif (stats?.isFile() === true) {\n\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\treturn stats?.isDirectory() === true\n\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t: undefined;\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * Its `snapshot` reads each file and directory once. It throws for an error\n * that does not mean a missing file, so the server does not start.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\tconst files: StaticFiles = {\n\t\tstat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),\n\t\topen: async (path, range) => {\n\t\t\tconst candidate = filePath(path);\n\t\t\tif (range != null && range.end - range.start < CHUNK_BYTES) {\n\t\t\t\treturn oneChunk(await readRange(candidate, range));\n\t\t\t}\n\t\t\t// Why: an unreadable file then gets a logged 500, not a 200 whose body fails. The check\n\t\t\t// holds no `FileHandle`, so a response that no one reads leaves nothing open.\n\t\t\tawait access(candidate, constants.R_OK);\n\t\t\treturn fileStream(candidate, range);\n\t\t},\n\t\tsnapshot: async () => {\n\t\t\tconst entries = new Map<string, FileInfo>();\n\t\t\t// Why the inodes of the parents: a symbolic link to a parent directory must not make the\n\t\t\t// walk endless. A link to another directory, such as a sibling, still lists its files.\n\t\t\tconst walk = async (\n\t\t\t\tpath: string,\n\t\t\t\tstats: Stats,\n\t\t\t\tparents: ReadonlySet<string>,\n\t\t\t): Promise<void> => {\n\t\t\t\tconst info = fileInfo(stats);\n\t\t\t\tif (info == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentries.set(path, info);\n\t\t\t\tconst inode = `${stats.dev}:${stats.ino}`;\n\t\t\t\tif (info.kind === \"file\" || parents.has(inode)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst inside = new Set(parents).add(inode);\n\t\t\t\tconst prefix = path === \"/\" ? \"\" : path;\n\t\t\t\t// Why: a deploy can remove a directory between its `stat` and this read.\n\t\t\t\tconst names = (await orMissing(readdir(filePath(path)))) ?? [];\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tnames.map(async (name) => {\n\t\t\t\t\t\tconst childPath = `${prefix}/${name}`;\n\t\t\t\t\t\tconst childStats = await orMissing(stat(filePath(childPath)));\n\t\t\t\t\t\tif (childStats != null) {\n\t\t\t\t\t\t\tawait walk(childPath, childStats, inside);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst rootStats = await orMissing(stat(root));\n\t\t\tif (rootStats != null) {\n\t\t\t\tawait walk(\"/\", rootStats, new Set());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstat: async (path) => {\n\t\t\t\t\tconst trimmed = path.length > 1 ? path.replace(/\\/$/u, \"\") : path;\n\t\t\t\t\tconst info = entries.get(trimmed);\n\t\t\t\t\t// Why only a directory after a `/`: as on the disk, `/docs/` finds `/docs`, and\n\t\t\t\t\t// `/llms.txt/` finds nothing.\n\t\t\t\t\treturn trimmed === path || info?.kind === \"directory\" ? info : undefined;\n\t\t\t\t},\n\t\t\t\topen: files.open,\n\t\t\t};\n\t\t},\n\t};\n\treturn files;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OutgoingHttpHeader, OutgoingHttpHeaders } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ListenerBindings, ResponseHeaders } from \"../core/types.js\";\nimport { publicScriptHashes } from \"./script-hashes.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Makes `outgoing` run `hooks` before it sends its head, and returns the\n * function that undoes it. Why `writeHead`: Node calls it for each\n * response, also from `write` and `end`.\n */\nfunction runHooksAtHead(outgoing: ServerResponse, hooks: readonly HeaderHook[]): () => void {\n\tconst headers: ResponseHeaders = {\n\t\tget: (name) => {\n\t\t\tconst value = outgoing.getHeader(name);\n\t\t\treturn value == null ? null : String(value);\n\t\t},\n\t\thas: (name) => outgoing.hasHeader(name),\n\t\tset: (name, value) => {\n\t\t\toutgoing.setHeader(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\toutgoing.removeHeader(name);\n\t\t},\n\t};\n\tconst writeHead = outgoing.writeHead.bind(outgoing);\n\toutgoing.writeHead = (\n\t\tstatusCode: number,\n\t\treason?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\tvalues?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t) => {\n\t\tconst [message, given] = typeof reason === \"string\" ? [reason, values] : [undefined, reason];\n\t\t// Why: the hooks must see the headers that `writeHead` gets, such as the content type of a file.\n\t\tif (Array.isArray(given)) {\n\t\t\t// Why remove, then append: Node reads a flat `[name, value, …]` list so. A name replaces the old value and can repeat.\n\t\t\tconst names = given.filter((_, index) => index % 2 === 0).map(String);\n\t\t\tfor (const name of names) {\n\t\t\t\toutgoing.removeHeader(name);\n\t\t\t}\n\t\t\tfor (const [index, name] of names.entries()) {\n\t\t\t\tconst value = given[index * 2 + 1];\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.appendHeader(name, typeof value === \"number\" ? String(value) : value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (given != null) {\n\t\t\tfor (const [name, value] of Object.entries(given)) {\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.setHeader(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Why reversed: in production, the hook of an inner stage runs first, so an outer stage has the last word.\n\t\tfor (const hook of hooks.toReversed()) {\n\t\t\thook(headers);\n\t\t}\n\t\treturn message == null ? writeHead(statusCode) : writeHead(statusCode, message);\n\t};\n\treturn () => {\n\t\toutgoing.writeHead = writeHead;\n\t};\n}\n\n/** Options for {@link devServerStage}. */\nexport type DevServerStageOptions = {\n\t/**\n\t * The directory that the middleware serves as it is, and the URL base that\n\t * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML\n\t * file from it gets the `contentSecurityPolicy` with the hashes of its\n\t * inline scripts, as it does in production. Why a function: a Vite restart\n\t * can change both.\n\t */\n\tpublicFiles?: () => { directory: string; base: string };\n};\n\n/** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */\nfunction publicFileHashes(\n\t{ directory, base }: { directory: string; base: string },\n\tpathname: string,\n): string[] | undefined {\n\tconst prefix = base.replace(/\\/$/u, \"\");\n\t// Why both forms: in middleware mode, Vite's base middleware passes a path with no base on as it is.\n\treturn publicScriptHashes(\n\t\tdirectory,\n\t\tpathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname,\n\t);\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {\n * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n * }));\n */\nexport function devServerStage(\n\tmiddleware: NodeMiddleware,\n\t{ publicFiles }: DevServerStageOptions = {},\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\tconst hashes =\n\t\t\tpublicFiles == null\n\t\t\t\t? undefined\n\t\t\t\t: publicFileHashes(publicFiles(), new URL(context.req.url).pathname);\n\t\tconst earlierHashes = context.get(\"documentScriptHashes\");\n\t\tif (hashes != null) {\n\t\t\tcontext.set(\"documentScriptHashes\", hashes);\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t\tconst undoHooks = runHooksAtHead(outgoing, hooks);\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\t// Why: the later stages answer, and each hook runs on their response.\n\t\t\t\tundoHooks();\n\t\t\t\t// Why: the middleware did not send the public file, so its hashes do not apply.\n\t\t\t\tif (hashes != null) {\n\t\t\t\t\tcontext.set(\"documentScriptHashes\", earlierHashes);\n\t\t\t\t}\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why empty the list: the hooks ran on the head that the middleware sent, so the server must\n\t\t\t// not run them again on the response below.\n\t\t\thooks.length = 0;\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and the\n\t\t\t// headers are the ones that the middleware sent, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\t\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\t\t\tif (each != null) {\n\t\t\t\t\t\theaders.append(name, String(each));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { brotliStream, gzipStream } from \"./compress.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tDevServerStageOptions,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tbrotli: brotliStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n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,4 +1,4 @@
|
|
|
1
|
-
import { t as requestListener } from "./response-writer-
|
|
1
|
+
import { t as requestListener } from "./response-writer-D7KHfr8n.js";
|
|
2
2
|
import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
|
|
3
3
|
import { createServer } from "node:http";
|
|
4
4
|
|
|
@@ -38,4 +38,4 @@ async function listen(fetch, options) {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
export { listen };
|
|
41
|
-
//# sourceMappingURL=node-
|
|
41
|
+
//# sourceMappingURL=node-D6m6e6EI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-
|
|
1
|
+
{"version":3,"file":"node-D6m6e6EI.js","names":[],"sources":["../src/node/runtimes/node.ts"],"sourcesContent":["import { createServer } from \"node:http\";\nimport type { FetchHandler, StartedListener } from \"../../core/types.js\";\nimport { requestListener } from \"../response-writer.js\";\nimport { listenerUrl } from \"./listen-options.js\";\nimport type { ListenOptions } from \"./listen-options.js\";\n\n/** Listens with `node:http`, and writes each response with the node response writer. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\tconst listener = requestListener(fetch, { trustForwardedProto: options.trustForwardedProto });\n\tconst server = createServer(\n\t\t{\n\t\t\tkeepAliveTimeout: options.idleTimeoutMs,\n\t\t\t// Why above the keep-alive timeout: Node closes a socket that is between requests when its\n\t\t\t// headers timer runs out first.\n\t\t\theadersTimeout: options.idleTimeoutMs + 1_000,\n\t\t},\n\t\t(incoming, outgoing) => {\n\t\t\tvoid listener(incoming, outgoing);\n\t\t},\n\t);\n\tawait new Promise<void>((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(options.port, options.hostname, () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\tconst address = server.address();\n\tconst port = typeof address === \"object\" && address != null ? address.port : options.port;\n\treturn {\n\t\turl: listenerUrl(options.hostname, port),\n\t\tstop: async ({ deadlineMs }) =>\n\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\tserver.closeAllConnections();\n\t\t\t\t}, deadlineMs);\n\t\t\t\tserver.close((error) => {\n\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\tif (error == null) {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tserver.closeIdleConnections();\n\t\t\t}),\n\t};\n}\n"],"mappings":";;;;;;AAOA,eAAsB,OACrB,OACA,SAC2B;CAC3B,MAAM,WAAW,gBAAgB,OAAO,EAAE,qBAAqB,QAAQ,oBAAoB,CAAC;CAC5F,MAAM,SAAS,aACd;EACC,kBAAkB,QAAQ;EAG1B,gBAAgB,QAAQ,gBAAgB;CACzC,IACC,UAAU,aAAa;EACvB,AAAK,SAAS,UAAU,QAAQ;CACjC,CACD;CACA,MAAM,IAAI,SAAe,SAAS,WAAW;EAC5C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,QAAQ,MAAM,QAAQ,gBAAgB;GACnD,OAAO,IAAI,SAAS,MAAM;GAC1B,QAAQ;EACT,CAAC;CACF,CAAC;CACD,MAAM,UAAU,OAAO,QAAQ;CAC/B,MAAM,OAAO,OAAO,YAAY,YAAY,WAAW,OAAO,QAAQ,OAAO,QAAQ;CACrF,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,IAAI;EACvC,MAAM,OAAO,EAAE,iBACd,IAAI,SAAe,SAAS,WAAW;GACtC,MAAM,WAAW,iBAAiB;IACjC,OAAO,oBAAoB;GAC5B,GAAG,UAAU;GACb,OAAO,OAAO,UAAU;IACvB,aAAa,QAAQ;IACrB,IAAI,SAAS,MACZ,QAAQ;SAER,OAAO,KAAK;GAEd,CAAC;GACD,OAAO,qBAAqB;EAC7B,CAAC;CACH;AACD"}
|
package/dist/node.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-
|
|
1
|
+
import { D as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-MgFtkNQW.js";
|
|
2
2
|
import { MiddlewareHandler } from "hono";
|
|
3
3
|
import { IncomingMessage, ServerResponse } from "node:http";
|
|
4
4
|
/** A Connect middleware, such as `vite.middlewares`. */
|
package/dist/node.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as tcp, t as parsePort } from "./tcp-
|
|
2
|
-
import { n as devServerStage, r as nodeFiles, t as host } from "./node-
|
|
1
|
+
import { n as tcp, t as parsePort } from "./tcp-BgDXbjOG.js";
|
|
2
|
+
import { n as devServerStage, r as nodeFiles, t as host } from "./node-CVVdk2N6.js";
|
|
3
3
|
|
|
4
4
|
export { devServerStage, host, nodeFiles, parsePort, tcp };
|
package/dist/react-router.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as Mode, a as FrameworkRuntime, y as RequestContext } from "./types-
|
|
1
|
+
import { _ as Mode, a as FrameworkRuntime, y as RequestContext } from "./types-MgFtkNQW.js";
|
|
2
2
|
import { ServerBuild } from "react-router";
|
|
3
3
|
/** What the server puts in React Router's context for each request. */
|
|
4
4
|
export type AppServerContext = RequestContext;
|