@ngrok/app-server 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +610 -76
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/{build-manifest-8NfD1wnO.js → build-manifest-UDNk81Ce.js} +24 -6
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/cli.js +45 -25
  7. package/dist/cli.js.map +1 -1
  8. package/dist/client.d.ts +141 -0
  9. package/dist/client.js +326 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/compression-7_gToa8R.js +97 -0
  12. package/dist/compression-7_gToa8R.js.map +1 -0
  13. package/dist/create-server-iE1-s6Bi.js +1409 -0
  14. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  15. package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
  16. package/dist/deno-aqhikNMG.js.map +1 -0
  17. package/dist/entry-DZ3qo7qF.js +116 -0
  18. package/dist/entry-DZ3qo7qF.js.map +1 -0
  19. package/dist/entry-DmJEqVfd.d.ts +622 -0
  20. package/dist/gzip-Doi4wqjX.js +294 -0
  21. package/dist/gzip-Doi4wqjX.js.map +1 -0
  22. package/dist/header-hook-Vzw9J9BY.js +159 -0
  23. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  24. package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
  25. package/dist/index.d.ts +99 -269
  26. package/dist/index.js +47 -59
  27. package/dist/index.js.map +1 -1
  28. package/dist/listen-options-7TaXjyrk.js.map +1 -1
  29. package/dist/{load-entry-C03qqmhr.js → load-entry-AfYS_zS9.js} +8 -4
  30. package/dist/{load-entry-C03qqmhr.js.map → load-entry-AfYS_zS9.js.map} +1 -1
  31. package/dist/log-BP6xXXZl.js +122 -0
  32. package/dist/log-BP6xXXZl.js.map +1 -0
  33. package/dist/node-BFH82eeL.js +333 -0
  34. package/dist/node-BFH82eeL.js.map +1 -0
  35. package/dist/node-tBVQPjQv.js +41 -0
  36. package/dist/node-tBVQPjQv.js.map +1 -0
  37. package/dist/node-vite.d.ts +5 -4
  38. package/dist/node-vite.js +2 -17
  39. package/dist/node.d.ts +23 -4
  40. package/dist/node.js +2 -2
  41. package/dist/react-router-vite.d.ts +4 -3
  42. package/dist/react-router-vite.js +2 -20
  43. package/dist/react-router.d.ts +1 -1
  44. package/dist/react-router.js +8 -7
  45. package/dist/react-router.js.map +1 -1
  46. package/dist/request-context-BtQ87VYb.js +40 -0
  47. package/dist/request-context-BtQ87VYb.js.map +1 -0
  48. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  49. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  50. package/dist/response-writer-B7FoJjEE.js +289 -0
  51. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  52. package/dist/script-hashes-hqUk6kG7.js +53 -0
  53. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  54. package/dist/{serve-Cleo8RMO.js → serve-CDNgThjk.js} +3 -3
  55. package/dist/{serve-Cleo8RMO.js.map → serve-CDNgThjk.js.map} +1 -1
  56. package/dist/{start-CINALHxy.js → start-TLIprD74.js} +14 -19
  57. package/dist/start-TLIprD74.js.map +1 -0
  58. package/dist/static-files-Beju9riB.js +302 -0
  59. package/dist/static-files-Beju9riB.js.map +1 -0
  60. package/dist/tanstack-start-vite.d.ts +6 -5
  61. package/dist/tanstack-start-vite.js +2 -23
  62. package/dist/tanstack-start.d.ts +19 -2
  63. package/dist/tanstack-start.js +5 -14
  64. package/dist/tanstack-start.js.map +1 -1
  65. package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
  66. package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
  67. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  68. package/dist/types-DLYxYS6M.d.ts +392 -0
  69. package/dist/vercel-vite.d.ts +35 -0
  70. package/dist/vercel-vite.js +142 -0
  71. package/dist/vercel-vite.js.map +1 -0
  72. package/dist/vercel.d.ts +35 -0
  73. package/dist/vercel.js +89 -0
  74. package/dist/vercel.js.map +1 -0
  75. package/dist/vite-B-GfswoH.js +22 -0
  76. package/dist/vite-B-GfswoH.js.map +1 -0
  77. package/dist/vite-D4hfj3ph.js +19 -0
  78. package/dist/vite-D4hfj3ph.js.map +1 -0
  79. package/dist/vite-DyrhyKEr.js +25 -0
  80. package/dist/vite-DyrhyKEr.js.map +1 -0
  81. package/dist/vite-iioAoxSt.js +752 -0
  82. package/dist/vite-iioAoxSt.js.map +1 -0
  83. package/dist/vite.d.ts +2 -2
  84. package/dist/vite.js +1 -1
  85. package/package.json +24 -4
  86. package/dist/build-manifest-8NfD1wnO.js.map +0 -1
  87. package/dist/deno-DNRgzHrk.js.map +0 -1
  88. package/dist/entry-BkdUub2S.js +0 -638
  89. package/dist/entry-BkdUub2S.js.map +0 -1
  90. package/dist/log-CsjaKM8U.js +0 -59
  91. package/dist/log-CsjaKM8U.js.map +0 -1
  92. package/dist/node-CG7qXuWZ.js +0 -58
  93. package/dist/node-CG7qXuWZ.js.map +0 -1
  94. package/dist/node-YWPGmzAk.js +0 -215
  95. package/dist/node-YWPGmzAk.js.map +0 -1
  96. package/dist/node-ZMowKZDB.js +0 -3
  97. package/dist/node-vite.js.map +0 -1
  98. package/dist/react-router-vite.js.map +0 -1
  99. package/dist/start-CINALHxy.js.map +0 -1
  100. package/dist/tanstack-start-vite.js.map +0 -1
  101. package/dist/types-BfCkS7kQ.d.ts +0 -203
  102. package/dist/vite-mYZ2Y69u.js +0 -144
  103. package/dist/vite-mYZ2Y69u.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/core/event-stream.ts","../src/core/plugins/build-id.ts","../src/core/plugins/runtime-env.ts"],"sourcesContent":["import { shutdownSignal } from \"./shutdown.js\";\n\n/** One server-sent event. */\nexport type ServerSentEvent = {\n\tdata: string;\n\tevent?: string;\n\tid?: string;\n};\n\n/** What {@link eventStream} passes to its producer. */\nexport type EventStreamSink = {\n\tsend: (event: ServerSentEvent) => void;\n\t/** Aborts when the client disconnects or the server shuts down. Stop the work on it. */\n\tsignal: AbortSignal;\n};\n\n/** Options for {@link eventStream}. */\nexport type EventStreamOptions = {\n\t/** The request's signal, so a client disconnect stops the stream. */\n\tsignal?: AbortSignal;\n\t/**\n\t * How often a `: ping` comment goes out, so that a proxy keeps a quiet stream open.\n\t * @default 15000\n\t */\n\theartbeatMs?: number;\n\t/** Extra response headers. */\n\theaders?: HeadersInit;\n};\n\nfunction formatEvent({ data, event, id }: ServerSentEvent): string {\n\t// Why: a line break in `event` or `id` would start another field or event.\n\tif (/[\\r\\n]/u.test(`${event ?? \"\"}${id ?? \"\"}`)) {\n\t\tthrow new TypeError(\"An event's `event` and `id` cannot contain a line break.\");\n\t}\n\tconst lines = [\n\t\t...(event == null ? [] : [`event: ${event}`]),\n\t\t...(id == null ? [] : [`id: ${id}`]),\n\t\t// Why `\\r` too: a client reads a lone carriage return as a line end.\n\t\t...data.split(/\\r\\n|\\r|\\n/u).map((line) => `data: ${line}`),\n\t];\n\treturn `${lines.join(\"\\n\")}\\n\\n`;\n}\n\n/**\n * A `text/event-stream` response that stays correct for its whole life: it\n * sends a heartbeat comment, it stops when the client disconnects, and it\n * closes at server shutdown so the drain does not wait for the deadline. The\n * stream closes when `produce` resolves.\n *\n * @example\n * export async function loader({ request }: Route.LoaderArgs) {\n * \treturn eventStream({ signal: request.signal }, async ({ send, signal }) => {\n * \t\tfor await (const update of watchUpdates({ signal })) {\n * \t\t\tsend({ event: \"update\", data: JSON.stringify(update) });\n * \t\t}\n * \t});\n * }\n */\nexport function eventStream(\n\t{ signal, heartbeatMs = 15_000, headers }: EventStreamOptions,\n\tproduce: (sink: EventStreamSink) => void | Promise<void>,\n): Response {\n\tconst encoder = new TextEncoder();\n\tconst stopped = new AbortController();\n\tconst stopSignal = AbortSignal.any([\n\t\tstopped.signal,\n\t\tshutdownSignal(),\n\t\t...(signal == null ? [] : [signal]),\n\t]);\n\tlet heartbeat: ReturnType<typeof setInterval> | undefined;\n\tlet closed = false;\n\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst close = () => {\n\t\t\t\tif (closed) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclosed = true;\n\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t// Why: the listener lives on `shutdownSignal()`, which lasts the life of the process.\n\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\tcontroller.close();\n\t\t\t};\n\t\t\tconst write = (text: string) => {\n\t\t\t\tif (!closed) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t}\n\t\t\t};\n\t\t\theartbeat = setInterval(() => {\n\t\t\t\twrite(\": ping\\n\\n\");\n\t\t\t}, heartbeatMs);\n\t\t\tstopSignal.addEventListener(\"abort\", close, { once: true });\n\t\t\tif (stopSignal.aborted) {\n\t\t\t\tclose();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tPromise.resolve()\n\t\t\t\t.then(async () =>\n\t\t\t\t\tproduce({\n\t\t\t\t\t\tsend: (event) => {\n\t\t\t\t\t\t\twrite(formatEvent(event));\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal: stopSignal,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.then(close, (error: unknown) => {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true;\n\t\t\tclearInterval(heartbeat);\n\t\t\tstopped.abort();\n\t\t},\n\t});\n\n\tconst responseHeaders = new Headers(headers);\n\tresponseHeaders.set(\"Content-Type\", \"text/event-stream; charset=utf-8\");\n\tresponseHeaders.set(\"Cache-Control\", \"no-cache\");\n\treturn new Response(body, { headers: responseHeaders });\n}\n","import type { Plugin, SetupInfo } from \"../types.js\";\n\n/** Options for {@link buildId}. */\nexport type BuildIdOptions = {\n\t/** @default \"X-Build-Id\" */\n\theader?: string;\n\t/** The deployed build, such as the image tag. Read it from the runtime env, not the build. */\n\tvalue: string;\n};\n\n/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/**\n * Sets a build ID header on documents and on the framework's data responses,\n * such as React Router `.data` files, so a client can see that a deploy\n * happened under it.\n *\n * @example\n * buildId({ value: env.values.PUBLIC_APP_VERSION });\n */\nexport function buildId({ header = \"X-Build-Id\", value }: BuildIdOptions): Plugin {\n\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn {\n\t\tname: \"build-id\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t},\n\t\t// Why: a 304 has no `Content-Type`, so a document that did not change on disk must still\n\t\t// answer 200 when the build ID changes.\n\t\tetagPart: () => value,\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\tconst isDocument = context.res.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false;\n\t\t\tif (isDocument || isDataRequest(context.req.path)) {\n\t\t\t\tcontext.header(header, value);\n\t\t\t}\n\t\t},\n\t};\n}\n","import type { Plugin } from \"../types.js\";\n\n// The Standard Schema interface (https://standardschema.dev), copied as its spec asks, so that\n// zod, valibot, and arktype schemas all work with no dependency on any of them.\ntype StandardIssue = {\n\treadonly message: string;\n\treadonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[] | undefined;\n};\ntype StandardResult<Output> =\n\t| { readonly value: Output; readonly issues?: undefined }\n\t| { readonly issues: readonly StandardIssue[] };\n\n/** A schema that follows the Standard Schema interface, such as a zod object. */\nexport type StandardSchemaV1<Input = unknown, Output = Input> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: string;\n\t\treadonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;\n\t\treadonly types?: { readonly input: Input; readonly output: Output } | undefined;\n\t};\n};\n\n/** The parsed type of a Standard Schema. */\nexport type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n\tSchema[\"~standard\"][\"types\"]\n>[\"output\"];\n\n/** The `id` of the JSON `<script>` that carries the public values into each HTML document. */\nexport const PUBLIC_ENV_SCRIPT_ID = \"app-server-public-env\";\n\n/** Stops the search for `</head>` after this many characters, so a page with none still streams. */\nconst HEAD_SEARCH_LIMIT = 1_048_576;\n\n/** Options for {@link runtimeEnv}. */\nexport type RuntimeEnvOptions = {\n\t/** @default process.env */\n\tsource?: Readonly<Record<string, string | undefined>>;\n\t/**\n\t * Values whose names start with this prefix reach the browser.\n\t * @default \"PUBLIC_\"\n\t */\n\tpublicPrefix?: string;\n};\n\n/** The plugin that {@link runtimeEnv} returns, with the parsed values. */\nexport type RuntimeEnv<Values> = Plugin & {\n\t/** The parsed values. The first read parses, and a bad value throws. */\n\treadonly values: Values;\n\t/** The parsed values whose names start with the public prefix. */\n\treadonly publicValues: Readonly<Record<string, unknown>>;\n};\n\nfunction formatIssue(issue: StandardIssue): string {\n\tconst path = (issue.path ?? [])\n\t\t.map((segment) => String(typeof segment === \"object\" ? segment.key : segment))\n\t\t.join(\".\");\n\treturn ` ${path === \"\" ? \"(root)\" : path}: ${issue.message}`;\n}\n\n/** A JSON data block. Escaping `<` keeps a value from closing the `<script>`. */\nfunction publicEnvScript(values: Readonly<Record<string, unknown>>): string {\n\tconst json = JSON.stringify(values).replaceAll(\"<\", String.raw`\\u003c`);\n\treturn `<script id=\"${PUBLIC_ENV_SCRIPT_ID}\" type=\"application/json\">${json}</script>`;\n}\n\n/** Inserts `html` before the first `</head>` of a streamed document. The rest streams as is. */\nfunction injectBeforeHeadEnd(\n\tbody: ReadableStream<Uint8Array>,\n\thtml: string,\n): ReadableStream<Uint8Array> {\n\t// Why decode every chunk: a chunk can end inside a multi-byte character.\n\tconst decoder = new TextDecoder();\n\tconst encoder = new TextEncoder();\n\tlet pending: string | undefined = \"\";\n\treturn body.pipeThrough(\n\t\tnew TransformStream<Uint8Array, Uint8Array>({\n\t\t\ttransform(chunk, controller) {\n\t\t\t\tconst text = decoder.decode(chunk, { stream: true });\n\t\t\t\tif (pending == null) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpending += text;\n\t\t\t\tconst index = pending.search(/<\\/head>/iu);\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\tencoder.encode(`${pending.slice(0, index)}${html}${pending.slice(index)}`),\n\t\t\t\t\t);\n\t\t\t\t\tpending = undefined;\n\t\t\t\t} else if (pending.length > HEAD_SEARCH_LIMIT) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(pending));\n\t\t\t\t\tpending = undefined;\n\t\t\t\t}\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tconst rest = `${pending ?? \"\"}${decoder.decode()}`;\n\t\t\t\tif (rest !== \"\") {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(rest));\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t);\n}\n\n/**\n * Validates the environment once, at startup, against a schema. A missing or\n * bad value stops the server with a message that names it. The typed values\n * are on `.values`.\n *\n * The values whose names start with `PUBLIC_` go into each HTML document,\n * prerendered or rendered, as a JSON `<script id=\"app-server-public-env\">`.\n * So one image serves every environment, and a prerendered page never keeps\n * the values of the build. Put this plugin before the static stages, so it\n * sees the prerendered pages.\n *\n * @example\n * export const env = runtimeEnv(\n * \tz.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),\n * );\n * env.values.SESSION_KEY; // => string\n *\n * // In the browser:\n * const publicEnv = JSON.parse(document.getElementById(\"app-server-public-env\")?.textContent ?? \"{}\");\n */\nexport function runtimeEnv<Schema extends StandardSchemaV1>(\n\tschema: Schema,\n\t{ source = process.env, publicPrefix = \"PUBLIC_\" }: RuntimeEnvOptions = {},\n): RuntimeEnv<InferOutput<Schema>> {\n\tlet parsed:\n\t\t| {\n\t\t\t\tvalues: InferOutput<Schema>;\n\t\t\t\tpublicValues: Readonly<Record<string, unknown>>;\n\t\t\t\tscript: string | undefined;\n\t\t }\n\t\t| undefined;\n\n\tconst parse = () => {\n\t\tif (parsed != null) {\n\t\t\treturn parsed;\n\t\t}\n\t\tconst result = schema[\"~standard\"].validate({ ...source });\n\t\tif (result instanceof Promise) {\n\t\t\tthrow new TypeError(\"runtimeEnv needs a schema that validates synchronously.\");\n\t\t}\n\t\tif (result.issues != null) {\n\t\t\tthrow new Error(\n\t\t\t\t`The environment is not valid:\\n${result.issues.map(formatIssue).join(\"\\n\")}`,\n\t\t\t);\n\t\t}\n\t\tconst values: InferOutput<Schema> = result.value;\n\t\tconst publicValues =\n\t\t\ttypeof values === \"object\" && values != null\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(values).filter(([name]) => name.startsWith(publicPrefix)),\n\t\t\t\t\t)\n\t\t\t\t: {};\n\t\tparsed = {\n\t\t\tvalues,\n\t\t\tpublicValues,\n\t\t\tscript: Object.keys(publicValues).length > 0 ? publicEnvScript(publicValues) : undefined,\n\t\t};\n\t\treturn parsed;\n\t};\n\n\treturn {\n\t\tname: \"runtime-env\",\n\t\tget values() {\n\t\t\treturn parse().values;\n\t\t},\n\t\tget publicValues() {\n\t\t\treturn parse().publicValues;\n\t\t},\n\t\tsetup: () => {\n\t\t\tparse();\n\t\t},\n\t\tetagPart: () => parse().script,\n\t\tmiddleware: async (context, next) => {\n\t\t\tawait next();\n\t\t\tconst { script } = parse();\n\t\t\tconst response = context.res;\n\t\t\tif (\n\t\t\t\tscript == null ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: the script changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\t!(response.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false)\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.body != null) {\n\t\t\t\tcontext.res = new Response(injectBeforeHeadEnd(response.body, script), response);\n\t\t\t}\n\t\t\t// Why for HEAD too: it gets the headers that GET gets. The script changes the length, and a\n\t\t\t// rendered document's ETag does not cover the values, so a 304 could keep old ones.\n\t\t\tcontext.header(\"Content-Length\", undefined);\n\t\t\tcontext.header(\"ETag\", undefined);\n\t\t},\n\t};\n}\n"],"mappings":";;;;AA6BA,SAAS,YAAY,EAAE,MAAM,OAAO,MAA+B;CAElE,IAAI,UAAU,KAAK,GAAG,SAAS,KAAK,MAAM,IAAI,GAC7C,MAAM,IAAI,UAAU,0DAA0D;CAQ/E,OAAO,GAAG;EALT,GAAI,SAAS,OAAO,CAAC,IAAI,CAAC,UAAU,OAAO;EAC3C,GAAI,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI;EAElC,GAAG,KAAK,MAAM,aAAa,CAAC,CAAC,KAAK,SAAS,SAAS,MAAM;CAE7C,CAAC,CAAC,KAAK,IAAI,EAAE;AAC5B;;;;;;;;;;;;;;;;AAiBA,SAAgB,YACf,EAAE,QAAQ,cAAc,MAAQ,WAChC,SACW;CACX,MAAM,UAAU,IAAI,YAAY;CAChC,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,aAAa,YAAY,IAAI;EAClC,QAAQ;EACR,eAAe;EACf,GAAI,UAAU,OAAO,CAAC,IAAI,CAAC,MAAM;CAClC,CAAC;CACD,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,OAAO,IAAI,eAA2B;EAC3C,MAAM,YAAY;GACjB,MAAM,cAAc;IACnB,IAAI,QACH;IAED,SAAS;IACT,cAAc,SAAS;IAEvB,WAAW,oBAAoB,SAAS,KAAK;IAC7C,WAAW,MA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
