@ngrok/app-server 0.3.3 → 0.3.4
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 +13 -9
- package/dist/brotli-only-DrA29Ecw.js +97 -0
- package/dist/brotli-only-DrA29Ecw.js.map +1 -0
- package/dist/cli.js +3 -3
- package/dist/compress-JuJf2HaO.js +377 -0
- package/dist/compress-JuJf2HaO.js.map +1 -0
- package/dist/{compression-7_gToa8R.js → compression-CT2mWlKM.js} +9 -2
- package/dist/compression-CT2mWlKM.js.map +1 -0
- package/dist/{create-server-jMl2ltHD.js → create-server-BX2rH6-E.js} +45 -26
- package/dist/{create-server-jMl2ltHD.js.map → create-server-BX2rH6-E.js.map} +1 -1
- package/dist/{create-server-D4-nVOVJ.d.ts → create-server-kxyhCdhv.d.ts} +3 -3
- package/dist/{entry-BPrgE_6K.d.ts → entry-CNL4OsEn.d.ts} +3 -3
- package/dist/{entry-D9H4LA9c.js → entry-ChHgs269.js} +4 -3
- package/dist/{entry-D9H4LA9c.js.map → entry-ChHgs269.js.map} +1 -1
- package/dist/{index-Db7dspq6.d.ts → index-B8LsM6Mh.d.ts} +21 -1
- package/dist/index.d.ts +13 -12
- package/dist/index.js +2 -2
- package/dist/{load-entry-D7r0mjEp.js → load-entry-BOgJPt1I.js} +4 -4
- package/dist/{load-entry-D7r0mjEp.js.map → load-entry-BOgJPt1I.js.map} +1 -1
- package/dist/{node-C1qudLs_.js → node-B0AYf_IA.js} +5 -4
- package/dist/{node-C1qudLs_.js.map → node-B0AYf_IA.js.map} +1 -1
- package/dist/{node-tBVQPjQv.js → node-C0Ad7CVL.js} +2 -2
- package/dist/{node-tBVQPjQv.js.map → node-C0Ad7CVL.js.map} +1 -1
- package/dist/node-vite.d.ts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +2 -2
- package/dist/react-router-vite.d.ts +1 -1
- package/dist/react-router.d.ts +1 -1
- package/dist/{response-writer-B7FoJjEE.js → response-writer-DzvUAz9x.js} +3 -3
- package/dist/response-writer-DzvUAz9x.js.map +1 -0
- package/dist/{script-hashes-C6hQ5XnP.js → script-hashes-CU7P9oZU.js} +2 -2
- package/dist/{script-hashes-C6hQ5XnP.js.map → script-hashes-CU7P9oZU.js.map} +1 -1
- package/dist/{serve-E0hSGe6_.js → serve-BUJ7ZonG.js} +2 -2
- package/dist/{serve-E0hSGe6_.js.map → serve-BUJ7ZonG.js.map} +1 -1
- package/dist/{start-CifYPRq1.js → start-DiQf9ttp.js} +6 -6
- package/dist/{start-CifYPRq1.js.map → start-DiQf9ttp.js.map} +1 -1
- package/dist/{static-files-Beju9riB.js → static-files-C2ea8KQ6.js} +11 -3
- package/dist/static-files-C2ea8KQ6.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +1 -1
- package/dist/tanstack-start.d.ts +2 -2
- package/dist/{tcp-Dd1Mt6sN.js → tcp-Bws6oEau.js} +2 -2
- package/dist/{tcp-Dd1Mt6sN.js.map → tcp-Bws6oEau.js.map} +1 -1
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +3 -3
- package/dist/{trailing-slash-CFSv_Gzx.d.ts → trailing-slash-DeOUxMYo.d.ts} +2 -2
- package/dist/{types-j29vspx_.d.ts → types-BKJxtIuj.d.ts} +10 -3
- package/dist/vercel-vite.d.ts +1 -1
- package/dist/vercel-vite.js +24 -4
- package/dist/vercel-vite.js.map +1 -1
- package/dist/vercel.d.ts +4 -3
- package/dist/vercel.js +7 -5
- package/dist/vercel.js.map +1 -1
- package/dist/{vite-BDREIgiH.js → vite-DPiSKHDn.js} +139 -33
- package/dist/vite-DPiSKHDn.js.map +1 -0
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/package.json +2 -1
- package/dist/compression-7_gToa8R.js.map +0 -1
- package/dist/gzip-Doi4wqjX.js +0 -294
- package/dist/gzip-Doi4wqjX.js.map +0 -1
- package/dist/response-writer-B7FoJjEE.js.map +0 -1
- package/dist/static-files-Beju9riB.js.map +0 -1
- package/dist/vite-BDREIgiH.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { g as Plugin, m as LogSink, t as AppServerEnv, u as Listener, x as SentResponse } from "./types-
|
|
2
|
-
import { t as TrailingSlash } from "./trailing-slash-
|
|
1
|
+
import { g as Plugin, m as LogSink, t as AppServerEnv, u as Listener, x as SentResponse } from "./types-BKJxtIuj.js";
|
|
2
|
+
import { t as TrailingSlash } from "./trailing-slash-DeOUxMYo.js";
|
|
3
3
|
import { Context, Hono } from "hono";
|
|
4
4
|
/** Options for {@link accessLog}. */
|
|
5
5
|
type AccessLogOptions = {
|
|
@@ -609,4 +609,4 @@ type CreateServerOptions = {
|
|
|
609
609
|
*/
|
|
610
610
|
declare function createServer({ plugins, logger, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
|
|
611
611
|
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 };
|
|
612
|
-
//# sourceMappingURL=create-server-
|
|
612
|
+
//# sourceMappingURL=create-server-kxyhCdhv.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, h as Mode, r as FetchHandler, t as AppServerEnv } from "./types-
|
|
2
|
-
import { t as AppServer } from "./create-server-
|
|
1
|
+
import { a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, h as Mode, r as FetchHandler, t as AppServerEnv } from "./types-BKJxtIuj.js";
|
|
2
|
+
import { t as AppServer } from "./create-server-kxyhCdhv.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-CNL4OsEn.d.ts.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as errorAttributes } from "./log-BP6xXXZl.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-
|
|
4
|
-
import { a as keptFiles } from "./static-files-
|
|
3
|
+
import { p as abortShutdownSignal, r as serverInternals } from "./create-server-BX2rH6-E.js";
|
|
4
|
+
import { a as keptFiles } from "./static-files-C2ea8KQ6.js";
|
|
5
5
|
|
|
6
6
|
// src/core/static-pages.ts
|
|
7
7
|
/** The headers that change with each request, such as the request ID. A CDN answer drops them. */
|
|
@@ -251,6 +251,7 @@ function createEntry({ app, host, framework, clientDirectory }) {
|
|
|
251
251
|
isDataRequest: runtime.isDataRequest ?? (() => false),
|
|
252
252
|
contentTypes: runtime.contentTypes ?? {},
|
|
253
253
|
gzip: host.gzip,
|
|
254
|
+
brotli: host.brotli,
|
|
254
255
|
logger: internals.logger
|
|
255
256
|
};
|
|
256
257
|
};
|
|
@@ -348,4 +349,4 @@ function isAppServerEntry(value) {
|
|
|
348
349
|
}
|
|
349
350
|
|
|
350
351
|
export { isAppServerEntry as n, createEntry as t };
|
|
351
|
-
//# sourceMappingURL=entry-
|
|
352
|
+
//# sourceMappingURL=entry-ChHgs269.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entry-D9H4LA9c.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 { errorAttributes } 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\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(\"error\", \"shutdown failed\", errorAttributes(error));\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(\"error\", \"setup failed\", errorAttributes(error));\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;EAA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C;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-ChHgs269.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 { errorAttributes } 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(\"error\", \"shutdown failed\", errorAttributes(error));\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(\"error\", \"setup failed\", errorAttributes(error));\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,c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AAU,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"}
|
|
@@ -77,6 +77,26 @@ type AppServerOptions = {
|
|
|
77
77
|
* default plugins.
|
|
78
78
|
*/
|
|
79
79
|
app?: string;
|
|
80
|
+
/**
|
|
81
|
+
* How the server build copies the packages that stay external, such as a
|
|
82
|
+
* native package. The build copies only the files that its modules can
|
|
83
|
+
* load, as `@vercel/nft` traces them. A native package and the packages
|
|
84
|
+
* that it depends on keep each file, and so does a package in
|
|
85
|
+
* `ssr.external`.
|
|
86
|
+
*/
|
|
87
|
+
externals?: {
|
|
88
|
+
/**
|
|
89
|
+
* Packages that keep each file, such as a package that reads a file
|
|
90
|
+
* whose path the trace cannot find.
|
|
91
|
+
*/
|
|
92
|
+
whole?: readonly string[];
|
|
93
|
+
/**
|
|
94
|
+
* Packages that the build does not copy, such as an optional dependency
|
|
95
|
+
* that a package loads in a `try`, as `@vercel/og` loads `sharp`. The
|
|
96
|
+
* server fails when it loads one with no `try`.
|
|
97
|
+
*/
|
|
98
|
+
omit?: readonly string[];
|
|
99
|
+
};
|
|
80
100
|
};
|
|
81
101
|
/** What {@link serverEntrySource} needs. */
|
|
82
102
|
type EntrySource = {
|
|
@@ -129,4 +149,4 @@ declare function serverEntrySource({ framework, host, appModule, clientDirectory
|
|
|
129
149
|
*/
|
|
130
150
|
declare function appServer(options?: AppServerOptions): Plugin[];
|
|
131
151
|
export { SERVER_ENTRY_ID as a, HostOutput as i, FrameworkBuild as n, appServer as o, HostBuild as r, serverEntrySource as s, AppServerOptions as t };
|
|
132
|
-
//# sourceMappingURL=index-
|
|
152
|
+
//# sourceMappingURL=index-B8LsM6Mh.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as SetupInfo, E as ResponseEdge, S as ServerBindings, T as StaticFiles, _ as RequestContext, a as FrameworkRuntime, b as ResponseHeaders, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as Plugin, h as Mode, i as FileInfo, l as Lifecycle, m as LogSink, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as RequestLogger, w as StartedListener, x as SentResponse, y as RequestStore } 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 SetupInfo, E as ResponseEdge, S as ServerBindings, T as StaticFiles, _ as RequestContext, a as FrameworkRuntime, b as ResponseHeaders, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as Plugin, h as Mode, i as FileInfo, l as Lifecycle, m as LogSink, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as RequestLogger, w as StartedListener, x as SentResponse, y as RequestStore } from "./types-BKJxtIuj.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-kxyhCdhv.js";
|
|
3
|
+
import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-DeOUxMYo.js";
|
|
4
|
+
import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-CNL4OsEn.js";
|
|
5
5
|
import { Context, Next } from "hono";
|
|
6
6
|
/** One server-sent event. */
|
|
7
7
|
type ServerSentEvent = {
|
|
@@ -111,14 +111,15 @@ export declare function bodyLimit({ maxBytes }: BodyLimitOptions): Plugin;
|
|
|
111
111
|
*/
|
|
112
112
|
export declare function privateDocuments(): Plugin;
|
|
113
113
|
/**
|
|
114
|
-
*
|
|
115
|
-
* or a server-sent event reaches the client
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
*
|
|
114
|
+
* Compresses text responses with brotli or gzip, and flushes after each
|
|
115
|
+
* chunk, so a streamed page shell or a server-sent event reaches the client
|
|
116
|
+
* at once. A client gets brotli when its `Accept-Encoding` ranks `br` at
|
|
117
|
+
* least as high as `gzip`. Chunks that the body has queued together are one
|
|
118
|
+
* chunk, up to 16 KiB. `hono/compress` holds a stream until it ends. Skips a
|
|
119
|
+
* response that is already encoded, a partial response, one marked
|
|
120
|
+
* `no-transform`, and one whose `Content-Length` is under 1 KiB. It adds
|
|
121
|
+
* `Accept-Encoding` to the `Vary` of each response that it can compress. The
|
|
122
|
+
* host gives the streams. On a host with none, the plugin does nothing.
|
|
122
123
|
*
|
|
123
124
|
* @example
|
|
124
125
|
* createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
|
package/dist/index.js
CHANGED
|
@@ -3,8 +3,8 @@ import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from
|
|
|
3
3
|
import { r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
|
|
4
4
|
import { r as jsonSink } from "./log-BP6xXXZl.js";
|
|
5
5
|
import { t as ResponseEdge } from "./response-edge-Bc1-C_Cx.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-
|
|
7
|
-
import { t as createEntry } from "./entry-
|
|
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-BX2rH6-E.js";
|
|
7
|
+
import { t as createEntry } from "./entry-ChHgs269.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-BX2rH6-E.js";
|
|
2
|
+
import { n as isAppServerEntry, t as createEntry } from "./entry-ChHgs269.js";
|
|
3
|
+
import { t as host } from "./node-B0AYf_IA.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-BOgJPt1I.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-entry-
|
|
1
|
+
{"version":3,"file":"load-entry-BOgJPt1I.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"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as tcp } from "./tcp-
|
|
1
|
+
import { n as tcp } from "./tcp-Bws6oEau.js";
|
|
2
2
|
import { n as flushLogs } from "./log-BP6xXXZl.js";
|
|
3
|
-
import {
|
|
4
|
-
import { t as publicScriptHashes } from "./script-hashes-
|
|
3
|
+
import { n as gzipStream, t as brotliStream } from "./compress-JuJf2HaO.js";
|
|
4
|
+
import { t as publicScriptHashes } from "./script-hashes-CU7P9oZU.js";
|
|
5
5
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
6
|
import { setTimeout } from "node:timers";
|
|
7
7
|
import { constants } from "node:fs";
|
|
@@ -320,6 +320,7 @@ const host = {
|
|
|
320
320
|
get: () => storage.getStore()
|
|
321
321
|
},
|
|
322
322
|
gzip: gzipStream,
|
|
323
|
+
brotli: brotliStream,
|
|
323
324
|
lifecycle: { onStop: (stop) => {
|
|
324
325
|
for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
|
|
325
326
|
stop().catch(() => {
|
|
@@ -330,4 +331,4 @@ const host = {
|
|
|
330
331
|
};
|
|
331
332
|
|
|
332
333
|
export { exitAfterFlush as i, devServerStage as n, nodeFiles as r, host as t };
|
|
333
|
-
//# sourceMappingURL=node-
|
|
334
|
+
//# sourceMappingURL=node-B0AYf_IA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-C1qudLs_.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\nimport { flushLogs } from \"../core/log.js\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tflushLogs();\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { constants } from \"node:fs\";\nimport { access, open, readdir, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ByteRange, FileInfo, StaticFiles } from \"../core/types.js\";\n\n/** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */\nconst CHUNK_BYTES = 65_536;\n\n/**\n * A file's bytes, one chunk for each pull. With `range`, it reads only those\n * bytes. The file opens on the first pull and closes at the end, on an error,\n * or on cancel.\n *\n * Why open on the first pull: a stage can drop a response that no one reads,\n * such as when a later stage throws. Node.js 26 throws an uncaught error when\n * garbage collection closes an open `FileHandle`.\n */\nfunction fileStream(path: string, range: ByteRange | undefined): ReadableStream<Uint8Array> {\n\tlet handle: FileHandle | undefined;\n\tlet position = range?.start ?? 0;\n\tconst end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;\n\tconst close = async () => {\n\t\tconst opened = handle;\n\t\thandle = undefined;\n\t\tawait opened?.close();\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst length = Math.min(CHUNK_BYTES, end - position);\n\t\t\t\t\tif (length > 0) {\n\t\t\t\t\t\thandle ??= await open(path);\n\t\t\t\t\t}\n\t\t\t\t\tconst { bytesRead, buffer } =\n\t\t\t\t\t\tlength <= 0 || handle == null\n\t\t\t\t\t\t\t? { bytesRead: 0, buffer: new Uint8Array(0) }\n\t\t\t\t\t\t\t: await handle.read({ buffer: new Uint8Array(length), position });\n\t\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\t\tawait close();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition += bytesRead;\n\t\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: close,\n\t\t},\n\t\t// Why 0: the stream opens and reads nothing until the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** The bytes of `range` in the file at `path`, usually from one read. */\nasync function readRange(path: string, range: ByteRange): Promise<Uint8Array> {\n\tconst buffer = new Uint8Array(range.end - range.start + 1);\n\tconst handle = await open(path);\n\ttry {\n\t\tlet filled = 0;\n\t\t// Why a loop: a read can give fewer bytes than it asks for before the end of the file.\n\t\twhile (filled < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read({\n\t\t\t\tbuffer,\n\t\t\t\toffset: filled,\n\t\t\t\tposition: range.start + filled,\n\t\t\t});\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfilled += bytesRead;\n\t\t}\n\t\treturn buffer.subarray(0, filled);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\n/** A stream of one chunk. */\nfunction oneChunk(chunk: Uint8Array): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tif (chunk.byteLength > 0) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n}\n\n/** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */\nconst MISSING_CODES = new Set([\"ENOENT\", \"ENOTDIR\", \"ENAMETOOLONG\"]);\n\n/** The value of `promise`, or `undefined` when it fails because nothing is at its path. */\nasync function orMissing<T>(promise: Promise<T>): Promise<T | undefined> {\n\ttry {\n\t\treturn await promise;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && MISSING_CODES.has(String(error.code))) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The {@link FileInfo} of a file or a directory, else `undefined`. */\nfunction fileInfo(stats: Stats | undefined): FileInfo | undefined {\n\tif (stats?.isFile() === true) {\n\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\treturn stats?.isDirectory() === true\n\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t: undefined;\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * Its `snapshot` reads each file and directory once. It throws for an error\n * that does not mean a missing file, so the server does not start.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\tconst files: StaticFiles = {\n\t\tstat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),\n\t\topen: async (path, range) => {\n\t\t\tconst candidate = filePath(path);\n\t\t\tif (range != null && range.end - range.start < CHUNK_BYTES) {\n\t\t\t\treturn oneChunk(await readRange(candidate, range));\n\t\t\t}\n\t\t\t// Why: an unreadable file then gets a logged 500, not a 200 whose body fails. The check\n\t\t\t// holds no `FileHandle`, so a response that no one reads leaves nothing open.\n\t\t\tawait access(candidate, constants.R_OK);\n\t\t\treturn fileStream(candidate, range);\n\t\t},\n\t\tsnapshot: async () => {\n\t\t\tconst entries = new Map<string, FileInfo>();\n\t\t\t// Why the inodes of the parents: a symbolic link to a parent directory must not make the\n\t\t\t// walk endless. A link to another directory, such as a sibling, still lists its files.\n\t\t\tconst walk = async (\n\t\t\t\tpath: string,\n\t\t\t\tstats: Stats,\n\t\t\t\tparents: ReadonlySet<string>,\n\t\t\t): Promise<void> => {\n\t\t\t\tconst info = fileInfo(stats);\n\t\t\t\tif (info == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentries.set(path, info);\n\t\t\t\tconst inode = `${stats.dev}:${stats.ino}`;\n\t\t\t\tif (info.kind === \"file\" || parents.has(inode)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst inside = new Set(parents).add(inode);\n\t\t\t\tconst prefix = path === \"/\" ? \"\" : path;\n\t\t\t\t// Why: a deploy can remove a directory between its `stat` and this read.\n\t\t\t\tconst names = (await orMissing(readdir(filePath(path)))) ?? [];\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tnames.map(async (name) => {\n\t\t\t\t\t\tconst childPath = `${prefix}/${name}`;\n\t\t\t\t\t\tconst childStats = await orMissing(stat(filePath(childPath)));\n\t\t\t\t\t\tif (childStats != null) {\n\t\t\t\t\t\t\tawait walk(childPath, childStats, inside);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst rootStats = await orMissing(stat(root));\n\t\t\tif (rootStats != null) {\n\t\t\t\tawait walk(\"/\", rootStats, new Set());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstat: async (path) => {\n\t\t\t\t\tconst trimmed = path.length > 1 ? path.replace(/\\/$/u, \"\") : path;\n\t\t\t\t\tconst info = entries.get(trimmed);\n\t\t\t\t\t// Why only a directory after a `/`: as on the disk, `/docs/` finds `/docs`, and\n\t\t\t\t\t// `/llms.txt/` finds nothing.\n\t\t\t\t\treturn trimmed === path || info?.kind === \"directory\" ? info : undefined;\n\t\t\t\t},\n\t\t\t\topen: files.open,\n\t\t\t};\n\t\t},\n\t};\n\treturn files;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OutgoingHttpHeader, OutgoingHttpHeaders } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ListenerBindings, ResponseHeaders } from \"../core/types.js\";\nimport { publicScriptHashes } from \"./script-hashes.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Makes `outgoing` run `hooks` before it sends its head, and returns the\n * function that undoes it. Why `writeHead`: Node calls it for each\n * response, also from `write` and `end`.\n */\nfunction runHooksAtHead(outgoing: ServerResponse, hooks: readonly HeaderHook[]): () => void {\n\tconst headers: ResponseHeaders = {\n\t\tget: (name) => {\n\t\t\tconst value = outgoing.getHeader(name);\n\t\t\treturn value == null ? null : String(value);\n\t\t},\n\t\thas: (name) => outgoing.hasHeader(name),\n\t\tset: (name, value) => {\n\t\t\toutgoing.setHeader(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\toutgoing.removeHeader(name);\n\t\t},\n\t};\n\tconst writeHead = outgoing.writeHead.bind(outgoing);\n\toutgoing.writeHead = (\n\t\tstatusCode: number,\n\t\treason?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\tvalues?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t) => {\n\t\tconst [message, given] = typeof reason === \"string\" ? [reason, values] : [undefined, reason];\n\t\t// Why: the hooks must see the headers that `writeHead` gets, such as the content type of a file.\n\t\tif (Array.isArray(given)) {\n\t\t\t// Why remove, then append: Node reads a flat `[name, value, …]` list so. A name replaces the old value and can repeat.\n\t\t\tconst names = given.filter((_, index) => index % 2 === 0).map(String);\n\t\t\tfor (const name of names) {\n\t\t\t\toutgoing.removeHeader(name);\n\t\t\t}\n\t\t\tfor (const [index, name] of names.entries()) {\n\t\t\t\tconst value = given[index * 2 + 1];\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.appendHeader(name, typeof value === \"number\" ? String(value) : value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (given != null) {\n\t\t\tfor (const [name, value] of Object.entries(given)) {\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.setHeader(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Why reversed: in production, the hook of an inner stage runs first, so an outer stage has the last word.\n\t\tfor (const hook of hooks.toReversed()) {\n\t\t\thook(headers);\n\t\t}\n\t\treturn message == null ? writeHead(statusCode) : writeHead(statusCode, message);\n\t};\n\treturn () => {\n\t\toutgoing.writeHead = writeHead;\n\t};\n}\n\n/** Options for {@link devServerStage}. */\nexport type DevServerStageOptions = {\n\t/**\n\t * The directory that the middleware serves as it is, and the URL base that\n\t * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML\n\t * file from it gets the `contentSecurityPolicy` with the hashes of its\n\t * inline scripts, as it does in production. Why a function: a Vite restart\n\t * can change both.\n\t */\n\tpublicFiles?: () => { directory: string; base: string };\n};\n\n/** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */\nfunction publicFileHashes(\n\t{ directory, base }: { directory: string; base: string },\n\tpathname: string,\n): string[] | undefined {\n\tconst prefix = base.replace(/\\/$/u, \"\");\n\t// Why both forms: in middleware mode, Vite's base middleware passes a path with no base on as it is.\n\treturn publicScriptHashes(\n\t\tdirectory,\n\t\tpathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname,\n\t);\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {\n * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n * }));\n */\nexport function devServerStage(\n\tmiddleware: NodeMiddleware,\n\t{ publicFiles }: DevServerStageOptions = {},\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\tconst hashes =\n\t\t\tpublicFiles == null\n\t\t\t\t? undefined\n\t\t\t\t: publicFileHashes(publicFiles(), new URL(context.req.url).pathname);\n\t\tconst earlierHashes = context.get(\"documentScriptHashes\");\n\t\tif (hashes != null) {\n\t\t\tcontext.set(\"documentScriptHashes\", hashes);\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t\tconst undoHooks = runHooksAtHead(outgoing, hooks);\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\t// Why: the later stages answer, and each hook runs on their response.\n\t\t\t\tundoHooks();\n\t\t\t\t// Why: the middleware did not send the public file, so its hashes do not apply.\n\t\t\t\tif (hashes != null) {\n\t\t\t\t\tcontext.set(\"documentScriptHashes\", earlierHashes);\n\t\t\t\t}\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why empty the list: the hooks ran on the head that the middleware sent, so the server must\n\t\t\t// not run them again on the response below.\n\t\t\thooks.length = 0;\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and the\n\t\t\t// headers are the ones that the middleware sent, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\t\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\t\t\tif (each != null) {\n\t\t\t\t\t\theaders.append(name, String(each));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { gzipStream } from \"./gzip.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tDevServerStageOptions,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tstop()\n\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.finally(exitAfterFlush);\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t},\n};\n"],"mappings":";;;;;;;;;;;;;;;AAIA,MAAM,mBAAmB;;;;;;;;;AAUzB,SAAgB,iBAAuB;CACtC,UAAU;CACV,IAAI,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,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,CAAC,MAAM,UAAU,OAAO,QAAQ,SAAS,WAAW,CAAC,GAC/D,KAAK,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GACvD,IAAI,QAAQ,MACX,QAAQ,OAAO,MAAM,OAAO,IAAI,CAAC;GAIpC,OAAO,IAAI,SAAS,MAAM;IAAE,QAAQ,SAAS;IAAY;GAAQ,CAAC;EACnE;EACA,OAAO,KAAK;CACb;AACD;;;ACvJA,MAAM,UAAU,IAAI,kBAAyC;;;;;;;;;;AAW7D,MAAa,OAAoB;CAChC,MAAM;CACN,OAAO;CACP,iBAAiB,CAAC,IAAI,CAAC;CACvB,SAAS;EACR,MAAM,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI;EAC7C,WAAW,QAAQ,SAAS;CAC7B;CACA,MAAM;CACN,WAAW,EACV,SAAS,SAAS;EACjB,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;GAC1B,KAAK,CAAC,CACJ,YAAY;IACZ,QAAQ,WAAW;GACpB,CAAC,CAAC,CACD,QAAQ,cAAc;EACzB,CAAC;CAEH,EACD;AACD"}
|
|
1
|
+
{"version":3,"file":"node-B0AYf_IA.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,S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M,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GACvD,IAAI,QAAQ,MACX,QAAQ,OAAO,MAAM,OAAO,IAAI,CAAC;GAIpC,OAAO,IAAI,SAAS,MAAM;IAAE,QAAQ,SAAS;IAAY;GAAQ,CAAC;EACnE;EACA,OAAO,KAAK;CACb;AACD;;;ACvJA,MAAM,UAAU,IAAI,kBAAyC;;;;;;;;;;AAW7D,MAAa,OAAoB;CAChC,MAAM;CACN,OAAO;CACP,iBAAiB,CAAC,IAAI,CAAC;CACvB,SAAS;EACR,MAAM,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI;EAC7C,WAAW,QAAQ,SAAS;CAC7B;CACA,MAAM;CACN,QAAQ;CACR,WAAW,EACV,SAAS,SAAS;EACjB,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;GAC1B,KAAK,CAAC,CACJ,YAAY;IACZ,QAAQ,WAAW;GACpB,CAAC,CAAC,CACD,QAAQ,cAAc;EACzB,CAAC;CAEH,EACD;AACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as requestListener } from "./response-writer-
|
|
1
|
+
import { t as requestListener } from "./response-writer-DzvUAz9x.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-C0Ad7CVL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-
|
|
1
|
+
{"version":3,"file":"node-C0Ad7CVL.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-vite.d.ts
CHANGED
package/dist/node.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { T as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-
|
|
1
|
+
import { T as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-BKJxtIuj.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-Bws6oEau.js";
|
|
2
|
+
import { n as devServerStage, r as nodeFiles, t as host } from "./node-B0AYf_IA.js";
|
|
3
3
|
|
|
4
4
|
export { devServerStage, host, nodeFiles, parsePort, tcp };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as FrameworkBuild } from "./index-
|
|
1
|
+
import { n as FrameworkBuild } from "./index-B8LsM6Mh.js";
|
|
2
2
|
/**
|
|
3
3
|
* The build side of the React Router adapter. `appServer` uses it when the
|
|
4
4
|
* Vite config has the React Router plugin, so pass it only to override that.
|
package/dist/react-router.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as RequestContext, a as FrameworkRuntime, h as Mode } from "./types-
|
|
1
|
+
import { _ as RequestContext, a as FrameworkRuntime, h as Mode } from "./types-BKJxtIuj.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;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
|
|
2
2
|
import { t as ResponseEdge } from "./response-edge-Bc1-C_Cx.js";
|
|
3
|
-
import { s as readIfQueued } from "./compression-
|
|
4
|
-
import {
|
|
3
|
+
import { s as readIfQueued } from "./compression-CT2mWlKM.js";
|
|
4
|
+
import { r as waitsForZlib } from "./compress-JuJf2HaO.js";
|
|
5
5
|
import { IncomingMessage, ServerResponse } from "node:http";
|
|
6
6
|
import { getRequestListener } from "@hono/node-server";
|
|
7
7
|
|
|
@@ -286,4 +286,4 @@ function listenerOf(answer) {
|
|
|
286
286
|
}
|
|
287
287
|
|
|
288
288
|
export { requestListener as t };
|
|
289
|
-
//# sourceMappingURL=response-writer-
|
|
289
|
+
//# sourceMappingURL=response-writer-DzvUAz9x.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"response-writer-DzvUAz9x.js","names":["targeted"],"sources":["../src/node/response-writer.ts"],"sourcesContent":["import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { readIfQueued } from \"../core/compression.js\";\nimport type { ReadResult } from \"../core/compression.js\";\nimport { headerIndex, headerList } from \"../core/header-hook.js\";\nimport { ResponseEdge } from \"../core/response-edge.js\";\nimport type { ListenerBindings } from \"../core/types.js\";\nimport type { NodeBindings } from \"./dev-server.js\";\nimport { waitsForZlib } from \"./compress.js\";\n\n/** The header of a response that went out through Node's response already, as the dev server stage sends it. */\nconst ALREADY_SENT_HEADER = \"x-hono-already-sent\";\n/** Why one object for all requests: `@hono/node-server` only reads its headers. */\nconst ALREADY_SENT = new Response(null, { headers: { [ALREADY_SENT_HEADER]: \"true\" } });\n/** The type that `@hono/node-server` gives a body with none. */\nconst DEFAULT_CONTENT_TYPE = \"text/plain; charset=UTF-8\";\n/** The body of the 500 that goes out when the response cannot. */\nconst ERROR_BODY = Buffer.from(\"Internal Server Error\");\n\n/** Resolves after the microtasks that are queued now, and the ones that they queue. */\nasync function afterMicrotasks(): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tprocess.nextTick(resolve);\n\t});\n}\n\n/** Resolves on the next `drain` of `outgoing`, or when it closes. */\nasync function drained(outgoing: ServerResponse): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tconst done = () => {\n\t\t\toutgoing.off(\"drain\", done);\n\t\t\toutgoing.off(\"close\", done);\n\t\t\tresolve();\n\t\t};\n\t\toutgoing.on(\"drain\", done);\n\t\toutgoing.on(\"close\", done);\n\t});\n}\n\n/** `value` as a body chunk. Why throw: a string chunk has no `byteLength`, and the Fetch standard allows bytes only. */\nfunction bytesOf(value: unknown): Uint8Array {\n\tif (value instanceof Uint8Array) {\n\t\treturn value;\n\t}\n\tthrow new TypeError(\"A response body gave a chunk that is not a Uint8Array.\");\n}\n\n/** The chunks that a body had queued in at most two reads, and the read that is still open. */\ntype Ahead = {\n\tchunks: Uint8Array[];\n\tsize: number;\n\tdone: boolean;\n\tpending: Promise<ReadResult> | undefined;\n};\n\n/**\n * Reads the chunks that `body` has queued, in at most two reads, and never\n * waits for its source. The exception is a stream of the host's gzip whose\n * source gave bytes: it waits for zlib's first chunk, so the head goes out\n * with it.\n */\nasync function readAhead(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tbody: ReadableStream<Uint8Array>,\n): Promise<Ahead> {\n\tconst ahead: Ahead = { chunks: [], size: 0, done: false, pending: undefined };\n\tfor (let reads = 0; reads < 2 && !ahead.done && ahead.pending == null; reads += 1) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- each read takes only a chunk that is queued already.\n\t\tlet next = await readIfQueued(reader);\n\t\tif (\"pending\" in next && reads === 0 && waitsForZlib(body) != null) {\n\t\t\t// Why wait: the host's gzip stream gets its source chunk in a later microtask.\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\tawait afterMicrotasks();\n\t\t\tif (waitsForZlib(body) === true) {\n\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\t\tnext = { result: await next.pending };\n\t\t\t}\n\t\t}\n\t\tif (\"pending\" in next) {\n\t\t\tahead.pending = next.pending;\n\t\t} else if (next.result.done) {\n\t\t\tahead.done = true;\n\t\t} else {\n\t\t\tconst chunk = bytesOf(next.result.value);\n\t\t\tahead.chunks.push(chunk);\n\t\t\tahead.size += chunk.byteLength;\n\t\t}\n\t}\n\treturn ahead;\n}\n\n/**\n * Writes the rest of the body at the pace of the client, then ends the\n * response. Why no length check: `strictContentLength` makes Node throw for a\n * body that does not match its `Content-Length`.\n */\nasync function pump(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tfirst: Promise<ReadResult>,\n\t{ outgoing, edge }: { outgoing: ServerResponse; edge: ResponseEdge },\n): Promise<void> {\n\tlet read = first;\n\tfor (;;) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- the next read waits for the socket.\n\t\tconst result = await read;\n\t\tif (outgoing.destroyed) {\n\t\t\treturn;\n\t\t}\n\t\tif (result.done) {\n\t\t\toutgoing.end();\n\t\t\treturn;\n\t\t}\n\t\tconst chunk = bytesOf(result.value);\n\t\tconst flowing = outgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t\tif (!flowing) {\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- the client sets the pace.\n\t\t\tawait drained(outgoing);\n\t\t}\n\t\tread = reader.read();\n\t}\n}\n\n/** The headers that `outgoing` sent, as a flat list. Why: the dev server stage sends its own head. */\nfunction sentHead(outgoing: ServerResponse): string[] {\n\tconst head: string[] = [];\n\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\tif (each != null) {\n\t\t\t\thead.push(name, String(each));\n\t\t\t}\n\t\t}\n\t}\n\treturn head;\n}\n\n/** Writes the head and the body of `response`, with `head` in place of its headers. */\nasync function writeBody(\n\tresponse: Response,\n\treader: ReadableStreamDefaultReader<Uint8Array> | undefined,\n\t{ outgoing, edge, head }: { outgoing: ServerResponse; edge: ResponseEdge; head: string[] },\n): Promise<void> {\n\tconst { body, status } = response;\n\tif (body == null || reader == null) {\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end();\n\t\treturn;\n\t}\n\tif (headerIndex(head, \"content-type\") === -1) {\n\t\thead.push(\"content-type\", DEFAULT_CONTENT_TYPE);\n\t}\n\tconst ahead = await readAhead(reader, body);\n\tif (outgoing.destroyed) {\n\t\treturn;\n\t}\n\tif (ahead.done) {\n\t\tconst index = headerIndex(head, \"content-length\");\n\t\tif (index === -1 && headerIndex(head, \"transfer-encoding\") === -1) {\n\t\t\thead.push(\"content-length\", String(ahead.size));\n\t\t} else if (index !== -1 && Number(head[index + 1]) !== ahead.size) {\n\t\t\tthrow new Error(\"The body does not match its Content-Length.\");\n\t\t}\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ahead.chunks.length === 1 ? ahead.chunks[0] : Buffer.concat(ahead.chunks));\n\t\tedge.bytes += ahead.size;\n\t\treturn;\n\t}\n\toutgoing.writeHead(status, head);\n\tfor (const chunk of ahead.chunks) {\n\t\toutgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t}\n\tif (ahead.chunks.length === 0) {\n\t\t// Why: the client gets the head at once, such as the open of an event stream.\n\t\toutgoing.flushHeaders();\n\t}\n\tawait pump(reader, ahead.pending ?? reader.read(), { outgoing, edge });\n}\n\n/**\n * Writes `response` to `outgoing`, with the headers that the server gave\n * `edge` for it, and counts the body bytes in `edge`. It never rejects.\n *\n * - A body that ends within two reads of the chunks that it has queued goes\n * out with its `Content-Length`, in one socket write with the head.\n * - When the first chunk is not ready, the head goes out at once, so an event\n * stream opens at once. A stream of the host's gzip whose source gave bytes\n * is the exception: zlib finishes it soon, so the head waits for it.\n * - It reads the next chunk only when Node takes the last one, and it cancels\n * the body when the socket closes.\n * - When a step fails before the head goes out, such as a body that fails or\n * a header that Node rejects, a 500 goes out. After the head, a failure or\n * a body that does not match its `Content-Length` destroys the socket, so\n * no client and no cache keeps a cut response as complete.\n */\nasync function writeResponse(\n\tresponse: Response,\n\toutgoing: ServerResponse,\n\tedge: ResponseEdge,\n): Promise<void> {\n\tconst { body } = response;\n\tlet { status } = response;\n\tconst sendsBody = outgoing.req.method !== \"HEAD\";\n\tif (body == null && response.headers.has(ALREADY_SENT_HEADER)) {\n\t\t// Why: the dev server stage answered through Node's response, and gave its status and length.\n\t\t// Node sends no body for HEAD.\n\t\tedge.bytes = sendsBody ? Number(response.headers.get(\"content-length\") ?? 0) : 0;\n\t\tedge.close(status, false, sentHead(outgoing));\n\t\treturn;\n\t}\n\t// Why one list: `writeBody` adds the headers that it sets, so the report gets the head that went out.\n\tlet head = edge.headersFor(response) ?? headerList(response.headers);\n\tif (outgoing.destroyed) {\n\t\tedge.close(status, true, head);\n\t\tawait body?.cancel().catch(() => {});\n\t\treturn;\n\t}\n\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t// Why one listener: it reports what went out and stops the body that the client no longer reads.\n\t// Why `on`: a response emits `close` once, and `once` adds a wrapper for each request.\n\toutgoing.on(\"close\", () => {\n\t\tedge.close(status, !outgoing.writableFinished, head);\n\t\treader?.cancel().catch(() => {});\n\t});\n\ttry {\n\t\treader = body?.getReader();\n\t\t// Why strict: Node then throws for a body that is longer or shorter than its `Content-Length`.\n\t\toutgoing.strictContentLength = true;\n\t\tawait writeBody(response, reader, { outgoing, edge, head });\n\t} catch (error) {\n\t\treader?.cancel(error).catch(() => {});\n\t\tedge.fail(error);\n\t\tif (outgoing.headersSent || outgoing.destroyed) {\n\t\t\toutgoing.destroy(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\t\tstatus = 500;\n\t\thead = [\"content-type\", DEFAULT_CONTENT_TYPE, \"content-length\", String(ERROR_BODY.byteLength)];\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ERROR_BODY);\n\t\tif (sendsBody) {\n\t\t\tedge.bytes += ERROR_BODY.byteLength;\n\t\t}\n\t}\n}\n\n/**\n * Runs `create`, which makes a listener of `@hono/node-server`, and keeps the\n * global `Response`. The listener makes its own `Request` class global.\n *\n * Why its `Request`: the listener gives each route a light request, and only\n * that class can copy it, such as `new Request(c.req.raw, init)` in Hono's\n * `methodOverride`. Why not its `Response`: a `fetch()` result must stay an\n * `instanceof Response`, as on Bun and Deno.\n *\n * @example\n * const listener = keepGlobalResponse(() => getRequestListener(app.fetch));\n */\nexport function keepGlobalResponse<T>(create: () => T): T {\n\t// Why the descriptor: on Deno, the listener leaves a `Response` that no one can assign.\n\tconst descriptor = Object.getOwnPropertyDescriptor(globalThis, \"Response\");\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tif (descriptor != null) {\n\t\t\tObject.defineProperty(globalThis, \"Response\", descriptor);\n\t\t}\n\t}\n}\n\n/** A `Host` header that a URL keeps as it is: a name or an address, and an optional port. */\nconst VALID_HOST = /^[a-z0-9.-]+(?::\\d{1,5})?$/iu;\n\n/** The request target that the client sent, on a request that {@link useForwardedProto} changed. */\nconst SENT_TARGET = Symbol(\"sentTarget\");\n\n/** A Node request whose target can carry the target that the client sent. */\ntype Targeted = IncomingMessage & { [SENT_TARGET]?: string };\n\n/**\n * Gives `incoming` an absolute target with the scheme of its\n * `X-Forwarded-Proto`. Why: `@hono/node-server` takes the scheme from the\n * socket, which is plain HTTP behind a proxy that ends TLS. A target with the\n * scheme gives the request its URL when it is made, so the server copies no\n * request to change it. {@link listenerOf} then puts the target that the\n * client sent back.\n */\nfunction useForwardedProto(incoming: Targeted): void {\n\tconst { host, \"x-forwarded-proto\": proto } = incoming.headers;\n\tconst target = incoming.url;\n\tif (\n\t\t(proto === \"https\" || proto === \"http\") &&\n\t\thost != null &&\n\t\tVALID_HOST.test(host) &&\n\t\ttarget?.startsWith(\"/\") === true\n\t) {\n\t\tincoming[SENT_TARGET] = target;\n\t\t// Why drop `:80` for https: a proxy can send the port of its own hop, and the server took the\n\t\t// scheme from the socket first, where 80 is the default port, so the URL never kept it.\n\t\tconst authority = proto === \"https\" && host.endsWith(\":80\") ? host.slice(0, -3) : host;\n\t\tincoming.url = `${proto}://${authority}${target}`;\n\t}\n}\n\n/**\n * Why not on Bun and Deno: their `node:http` does not always emit `close` or\n * set `destroyed`, so `@hono/node-server` writes the response there.\n */\nconst writesResponses = !(\"Bun\" in globalThis) && !(\"Deno\" in globalThis);\n\n/**\n * A `node:http` request listener. `@hono/node-server` builds each request,\n * `answer` makes the response, and the listener writes it. Each HTTP/1\n * request on Node.js gets an `edge` binding, so the server gives the listener\n * the headers after its header hooks, and the access log takes the bytes from\n * the listener.\n * With `trustForwardedProto`, each request takes its scheme from\n * `X-Forwarded-Proto`, as the server option does.\n *\n * @example\n * http.createServer(requestListener(async (request, bindings) => app.fetch(request, bindings)));\n */\nexport function requestListener(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n\t{ trustForwardedProto = false }: { trustForwardedProto?: boolean } = {},\n): ReturnType<typeof getRequestListener> {\n\tconst listener = listenerOf(answer);\n\treturn trustForwardedProto\n\t\t? async (incoming, outgoing) => {\n\t\t\t\tif (incoming instanceof IncomingMessage) {\n\t\t\t\t\tuseForwardedProto(incoming);\n\t\t\t\t}\n\t\t\t\treturn listener(incoming, outgoing);\n\t\t\t}\n\t\t: listener;\n}\n\n/** The listener of {@link requestListener}, with no scheme from `X-Forwarded-Proto`. */\nfunction listenerOf(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n): ReturnType<typeof getRequestListener> {\n\treturn keepGlobalResponse(() =>\n\t\tgetRequestListener(async (request, { incoming, outgoing }) => {\n\t\t\tconst { remoteAddress } = incoming.socket;\n\t\t\t// Why: an HTTP/2 response is not a `ServerResponse`, so `@hono/node-server` writes it.\n\t\t\tif (!(incoming instanceof IncomingMessage) || !(outgoing instanceof ServerResponse)) {\n\t\t\t\treturn answer(request, { remoteAddress } satisfies ListenerBindings);\n\t\t\t}\n\t\t\tconst targeted: Targeted = incoming;\n\t\t\tconst target = targeted[SENT_TARGET];\n\t\t\t// Why: the request has its URL now, and the app gets the target that the client sent.\n\t\t\tif (target != null) {\n\t\t\t\tincoming.url = target;\n\t\t\t}\n\t\t\tif (!writesResponses) {\n\t\t\t\tconst response = await answer(request, { remoteAddress, incoming, outgoing });\n\t\t\t\t// Why: `@hono/node-server` drops the body of a response whose socket closed, with no cancel.\n\t\t\t\tif (outgoing.destroyed) {\n\t\t\t\t\tawait response.body?.cancel();\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\tconst edge = new ResponseEdge();\n\t\t\tlet response: Response;\n\t\t\ttry {\n\t\t\t\tresponse = await answer(request, { remoteAddress, incoming, outgoing, edge });\n\t\t\t} catch (error) {\n\t\t\t\t// Why 500 with no headers: `@hono/node-server` answers a failed request with one.\n\t\t\t\tedge.close(500, false, []);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait writeResponse(response, outgoing, edge);\n\t\t\treturn ALREADY_SENT;\n\t\t}),\n\t);\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM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