@ngrok/app-server 0.3.2 → 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 +63 -23
- package/dist/brotli-only-DrA29Ecw.js +97 -0
- package/dist/brotli-only-DrA29Ecw.js.map +1 -0
- package/dist/{build-id-C6sYO9Yp.js → build-id-B0448vZH.js} +27 -2
- package/dist/build-id-B0448vZH.js.map +1 -0
- package/dist/{build-manifest-UDNk81Ce.js → build-manifest-DBMWe3Lx.js} +12 -2
- package/dist/build-manifest-DBMWe3Lx.js.map +1 -0
- package/dist/cli.js +3 -3
- package/dist/client-browser.js +1 -1
- package/dist/client.js +1 -1
- 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-D0De6R7Q.js → create-server-BX2rH6-E.js} +616 -547
- package/dist/create-server-BX2rH6-E.js.map +1 -0
- package/dist/{create-server-kzZWd_Lo.d.ts → create-server-kxyhCdhv.d.ts} +50 -13
- package/dist/{entry-DuGgSKeB.d.ts → entry-CNL4OsEn.d.ts} +39 -3
- package/dist/entry-ChHgs269.js +352 -0
- package/dist/entry-ChHgs269.js.map +1 -0
- package/dist/{index-Bo5G9LuQ.d.ts → index-B8LsM6Mh.d.ts} +26 -1
- package/dist/index.d.ts +14 -23
- package/dist/index.js +3 -3
- package/dist/{load-entry-Bodyd2Ok.js → load-entry-BOgJPt1I.js} +4 -4
- package/dist/{load-entry-Bodyd2Ok.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 +3 -2
- package/dist/react-router.js +31 -2
- package/dist/react-router.js.map +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-caOkS3o5.js → serve-BUJ7ZonG.js} +2 -2
- package/dist/{serve-caOkS3o5.js.map → serve-BUJ7ZonG.js.map} +1 -1
- package/dist/{stale-build-navigation-PnMLtTF8.js → stale-build-navigation-rg5xxmTr.js} +2 -2
- package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map} +1 -1
- package/dist/{start-DREqYrZh.js → start-DiQf9ttp.js} +36 -8
- package/dist/start-DiQf9ttp.js.map +1 -0
- 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 +4 -4
- package/dist/{trailing-slash-BrymAEGv.d.ts → trailing-slash-DeOUxMYo.d.ts} +2 -2
- package/dist/{types-CEvzAmcn.d.ts → types-BKJxtIuj.d.ts} +24 -3
- package/dist/vercel-pages.d.ts +32 -0
- package/dist/vercel-pages.js +54 -0
- package/dist/vercel-pages.js.map +1 -0
- package/dist/vercel-vite.d.ts +30 -9
- package/dist/vercel-vite.js +183 -20
- 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-tTxVimP6.js → vite-DPiSKHDn.js} +182 -51
- 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/build-id-C6sYO9Yp.js.map +0 -1
- package/dist/build-manifest-UDNk81Ce.js.map +0 -1
- package/dist/compression-7_gToa8R.js.map +0 -1
- package/dist/create-server-D0De6R7Q.js.map +0 -1
- package/dist/entry-UDsxuqBC.js +0 -116
- package/dist/entry-UDsxuqBC.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/start-DREqYrZh.js.map +0 -1
- package/dist/static-files-Beju9riB.js.map +0 -1
- package/dist/vite-tTxVimP6.js.map +0 -1
|
@@ -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,gBAAgB,CAAC,CAAC,MAAM;AAC5B;;AAGA,SAAS,MAAM,QAA4B,MAAwB;CAClE,IAAI,SAAS,YAAY;EAGxB,OAAO,IAAI,IAAI;EACf;CACD;CAGA,OAAO,MAAM,IAAI,IAAI;AACtB;;;;ACjCA,MAAM,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AC;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,SAAS,YAAY;EAGxB,OAAO,IAAI,IAAI;EACf;CACD;CAGA,OAAO,MAAM,IAAI,IAAI;AACtB;;;;ACjCA,MAAM,cAAc;;;;;;;;;;AAWpB,SAAS,WAAW,MAAc,OAA0D;CAC3F,IAAI;CACJ,IAAI,WAAW,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ACA,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;
|
|
@@ -23,7 +23,8 @@ export declare const appServerContext: import("react-router").RouterContext<Requ
|
|
|
23
23
|
export declare function isServerBuild(value: unknown): value is ServerBuild;
|
|
24
24
|
/**
|
|
25
25
|
* The run side of the React Router adapter, for a server build. Each request
|
|
26
|
-
* gets a `RouterContextProvider` that holds {@link appServerContext}.
|
|
26
|
+
* gets a `RouterContextProvider` that holds {@link appServerContext}. The
|
|
27
|
+
* access log gets the route pattern that React Router matched.
|
|
27
28
|
*
|
|
28
29
|
* @example
|
|
29
30
|
* const framework = runtime(build, { mode: "production" });
|
package/dist/react-router.js
CHANGED
|
@@ -20,6 +20,33 @@ const appServerContext = createContext({
|
|
|
20
20
|
cspNonce: void 0,
|
|
21
21
|
clientAddress: void 0
|
|
22
22
|
});
|
|
23
|
+
/** The Hono context of the request, for {@link recordRoutePattern}. */
|
|
24
|
+
const honoContext = createContext();
|
|
25
|
+
/**
|
|
26
|
+
* Sets `routePattern` on the Hono context to the route pattern that React
|
|
27
|
+
* Router matched, such as `/domains/:domainId`, so the access log writes
|
|
28
|
+
* `http.route`. Why a root middleware: it runs for each document, data, and
|
|
29
|
+
* resource request, and it costs less for each request than a request
|
|
30
|
+
* handler instrumentation.
|
|
31
|
+
*/
|
|
32
|
+
const recordRoutePattern = async ({ pattern, context }, next) => {
|
|
33
|
+
if (pattern !== "") context.get(honoContext).set("routePattern", pattern.startsWith("/") ? pattern : `/${pattern}`);
|
|
34
|
+
return next();
|
|
35
|
+
};
|
|
36
|
+
/** `build` with {@link recordRoutePattern} before the middleware of each root route. */
|
|
37
|
+
function withRoutePattern(build) {
|
|
38
|
+
const routes = Object.fromEntries(Object.entries(build.routes).map(([id, route]) => [id, route == null || route.parentId != null ? route : {
|
|
39
|
+
...route,
|
|
40
|
+
module: {
|
|
41
|
+
...route.module,
|
|
42
|
+
middleware: [recordRoutePattern, ...route.module.middleware ?? []]
|
|
43
|
+
}
|
|
44
|
+
}]));
|
|
45
|
+
return {
|
|
46
|
+
...build,
|
|
47
|
+
routes
|
|
48
|
+
};
|
|
49
|
+
}
|
|
23
50
|
/**
|
|
24
51
|
* Whether a module is a React Router server build.
|
|
25
52
|
*
|
|
@@ -31,7 +58,8 @@ function isServerBuild(value) {
|
|
|
31
58
|
}
|
|
32
59
|
/**
|
|
33
60
|
* The run side of the React Router adapter, for a server build. Each request
|
|
34
|
-
* gets a `RouterContextProvider` that holds {@link appServerContext}.
|
|
61
|
+
* gets a `RouterContextProvider` that holds {@link appServerContext}. The
|
|
62
|
+
* access log gets the route pattern that React Router matched.
|
|
35
63
|
*
|
|
36
64
|
* @example
|
|
37
65
|
* const framework = runtime(build, { mode: "production" });
|
|
@@ -39,7 +67,7 @@ function isServerBuild(value) {
|
|
|
39
67
|
function runtime(build, { mode }) {
|
|
40
68
|
if (!isServerBuild(build)) throw new Error("The server module is not a React Router server build.");
|
|
41
69
|
if (build.publicPath !== "/") throw new Error(`@ngrok/app-server serves a build at "/" only, and this build has the publicPath "${build.publicPath}".`);
|
|
42
|
-
const handler = createRequestHandler(build, mode);
|
|
70
|
+
const handler = createRequestHandler(withRoutePattern(build), mode);
|
|
43
71
|
const manifestPath = build.routeDiscovery.mode === "lazy" ? [build.basename ?? "", build.routeDiscovery.manifestPath || "/__manifest"].join("/").replaceAll(/\/+/gu, "/") : void 0;
|
|
44
72
|
return {
|
|
45
73
|
name: "react-router",
|
|
@@ -50,6 +78,7 @@ function runtime(build, { mode }) {
|
|
|
50
78
|
fetch: async (request, context) => {
|
|
51
79
|
const routerContext = new RouterContextProvider();
|
|
52
80
|
routerContext.set(appServerContext, requestContextValues(context));
|
|
81
|
+
routerContext.set(honoContext, context);
|
|
53
82
|
return handler(request, routerContext);
|
|
54
83
|
}
|
|
55
84
|
};
|
package/dist/react-router.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-router.js","names":[],"sources":["../src/react-router/index.ts"],"sourcesContent":["import { createContext, createRequestHandler, RouterContextProvider } from \"react-router\";\nimport type { ServerBuild } from \"react-router\";\nimport { jsonSink, sinkLogger } from \"../core/log.js\";\nimport { requestContextValues } from \"../core/request-context.js\";\nimport type { FrameworkRuntime, Mode, RequestContext } from \"../core/types.js\";\n\n/** What the server puts in React Router's context for each request. */\nexport type AppServerContext = RequestContext;\n\n/**\n * The React Router context key for {@link AppServerContext}. Outside a server\n * request, such as in React Router's prerender pass, it holds no request ID\n * and a logger that writes to `jsonSink()`. `requestContext()` from\n * `@ngrok/app-server` gives the same values.\n *\n * @example\n * export async function loader({ context }: Route.LoaderArgs) {\n * \tcontext.get(appServerContext).logger.info(\"loading the dashboard\");\n * }\n */\nexport const appServerContext = createContext<AppServerContext>({\n\trequestId: undefined,\n\tlogger: sinkLogger(jsonSink()),\n\tcspNonce: undefined,\n\tclientAddress: undefined,\n});\n\n/**\n * Whether a module is a React Router server build.\n *\n * @example\n * isServerBuild(await import(\"./build/server/index.js\")); // => true\n */\nexport function isServerBuild(value: unknown): value is ServerBuild {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"routes\" in value &&\n\t\t\"entry\" in value &&\n\t\t\"assetsBuildDirectory\" in value &&\n\t\ttypeof value.assetsBuildDirectory === \"string\"\n\t);\n}\n\n/**\n * The run side of the React Router adapter, for a server build. Each request\n * gets a `RouterContextProvider` that holds {@link appServerContext}.\n *\n * @example\n * const framework = runtime(build, { mode: \"production\" });\n */\nexport function runtime(build: unknown, { mode }: { mode: Mode }): FrameworkRuntime {\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server module is not a React Router server build.\");\n\t}\n\t// Why also here: the Vite plugin checks the base, but a plain build skips the plugin.\n\tif (build.publicPath !== \"/\") {\n\t\tthrow new Error(\n\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this build has the publicPath \"${build.publicPath}\".`,\n\t\t);\n\t}\n\tconst handler = createRequestHandler(build, mode);\n\t// Why: lazy route discovery fetches this exact path, so a redirect breaks it.\n\tconst manifestPath =\n\t\tbuild.routeDiscovery.mode === \"lazy\"\n\t\t\t? [build.basename ?? \"\", build.routeDiscovery.manifestPath || \"/__manifest\"]\n\t\t\t\t\t.join(\"/\")\n\t\t\t\t\t.replaceAll(/\\/+/gu, \"/\")\n\t\t\t: undefined;\n\treturn {\n\t\tname: \"react-router\",\n\t\tclientDirectory: build.assetsBuildDirectory,\n\t\tprerenderedPaths: build.prerender,\n\t\tisDataRequest: (path) => path.endsWith(\".data\") || path === manifestPath,\n\t\tcontentTypes: { \".data\": \"text/x-script\" },\n\t\tfetch: async (request, context) => {\n\t\t\tconst routerContext = new RouterContextProvider();\n\t\t\trouterContext.set(appServerContext, requestContextValues(context));\n\t\t\treturn handler(request, routerContext);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"react-router.js","names":[],"sources":["../src/react-router/index.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { createContext, createRequestHandler, RouterContextProvider } from \"react-router\";\nimport type { MiddlewareFunction, ServerBuild } from \"react-router\";\nimport { jsonSink, sinkLogger } from \"../core/log.js\";\nimport { requestContextValues } from \"../core/request-context.js\";\nimport type { AppServerEnv, FrameworkRuntime, Mode, RequestContext } from \"../core/types.js\";\n\n/** What the server puts in React Router's context for each request. */\nexport type AppServerContext = RequestContext;\n\n/**\n * The React Router context key for {@link AppServerContext}. Outside a server\n * request, such as in React Router's prerender pass, it holds no request ID\n * and a logger that writes to `jsonSink()`. `requestContext()` from\n * `@ngrok/app-server` gives the same values.\n *\n * @example\n * export async function loader({ context }: Route.LoaderArgs) {\n * \tcontext.get(appServerContext).logger.info(\"loading the dashboard\");\n * }\n */\nexport const appServerContext = createContext<AppServerContext>({\n\trequestId: undefined,\n\tlogger: sinkLogger(jsonSink()),\n\tcspNonce: undefined,\n\tclientAddress: undefined,\n});\n\n/** The Hono context of the request, for {@link recordRoutePattern}. */\nconst honoContext = createContext<Context<AppServerEnv>>();\n\n/**\n * Sets `routePattern` on the Hono context to the route pattern that React\n * Router matched, such as `/domains/:domainId`, so the access log writes\n * `http.route`. Why a root middleware: it runs for each document, data, and\n * resource request, and it costs less for each request than a request\n * handler instrumentation.\n */\nconst recordRoutePattern: MiddlewareFunction<Response> = async ({ pattern, context }, next) => {\n\tif (pattern !== \"\") {\n\t\t// Why the slash: React Router joins the relative paths of the routes, such as `domains/:domainId`.\n\t\tcontext.get(honoContext).set(\"routePattern\", pattern.startsWith(\"/\") ? pattern : `/${pattern}`);\n\t}\n\treturn next();\n};\n\n/** `build` with {@link recordRoutePattern} before the middleware of each root route. */\nfunction withRoutePattern(build: ServerBuild): ServerBuild {\n\tconst routes = Object.fromEntries(\n\t\tObject.entries(build.routes).map(([id, route]) => [\n\t\t\tid,\n\t\t\troute == null || route.parentId != null\n\t\t\t\t? route\n\t\t\t\t: {\n\t\t\t\t\t\t...route,\n\t\t\t\t\t\tmodule: {\n\t\t\t\t\t\t\t...route.module,\n\t\t\t\t\t\t\tmiddleware: [recordRoutePattern, ...(route.module.middleware ?? [])],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t]),\n\t);\n\treturn { ...build, routes };\n}\n\n/**\n * Whether a module is a React Router server build.\n *\n * @example\n * isServerBuild(await import(\"./build/server/index.js\")); // => true\n */\nexport function isServerBuild(value: unknown): value is ServerBuild {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"routes\" in value &&\n\t\t\"entry\" in value &&\n\t\t\"assetsBuildDirectory\" in value &&\n\t\ttypeof value.assetsBuildDirectory === \"string\"\n\t);\n}\n\n/**\n * The run side of the React Router adapter, for a server build. Each request\n * gets a `RouterContextProvider` that holds {@link appServerContext}. The\n * access log gets the route pattern that React Router matched.\n *\n * @example\n * const framework = runtime(build, { mode: \"production\" });\n */\nexport function runtime(build: unknown, { mode }: { mode: Mode }): FrameworkRuntime {\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server module is not a React Router server build.\");\n\t}\n\t// Why also here: the Vite plugin checks the base, but a plain build skips the plugin.\n\tif (build.publicPath !== \"/\") {\n\t\tthrow new Error(\n\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this build has the publicPath \"${build.publicPath}\".`,\n\t\t);\n\t}\n\tconst handler = createRequestHandler(withRoutePattern(build), mode);\n\t// Why: lazy route discovery fetches this exact path, so a redirect breaks it.\n\tconst manifestPath =\n\t\tbuild.routeDiscovery.mode === \"lazy\"\n\t\t\t? [build.basename ?? \"\", build.routeDiscovery.manifestPath || \"/__manifest\"]\n\t\t\t\t\t.join(\"/\")\n\t\t\t\t\t.replaceAll(/\\/+/gu, \"/\")\n\t\t\t: undefined;\n\treturn {\n\t\tname: \"react-router\",\n\t\tclientDirectory: build.assetsBuildDirectory,\n\t\tprerenderedPaths: build.prerender,\n\t\tisDataRequest: (path) => path.endsWith(\".data\") || path === manifestPath,\n\t\tcontentTypes: { \".data\": \"text/x-script\" },\n\t\tfetch: async (request, context) => {\n\t\t\tconst routerContext = new RouterContextProvider();\n\t\t\trouterContext.set(appServerContext, requestContextValues(context));\n\t\t\trouterContext.set(honoContext, context);\n\t\t\treturn handler(request, routerContext);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,MAAa,mBAAmB,cAAgC;CAC/D,WAAW;CACX,QAAQ,WAAW,SAAS,CAAC;CAC7B,UAAU;CACV,eAAe;AAChB,CAAC;;AAGD,MAAM,cAAc,cAAqC;;;;;;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AY;GAClC,MAAM,gBAAgB,IAAI,sBAAsB;GAChD,cAAc,IAAI,kBAAkB,qBAAqB,OAAO,CAAC;GACjE,cAAc,IAAI,aAAa,OAAO;GACtC,OAAO,QAAQ,SAAS,aAAa;EACtC;CACD;AACD"}
|
|
@@ -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,sBAAsB;;AAE5B,MAAM,eAAe,IAAI,SAAS,MAAM,EAAE,SAAS,GAAG,sBAAsB,OAAO,EAAE,CAAC;;AAEtF,MAAM,uBAAuB;;AAE7B,MAAM,aAAa,OAAO,KAAK,uBAAuB;;AAGtD,eAAe,kBAAiC;CAC/C,OAAO,IAAI,SAAS,YAAY;EAC/B,QAAQ,SAAS,OAAO;CACzB,CAAC;AACF;;AAGA,eAAe,QAAQ,UAAyC;CAC/D,OAAO,IAAI,SAAS,YAAY;EAC/B,MAAM,aAAa;GAClB,SAAS,IAAI,SAAS,IAAI;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,SAAS,WACZ,MAAM,SAAS,MAAM,OAAO;GAE7B,OAAO;EACR;EACA,MAAM,OAAO,IAAI,aAAa;EAC9B,IAAI;EACJ,IAAI;GACH,WAAW,MAAM,OAAO,SAAS;IAAE;IAAe;IAAU;IAAU;GAAK,CAAC;EAC7E,SAAS,OAAO;GAEf,KAAK,MAAM,KAAK,OAAO,CAAC,CAAC;GACzB,MAAM;EACP;EACA,MAAM,cAAc,UAAU,UAAU,IAAI;EAC5C,OAAO;CACR,CAAC,CACF;AACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as contentType } from "./static-files-
|
|
1
|
+
import { t as contentType } from "./static-files-C2ea8KQ6.js";
|
|
2
2
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
3
3
|
import { join, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
@@ -68,4 +68,4 @@ function scriptHashesOf(clientDirectory) {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
export { scriptHashesOf as n, publicScriptHashes as t };
|
|
71
|
-
//# sourceMappingURL=script-hashes-
|
|
71
|
+
//# sourceMappingURL=script-hashes-CU7P9oZU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"script-hashes-
|
|
1
|
+
{"version":3,"file":"script-hashes-CU7P9oZU.js","names":[],"sources":["../src/node/script-hashes.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\nimport { contentType } from \"../core/static-files.js\";\n\n/**\n * An HTML comment, or a `<script>` element. The `attributes` group is the\n * script's attributes, and the `text` group is its text. Why the comment: a\n * `<script>` tag in a comment starts no element.\n */\nconst COMMENT_OR_SCRIPT =\n\t/<!--[\\s\\S]*?-->|<script(?=[\\s/>])(?<attributes>(?:[^>\"']|\"[^\"]*\"|'[^']*')*)>(?<text>[\\s\\S]*?)<\\/script(?=[\\s/>])/giu;\n\n/** An attribute value, so that a `src=` in a value is not the `src` attribute. */\nconst ATTRIBUTE_VALUE = /[=]\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/gu;\n\n/** A `src` attribute, in attributes with no values. */\nconst SRC_ATTRIBUTE = /(?:^|[\\s/])src(?:[\\s/=]|$)/iu;\n\n/**\n * The base64 `SHA-256` of each inline script in `html`, once each, in\n * document order. Why each type: a hash of a data block, such as JSON, trusts\n * no code, and a scan that skips a type that runs breaks the page. Why LF:\n * the browser changes each CRLF and CR to LF before it hashes a script.\n *\n * @example\n * inlineScriptHashes(\"<script>go()</script>\"); // => [\"…base64…\"]\n */\nexport function inlineScriptHashes(html: string): string[] {\n\tconst hashes: string[] = [];\n\tfor (const { groups } of html.replaceAll(/\\r\\n?/gu, \"\\n\").matchAll(COMMENT_OR_SCRIPT)) {\n\t\tif (\n\t\t\tgroups?.text != null &&\n\t\t\t!SRC_ATTRIBUTE.test((groups.attributes ?? \"\").replaceAll(ATTRIBUTE_VALUE, \"=\"))\n\t\t) {\n\t\t\thashes.push(createHash(\"sha256\").update(groups.text).digest(\"base64\"));\n\t\t}\n\t}\n\treturn [...new Set(hashes)];\n}\n\n/**\n * The {@link inlineScriptHashes} of the HTML file at the URL `path` in\n * `directory`, such as Vite's public directory, or `undefined` when it has no\n * such file. Why it reads the file for each call: a developer can edit it at\n * any time, and only a request for an HTML file reads it.\n *\n * @example\n * publicScriptHashes(\"/app/public\", \"/offline.html\"); // => [\"…base64…\"]\n */\nexport function publicScriptHashes(directory: string, path: string): string[] | undefined {\n\tif (directory === \"\") {\n\t\treturn undefined;\n\t}\n\t// Why one `try`: a path that does not decode, a path with a null byte, and a file that the\n\t// developer deletes or locks between the checks each throw. The middleware then answers.\n\ttry {\n\t\tconst decoded = decodeURIComponent(path);\n\t\tconst file = resolve(directory, `.${decoded}`);\n\t\t// Why: a path such as `/../secret.html` must not leave the directory.\n\t\tif (\n\t\t\t!contentType(decoded, {}).startsWith(\"text/html\") ||\n\t\t\t!file.startsWith(`${resolve(directory)}${sep}`) ||\n\t\t\tstatSync(file, { throwIfNoEntry: false })?.isFile() !== true\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn inlineScriptHashes(readFileSync(file, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * The {@link inlineScriptHashes} of each HTML file in the client build, by its URL path.\n *\n * @example\n * scriptHashesOf(\"/app/build/client\"); // => { \"/about/index.html\": [\"…base64…\"] }\n */\nexport function scriptHashesOf(clientDirectory: string): BuildManifest[\"scriptHashes\"] {\n\tconst hashes: BuildManifest[\"scriptHashes\"] = {};\n\tfor (const entry of readdirSync(clientDirectory, { recursive: true, withFileTypes: true })) {\n\t\t// Why `contentType`: the static stages send each file of an HTML type, such as `.htm`, as a document.\n\t\tif (entry.isFile() && contentType(entry.name, {}).startsWith(\"text/html\")) {\n\t\t\tconst path = join(entry.parentPath, entry.name);\n\t\t\tconst urlPath = `/${relative(clientDirectory, path).split(sep).join(\"/\")}`;\n\t\t\thashes[urlPath] = inlineScriptHashes(readFileSync(path, \"utf8\"));\n\t\t}\n\t}\n\treturn Object.fromEntries(\n\t\tObject.entries(hashes).toSorted(([first], [second]) => first.localeCompare(second)),\n\t);\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,oBACL;;AAGD,MAAM,kBAAkB;;AAGxB,MAAM,gBAAgB;;;;;;;;;;AAWtB,SAAgB,mBAAmB,MAAwB;CAC1D,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,EAAE,YAAY,KAAK,WAAW,WAAW,IAAI,CAAC,CAAC,SAAS,iBAAiB,GACnF,IACC,QAAQ,QAAQ,QAChB,CAAC,cAAc,MAAM,OAAO,cAAc,GAAE,CAAE,WAAW,iBAAiB,GAAG,CAAC,GAE9E,OAAO,KAAK,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,IAAI,CAAC,CAAC,OAAO,QAAQ,CAAC;CAGvE,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC3B;;;;;;;;;;AAWA,SAAgB,mBAAmB,WAAmB,MAAoC;CACzF,IAAI,cAAc,IACjB;CAID,IAAI;EACH,MAAM,UAAU,mBAAmB,IAAI;EACvC,MAAM,OAAO,QAAQ,WAAW,IAAI,SAAS;EAE7C,IACC,CAAC,YAAY,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,KAChD,CAAC,KAAK,WAAW,GAAG,QAAQ,SAAS,IAAI,KAAK,KAC9C,SAAS,MAAM,EAAE,gBAAgB,MAAM,CAAC,CAAC,EAAE,OAAO,MAAM,MAExD;EAED,OAAO,mBAAmB,aAAa,MAAM,MAAM,CAAC;CACrD,QAAQ;EACP;CACD;AACD;;;;;;;AAQA,SAAgB,eAAe,iBAAwD;CACtF,MAAM,SAAwC,CAAC;CAC/C,KAAK,MAAM,SAAS,YAAY,iBAAiB;EAAE,WAAW;EAAM,eAAe;CAAK,CAAC,GAExF,IAAI,MAAM,OAAO,KAAK,YAAY,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,GAAG;EAC1E,MAAM,OAAO,KAAK,MAAM,YAAY,MAAM,IAAI;EAC9C,MAAM,UAAU,IAAI,SAAS,iBAAiB,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;EACvE,OAAO,WAAW,mBAAmB,aAAa,MAAM,MAAM,CAAC;CAChE;CAED,OAAO,OAAO,YACb,OAAO,QAAQ,MAAM,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,YAAY,MAAM,cAAc,MAAM,CAAC,CACnF;AACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as loadEntry } from "./load-entry-
|
|
1
|
+
import { t as loadEntry } from "./load-entry-BOgJPt1I.js";
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
@@ -26,4 +26,4 @@ async function serve({ buildPath }) {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
export { serve };
|
|
29
|
-
//# sourceMappingURL=serve-
|
|
29
|
+
//# sourceMappingURL=serve-BUJ7ZonG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve-
|
|
1
|
+
{"version":3,"file":"serve-BUJ7ZonG.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as serverTimingMetrics, i as isBuildMetric, n as BUILD_ID_METRIC, t as BUILD_ID_HEADER } from "./build-id-
|
|
1
|
+
import { a as serverTimingMetrics, i as isBuildMetric, n as BUILD_ID_METRIC, t as BUILD_ID_HEADER } from "./build-id-B0448vZH.js";
|
|
2
2
|
|
|
3
3
|
// src/client/document-nonce.ts
|
|
4
4
|
/**
|
|
@@ -336,4 +336,4 @@ function staleBuildTanStack(router, options = {}) {
|
|
|
336
336
|
}
|
|
337
337
|
|
|
338
338
|
export { staleBuildTanStack as n, documentNonce as r, staleBuildReactRouter as t };
|
|
339
|
-
//# sourceMappingURL=stale-build-navigation-
|
|
339
|
+
//# sourceMappingURL=stale-build-navigation-rg5xxmTr.js.map
|
package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stale-build-navigation-PnMLtTF8.js","names":[],"sources":["../src/client/document-nonce.ts","../src/client/stale-build-navigation.ts"],"sourcesContent":["/**\n * The CSP nonce of the document's first element with a nonce, or `undefined`\n * when it has none. The browser build of `@ngrok/app-server/client` exports it\n * as `cspNonce()`, so the browser bundle holds no server code.\n *\n * @example\n * documentNonce(); // => \"d2hhdCBhIG5vbmNl\"\n */\nexport function documentNonce(): string | undefined {\n\t// Why the property: a browser hides the value of the `nonce` attribute when the page's CSP applies.\n\treturn document.querySelector<HTMLElement>(\"[nonce]\")?.nonce;\n}\n","import {\n\tBUILD_ID_HEADER,\n\tBUILD_ID_METRIC,\n\tisBuildMetric,\n\tserverTimingMetrics,\n} from \"../core/plugins/build-id.js\";\n\n/** Options for {@link staleBuildReactRouter} and {@link staleBuildTanStack}. */\nexport type StaleBuildOptions = {\n\t/**\n\t * The header that `buildId()` sets on data responses.\n\t * @default \"X-Build-Id\"\n\t */\n\theader?: string;\n\t/**\n\t * The build that this document runs. Set it only when the server does not\n\t * send it.\n\t * @default the `build` metric of the document's `Server-Timing`, which `buildId()` sends\n\t */\n\tbuild?: string;\n\t/**\n\t * Runs once, when the tab first sees a response from another build. Use\n\t * it to count stale tabs in the app's RUM tool.\n\t */\n\tonNewBuild?: (served: string) => void;\n};\n\n/** The context that React Router gives `unstable_fetch` with each request. */\nexport type RouterFetchContext = {\n\t/** `\"navigation\"` for the data request of a navigation that the router started. */\n\ttype: string;\n\t/** `\"PUSH\"`, `\"REPLACE\"`, or `\"POP\"` for a navigation. */\n\tnavigationType?: string | null;\n\t/** The fetcher that sends the request, also in a navigation that revalidates it. */\n\tfetcherKey?: string | null;\n};\n\n/** The location in a TanStack Router event. */\ntype EventLocation = { pathname: string; searchStr: string };\n\n/** The part of a TanStack Router that {@link staleBuildTanStack} reads. */\nexport type NavigationEvents = {\n\thistory: { flush: () => void };\n\tclearCache: () => void;\n\tsubscribe: (\n\t\ttype: \"onBeforeNavigate\" | \"onResolved\",\n\t\tlistener: (event: { fromLocation?: EventLocation; toLocation: EventLocation }) => void,\n\t) => () => void;\n};\n\n/** Whether `url` is on the origin of this page. */\nfunction isOwn(url: string): boolean {\n\treturn new URL(url, location.href).origin === location.origin;\n}\n\n/** The build in the `Server-Timing` of the first of `entries` that has one, from this origin only. */\nfunction timingBuild(entries: PerformanceEntryList): string | undefined {\n\treturn (\n\t\tentries\n\t\t\t.filter(\n\t\t\t\t(entry): entry is PerformanceResourceTiming => \"serverTiming\" in entry && isOwn(entry.name),\n\t\t\t)\n\t\t\t// Why: a redirected resource keeps its first URL as its name, and the redirect can end on\n\t\t\t// another origin. A document entry has its final URL.\n\t\t\t.filter((entry) => entry.entryType !== \"resource\" || entry.redirectStart === 0)\n\t\t\t.flatMap((entry) => entry.serverTiming)\n\t\t\t.find((metric) => metric.name === BUILD_ID_METRIC)?.description\n\t);\n}\n\n/** The build in a `Server-Timing` header, as `buildId()` writes it. */\nfunction headerBuild(header: string | null): string | undefined {\n\tconst { quoted, token } =\n\t\tserverTimingMetrics(header)\n\t\t\t.find((metric) => isBuildMetric(metric))\n\t\t\t?.match(/;\\s*desc\\s*=\\s*(?:\"(?<quoted>(?:[^\"\\\\]|\\\\.)*)\"|(?<token>[^;\\s]*))/iu)?.groups ?? {};\n\treturn quoted?.replaceAll(/\\\\(?<char>.)/gu, \"$<char>\") ?? token;\n}\n\n/** The page of `url`: the router renders a new route for a new path or query, not for a new fragment. */\nfunction pageOf(url: string): string {\n\tconst { origin, pathname, search } = new URL(url, location.href);\n\treturn `${origin}${pathname}${search}`;\n}\n\n/** The page of a TanStack Router location, as {@link pageOf} reads a URL. */\nfunction eventPage({ pathname, searchStr }: EventLocation): string {\n\treturn `${pathname}${searchStr}`;\n}\n\n/** The URL of a `fetch` call. */\nfunction urlOf(input: RequestInfo | URL): string {\n\treturn input instanceof Request ? input.url : String(input);\n}\n\n/** The method of a `fetch` call. */\nfunction methodOf(input: RequestInfo | URL, init: RequestInit | undefined): string {\n\treturn (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n}\n\n/** The page that a React Router data request loads: `/a.data` loads `/a`, and `/a/_.data` loads `/a/`. */\nfunction targetOf(request: Request): string {\n\tconst url = new URL(request.url);\n\turl.pathname = url.pathname.replace(/\\/_\\.data$/u, \"/\").replace(/\\.data$/u, \"\");\n\turl.searchParams.delete(\"_routes\");\n\treturn url.href;\n}\n\n/**\n * Reloads a document that the back/forward cache shows again. Why: Back can\n * show the document that {@link loadDocument} left, with its router still in a\n * navigation that never ends. Why one function: the browser adds it once.\n */\nfunction reloadIfRestored(event: PageTransitionEvent): void {\n\tif (event.persisted) {\n\t\tlocation.reload();\n\t}\n}\n\n/**\n * Loads `target` as a document, so the old code never gets the new build's\n * data. It returns a promise that never settles, because the page unloads.\n */\nasync function loadDocument(\n\ttarget: string,\n\t{\n\t\tresponse,\n\t\tnavigationType,\n\t}: { response?: Response | undefined; navigationType?: string | null | undefined } = {},\n): Promise<never> {\n\t// Why no wait: the cancel of a cloned body waits for the other branch.\n\tresponse?.body?.cancel().catch(() => undefined);\n\t// Why reload on this page: the router can move history first, and `assign` to the same page\n\t// with a fragment scrolls with no document load. A history step already moved history. Why\n\t// not to remove a fragment: `assign` to a URL with no fragment loads the document.\n\tconst isSamePage = pageOf(target) === pageOf(location.href);\n\tconst removesFragment = new URL(target, location.href).hash === \"\" && location.hash !== \"\";\n\taddEventListener(\"pageshow\", reloadIfRestored, { once: true });\n\tif (navigationType === \"POP\" || (isSamePage && !removesFragment)) {\n\t\tlocation.reload();\n\t} else if (navigationType === \"REPLACE\") {\n\t\tlocation.replace(target);\n\t} else {\n\t\tlocation.assign(target);\n\t}\n\treturn new Promise<never>(() => {});\n}\n\n/**\n * Runs `clear` when `signal` aborts. Why: the router aborts a navigation when a\n * newer one starts, such as after the visitor stays on the page at a leave prompt.\n */\nfunction onAbort(signal: AbortSignal, clear: () => void): void {\n\tsignal.addEventListener(\"abort\", clear, { once: true });\n}\n\n/** Reads the build of each response, and tells when the server runs a new build. */\nfunction watchBuild({ header = BUILD_ID_HEADER, build, onNewBuild }: StaleBuildOptions) {\n\t// Why: on the server, such as in a router factory that runs for each request, there is no tab to move.\n\tif (typeof document === \"undefined\") {\n\t\treturn null;\n\t}\n\tconst current = build ?? timingBuild(performance.getEntriesByType(\"navigation\"));\n\tif (current == null) {\n\t\treturn null;\n\t}\n\tlet stale = false;\n\tconst see = (served: string | null | undefined) => {\n\t\tif (served == null || served === current || stale) {\n\t\t\treturn;\n\t\t}\n\t\tstale = true;\n\t\t// Why a catch: an error in the app's callback must not fail the request that found the build.\n\t\ttry {\n\t\t\tonNewBuild?.(served);\n\t\t} catch (error) {\n\t\t\treportError(error);\n\t\t}\n\t};\n\t// Why resource timing: it shows the build of a response that no script fetched, such as a\n\t// prefetch on hover, so the tab can find a new build before the click. Why buffered: a prefetch\n\t// can finish before this module runs.\n\tconst observer =\n\t\ttypeof PerformanceObserver === \"function\"\n\t\t\t? new PerformanceObserver((list) => {\n\t\t\t\t\t// Why each entry: one delivery can hold the old build first and the new build after it.\n\t\t\t\t\tfor (const entry of list.getEntries()) {\n\t\t\t\t\t\tsee(timingBuild([entry]));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: undefined;\n\tobserver?.observe({ type: \"resource\", buffered: true });\n\treturn {\n\t\tisStale: () => stale,\n\t\t/** Whether `response` comes from a new build of this origin. `url` is the URL of the request. */\n\t\tisNew: (response: Response, url: string) => {\n\t\t\t// Why the final URL: a redirect can end on another origin. Why `Server-Timing`: a proxy\n\t\t\t// route of `buildId({ paths })` sends no build header.\n\t\t\tconst served = isOwn(response.url === \"\" ? url : response.url)\n\t\t\t\t? (response.headers.get(header) ?? headerBuild(response.headers.get(\"Server-Timing\")))\n\t\t\t\t: null;\n\t\t\tsee(served);\n\t\t\treturn served != null && served !== current;\n\t\t},\n\t\tstop: () => observer?.disconnect(),\n\t};\n}\n\n/** The `navigate` call of a React Router instrumentation. */\ntype NavigateInfo = { to: string | number; formMethod?: string };\n\n/** The router instrumentations that {@link staleBuildReactRouter} adds. */\ntype RouterInstrumentations = {\n\tnavigate: (handler: () => Promise<unknown>, info: NavigateInfo) => Promise<void>;\n};\n\n/**\n * The arguments of a client middleware call. Why the `unstable_` fields: React\n * Router gives the middleware the arguments of its data strategy, which tell a\n * navigation from a fetcher and give its history action.\n */\ntype MiddlewareArgs = {\n\trequest: Request;\n\tunstable_initiator?: string;\n\tunstable_navigationType?: string | null;\n};\n\n/** The hooks that {@link staleBuildReactRouter} gives to React Router. */\nexport type StaleBuildReactRouter = {\n\t/** Give it to `HydratedRouter` as `unstable_fetch`. */\n\tfetch: (request: Request, context: RouterFetchContext) => Promise<Response>;\n\t/** Give it to `HydratedRouter` in `instrumentations`. */\n\tinstrumentation: {\n\t\trouter: (router: { instrument: (instrumentations: RouterInstrumentations) => void }) => void;\n\t};\n\t/** Export it from `app/root.tsx` in `clientMiddleware`. */\n\tmiddleware: <Result>(args: { request: Request }, next: () => Promise<Result>) => Promise<Result>;\n};\n\n/** The fragment of a `navigate` target, such as `#usage`, or `\"\"`. */\nfunction hashOf(to: string | number): string {\n\treturn typeof to === \"string\" && to.includes(\"#\") ? to.slice(to.indexOf(\"#\")) : \"\";\n}\n\n/**\n * Moves an open React Router tab to a new build at a navigation, so the old\n * client code never renders data from the new server, and the page that the\n * visitor reads never reloads. Create it in a module that the client entry\n * and `app/root.tsx` both import. It reads no browser state until React\n * Router calls it, so the server can import it.\n *\n * - When the data request of a navigation gets a response from a new build,\n * the browser loads the target URL as a document.\n * - When the tab already knows of a new build, a `navigate` call, such as a\n * link click, loads its target as a document before the router renders it\n * or sends a data request. The root middleware does this also for a route\n * with no loader.\n * - A revalidation, a fetcher, an action, and the loaders after an action\n * get their response. They only mark the tab, so the page that the visitor\n * reads never reloads.\n * - The router's blockers run first, and a canceled navigation never loads\n * its target.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n *\n * @example\n * // app/stale-build.ts\n * export const staleBuild = staleBuildReactRouter();\n *\n * // app/root.tsx\n * export const clientMiddleware = [staleBuild.middleware];\n *\n * // app/entry.client.tsx\n * startTransition(() => {\n * \thydrateRoot(\n * \t\tdocument,\n * \t\t<HydratedRouter\n * \t\t\tunstable_fetch={staleBuild.fetch}\n * \t\t\tinstrumentations={[staleBuild.instrumentation]}\n * \t\t/>,\n * \t);\n * });\n */\nexport function staleBuildReactRouter(options: StaleBuildOptions = {}): StaleBuildReactRouter {\n\t// Why lazy: `app/root.tsx` also runs on the server, which has no tab to watch.\n\tlet watched: { watch: ReturnType<typeof watchBuild> } | undefined;\n\tconst watch = () => {\n\t\twatched ??= { watch: watchBuild(options) };\n\t\treturn watched.watch;\n\t};\n\t/**\n\t * The path of the last action of a navigation, until its loaders run. The\n\t * router revalidates the page with one or more loader requests after it.\n\t * `loading` is true while they run.\n\t */\n\tlet action: { path: string; loading: boolean } | undefined;\n\t/** The target that the tab loads as a document now. */\n\tlet leaving: string | undefined;\n\t/**\n\t * The last `navigate` call. `claimed` is true when its first middleware call\n\t * already ran, or when it is not a page load. `page` is the target page of\n\t * that first call.\n\t */\n\tlet navigating: { hash: string; claimed: boolean; page?: string } | undefined;\n\tconst load = async (\n\t\trequest: Request,\n\t\ttarget: string,\n\t\t{ response, navigationType }: { response?: Response; navigationType?: string | null } = {},\n\t) => {\n\t\tif (leaving === target) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<never>(() => {});\n\t\t}\n\t\tleaving = target;\n\t\tonAbort(request.signal, () => {\n\t\t\tif (leaving === target) {\n\t\t\t\tleaving = undefined;\n\t\t\t}\n\t\t});\n\t\treturn loadDocument(target, { response, navigationType });\n\t};\n\treturn {\n\t\tfetch: async (request, context) => {\n\t\t\tconst navigationType =\n\t\t\t\tcontext.type === \"navigation\" && context.fetcherKey == null\n\t\t\t\t\t? context.navigationType\n\t\t\t\t\t: undefined;\n\t\t\t// Why the global at each call: an app can wrap `fetch` after this module, such as for RUM.\n\t\t\tconst send = async () => {\n\t\t\t\tconst response = await globalThis.fetch(request);\n\t\t\t\treturn { response, isNew: watch()?.isNew(response, request.url) === true };\n\t\t\t};\n\t\t\tif (watch() == null || navigationType == null) {\n\t\t\t\treturn (await send()).response;\n\t\t\t}\n\t\t\t// Why the hash of the `navigate` call: the router removes it from the data request. Why\n\t\t\t// its page only: a redirect goes to another page with no `navigate` call.\n\t\t\tconst page = targetOf(request);\n\t\t\tconst hash =\n\t\t\t\tnavigationType !== \"POP\" && navigating?.page === pageOf(page) ? navigating.hash : \"\";\n\t\t\tconst target = page + hash;\n\t\t\tconst path = new URL(target).pathname;\n\t\t\tconst isAfterAction = request.method === \"GET\" && action?.path === path;\n\t\t\t// Why check the signal: a canceled navigation must never load its target.\n\t\t\tconst isNavigation = () =>\n\t\t\t\trequest.method === \"GET\" && !isAfterAction && !request.signal.aborted;\n\t\t\tif (isNavigation() && watch()?.isStale() === true) {\n\t\t\t\treturn load(request, target, { navigationType });\n\t\t\t}\n\t\t\tconst { response, isNew } = await send();\n\t\t\tif (!isNew || !isNavigation()) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\treturn load(request, target, { response, navigationType });\n\t\t},\n\t\tinstrumentation: {\n\t\t\trouter: ({ instrument }) => {\n\t\t\t\twatch();\n\t\t\t\tinstrument({\n\t\t\t\t\tnavigate: async (handler, { to, formMethod }) => {\n\t\t\t\t\t\t// Why claimed: a history step and a form submission are not a page load to take over.\n\t\t\t\t\t\tconst current = {\n\t\t\t\t\t\t\thash: hashOf(to),\n\t\t\t\t\t\t\tclaimed: typeof to === \"number\" || (formMethod ?? \"GET\").toUpperCase() !== \"GET\",\n\t\t\t\t\t\t};\n\t\t\t\t\t\tnavigating = current;\n\t\t\t\t\t\tawait handler();\n\t\t\t\t\t\t// Why keep an unclaimed call: a blocker stops it, and `blocker.proceed()` starts it\n\t\t\t\t\t\t// again with no `navigate` call.\n\t\t\t\t\t\tif (navigating === current && current.claimed) {\n\t\t\t\t\t\t\tnavigating = undefined;\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},\n\t\tmiddleware: async (args, next) => {\n\t\t\tconst {\n\t\t\t\trequest,\n\t\t\t\tunstable_initiator: initiator,\n\t\t\t\tunstable_navigationType: navigationType,\n\t\t\t} = args as MiddlewareArgs;\n\t\t\tconst current = navigating;\n\t\t\tif (initiator === \"navigation\") {\n\t\t\t\t// Why here: a `clientAction` sends no request, and the router runs the middleware once\n\t\t\t\t// for an action and once for all the loaders after it.\n\t\t\t\tconst path = new URL(request.url).pathname;\n\t\t\t\tconst mark = action;\n\t\t\t\tif (navigationType === \"POP\") {\n\t\t\t\t\taction = undefined;\n\t\t\t\t} else if (request.method !== \"GET\") {\n\t\t\t\t\tconst started = { path, loading: false };\n\t\t\t\t\taction = started;\n\t\t\t\t\tonAbort(request.signal, () => {\n\t\t\t\t\t\tif (action === started) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn next();\n\t\t\t\t} else if (mark?.path === path) {\n\t\t\t\t\tmark.loading = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await next();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (action === mark) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (mark?.loading === false) {\n\t\t\t\t\t// Why: a redirect after the action goes to another page, and its loaders never run.\n\t\t\t\t\t// Why not while they run: the router revalidates the fetchers next to them.\n\t\t\t\t\taction = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Why no history step: it comes from no `navigate` call, and the fetch hook reloads it.\n\t\t\t// Why the first call only: the router runs the middleware of a navigation before the\n\t\t\t// fetchers that it revalidates, and they have the same initiator.\n\t\t\tif (\n\t\t\t\tinitiator !== \"navigation\" ||\n\t\t\t\tnavigationType == null ||\n\t\t\t\tnavigationType === \"POP\" ||\n\t\t\t\tcurrent == null ||\n\t\t\t\tcurrent.claimed\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tcurrent.claimed = true;\n\t\t\tcurrent.page = pageOf(request.url);\n\t\t\tif (\n\t\t\t\trequest.signal.aborted ||\n\t\t\t\twatch()?.isStale() !== true ||\n\t\t\t\tpageOf(request.url) === pageOf(location.href)\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\treturn load(request, request.url + current.hash, { navigationType });\n\t\t},\n\t};\n}\n\n/**\n * Moves an open TanStack Router tab to a new build at a navigation, so the\n * old client code never renders data from the new server, and the page that\n * the visitor reads never reloads. Call it with the router on the client.\n *\n * - A navigation runs from `onBeforeNavigate` to `onResolved`. The router\n * moves history and runs its blockers before it.\n * - When a GET response from a new build comes back while a navigation\n * runs, such as from a server function in a loader, the browser loads the\n * page as a document.\n * - When the tab already knows of a new build, a navigation to a new path or\n * query clears the router cache and loads the page as a document.\n * - A request outside a navigation gets its response, and only marks the tab.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n * It returns a function that stops it and gives back `fetch`. If the app\n * wrapped `fetch` after it, the wrapper stays, and each request passes on.\n *\n * @example\n * // src/router.tsx\n * export function getRouter() {\n * \tconst router = createRouter({ routeTree });\n * \tif (!router.isServer) {\n * \t\tstaleBuildTanStack(router);\n * \t}\n * \treturn router;\n * }\n */\nexport function staleBuildTanStack(\n\trouter: NavigationEvents,\n\toptions: StaleBuildOptions = {},\n): () => void {\n\tconst watch = watchBuild(options);\n\tif (watch == null) {\n\t\treturn () => {};\n\t}\n\t/** The navigation that runs now. `leaving` is true when it already loads its page as a document. */\n\tlet navigation: { leaving: boolean } | undefined;\n\tconst reload = async (current: { leaving: boolean }, response?: Response) => {\n\t\tif (current.leaving) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<Response>(() => {});\n\t\t}\n\t\tcurrent.leaving = true;\n\t\t// Why flush: the router's history moves the browser's URL in a microtask, after\n\t\t// `onBeforeNavigate`. A reload before that loads the page that the visitor leaves.\n\t\trouter.history.flush();\n\t\treturn loadDocument(location.href, { response });\n\t};\n\tconst unsubscribe = [\n\t\trouter.subscribe(\"onBeforeNavigate\", ({ fromLocation, toLocation }) => {\n\t\t\t// Why clear first: a change to the fragment replaces a navigation that has not ended.\n\t\t\tnavigation = undefined;\n\t\t\tif (fromLocation == null || eventPage(fromLocation) === eventPage(toLocation)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tnavigation = { leaving: false };\n\t\t\tif (watch.isStale()) {\n\t\t\t\t// Why clear: the router matches the target after this event, and a preload can hold the\n\t\t\t\t// new build's data. With no cache, each loader fetches again, and `fetch` holds it.\n\t\t\t\trouter.clearCache();\n\t\t\t\tvoid reload(navigation);\n\t\t\t}\n\t\t}),\n\t\trouter.subscribe(\"onResolved\", () => {\n\t\t\tnavigation = undefined;\n\t\t}),\n\t];\n\tconst send = globalThis.fetch;\n\tlet isStopped = false;\n\tconst patched: typeof fetch = async (input, init) => {\n\t\tif (isStopped) {\n\t\t\treturn send.call(globalThis, input, init);\n\t\t}\n\t\tconst isGet = methodOf(input, init) === \"GET\";\n\t\tif (isGet && navigation != null && watch.isStale()) {\n\t\t\treturn reload(navigation);\n\t\t}\n\t\tconst response = await send.call(globalThis, input, init);\n\t\t// Why the navigation at the response: a navigation can take the pending loader of a preload,\n\t\t// or of the navigation that it replaced.\n\t\tif (!watch.isNew(response, urlOf(input)) || !isGet || navigation == null) {\n\t\t\treturn response;\n\t\t}\n\t\treturn reload(navigation, response);\n\t};\n\tglobalThis.fetch = patched;\n\treturn () => {\n\t\tfor (const stop of unsubscribe) {\n\t\t\tstop();\n\t\t}\n\t\twatch.stop();\n\t\tisStopped = true;\n\t\tnavigation = undefined;\n\t\t// Why check: a wrapper that the app adds later still calls this one, and must stay.\n\t\tif (globalThis.fetch === patched) {\n\t\t\tglobalThis.fetch = send;\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAgB,gBAAoC;CAEnD,OAAO,SAAS,cAA2B,SAAS,CAAC,EAAE;AACxD;;;;ACwCA,SAAS,MAAM,KAAsB;CACpC,OAAO,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,WAAW,SAAS;AACxD;;AAGA,SAAS,YAAY,SAAmD;CACvE,OACC,QACE,QACC,UAA8C,kBAAkB,SAAS,MAAM,MAAM,IAAI,CAC3F,CAAC,CAGA,QAAQ,UAAU,MAAM,cAAc,cAAc,MAAM,kBAAkB,CAAC,CAAC,CAC9E,SAAS,UAAU,MAAM,YAAY,CAAC,CACtC,MAAM,WAAW,OAAO,SAAS,eAAe,CAAC,EAAE;AAEvD;;AAGA,SAAS,YAAY,QAA2C;CAC/D,MAAM,EAAE,QAAQ,UACf,oBAAoB,MAAM,CAAC,CACzB,MAAM,WAAW,cAAc,MAAM,CAAC,CAAC,EACtC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AO;EAER,OAAO,OAAO,YAAY,QAAQ;CACnC;CACA,WAAW,QAAQ;CACnB,aAAa;EACZ,KAAK,MAAM,QAAQ,aAClB,KAAK;EAEN,MAAM,KAAK;EACX,YAAY;EACZ,aAAa;EAEb,IAAI,WAAW,UAAU,SACxB,WAAW,QAAQ;CAErB;AACD"}
|
|
1
|
+
{"version":3,"file":"stale-build-navigation-rg5xxmTr.js","names":[],"sources":["../src/client/document-nonce.ts","../src/client/stale-build-navigation.ts"],"sourcesContent":["/**\n * The CSP nonce of the document's first element with a nonce, or `undefined`\n * when it has none. The browser build of `@ngrok/app-server/client` exports it\n * as `cspNonce()`, so the browser bundle holds no server code.\n *\n * @example\n * documentNonce(); // => \"d2hhdCBhIG5vbmNl\"\n */\nexport function documentNonce(): string | undefined {\n\t// Why the property: a browser hides the value of the `nonce` attribute when the page's CSP applies.\n\treturn document.querySelector<HTMLElement>(\"[nonce]\")?.nonce;\n}\n","import {\n\tBUILD_ID_HEADER,\n\tBUILD_ID_METRIC,\n\tisBuildMetric,\n\tserverTimingMetrics,\n} from \"../core/plugins/build-id.js\";\n\n/** Options for {@link staleBuildReactRouter} and {@link staleBuildTanStack}. */\nexport type StaleBuildOptions = {\n\t/**\n\t * The header that `buildId()` sets on data responses.\n\t * @default \"X-Build-Id\"\n\t */\n\theader?: string;\n\t/**\n\t * The build that this document runs. Set it only when the server does not\n\t * send it.\n\t * @default the `build` metric of the document's `Server-Timing`, which `buildId()` sends\n\t */\n\tbuild?: string;\n\t/**\n\t * Runs once, when the tab first sees a response from another build. Use\n\t * it to count stale tabs in the app's RUM tool.\n\t */\n\tonNewBuild?: (served: string) => void;\n};\n\n/** The context that React Router gives `unstable_fetch` with each request. */\nexport type RouterFetchContext = {\n\t/** `\"navigation\"` for the data request of a navigation that the router started. */\n\ttype: string;\n\t/** `\"PUSH\"`, `\"REPLACE\"`, or `\"POP\"` for a navigation. */\n\tnavigationType?: string | null;\n\t/** The fetcher that sends the request, also in a navigation that revalidates it. */\n\tfetcherKey?: string | null;\n};\n\n/** The location in a TanStack Router event. */\ntype EventLocation = { pathname: string; searchStr: string };\n\n/** The part of a TanStack Router that {@link staleBuildTanStack} reads. */\nexport type NavigationEvents = {\n\thistory: { flush: () => void };\n\tclearCache: () => void;\n\tsubscribe: (\n\t\ttype: \"onBeforeNavigate\" | \"onResolved\",\n\t\tlistener: (event: { fromLocation?: EventLocation; toLocation: EventLocation }) => void,\n\t) => () => void;\n};\n\n/** Whether `url` is on the origin of this page. */\nfunction isOwn(url: string): boolean {\n\treturn new URL(url, location.href).origin === location.origin;\n}\n\n/** The build in the `Server-Timing` of the first of `entries` that has one, from this origin only. */\nfunction timingBuild(entries: PerformanceEntryList): string | undefined {\n\treturn (\n\t\tentries\n\t\t\t.filter(\n\t\t\t\t(entry): entry is PerformanceResourceTiming => \"serverTiming\" in entry && isOwn(entry.name),\n\t\t\t)\n\t\t\t// Why: a redirected resource keeps its first URL as its name, and the redirect can end on\n\t\t\t// another origin. A document entry has its final URL.\n\t\t\t.filter((entry) => entry.entryType !== \"resource\" || entry.redirectStart === 0)\n\t\t\t.flatMap((entry) => entry.serverTiming)\n\t\t\t.find((metric) => metric.name === BUILD_ID_METRIC)?.description\n\t);\n}\n\n/** The build in a `Server-Timing` header, as `buildId()` writes it. */\nfunction headerBuild(header: string | null): string | undefined {\n\tconst { quoted, token } =\n\t\tserverTimingMetrics(header)\n\t\t\t.find((metric) => isBuildMetric(metric))\n\t\t\t?.match(/;\\s*desc\\s*=\\s*(?:\"(?<quoted>(?:[^\"\\\\]|\\\\.)*)\"|(?<token>[^;\\s]*))/iu)?.groups ?? {};\n\treturn quoted?.replaceAll(/\\\\(?<char>.)/gu, \"$<char>\") ?? token;\n}\n\n/** The page of `url`: the router renders a new route for a new path or query, not for a new fragment. */\nfunction pageOf(url: string): string {\n\tconst { origin, pathname, search } = new URL(url, location.href);\n\treturn `${origin}${pathname}${search}`;\n}\n\n/** The page of a TanStack Router location, as {@link pageOf} reads a URL. */\nfunction eventPage({ pathname, searchStr }: EventLocation): string {\n\treturn `${pathname}${searchStr}`;\n}\n\n/** The URL of a `fetch` call. */\nfunction urlOf(input: RequestInfo | URL): string {\n\treturn input instanceof Request ? input.url : String(input);\n}\n\n/** The method of a `fetch` call. */\nfunction methodOf(input: RequestInfo | URL, init: RequestInit | undefined): string {\n\treturn (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n}\n\n/** The page that a React Router data request loads: `/a.data` loads `/a`, and `/a/_.data` loads `/a/`. */\nfunction targetOf(request: Request): string {\n\tconst url = new URL(request.url);\n\turl.pathname = url.pathname.replace(/\\/_\\.data$/u, \"/\").replace(/\\.data$/u, \"\");\n\turl.searchParams.delete(\"_routes\");\n\treturn url.href;\n}\n\n/**\n * Reloads a document that the back/forward cache shows again. Why: Back can\n * show the document that {@link loadDocument} left, with its router still in a\n * navigation that never ends. Why one function: the browser adds it once.\n */\nfunction reloadIfRestored(event: PageTransitionEvent): void {\n\tif (event.persisted) {\n\t\tlocation.reload();\n\t}\n}\n\n/**\n * Loads `target` as a document, so the old code never gets the new build's\n * data. It returns a promise that never settles, because the page unloads.\n */\nasync function loadDocument(\n\ttarget: string,\n\t{\n\t\tresponse,\n\t\tnavigationType,\n\t}: { response?: Response | undefined; navigationType?: string | null | undefined } = {},\n): Promise<never> {\n\t// Why no wait: the cancel of a cloned body waits for the other branch.\n\tresponse?.body?.cancel().catch(() => undefined);\n\t// Why reload on this page: the router can move history first, and `assign` to the same page\n\t// with a fragment scrolls with no document load. A history step already moved history. Why\n\t// not to remove a fragment: `assign` to a URL with no fragment loads the document.\n\tconst isSamePage = pageOf(target) === pageOf(location.href);\n\tconst removesFragment = new URL(target, location.href).hash === \"\" && location.hash !== \"\";\n\taddEventListener(\"pageshow\", reloadIfRestored, { once: true });\n\tif (navigationType === \"POP\" || (isSamePage && !removesFragment)) {\n\t\tlocation.reload();\n\t} else if (navigationType === \"REPLACE\") {\n\t\tlocation.replace(target);\n\t} else {\n\t\tlocation.assign(target);\n\t}\n\treturn new Promise<never>(() => {});\n}\n\n/**\n * Runs `clear` when `signal` aborts. Why: the router aborts a navigation when a\n * newer one starts, such as after the visitor stays on the page at a leave prompt.\n */\nfunction onAbort(signal: AbortSignal, clear: () => void): void {\n\tsignal.addEventListener(\"abort\", clear, { once: true });\n}\n\n/** Reads the build of each response, and tells when the server runs a new build. */\nfunction watchBuild({ header = BUILD_ID_HEADER, build, onNewBuild }: StaleBuildOptions) {\n\t// Why: on the server, such as in a router factory that runs for each request, there is no tab to move.\n\tif (typeof document === \"undefined\") {\n\t\treturn null;\n\t}\n\tconst current = build ?? timingBuild(performance.getEntriesByType(\"navigation\"));\n\tif (current == null) {\n\t\treturn null;\n\t}\n\tlet stale = false;\n\tconst see = (served: string | null | undefined) => {\n\t\tif (served == null || served === current || stale) {\n\t\t\treturn;\n\t\t}\n\t\tstale = true;\n\t\t// Why a catch: an error in the app's callback must not fail the request that found the build.\n\t\ttry {\n\t\t\tonNewBuild?.(served);\n\t\t} catch (error) {\n\t\t\treportError(error);\n\t\t}\n\t};\n\t// Why resource timing: it shows the build of a response that no script fetched, such as a\n\t// prefetch on hover, so the tab can find a new build before the click. Why buffered: a prefetch\n\t// can finish before this module runs.\n\tconst observer =\n\t\ttypeof PerformanceObserver === \"function\"\n\t\t\t? new PerformanceObserver((list) => {\n\t\t\t\t\t// Why each entry: one delivery can hold the old build first and the new build after it.\n\t\t\t\t\tfor (const entry of list.getEntries()) {\n\t\t\t\t\t\tsee(timingBuild([entry]));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: undefined;\n\tobserver?.observe({ type: \"resource\", buffered: true });\n\treturn {\n\t\tisStale: () => stale,\n\t\t/** Whether `response` comes from a new build of this origin. `url` is the URL of the request. */\n\t\tisNew: (response: Response, url: string) => {\n\t\t\t// Why the final URL: a redirect can end on another origin. Why `Server-Timing`: a proxy\n\t\t\t// route of `buildId({ paths })` sends no build header.\n\t\t\tconst served = isOwn(response.url === \"\" ? url : response.url)\n\t\t\t\t? (response.headers.get(header) ?? headerBuild(response.headers.get(\"Server-Timing\")))\n\t\t\t\t: null;\n\t\t\tsee(served);\n\t\t\treturn served != null && served !== current;\n\t\t},\n\t\tstop: () => observer?.disconnect(),\n\t};\n}\n\n/** The `navigate` call of a React Router instrumentation. */\ntype NavigateInfo = { to: string | number; formMethod?: string };\n\n/** The router instrumentations that {@link staleBuildReactRouter} adds. */\ntype RouterInstrumentations = {\n\tnavigate: (handler: () => Promise<unknown>, info: NavigateInfo) => Promise<void>;\n};\n\n/**\n * The arguments of a client middleware call. Why the `unstable_` fields: React\n * Router gives the middleware the arguments of its data strategy, which tell a\n * navigation from a fetcher and give its history action.\n */\ntype MiddlewareArgs = {\n\trequest: Request;\n\tunstable_initiator?: string;\n\tunstable_navigationType?: string | null;\n};\n\n/** The hooks that {@link staleBuildReactRouter} gives to React Router. */\nexport type StaleBuildReactRouter = {\n\t/** Give it to `HydratedRouter` as `unstable_fetch`. */\n\tfetch: (request: Request, context: RouterFetchContext) => Promise<Response>;\n\t/** Give it to `HydratedRouter` in `instrumentations`. */\n\tinstrumentation: {\n\t\trouter: (router: { instrument: (instrumentations: RouterInstrumentations) => void }) => void;\n\t};\n\t/** Export it from `app/root.tsx` in `clientMiddleware`. */\n\tmiddleware: <Result>(args: { request: Request }, next: () => Promise<Result>) => Promise<Result>;\n};\n\n/** The fragment of a `navigate` target, such as `#usage`, or `\"\"`. */\nfunction hashOf(to: string | number): string {\n\treturn typeof to === \"string\" && to.includes(\"#\") ? to.slice(to.indexOf(\"#\")) : \"\";\n}\n\n/**\n * Moves an open React Router tab to a new build at a navigation, so the old\n * client code never renders data from the new server, and the page that the\n * visitor reads never reloads. Create it in a module that the client entry\n * and `app/root.tsx` both import. It reads no browser state until React\n * Router calls it, so the server can import it.\n *\n * - When the data request of a navigation gets a response from a new build,\n * the browser loads the target URL as a document.\n * - When the tab already knows of a new build, a `navigate` call, such as a\n * link click, loads its target as a document before the router renders it\n * or sends a data request. The root middleware does this also for a route\n * with no loader.\n * - A revalidation, a fetcher, an action, and the loaders after an action\n * get their response. They only mark the tab, so the page that the visitor\n * reads never reloads.\n * - The router's blockers run first, and a canceled navigation never loads\n * its target.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n *\n * @example\n * // app/stale-build.ts\n * export const staleBuild = staleBuildReactRouter();\n *\n * // app/root.tsx\n * export const clientMiddleware = [staleBuild.middleware];\n *\n * // app/entry.client.tsx\n * startTransition(() => {\n * \thydrateRoot(\n * \t\tdocument,\n * \t\t<HydratedRouter\n * \t\t\tunstable_fetch={staleBuild.fetch}\n * \t\t\tinstrumentations={[staleBuild.instrumentation]}\n * \t\t/>,\n * \t);\n * });\n */\nexport function staleBuildReactRouter(options: StaleBuildOptions = {}): StaleBuildReactRouter {\n\t// Why lazy: `app/root.tsx` also runs on the server, which has no tab to watch.\n\tlet watched: { watch: ReturnType<typeof watchBuild> } | undefined;\n\tconst watch = () => {\n\t\twatched ??= { watch: watchBuild(options) };\n\t\treturn watched.watch;\n\t};\n\t/**\n\t * The path of the last action of a navigation, until its loaders run. The\n\t * router revalidates the page with one or more loader requests after it.\n\t * `loading` is true while they run.\n\t */\n\tlet action: { path: string; loading: boolean } | undefined;\n\t/** The target that the tab loads as a document now. */\n\tlet leaving: string | undefined;\n\t/**\n\t * The last `navigate` call. `claimed` is true when its first middleware call\n\t * already ran, or when it is not a page load. `page` is the target page of\n\t * that first call.\n\t */\n\tlet navigating: { hash: string; claimed: boolean; page?: string } | undefined;\n\tconst load = async (\n\t\trequest: Request,\n\t\ttarget: string,\n\t\t{ response, navigationType }: { response?: Response; navigationType?: string | null } = {},\n\t) => {\n\t\tif (leaving === target) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<never>(() => {});\n\t\t}\n\t\tleaving = target;\n\t\tonAbort(request.signal, () => {\n\t\t\tif (leaving === target) {\n\t\t\t\tleaving = undefined;\n\t\t\t}\n\t\t});\n\t\treturn loadDocument(target, { response, navigationType });\n\t};\n\treturn {\n\t\tfetch: async (request, context) => {\n\t\t\tconst navigationType =\n\t\t\t\tcontext.type === \"navigation\" && context.fetcherKey == null\n\t\t\t\t\t? context.navigationType\n\t\t\t\t\t: undefined;\n\t\t\t// Why the global at each call: an app can wrap `fetch` after this module, such as for RUM.\n\t\t\tconst send = async () => {\n\t\t\t\tconst response = await globalThis.fetch(request);\n\t\t\t\treturn { response, isNew: watch()?.isNew(response, request.url) === true };\n\t\t\t};\n\t\t\tif (watch() == null || navigationType == null) {\n\t\t\t\treturn (await send()).response;\n\t\t\t}\n\t\t\t// Why the hash of the `navigate` call: the router removes it from the data request. Why\n\t\t\t// its page only: a redirect goes to another page with no `navigate` call.\n\t\t\tconst page = targetOf(request);\n\t\t\tconst hash =\n\t\t\t\tnavigationType !== \"POP\" && navigating?.page === pageOf(page) ? navigating.hash : \"\";\n\t\t\tconst target = page + hash;\n\t\t\tconst path = new URL(target).pathname;\n\t\t\tconst isAfterAction = request.method === \"GET\" && action?.path === path;\n\t\t\t// Why check the signal: a canceled navigation must never load its target.\n\t\t\tconst isNavigation = () =>\n\t\t\t\trequest.method === \"GET\" && !isAfterAction && !request.signal.aborted;\n\t\t\tif (isNavigation() && watch()?.isStale() === true) {\n\t\t\t\treturn load(request, target, { navigationType });\n\t\t\t}\n\t\t\tconst { response, isNew } = await send();\n\t\t\tif (!isNew || !isNavigation()) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\treturn load(request, target, { response, navigationType });\n\t\t},\n\t\tinstrumentation: {\n\t\t\trouter: ({ instrument }) => {\n\t\t\t\twatch();\n\t\t\t\tinstrument({\n\t\t\t\t\tnavigate: async (handler, { to, formMethod }) => {\n\t\t\t\t\t\t// Why claimed: a history step and a form submission are not a page load to take over.\n\t\t\t\t\t\tconst current = {\n\t\t\t\t\t\t\thash: hashOf(to),\n\t\t\t\t\t\t\tclaimed: typeof to === \"number\" || (formMethod ?? \"GET\").toUpperCase() !== \"GET\",\n\t\t\t\t\t\t};\n\t\t\t\t\t\tnavigating = current;\n\t\t\t\t\t\tawait handler();\n\t\t\t\t\t\t// Why keep an unclaimed call: a blocker stops it, and `blocker.proceed()` starts it\n\t\t\t\t\t\t// again with no `navigate` call.\n\t\t\t\t\t\tif (navigating === current && current.claimed) {\n\t\t\t\t\t\t\tnavigating = undefined;\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},\n\t\tmiddleware: async (args, next) => {\n\t\t\tconst {\n\t\t\t\trequest,\n\t\t\t\tunstable_initiator: initiator,\n\t\t\t\tunstable_navigationType: navigationType,\n\t\t\t} = args as MiddlewareArgs;\n\t\t\tconst current = navigating;\n\t\t\tif (initiator === \"navigation\") {\n\t\t\t\t// Why here: a `clientAction` sends no request, and the router runs the middleware once\n\t\t\t\t// for an action and once for all the loaders after it.\n\t\t\t\tconst path = new URL(request.url).pathname;\n\t\t\t\tconst mark = action;\n\t\t\t\tif (navigationType === \"POP\") {\n\t\t\t\t\taction = undefined;\n\t\t\t\t} else if (request.method !== \"GET\") {\n\t\t\t\t\tconst started = { path, loading: false };\n\t\t\t\t\taction = started;\n\t\t\t\t\tonAbort(request.signal, () => {\n\t\t\t\t\t\tif (action === started) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn next();\n\t\t\t\t} else if (mark?.path === path) {\n\t\t\t\t\tmark.loading = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await next();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (action === mark) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (mark?.loading === false) {\n\t\t\t\t\t// Why: a redirect after the action goes to another page, and its loaders never run.\n\t\t\t\t\t// Why not while they run: the router revalidates the fetchers next to them.\n\t\t\t\t\taction = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Why no history step: it comes from no `navigate` call, and the fetch hook reloads it.\n\t\t\t// Why the first call only: the router runs the middleware of a navigation before the\n\t\t\t// fetchers that it revalidates, and they have the same initiator.\n\t\t\tif (\n\t\t\t\tinitiator !== \"navigation\" ||\n\t\t\t\tnavigationType == null ||\n\t\t\t\tnavigationType === \"POP\" ||\n\t\t\t\tcurrent == null ||\n\t\t\t\tcurrent.claimed\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tcurrent.claimed = true;\n\t\t\tcurrent.page = pageOf(request.url);\n\t\t\tif (\n\t\t\t\trequest.signal.aborted ||\n\t\t\t\twatch()?.isStale() !== true ||\n\t\t\t\tpageOf(request.url) === pageOf(location.href)\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\treturn load(request, request.url + current.hash, { navigationType });\n\t\t},\n\t};\n}\n\n/**\n * Moves an open TanStack Router tab to a new build at a navigation, so the\n * old client code never renders data from the new server, and the page that\n * the visitor reads never reloads. Call it with the router on the client.\n *\n * - A navigation runs from `onBeforeNavigate` to `onResolved`. The router\n * moves history and runs its blockers before it.\n * - When a GET response from a new build comes back while a navigation\n * runs, such as from a server function in a loader, the browser loads the\n * page as a document.\n * - When the tab already knows of a new build, a navigation to a new path or\n * query clears the router cache and loads the page as a document.\n * - A request outside a navigation gets its response, and only marks the tab.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n * It returns a function that stops it and gives back `fetch`. If the app\n * wrapped `fetch` after it, the wrapper stays, and each request passes on.\n *\n * @example\n * // src/router.tsx\n * export function getRouter() {\n * \tconst router = createRouter({ routeTree });\n * \tif (!router.isServer) {\n * \t\tstaleBuildTanStack(router);\n * \t}\n * \treturn router;\n * }\n */\nexport function staleBuildTanStack(\n\trouter: NavigationEvents,\n\toptions: StaleBuildOptions = {},\n): () => void {\n\tconst watch = watchBuild(options);\n\tif (watch == null) {\n\t\treturn () => {};\n\t}\n\t/** The navigation that runs now. `leaving` is true when it already loads its page as a document. */\n\tlet navigation: { leaving: boolean } | undefined;\n\tconst reload = async (current: { leaving: boolean }, response?: Response) => {\n\t\tif (current.leaving) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<Response>(() => {});\n\t\t}\n\t\tcurrent.leaving = true;\n\t\t// Why flush: the router's history moves the browser's URL in a microtask, after\n\t\t// `onBeforeNavigate`. A reload before that loads the page that the visitor leaves.\n\t\trouter.history.flush();\n\t\treturn loadDocument(location.href, { response });\n\t};\n\tconst unsubscribe = [\n\t\trouter.subscribe(\"onBeforeNavigate\", ({ fromLocation, toLocation }) => {\n\t\t\t// Why clear first: a change to the fragment replaces a navigation that has not ended.\n\t\t\tnavigation = undefined;\n\t\t\tif (fromLocation == null || eventPage(fromLocation) === eventPage(toLocation)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tnavigation = { leaving: false };\n\t\t\tif (watch.isStale()) {\n\t\t\t\t// Why clear: the router matches the target after this event, and a preload can hold the\n\t\t\t\t// new build's data. With no cache, each loader fetches again, and `fetch` holds it.\n\t\t\t\trouter.clearCache();\n\t\t\t\tvoid reload(navigation);\n\t\t\t}\n\t\t}),\n\t\trouter.subscribe(\"onResolved\", () => {\n\t\t\tnavigation = undefined;\n\t\t}),\n\t];\n\tconst send = globalThis.fetch;\n\tlet isStopped = false;\n\tconst patched: typeof fetch = async (input, init) => {\n\t\tif (isStopped) {\n\t\t\treturn send.call(globalThis, input, init);\n\t\t}\n\t\tconst isGet = methodOf(input, init) === \"GET\";\n\t\tif (isGet && navigation != null && watch.isStale()) {\n\t\t\treturn reload(navigation);\n\t\t}\n\t\tconst response = await send.call(globalThis, input, init);\n\t\t// Why the navigation at the response: a navigation can take the pending loader of a preload,\n\t\t// or of the navigation that it replaced.\n\t\tif (!watch.isNew(response, urlOf(input)) || !isGet || navigation == null) {\n\t\t\treturn response;\n\t\t}\n\t\treturn reload(navigation, response);\n\t};\n\tglobalThis.fetch = patched;\n\treturn () => {\n\t\tfor (const stop of unsubscribe) {\n\t\t\tstop();\n\t\t}\n\t\twatch.stop();\n\t\tisStopped = true;\n\t\tnavigation = undefined;\n\t\t// Why check: a wrapper that the app adds later still calls this one, and must stay.\n\t\tif (globalThis.fetch === patched) {\n\t\t\tglobalThis.fetch = send;\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAgB,gBAAoC;CAEnD,OAAO,SAAS,cAA2B,SAAS,CAAC,EAAE;AACxD;;;;ACwCA,SAAS,MAAM,KAAsB;CACpC,OAAO,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,WAAW,SAAS;AACxD;;AAGA,SAAS,YAAY,SAAmD;CACvE,OACC,QACE,QACC,UAA8C,kBAAkB,SAAS,MAAM,MAAM,IAAI,CAC3F,CAAC,CAGA,QAAQ,UAAU,MAAM,cAAc,cAAc,MAAM,kBAAkB,CAAC,CAAC,CAC9E,SAAS,UAAU,MAAM,YAAY,CAAC,CACtC,MAAM,WAAW,OAAO,SAAS,eAAe,CAAC,EAAE;AAEvD;;AAGA,SAAS,YAAY,QAA2C;CAC/D,MAAM,EAAE,QAAQ,UACf,oBAAoB,MAAM,CAAC,CACzB,MAAM,WAAW,cAAc,MAAM,CAAC,CAAC,EACtC,MAAM,qEAAqE,CAAC,EAAE,UAAU,CAAC;CAC7F,OAAO,QAAQ,WAAW,kBAAkB,SAAS,KAAK;AAC3D;;AAGA,SAAS,OAAO,KAAqB;CACpC,MAAM,EAAE,QAAQ,UAAU,WAAW,IAAI,IAAI,KAAK,SAAS,IAAI;CAC/D,OAAO,GAAG,SAAS,WAAW;AAC/B;;AAGA,SAAS,UAAU,EAAE,UAAU,aAAoC;CAClE,OAAO,GAAG,WAAW;AACtB;;AAGA,SAAS,MAAM,OAAkC;CAChD,OAAO,iBAAiB,UAAU,MAAM,MAAM,OAAO,KAAK;AAC3D;;AAGA,SAAS,SAAS,OAA0B,MAAuC;CAClF,QAAQ,MAA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