+ {"version":3,"file":"index.js","names":[],"sources":["../src/core/event-stream.ts","../src/core/plugins/runtime-env.ts"],"sourcesContent":["import { shutdownSignal } from \"./shutdown.js\";\n\n/** One server-sent event. */\nexport type ServerSentEvent = {\n\tdata: string;\n\tevent?: string;\n\tid?: string;\n};\n\n/** What {@link eventStream} passes to its producer. */\nexport type EventStreamSink = {\n\tsend: (event: ServerSentEvent) => void;\n\t/** Aborts when the client disconnects or the server shuts down. Stop the work on it. */\n\tsignal: AbortSignal;\n};\n\n/** Options for {@link eventStream}. */\nexport type EventStreamOptions = {\n\t/** The request's signal, so a client disconnect stops the stream. */\n\tsignal?: AbortSignal;\n\t/**\n\t * How often a `: ping` comment goes out, so that a proxy keeps a quiet stream open.\n\t * @default 15000\n\t */\n\theartbeatMs?: number;\n\t/** Extra response headers. */\n\theaders?: HeadersInit;\n};\n\nfunction formatEvent({ data, event, id }: ServerSentEvent): string {\n\t// Why: a line break in `event` or `id` would start another field or event.\n\tif (/[\\r\\n]/u.test(`${event ?? \"\"}${id ?? \"\"}`)) {\n\t\tthrow new TypeError(\"An event's `event` and `id` cannot contain a line break.\");\n\t}\n\tconst lines = [\n\t\t...(event == null ? [] : [`event: ${event}`]),\n\t\t...(id == null ? [] : [`id: ${id}`]),\n\t\t// Why `\\r` too: a client reads a lone carriage return as a line end.\n\t\t...data.split(/\\r\\n|\\r|\\n/u).map((line) => `data: ${line}`),\n\t];\n\treturn `${lines.join(\"\\n\")}\\n\\n`;\n}\n\n/**\n * A `text/event-stream` response that stays correct for its whole life: it\n * sends a heartbeat comment, it stops when the client disconnects, and it\n * closes at server shutdown so the drain does not wait for the deadline. The\n * stream closes when `produce` resolves.\n *\n * @example\n * export async function loader({ request }: Route.LoaderArgs) {\n * \treturn eventStream({ signal: request.signal }, async ({ send, signal }) => {\n * \t\tfor await (const update of watchUpdates({ signal })) {\n * \t\t\tsend({ event: \"update\", data: JSON.stringify(update) });\n * \t\t}\n * \t});\n * }\n */\nexport function eventStream(\n\t{ signal, heartbeatMs = 15_000, headers }: EventStreamOptions,\n\tproduce: (sink: EventStreamSink) => void | Promise<void>,\n): Response {\n\tconst encoder = new TextEncoder();\n\tconst stopped = new AbortController();\n\tconst stopSignal = AbortSignal.any([\n\t\tstopped.signal,\n\t\tshutdownSignal(),\n\t\t...(signal == null ? [] : [signal]),\n\t]);\n\tlet heartbeat: ReturnType<typeof setInterval> | undefined;\n\tlet closed = false;\n\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst close = () => {\n\t\t\t\tif (closed) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclosed = true;\n\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t// Why: the listener lives on `shutdownSignal()`, which lasts the life of the process.\n\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\tcontroller.close();\n\t\t\t};\n\t\t\tconst write = (text: string) => {\n\t\t\t\tif (!closed) {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t}\n\t\t\t};\n\t\t\theartbeat = setInterval(() => {\n\t\t\t\twrite(\": ping\\n\\n\");\n\t\t\t}, heartbeatMs);\n\t\t\tstopSignal.addEventListener(\"abort\", close, { once: true });\n\t\t\tif (stopSignal.aborted) {\n\t\t\t\tclose();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tPromise.resolve()\n\t\t\t\t.then(async () =>\n\t\t\t\t\tproduce({\n\t\t\t\t\t\tsend: (event) => {\n\t\t\t\t\t\t\twrite(formatEvent(event));\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal: stopSignal,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.then(close, (error: unknown) => {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tclearInterval(heartbeat);\n\t\t\t\t\tstopSignal.removeEventListener(\"abort\", close);\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true;\n\t\t\tclearInterval(heartbeat);\n\t\t\tstopped.abort();\n\t\t},\n\t});\n\n\tconst responseHeaders = new Headers(headers);\n\tresponseHeaders.set(\"Content-Type\", \"text/event-stream; charset=utf-8\");\n\tresponseHeaders.set(\"Cache-Control\", \"no-cache\");\n\treturn new Response(body, { headers: responseHeaders });\n}\n","import { replaceResponse, writableHeaders } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { Plugin } from \"../types.js\";\n\n// The Standard Schema interface (https://standardschema.dev), copied as its spec asks, so that\n// zod, valibot, and arktype schemas all work with no dependency on any of them.\ntype StandardIssue = {\n\treadonly message: string;\n\treadonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[] | undefined;\n};\ntype StandardResult<Output> =\n\t| { readonly value: Output; readonly issues?: undefined }\n\t| { readonly issues: readonly StandardIssue[] };\n\n/** A schema that follows the Standard Schema interface, such as a zod object. */\nexport type StandardSchemaV1<Input = unknown, Output = Input> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: string;\n\t\treadonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;\n\t\treadonly types?: { readonly input: Input; readonly output: Output } | undefined;\n\t};\n};\n\n/** The parsed type of a Standard Schema. */\nexport type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n\tSchema[\"~standard\"][\"types\"]\n>[\"output\"];\n\n/** The `id` of the JSON `<script>` that carries the public values into each HTML document. */\nexport const PUBLIC_ENV_SCRIPT_ID = \"app-server-public-env\";\n\n/** Stops the search for `</head>` after this many characters, so a page with none still streams. */\nconst HEAD_SEARCH_LIMIT = 1_048_576;\n\n/** Options for {@link runtimeEnv}. */\nexport type RuntimeEnvOptions = {\n\t/** @default process.env */\n\tsource?: Readonly<Record<string, string | undefined>>;\n\t/**\n\t * Values whose names start with this prefix reach the browser.\n\t * @default \"PUBLIC_\"\n\t */\n\tpublicPrefix?: string;\n};\n\n/** The plugin that {@link runtimeEnv} returns, with the parsed values. */\nexport type RuntimeEnv<Values> = Plugin & {\n\t/** The parsed values. The first read parses, and a bad value throws. */\n\treadonly values: Values;\n\t/** The parsed values whose names start with the public prefix. */\n\treadonly publicValues: Readonly<Record<string, unknown>>;\n};\n\nfunction formatIssue(issue: StandardIssue): string {\n\tconst path = (issue.path ?? [])\n\t\t.map((segment) => String(typeof segment === \"object\" ? segment.key : segment))\n\t\t.join(\".\");\n\treturn ` ${path === \"\" ? \"(root)\" : path}: ${issue.message}`;\n}\n\n/** A JSON data block. Escaping `<` keeps a value from closing the `<script>`. */\nfunction publicEnvScript(values: Readonly<Record<string, unknown>>): string {\n\tconst json = JSON.stringify(values).replaceAll(\"<\", String.raw`\\u003c`);\n\treturn `<script id=\"${PUBLIC_ENV_SCRIPT_ID}\" type=\"application/json\">${json}</script>`;\n}\n\n/** Inserts `html` before the first `</head>` of a streamed document. The rest streams as is. */\nfunction injectBeforeHeadEnd(\n\tbody: ReadableStream<Uint8Array>,\n\thtml: string,\n): ReadableStream<Uint8Array> {\n\t// Why decode every chunk: a chunk can end inside a multi-byte character.\n\tconst decoder = new TextDecoder();\n\tconst encoder = new TextEncoder();\n\tconst reader = body.getReader();\n\tlet pending: string | undefined = \"\";\n\t/** The text to send for `text`, or `undefined` while the search for `</head>` goes on. */\n\tconst transform = (text: string): string | undefined => {\n\t\tif (pending == null) {\n\t\t\treturn text;\n\t\t}\n\t\tpending += text;\n\t\tconst index = pending.search(/<\\/head>/iu);\n\t\tif (index === -1 && pending.length <= HEAD_SEARCH_LIMIT) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst out = index === -1 ? pending : `${pending.slice(0, index)}${html}${pending.slice(index)}`;\n\t\tpending = undefined;\n\t\treturn out;\n\t};\n\t// Why not `pipeThrough`: a pipe reads the source before the client reads. On Node.js 26, a\n\t// static file that a later stage drops then holds an open `FileHandle` until garbage collection.\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\t// Why a loop: a pull that enqueues nothing is not called again.\n\t\t\t\tfor (;;) {\n\t\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- each read depends on the one before it.\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tconst rest = `${pending ?? \"\"}${decoder.decode()}`;\n\t\t\t\t\t\tif (rest !== \"\") {\n\t\t\t\t\t\t\tcontroller.enqueue(encoder.encode(rest));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst out = transform(decoder.decode(value, { stream: true }));\n\t\t\t\t\tif (out != null) {\n\t\t\t\t\t\tcontroller.enqueue(encoder.encode(out));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: async (reason) => reader.cancel(reason),\n\t\t},\n\t\t// Why 0: the stream reads its source only when the client reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * Validates the environment once, at startup, against a schema. A missing or\n * bad value stops the server with a message that names it. The typed values\n * are on `.values`.\n *\n * The values whose names start with `PUBLIC_` go into each HTML document,\n * prerendered or rendered, as a JSON `<script id=\"app-server-public-env\">`.\n * So one image serves every environment, and a prerendered page never keeps\n * the values of the build. Give it to the `env` option of `defaultPlugins()`,\n * which puts it before the static stages, so it sees the prerendered pages.\n *\n * @example\n * export const env = runtimeEnv(\n * \tz.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),\n * );\n * env.values.SESSION_KEY; // => string\n * createServer({ plugins: defaultPlugins({ env }) });\n *\n * // In the browser:\n * const publicEnv = JSON.parse(document.getElementById(\"app-server-public-env\")?.textContent ?? \"{}\");\n */\nexport function runtimeEnv<Schema extends StandardSchemaV1>(\n\tschema: Schema,\n\t{ source = process.env, publicPrefix = \"PUBLIC_\" }: RuntimeEnvOptions = {},\n): RuntimeEnv<InferOutput<Schema>> {\n\tlet parsed:\n\t\t| {\n\t\t\t\tvalues: InferOutput<Schema>;\n\t\t\t\tpublicValues: Readonly<Record<string, unknown>>;\n\t\t\t\tscript: string | undefined;\n\t\t }\n\t\t| undefined;\n\n\tconst parse = () => {\n\t\tif (parsed != null) {\n\t\t\treturn parsed;\n\t\t}\n\t\tconst result = schema[\"~standard\"].validate({ ...source });\n\t\tif (result instanceof Promise) {\n\t\t\tthrow new TypeError(\"runtimeEnv needs a schema that validates synchronously.\");\n\t\t}\n\t\tif (result.issues != null) {\n\t\t\tthrow new Error(\n\t\t\t\t`The environment is not valid:\\n${result.issues.map(formatIssue).join(\"\\n\")}`,\n\t\t\t);\n\t\t}\n\t\tconst values: InferOutput<Schema> = result.value;\n\t\tconst publicValues =\n\t\t\ttypeof values === \"object\" && values != null\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(values).filter(([name]) => name.startsWith(publicPrefix)),\n\t\t\t\t\t)\n\t\t\t\t: {};\n\t\tparsed = {\n\t\t\tvalues,\n\t\t\tpublicValues,\n\t\t\tscript: Object.keys(publicValues).length > 0 ? publicEnvScript(publicValues) : undefined,\n\t\t};\n\t\treturn parsed;\n\t};\n\n\treturn optionPlugin(\"env\", {\n\t\tname: \"runtime-env\",\n\t\tget values() {\n\t\t\treturn parse().values;\n\t\t},\n\t\tget publicValues() {\n\t\t\treturn parse().publicValues;\n\t\t},\n\t\tsetup: () => {\n\t\t\tparse();\n\t\t},\n\t\tetagPart: () => parse().script,\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { script } = parse();\n\t\t\t// Why a request value, not an option: the static stages send the HTML file, not its compressed\n\t\t\t// copy, only to a request that gets the script. An app with no public values keeps the copies.\n\t\t\tif (script != null) {\n\t\t\t\tcontext.set(\"rewritesHtml\", true);\n\t\t\t}\n\t\t\tawait next();\n\t\t\tconst response = context.res;\n\t\t\tif (\n\t\t\t\tscript == null ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: the script changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\t!(response.headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false)\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.body != null) {\n\t\t\t\treplaceResponse(\n\t\t\t\t\tcontext,\n\t\t\t\t\tnew Response(injectBeforeHeadEnd(response.body, script), response),\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Why for HEAD too: it gets the headers that GET gets. The script changes the length, and a\n\t\t\t// rendered document's ETag does not cover the values, so a 304 could keep old ones.\n\t\t\tconst headers = writableHeaders(context);\n\t\t\theaders.delete(\"Content-Length\");\n\t\t\theaders.delete(\"ETag\");\n\t\t},\n\t});\n}\n"],"mappings":";;;;;;;;;AA6BA,SAAS,YAAY,EAAE,MAAM,OAAO,MAA+B;CAElE,IAAI,UAAU,KAAK,GAAG,SAAS,KAAK,MAAM,IAAI,GAC7C,MAAM,IAAI,UAAU,0DAA0D;CAQ/E,OAAO,GAAG;EALT,GAAI,SAAS,OAAO,CAAC,IAAI,CAAC,UAAU,OAAO;EAC3C,GAAI,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI;EAElC,GAAG,KAAK,MAAM,aAAa,CAAC,CAAC,KAAK,SAAS,SAAS,MAAM;CAE7C,CAAC,CAAC,KAAK,IAAI,EAAE;AAC5B;;;;;;;;;;;;;;;;AAiBA,SAAgB,YACf,EAAE,QAAQ,cAAc,MAAQ,WAChC,SACW;CACX,MAAM,UAAU,IAAI,YAAY;CAChC,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,aAAa,YAAY,IAAI;EAClC,QAAQ;EACR,eAAe;EACf,GAAI,UAAU,OAAO,CAAC,IAAI,CAAC,MAAM;CAClC,CAAC;CACD,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,OAAO,IAAI,eAA2B;EAC3C,MAAM,YAAY;GACjB,MAAM,cAAc;IACnB,IAAI,QACH;IAED,SAAS;IACT,cAA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,yDAAyD;EAE9E,IAAI,OAAO,UAAU,MACpB,MAAM,IAAI,MACT,kCAAkC,OAAO,OAAO,IAAI,WAAW,CAAC,CAAC,KAAK,IAAI,GAC3E;EAED,MAAM,SAA8B,OAAO;EAC3C,MAAM,eACL,OAAO,WAAW,YAAY,UAAU,OACrC,OAAO,YACP,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,CAAC,UAAU,KAAK,WAAW,YAAY,CAAC,CACxE,IACC,CAAC;EACL,SAAS;GACR;GACA;GACA,QAAQ,OAAO,KAAK,YAAY,CAAC,CAAC,SAAS,IAAI,gBAAgB,YAAY,IAAI;EAChF;EACA,OAAO;CACR;CAEA,OAAO,aAAa,OAAO;EAC1B,MAAM;EACN,IAAI,SAAS;GACZ,OAAO,MAAM,CAAC,CAAC;EAChB;EACA,IAAI,eAAe;GAClB,OAAO,MAAM,CAAC,CAAC;EAChB;EACA,aAAa;GACZ,MAAM;EACP;EACA,gBAAgB,MAAM,CAAC,CAAC;EACxB,YAAY,OAAO,SAAS,SAAS;GACpC,MAAM,EAAE,WAAW,MAAM;GAGzB,IAAI,UAAU,MACb,QAAQ,IAAI,gBAAgB,IAAI;GAEjC,MAAM,KAAK;GACX,MAAM,WAAW,QAAQ;GACzB,IACC,UAAU,QACV,SAAS,QAAQ,IAAI,kBAAkB,KAEvC,SAAS,QAAQ,IAAI,eAAe,KACpC,EAAE,SAAS,QAAQ,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,QAEnE;GAED,IAAI,SAAS,QAAQ,MACpB,gBACC,SACA,IAAI,SAAS,oBAAoB,SAAS,MAAM,MAAM,GAAG,QAAQ,CAClE;GAID,MAAM,UAAU,gBAAgB,OAAO;GACvC,QAAQ,OAAO,gBAAgB;GAC/B,QAAQ,OAAO,MAAM;EACtB;CACD,CAAC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"listen-options-7TaXjyrk.js","names":[],"sources":["../src/node/runtimes/listen-options.ts"],"sourcesContent":["/** What every runtime listener takes. */\nexport type ListenOptions = {\n\tport: number;\n\t/** The interface to bind. When omitted, the listener binds every interface. */\n\thostname: string | undefined;\n\t/** How long an idle keep-alive connection stays open. */\n\tidleTimeoutMs: number;\n};\n\n/**\n * The URL a listener answers on. A wildcard bind reads as `localhost`.\n *\n * @example\n * listenerUrl(\"0.0.0.0\", 3000); // => \"http://localhost:3000/\"\n * listenerUrl(\"::1\", 3000); // => \"http://[::1]:3000/\"\n */\nexport function listenerUrl(hostname: string | undefined, port: number): string {\n\tif (hostname == null || hostname === \"\" || hostname === \"0.0.0.0\" || hostname === \"::\") {\n\t\treturn `http://localhost:${port}/`;\n\t}\n\treturn hostname.includes(\":\") ? `http://[${hostname}]:${port}/` : `http://${hostname}:${port}/`;\n}\n"],"mappings":";;;;;;;;AAgBA,SAAgB,YAAY,UAA8B,MAAsB;CAC/E,IAAI,YAAY,QAAQ,aAAa,MAAM,aAAa,aAAa,aAAa,MACjF,OAAO,oBAAoB,KAAK;CAEjC,OAAO,SAAS,SAAS,GAAG,IAAI,WAAW,SAAS,IAAI,KAAK,KAAK,UAAU,SAAS,GAAG,KAAK;AAC9F"}
1
+ {"version":3,"file":"listen-options-7TaXjyrk.js","names":[],"sources":["../src/node/runtimes/listen-options.ts"],"sourcesContent":["/** What every runtime listener takes. */\nexport type ListenOptions = {\n\tport: number;\n\t/** The interface to bind. When omitted, the listener binds every interface. */\n\thostname: string | undefined;\n\t/** How long an idle keep-alive connection stays open. */\n\tidleTimeoutMs: number;\n\t/** The `trustForwardedProto` of the server. */\n\ttrustForwardedProto: boolean;\n};\n\n/**\n * The URL a listener answers on. A wildcard bind reads as `localhost`.\n *\n * @example\n * listenerUrl(\"0.0.0.0\", 3000); // => \"http://localhost:3000/\"\n * listenerUrl(\"::1\", 3000); // => \"http://[::1]:3000/\"\n */\nexport function listenerUrl(hostname: string | undefined, port: number): string {\n\tif (hostname == null || hostname === \"\" || hostname === \"0.0.0.0\" || hostname === \"::\") {\n\t\treturn `http://localhost:${port}/`;\n\t}\n\treturn hostname.includes(\":\") ? `http://[${hostname}]:${port}/` : `http://${hostname}:${port}/`;\n}\n"],"mappings":";;;;;;;;AAkBA,SAAgB,YAAY,UAA8B,MAAsB;CAC/E,IAAI,YAAY,QAAQ,aAAa,MAAM,aAAa,aAAa,aAAa,MACjF,OAAO,oBAAoB,KAAK;CAEjC,OAAO,SAAS,SAAS,GAAG,IAAI,WAAW,SAAS,IAAI,KAAK,KAAK,UAAU,SAAS,GAAG,KAAK;AAC9F"}
@@ -1,5 +1,6 @@
1
- import { n as isAppServerEntry, r as createServer, t as createEntry } from "./entry-BkdUub2S.js";
2
- import { t as host } from "./node-YWPGmzAk.js";
1
+ import { t as createServer } from "./create-server-iE1-s6Bi.js";
2
+ import { n as isAppServerEntry, t as createEntry } from "./entry-DZ3qo7qF.js";
3
+ import { t as host } from "./node-BFH82eeL.js";
3
4
 
4
5
  // src/cli/load-entry.ts
5
6
  /** Entries that this copy made for plain React Router builds, by build module. */
@@ -21,7 +22,10 @@ async function loadEntry(build) {
21
22
  const { isServerBuild, runtime } = await import("./react-router.js");
22
23
  if (!isServerBuild(build)) throw new Error("The server build entry is not a React Router server build.");
23
24
  const entry = createEntry({
24
- app: createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1" }),
25
+ app: createServer({
26
+ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1",
27
+ trustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0)
28
+ }),
25
29
  host,
26
30
  framework: (mode) => runtime(build, { mode })
27
31
  });
@@ -30,4 +34,4 @@ async function loadEntry(build) {
30
34
  }
31
35
 
32
36
  export { loadEntry as t };
33
- //# sourceMappingURL=load-entry-C03qqmhr.js.map
37
+ //# sourceMappingURL=load-entry-AfYS_zS9.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"load-entry-C03qqmhr.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\" }),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa,EAAE,qBAAqB,QAAQ,IAAI,0BAA0B,IAAI,CAAC;EACpF;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
1
+ {"version":3,"file":"load-entry-AfYS_zS9.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
@@ -0,0 +1,122 @@
1
+ // src/core/log.ts
2
+ /** The standard output (stdout) lines that wait for {@link flushLogs}. */
3
+ let pending = "";
4
+ /** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */
5
+ let exiting = false;
6
+ process.on("exit", () => {
7
+ exiting = true;
8
+ process.stdout._handle?.setBlocking?.(true);
9
+ for (const line of pending.match(/[^\n]*\n/gu) ?? []) process.stdout.write(line);
10
+ pending = "";
11
+ });
12
+ /**
13
+ * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it
14
+ * before the process exits.
15
+ */
16
+ function flushLogs() {
17
+ if (pending === "") return;
18
+ const lines = pending;
19
+ pending = "";
20
+ process.stdout.write(lines);
21
+ }
22
+ /**
23
+ * Adds `line` to the next stdout write. Why one write for each turn of the
24
+ * event loop: a write to a pipe, such as stdout in Docker, is a system call,
25
+ * and under load many requests end in one turn.
26
+ */
27
+ function writeStdout(line) {
28
+ if (exiting) {
29
+ process.stdout.write(line);
30
+ return;
31
+ }
32
+ if (pending === "") setImmediate(flushLogs);
33
+ pending += line;
34
+ }
35
+ /**
36
+ * A log sink that writes one JSON object per line. Each line has `time`,
37
+ * `level`, `message`, and the flat attributes, which Datadog reads as its
38
+ * standard attributes. The default writes the lines of one event-loop turn
39
+ * to stdout at the end of the turn.
40
+ *
41
+ * @param write - Where each line goes. Defaults to stdout.
42
+ *
43
+ * @example
44
+ * createServer({ logger: jsonSink() });
45
+ * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
46
+ */
47
+ function jsonSink(write = writeStdout) {
48
+ return { log: (level, message, attributes) => {
49
+ write(`${JSON.stringify({
50
+ time: isoNow(),
51
+ level,
52
+ message,
53
+ ...attributes
54
+ })}\n`);
55
+ } };
56
+ }
57
+ /** The millisecond of the last `time`, and its ISO string. */
58
+ let lastMs = NaN;
59
+ let lastTime = "";
60
+ /** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */
61
+ let lastSecond = NaN;
62
+ let secondPrefix = "";
63
+ /**
64
+ * The time now, as `new Date().toISOString()` gives it. Why keep the last
65
+ * time: under load, many lines share a millisecond. Why keep the prefix of
66
+ * the second: `toISOString()` costs more than the rest of a line.
67
+ */
68
+ function isoNow() {
69
+ const now = Date.now();
70
+ if (now !== lastMs) {
71
+ lastMs = now;
72
+ const second = Math.floor(now / 1e3);
73
+ if (second !== lastSecond) {
74
+ lastSecond = second;
75
+ secondPrefix = new Date(now).toISOString().slice(0, -4);
76
+ }
77
+ lastTime = `${secondPrefix}${String(now - second * 1e3).padStart(3, "0")}Z`;
78
+ }
79
+ return lastTime;
80
+ }
81
+ /** Flat `error.*` attributes for a thrown value. */
82
+ function errorAttributes(error) {
83
+ if (error instanceof Error) return {
84
+ "error.kind": error.name,
85
+ "error.message": error.message,
86
+ "error.stack": error.stack
87
+ };
88
+ return { "error.message": String(error) };
89
+ }
90
+ /**
91
+ * A logger that writes to `sink`. `withBase` gives the attributes of each
92
+ * line as a new object, from the attributes that the caller gives.
93
+ */
94
+ function sinkLogger(sink, withBase = (attributes) => ({ ...attributes })) {
95
+ return {
96
+ debug: (message, attributes = {}) => {
97
+ sink.log("debug", message, withBase(attributes));
98
+ },
99
+ info: (message, attributes = {}) => {
100
+ sink.log("info", message, withBase(attributes));
101
+ },
102
+ warn: (message, attributes = {}) => {
103
+ sink.log("warn", message, withBase(attributes));
104
+ },
105
+ error: (message, attributes = {}) => {
106
+ sink.log("error", message, withBase(attributes));
107
+ }
108
+ };
109
+ }
110
+ /** A logger whose lines carry the request's ID, method, path, and `logAttributes`. */
111
+ function requestLogger(sink, context) {
112
+ return sinkLogger(sink, (attributes) => ({
113
+ "http.request_id": context.get("requestId"),
114
+ "http.method": context.req.method,
115
+ "http.url_details.path": context.req.path,
116
+ ...context.get("logAttributes"),
117
+ ...attributes
118
+ }));
119
+ }
120
+
121
+ export { sinkLogger as a, requestLogger as i, flushLogs as n, jsonSink as r, errorAttributes as t };
122
+ //# sourceMappingURL=log-BP6xXXZl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-BP6xXXZl.js","names":[],"sources":["../src/core/log.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, LogSink, RequestLogger } from \"./types.js\";\n\n/** The standard output (stdout) lines that wait for {@link flushLogs}. */\nlet pending = \"\";\n/** Whether the process emits `exit`. Then no turn of the event loop follows, so each line goes to stdout at once. */\nlet exiting = false;\n\n/** The libuv handle of stdout on Node.js. Bun and Deno have none. */\ntype StdoutHandle = { _handle?: { setBlocking?: (blocking: boolean) => number } };\n\n// Why: a process that crashes or calls `process.exit()` before the next turn keeps its last lines.\nprocess.on(\"exit\", () => {\n\texiting = true;\n\t// Why block: the exit drops a write that waits for a full pipe. On POSIX, a write to a file or\n\t// a terminal already blocks.\n\t// oxlint-disable-next-line no-underscore-dangle -- Node.js has no public way to block stdout.\n\t(process.stdout as NodeJS.WriteStream & StdoutHandle)._handle?.setBlocking?.(true);\n\t// Why one write for each line: Bun cannot block. Between small writes, the reader can empty the pipe.\n\tfor (const line of pending.match(/[^\\n]*\\n/gu) ?? []) {\n\t\tprocess.stdout.write(line);\n\t}\n\tpending = \"\";\n});\n\n/**\n * Writes the stdout lines of {@link jsonSink} that wait, in one write. Call it\n * before the process exits.\n */\nexport function flushLogs(): void {\n\tif (pending === \"\") {\n\t\treturn;\n\t}\n\tconst lines = pending;\n\tpending = \"\";\n\tprocess.stdout.write(lines);\n}\n\n/**\n * Adds `line` to the next stdout write. Why one write for each turn of the\n * event loop: a write to a pipe, such as stdout in Docker, is a system call,\n * and under load many requests end in one turn.\n */\nfunction writeStdout(line: string): void {\n\tif (exiting) {\n\t\tprocess.stdout.write(line);\n\t\treturn;\n\t}\n\tif (pending === \"\") {\n\t\tsetImmediate(flushLogs);\n\t}\n\tpending += line;\n}\n\n/**\n * A log sink that writes one JSON object per line. Each line has `time`,\n * `level`, `message`, and the flat attributes, which Datadog reads as its\n * standard attributes. The default writes the lines of one event-loop turn\n * to stdout at the end of the turn.\n *\n * @param write - Where each line goes. Defaults to stdout.\n *\n * @example\n * createServer({ logger: jsonSink() });\n * // {\"time\":\"2026-10-28T12:00:00.000Z\",\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200}\n */\nexport function jsonSink(write: (line: string) => void = writeStdout): LogSink {\n\treturn {\n\t\tlog: (level, message, attributes) => {\n\t\t\twrite(`${JSON.stringify({ time: isoNow(), level, message, ...attributes })}\\n`);\n\t\t},\n\t};\n}\n\n/** The millisecond of the last `time`, and its ISO string. */\nlet lastMs = Number.NaN;\nlet lastTime = \"\";\n/** The second of `secondPrefix`, and its ISO string up to the milliseconds, such as `2026-11-03T12:00:00.`. */\nlet lastSecond = Number.NaN;\nlet secondPrefix = \"\";\n\n/**\n * The time now, as `new Date().toISOString()` gives it. Why keep the last\n * time: under load, many lines share a millisecond. Why keep the prefix of\n * the second: `toISOString()` costs more than the rest of a line.\n */\nfunction isoNow(): string {\n\tconst now = Date.now();\n\tif (now !== lastMs) {\n\t\tlastMs = now;\n\t\tconst second = Math.floor(now / 1000);\n\t\tif (second !== lastSecond) {\n\t\t\tlastSecond = second;\n\t\t\tsecondPrefix = new Date(now).toISOString().slice(0, -4);\n\t\t}\n\t\tlastTime = `${secondPrefix}${String(now - second * 1000).padStart(3, \"0\")}Z`;\n\t}\n\treturn lastTime;\n}\n\n/** Flat `error.*` attributes for a thrown value. */\nexport function errorAttributes(error: unknown): Record<string, unknown> {\n\tif (error instanceof Error) {\n\t\treturn { \"error.kind\": error.name, \"error.message\": error.message, \"error.stack\": error.stack };\n\t}\n\treturn { \"error.message\": String(error) };\n}\n\ntype Attributes = Readonly<Record<string, unknown>>;\n\n/**\n * A logger that writes to `sink`. `withBase` gives the attributes of each\n * line as a new object, from the attributes that the caller gives.\n */\nexport function sinkLogger(\n\tsink: LogSink,\n\twithBase: (attributes: Attributes) => Attributes = (attributes) => ({ ...attributes }),\n): RequestLogger {\n\t// Why four functions in one scope: a function that makes each one adds a scope for each, on each request.\n\treturn {\n\t\tdebug: (message, attributes = {}) => {\n\t\t\tsink.log(\"debug\", message, withBase(attributes));\n\t\t},\n\t\tinfo: (message, attributes = {}) => {\n\t\t\tsink.log(\"info\", message, withBase(attributes));\n\t\t},\n\t\twarn: (message, attributes = {}) => {\n\t\t\tsink.log(\"warn\", message, withBase(attributes));\n\t\t},\n\t\terror: (message, attributes = {}) => {\n\t\t\tsink.log(\"error\", message, withBase(attributes));\n\t\t},\n\t};\n}\n\n/** A logger whose lines carry the request's ID, method, path, and `logAttributes`. */\nexport function requestLogger(sink: LogSink, context: Context<AppServerEnv>): RequestLogger {\n\t// Why read at call time: the `requestId` plugin runs after this logger is made. Why one object:\n\t// a base object and then a merge copy each attribute two times.\n\treturn sinkLogger(sink, (attributes) => ({\n\t\t\"http.request_id\": context.get(\"requestId\"),\n\t\t\"http.method\": context.req.method,\n\t\t\"http.url_details.path\": context.req.path,\n\t\t...context.get(\"logAttributes\"),\n\t\t...attributes,\n\t}));\n}\n"],"mappings":";;AAIA,IAAI,UAAU;;AAEd,IAAI,UAAU;AAMd,QAAQ,GAAG,cAAc;CACxB,UAAU;CAIV,AAAC,QAAQ,OAA6C,SAAS,cAAc,IAAI;CAEjF,KAAK,MAAM,QAAQ,QAAQ,MAAM,YAAY,KAAK,CAAC,GAClD,QAAQ,OAAO,MAAM,IAAI;CAE1B,UAAU;AACX,CAAC;;;;;AAMD,SAAgB,YAAkB;CACjC,IAAI,YAAY,IACf;CAED,MAAM,QAAQ;CACd,UAAU;CACV,QAAQ,OAAO,MAAM,KAAK;AAC3B;;;;;;AAOA,SAAS,YAAY,MAAoB;CACxC,IAAI,SAAS;EACZ,QAAQ,OAAO,MAAM,IAAI;EACzB;CACD;CACA,IAAI,YAAY,IACf,aAAa,SAAS;CAEvB,WAAW;AACZ;;;;;;;;;;;;;AAcA,SAAgB,SAAS,QAAgC,aAAsB;CAC9E,OAAO,EACN,MAAM,OAAO,SAAS,eAAe;EACpC,MAAM,GAAG,KAAK,UAAU;GAAE,MAAM,OAAO;GAAG;GAAO;GAAS,GAAG;EAAW,CAAC,EAAE,GAAG;CAC/E,EACD;AACD;;AAGA,IAAI,SAAS;AACb,IAAI,WAAW;;AAEf,IAAI,aAAa;AACjB,IAAI,eAAe;;;;;;AAOnB,SAAS,SAAiB;CACzB,MAAM,MAAM,KAAK,IAAI;CACrB,IAAI,QAAQ,QAAQ;EACnB,SAAS;EACT,MAAM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i4wqjX.js";
4
+ import { n as publicScriptHashes } from "./script-hashes-hqUk6kG7.js";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { setTimeout } from "node:timers";
7
+ import { constants } from "node:fs";
8
+ import { access, open, readdir, stat } from "node:fs/promises";
9
+ import { join, resolve, sep } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { IncomingMessage, ServerResponse } from "node:http";
12
+ import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
13
+
14
+ // src/node/exit.ts
15
+ /** How long the exit waits for stdout and stderr. */
16
+ const FLUSH_TIMEOUT_MS = 1e3;
17
+ /**
18
+ * Exits the process after stdout and stderr write what they hold, so the last
19
+ * log lines are not lost. The exit code is `process.exitCode`, else 0.
20
+ *
21
+ * Why exit at all: when shutdown is done, the server holds nothing open. A
22
+ * timer that the app left, such as the render abort timer in React Router's
23
+ * `entry.server`, would otherwise keep the stopped process alive.
24
+ */
25
+ function exitAfterFlush() {
26
+ flushLogs();
27
+ let pending = 2;
28
+ const done = () => {
29
+ pending -= 1;
30
+ if (pending === 0) process.exit();
31
+ };
32
+ flush(process.stdout, done);
33
+ flush(process.stderr, done);
34
+ setTimeout(() => {
35
+ process.exit();
36
+ }, FLUSH_TIMEOUT_MS).unref();
37
+ }
38
+ /** Calls `done` after `stream` writes what it holds. */
39
+ function flush(stream, done) {
40
+ if ("Bun" in globalThis) {
41
+ stream.end(done);
42
+ return;
43
+ }
44
+ stream.write("", done);
45
+ }
46
+
47
+ // src/node/files.ts
48
+ /** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */
49
+ const CHUNK_BYTES = 65536;
50
+ /**
51
+ * A file's bytes, one chunk for each pull. With `range`, it reads only those
52
+ * bytes. The file opens on the first pull and closes at the end, on an error,
53
+ * or on cancel.
54
+ *
55
+ * Why open on the first pull: a stage can drop a response that no one reads,
56
+ * such as when a later stage throws. Node.js 26 throws an uncaught error when
57
+ * garbage collection closes an open `FileHandle`.
58
+ */
59
+ function fileStream(path, range) {
60
+ let handle;
61
+ let position = range?.start ?? 0;
62
+ const end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;
63
+ const close = async () => {
64
+ const opened = handle;
65
+ handle = void 0;
66
+ await opened?.close();
67
+ };
68
+ return new ReadableStream({
69
+ async pull(controller) {
70
+ try {
71
+ const length = Math.min(CHUNK_BYTES, end - position);
72
+ if (length > 0) handle ??= await open(path);
73
+ const { bytesRead, buffer } = length <= 0 || handle == null ? {
74
+ bytesRead: 0,
75
+ buffer: /* @__PURE__ */ new Uint8Array(0)
76
+ } : await handle.read({
77
+ buffer: new Uint8Array(length),
78
+ position
79
+ });
80
+ if (bytesRead === 0) {
81
+ await close();
82
+ controller.close();
83
+ } else {
84
+ position += bytesRead;
85
+ controller.enqueue(buffer.subarray(0, bytesRead));
86
+ }
87
+ } catch (error) {
88
+ await close();
89
+ throw error;
90
+ }
91
+ },
92
+ cancel: close
93
+ }, { highWaterMark: 0 });
94
+ }
95
+ /** The bytes of `range` in the file at `path`, usually from one read. */
96
+ async function readRange(path, range) {
97
+ const buffer = new Uint8Array(range.end - range.start + 1);
98
+ const handle = await open(path);
99
+ try {
100
+ let filled = 0;
101
+ while (filled < buffer.byteLength) {
102
+ const { bytesRead } = await handle.read({
103
+ buffer,
104
+ offset: filled,
105
+ position: range.start + filled
106
+ });
107
+ if (bytesRead === 0) break;
108
+ filled += bytesRead;
109
+ }
110
+ return buffer.subarray(0, filled);
111
+ } finally {
112
+ await handle.close();
113
+ }
114
+ }
115
+ /** A stream of one chunk. */
116
+ function oneChunk(chunk) {
117
+ return new ReadableStream({ start(controller) {
118
+ if (chunk.byteLength > 0) controller.enqueue(chunk);
119
+ controller.close();
120
+ } });
121
+ }
122
+ /** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */
123
+ const MISSING_CODES = /* @__PURE__ */ new Set([
124
+ "ENOENT",
125
+ "ENOTDIR",
126
+ "ENAMETOOLONG"
127
+ ]);
128
+ /** The value of `promise`, or `undefined` when it fails because nothing is at its path. */
129
+ async function orMissing(promise) {
130
+ try {
131
+ return await promise;
132
+ } catch (error) {
133
+ if (error instanceof Error && "code" in error && MISSING_CODES.has(String(error.code))) return;
134
+ throw error;
135
+ }
136
+ }
137
+ /** The {@link FileInfo} of a file or a directory, else `undefined`. */
138
+ function fileInfo(stats) {
139
+ if (stats?.isFile() === true) return {
140
+ kind: "file",
141
+ size: stats.size,
142
+ mtimeMs: stats.mtimeMs
143
+ };
144
+ return stats?.isDirectory() === true ? {
145
+ kind: "directory",
146
+ size: 0,
147
+ mtimeMs: stats.mtimeMs
148
+ } : void 0;
149
+ }
150
+ /**
151
+ * The client build on the file system. A relative `clientDirectory` is
152
+ * relative to the working directory.
153
+ *
154
+ * Its `snapshot` reads each file and directory once. It throws for an error
155
+ * that does not mean a missing file, so the server does not start.
156
+ *
157
+ * @example
158
+ * nodeFiles("build/client").stat("/llms.txt");
159
+ */
160
+ function nodeFiles(clientDirectory) {
161
+ const root = resolve(clientDirectory.startsWith("file:") ? fileURLToPath(clientDirectory) : clientDirectory);
162
+ const filePath = (path) => {
163
+ const candidate = join(root, path);
164
+ if (candidate !== root && !candidate.startsWith(`${root}${sep}`)) throw new Error(`The path ${path} is outside the client build.`);
165
+ return candidate;
166
+ };
167
+ const files = {
168
+ stat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),
169
+ open: async (path, range) => {
170
+ const candidate = filePath(path);
171
+ if (range != null && range.end - range.start < CHUNK_BYTES) return oneChunk(await readRange(candidate, range));
172
+ await access(candidate, constants.R_OK);
173
+ return fileStream(candidate, range);
174
+ },
175
+ snapshot: async () => {
176
+ const entries = /* @__PURE__ */ new Map();
177
+ const walk = async (path, stats, parents) => {
178
+ const info = fileInfo(stats);
179
+ if (info == null) return;
180
+ entries.set(path, info);
181
+ const inode = `${stats.dev}:${stats.ino}`;
182
+ if (info.kind === "file" || parents.has(inode)) return;
183
+ const inside = new Set(parents).add(inode);
184
+ const prefix = path === "/" ? "" : path;
185
+ const names = await orMissing(readdir(filePath(path))) ?? [];
186
+ await Promise.all(names.map(async (name) => {
187
+ const childPath = `${prefix}/${name}`;
188
+ const childStats = await orMissing(stat(filePath(childPath)));
189
+ if (childStats != null) await walk(childPath, childStats, inside);
190
+ }));
191
+ };
192
+ const rootStats = await orMissing(stat(root));
193
+ if (rootStats != null) await walk("/", rootStats, /* @__PURE__ */ new Set());
194
+ return {
195
+ stat: async (path) => {
196
+ const trimmed = path.length > 1 ? path.replace(/\/$/u, "") : path;
197
+ const info = entries.get(trimmed);
198
+ return trimmed === path || info?.kind === "directory" ? info : void 0;
199
+ },
200
+ open: files.open
201
+ };
202
+ }
203
+ };
204
+ return files;
205
+ }
206
+
207
+ // src/node/dev-server.ts
208
+ function isServerResponse(value) {
209
+ return value instanceof ServerResponse;
210
+ }
211
+ /**
212
+ * Makes `outgoing` run `hooks` before it sends its head, and returns the
213
+ * function that undoes it. Why `writeHead`: Node calls it for each
214
+ * response, also from `write` and `end`.
215
+ */
216
+ function runHooksAtHead(outgoing, hooks) {
217
+ const headers = {
218
+ get: (name) => {
219
+ const value = outgoing.getHeader(name);
220
+ return value == null ? null : String(value);
221
+ },
222
+ has: (name) => outgoing.hasHeader(name),
223
+ set: (name, value) => {
224
+ outgoing.setHeader(name, value);
225
+ },
226
+ append: (name, value) => {
227
+ outgoing.appendHeader(name, value);
228
+ },
229
+ delete: (name) => {
230
+ outgoing.removeHeader(name);
231
+ }
232
+ };
233
+ const writeHead = outgoing.writeHead.bind(outgoing);
234
+ outgoing.writeHead = (statusCode, reason, values) => {
235
+ const [message, given] = typeof reason === "string" ? [reason, values] : [void 0, reason];
236
+ if (Array.isArray(given)) {
237
+ const names = given.filter((_, index) => index % 2 === 0).map(String);
238
+ for (const name of names) outgoing.removeHeader(name);
239
+ for (const [index, name] of names.entries()) {
240
+ const value = given[index * 2 + 1];
241
+ if (value != null) outgoing.appendHeader(name, typeof value === "number" ? String(value) : value);
242
+ }
243
+ } else if (given != null) {
244
+ for (const [name, value] of Object.entries(given)) if (value != null) outgoing.setHeader(name, value);
245
+ }
246
+ for (const hook of hooks.toReversed()) hook(headers);
247
+ return message == null ? writeHead(statusCode) : writeHead(statusCode, message);
248
+ };
249
+ return () => {
250
+ outgoing.writeHead = writeHead;
251
+ };
252
+ }
253
+ /** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */
254
+ function publicFileHashes({ directory, base }, pathname) {
255
+ const prefix = base.replace(/\/$/u, "");
256
+ return publicScriptHashes(directory, pathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname);
257
+ }
258
+ /**
259
+ * Runs a Connect middleware, such as Vite's, inside the pipeline. The
260
+ * middleware answers or calls `next`. A request with no Node request and
261
+ * response goes on.
262
+ *
263
+ * @example
264
+ * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {
265
+ * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),
266
+ * }));
267
+ */
268
+ function devServerStage(middleware, { publicFiles } = {}) {
269
+ return async (context, next) => {
270
+ const { incoming, outgoing } = context.env;
271
+ if (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) return next();
272
+ const hashes = publicFiles == null ? void 0 : publicFileHashes(publicFiles(), new URL(context.req.url).pathname);
273
+ const earlierHashes = context.get("documentScriptHashes");
274
+ if (hashes != null) context.set("documentScriptHashes", hashes);
275
+ for (const [name, value] of context.res.headers) outgoing.appendHeader(name, value);
276
+ const hooks = context.get("headerHooks") ?? [];
277
+ const undoHooks = runHooksAtHead(outgoing, hooks);
278
+ if (await new Promise((resolve, reject) => {
279
+ const onFinish = () => {
280
+ resolve(true);
281
+ };
282
+ outgoing.once("finish", onFinish);
283
+ middleware(incoming, outgoing, (error) => {
284
+ outgoing.off("finish", onFinish);
285
+ undoHooks();
286
+ if (hashes != null) context.set("documentScriptHashes", earlierHashes);
287
+ if (error == null) resolve(false);
288
+ else reject(new Error("The dev server middleware failed", { cause: error }));
289
+ });
290
+ })) {
291
+ hooks.length = 0;
292
+ const headers = new Headers(RESPONSE_ALREADY_SENT.headers);
293
+ for (const [name, value] of Object.entries(outgoing.getHeaders())) for (const each of Array.isArray(value) ? value : [value]) if (each != null) headers.append(name, String(each));
294
+ return new Response(null, {
295
+ status: outgoing.statusCode,
296
+ headers
297
+ });
298
+ }
299
+ return next();
300
+ };
301
+ }
302
+
303
+ // src/node/index.ts
304
+ const storage = new AsyncLocalStorage();
305
+ /**
306
+ * The node host: one long-lived process on Node, Bun, or Deno, such as a
307
+ * Docker image. It listens with `tcp()`, reads the client build from the file
308
+ * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or
309
+ * `SIGINT`, it shuts down, then exits the process.
310
+ *
311
+ * @example
312
+ * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
313
+ */
314
+ const host = {
315
+ name: "node",
316
+ files: nodeFiles,
317
+ listeners: () => [tcp()],
318
+ storage: {
319
+ run: (value, work) => storage.run(value, work),
320
+ get: () => storage.getStore()
321
+ },
322
+ gzip: gzipStream,
323
+ lifecycle: { onStop: (stop) => {
324
+ for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
325
+ stop().catch(() => {
326
+ process.exitCode = 1;
327
+ }).finally(exitAfterFlush);
328
+ });
329
+ } }
330
+ };
331
+
332
+ export { exitAfterFlush as i, devServerStage as n, nodeFiles as r, host as t };
333
+ //# sourceMappingURL=node-BFH82eeL.js.map