@ngrok/app-server 0.3.6 → 0.4.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.
- package/README.md +40 -9
- package/dist/cli.js +3 -3
- package/dist/client.js +1 -1
- package/dist/{create-server-C_90R50y.js → create-server-C63luLkn.js} +71 -30
- package/dist/create-server-C63luLkn.js.map +1 -0
- package/dist/{create-server-kxyhCdhv.d.ts → create-server-DKJ0wASH.d.ts} +33 -13
- package/dist/{entry-65IESBSA.js → entry-BSbsQ_kq.js} +13 -5
- package/dist/entry-BSbsQ_kq.js.map +1 -0
- package/dist/{entry-CNL4OsEn.d.ts → entry-C9bBcYeP.d.ts} +3 -3
- package/dist/index.d.ts +18 -5
- package/dist/index.js +6 -6
- package/dist/{load-entry-BftQ3qlz.js → load-entry-DgZyPtoD.js} +4 -4
- package/dist/{load-entry-BftQ3qlz.js.map → load-entry-DgZyPtoD.js.map} +1 -1
- package/dist/log-CW_g1pWk.js +304 -0
- package/dist/log-CW_g1pWk.js.map +1 -0
- package/dist/{node-Fo6EodEV.js → node-DBwgrye_.js} +2 -2
- package/dist/{node-Fo6EodEV.js.map → node-DBwgrye_.js.map} +1 -1
- package/dist/{node-CA7t-s6D.js → node-DiMwdTOC.js} +3 -3
- package/dist/{node-CA7t-s6D.js.map → node-DiMwdTOC.js.map} +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +2 -2
- package/dist/react-router.d.ts +2 -2
- package/dist/react-router.js +3 -4
- package/dist/react-router.js.map +1 -1
- package/dist/request-context-BdAH1D-2.js +80 -0
- package/dist/request-context-BdAH1D-2.js.map +1 -0
- package/dist/{response-edge-D3CAjukJ.js → response-edge-7eUl2ewl.js} +3 -3
- package/dist/response-edge-7eUl2ewl.js.map +1 -0
- package/dist/{response-writer-BUyOW4n2.js → response-writer-CLtCseu5.js} +2 -2
- package/dist/{response-writer-BUyOW4n2.js.map → response-writer-CLtCseu5.js.map} +1 -1
- package/dist/{serve-CEecObwD.js → serve-DCaIBTM-.js} +2 -2
- package/dist/{serve-CEecObwD.js.map → serve-DCaIBTM-.js.map} +1 -1
- package/dist/{start-CDnHKNca.js → start-D2IVWkow.js} +29 -13
- package/dist/start-D2IVWkow.js.map +1 -0
- package/dist/tanstack-start.d.ts +2 -2
- package/dist/tanstack-start.js +1 -1
- package/dist/{tcp-BPeUZaNg.js → tcp-B8aFGQRB.js} +2 -2
- package/dist/{tcp-BPeUZaNg.js.map → tcp-B8aFGQRB.js.map} +1 -1
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +4 -4
- package/dist/{trailing-slash-DeOUxMYo.d.ts → trailing-slash-D_52DJaQ.d.ts} +2 -2
- package/dist/{types-BKJxtIuj.d.ts → types-C_I3i62n.d.ts} +32 -4
- package/dist/vercel.d.ts +2 -2
- package/dist/vercel.js +4 -4
- package/package.json +1 -1
- package/dist/create-server-C_90R50y.js.map +0 -1
- package/dist/entry-65IESBSA.js.map +0 -1
- package/dist/log-C8LGQ23s.js +0 -149
- package/dist/log-C8LGQ23s.js.map +0 -1
- package/dist/request-context-BtQ87VYb.js +0 -40
- package/dist/request-context-BtQ87VYb.js.map +0 -1
- package/dist/response-edge-D3CAjukJ.js.map +0 -1
- package/dist/start-CDnHKNca.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-server-C63luLkn.js","names":["isFilePath"],"sources":["../src/core/prefers-markdown.ts","../src/core/safe-local-path.ts","../src/core/plugins/trailing-slash.ts","../src/core/plugins/static.ts","../src/core/plugins/access-log.ts","../src/core/plugins/body-limit.ts","../src/core/shutdown.ts","../src/core/plugins/health.ts","../src/core/plugins/noindex.ts","../src/core/plugins/private-documents.ts","../src/core/plugins/redirects.ts","../src/core/plugins/security-headers.ts","../src/core/plugins/request-id.ts","../src/core/plugins/streaming-compress.ts","../src/core/create-server.ts"],"sourcesContent":["/** One media range of an `Accept` header. */\ntype MediaRange = {\n\t/** The media type in lowercase, such as `text/html` or `*\\/*`. */\n\ttype: string;\n\t/** The `q` value, from 0 to 1. */\n\tquality: number;\n\t/** The `charset` parameter in lowercase, when the range has one. */\n\tcharset: string | undefined;\n};\n\n/** A `q` value as RFC 9110 writes it: 0 to 1, with up to three decimals. */\nconst QVALUE = /^(?:0(?:\\.\\d{0,3})?|1(?:\\.0{0,3})?)$/u;\n\n/** The charset of each answer that a caller of {@link prefersMarkdown} sends. */\n// oxlint-disable-next-line unicorn/text-encoding-identifier-case -- HTTP names the charset `utf-8`.\nconst CHARSET = \"utf-8\";\n\n/**\n * The parts of `value` between each `separator`. Why a scan, not `split`: a\n * quoted parameter value can hold a `,` or a `;`.\n */\nfunction splitOutsideQuotes(value: string, separator: string): string[] {\n\tconst parts: string[] = [];\n\tlet part = \"\";\n\tlet quoted = false;\n\tlet escaped = false;\n\tfor (const character of value) {\n\t\tif (!quoted && character === separator) {\n\t\t\tparts.push(part);\n\t\t\tpart = \"\";\n\t\t} else {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t} else if (quoted && character === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t} else if (character === '\"') {\n\t\t\t\tquoted = !quoted;\n\t\t\t}\n\t\t\tpart += character;\n\t\t}\n\t}\n\tparts.push(part);\n\treturn parts;\n}\n\n/** The parameters of a media range, by lowercase name, with quotes removed. */\nfunction parameterMap(parameters: readonly string[]): Map<string, string> {\n\treturn new Map(\n\t\tparameters.map((parameter) => {\n\t\t\tconst index = parameter.indexOf(\"=\");\n\t\t\tconst name = (index === -1 ? parameter : parameter.slice(0, index)).trim().toLowerCase();\n\t\t\tconst value = index === -1 ? \"\" : parameter.slice(index + 1).trim();\n\t\t\tconst unquoted = /^\".*\"$/su.test(value)\n\t\t\t\t? value.slice(1, -1).replaceAll(/\\\\(?<character>.)/gsu, \"$<character>\")\n\t\t\t\t: value;\n\t\t\treturn [name, unquoted];\n\t\t}),\n\t);\n}\n\n/**\n * The media ranges of an `Accept` header. A missing `q` counts as 1, the RFC\n * 9110 default. Why a malformed `q` also counts as 1: the client still named\n * the media type.\n */\nfunction mediaRanges(accept: string): MediaRange[] {\n\treturn splitOutsideQuotes(accept, \",\").map((entry) => {\n\t\tconst [type = \"\", ...parameters] = splitOutsideQuotes(entry, \";\");\n\t\tconst parameterValues = parameterMap(parameters);\n\t\tconst quality = parameterValues.get(\"q\") ?? \"1\";\n\t\treturn {\n\t\t\ttype: type.trim().toLowerCase(),\n\t\t\tquality: QVALUE.test(quality) ? Number(quality) : 1,\n\t\t\tcharset: parameterValues.get(\"charset\")?.toLowerCase(),\n\t\t};\n\t});\n}\n\n/**\n * The `q` of an answer of `type` in UTF-8, from the most specific ranges with\n * that type, or `undefined` when no range matches it. A range with\n * `charset=utf-8` is more specific than a range with no charset. A range with\n * another charset does not match. Other parameters, such as `variant`, do not\n * change the match.\n */\nfunction qualityOf(ranges: readonly MediaRange[], type: string): number | undefined {\n\tconst matches = ranges.filter(\n\t\t(range) => range.type === type && (range.charset == null || range.charset === CHARSET),\n\t);\n\tconst withCharset = matches.filter((range) => range.charset === CHARSET);\n\tconst specific = withCharset.length > 0 ? withCharset : matches;\n\treturn specific.length === 0 ? undefined : Math.max(...specific.map((range) => range.quality));\n}\n\n/**\n * Whether a request asks for markdown before HTML, per\n * https://acceptmarkdown.com. Use it to choose between the HTML and the\n * markdown answer for one URL.\n *\n * The rules:\n *\n * - Only an explicit `text/markdown` range counts for markdown. A wildcard,\n * such as `*\\/*` or `text/*`, never selects markdown, so a browser and a\n * client with no `Accept` get HTML.\n * - `text/markdown;q=0` refuses markdown.\n * - The `q` of markdown must be equal to or higher than the `q` of HTML. The\n * `q` of HTML comes from the most specific range that matches it:\n * `text/html`, then `text/*`, then `*\\/*`. A tie selects markdown, because\n * the client named it.\n * - Both answers are UTF-8. A range with `charset=utf-8` is more specific\n * than a range with no charset, and a range with another charset does not\n * match. Other parameters, such as `variant`, do not change the match.\n * - Media types and parameter names are not case-sensitive. A quoted\n * parameter value can hold a `,` or a `;`.\n *\n * When the answer for a URL depends on this function, send `Vary: Accept` on\n * both the HTML and the markdown answer. Else a shared cache can give the\n * markdown to a browser.\n *\n * @example\n * prefersMarkdown(new Request(\"https://example.com/\", { headers: { Accept: \"text/markdown\" } }));\n * // => true\n * prefersMarkdown(new Request(\"https://example.com/\", { headers: { Accept: \"text/html, text/markdown;q=0.5\" } }));\n * // => false\n */\nexport function prefersMarkdown(request: Request): boolean {\n\tconst accept = request.headers.get(\"Accept\");\n\t// Why the substring check: a browser never names markdown, and it skips the parse of its long `Accept`.\n\tif (accept == null || !/markdown/iu.test(accept)) {\n\t\treturn false;\n\t}\n\tconst ranges = mediaRanges(accept);\n\tconst markdown = qualityOf(ranges, \"text/markdown\") ?? 0;\n\tconst html =\n\t\tqualityOf(ranges, \"text/html\") ?? qualityOf(ranges, \"text/*\") ?? qualityOf(ranges, \"*/*\") ?? 0;\n\treturn markdown > 0 && markdown >= html;\n}\n","/**\n * Whether `value` is a safe same-origin path for a `Location` header. The\n * value starts with one `/`, the next character is not `/` or `\\`, and each\n * character is printable ASCII (0x20 to 0x7E).\n *\n * The check stops these attacks:\n *\n * - An open redirect: `//evil.com`, `/\\evil.com`, and `https://evil.com` go to\n * another host. A browser reads `/\\` as `//`.\n * - A scheme that does not navigate, such as `javascript:` or `data:`.\n * - A control character, such as CR or LF, that splits the response.\n *\n * Why strict: a short allow list is easy to audit. The check rejects some safe\n * values, such as a path with raw UTF-8. Percent-encode the path first.\n *\n * Ported from the ngrok frontend `isSafeLocalPath`, with its test cases.\n *\n * @example\n * isSafeLocalPath(\"/components/button?tab=props\"); // => true\n * isSafeLocalPath(\"//evil.com/foo\"); // => false\n * isSafeLocalPath(\"/café\"); // => false\n */\nexport function isSafeLocalPath(value: string): boolean {\n\treturn /^\\/(?![/\\\\])/u.test(value) && !/[^\\u0020-\\u007E]/u.test(value);\n}\n","import type { Context, MiddlewareHandler } from \"hono\";\nimport { matchedRoutes } from \"hono/route\";\nimport { isSafeLocalPath } from \"../safe-local-path.js\";\nimport { findStaticFile } from \"../static-files.js\";\nimport type { AppServerEnv, Plugin, StaticFiles } from \"../types.js\";\n\n/**\n * How a page URL ends:\n *\n * - `never`: with no trailing slash, such as `/docs/button`.\n * - `always`: with a trailing slash, such as `/docs/button/`.\n * - `preserve`: as the request has it. The server sends no redirect.\n */\nexport type TrailingSlash = \"never\" | \"always\" | \"preserve\";\n\n/** Options for {@link trailingSlash}. */\nexport type TrailingSlashOptions = {\n\tmode: TrailingSlash;\n};\n\n/** Whether the last segment of a URL path has a dot, as a file name such as `llms.txt` or `x.data` has. */\nfunction isFilePath(path: string): boolean {\n\treturn path.slice(path.lastIndexOf(\"/\") + 1).includes(\".\");\n}\n\n/** `path` with no trailing slashes. Why a scan, not `/\\/+$/`: that regex takes quadratic time on a long run of slashes inside the path. */\nexport function trimTrailingSlashes(path: string): string {\n\tlet end = path.length;\n\twhile (end > 0 && path[end - 1] === \"/\") {\n\t\tend -= 1;\n\t}\n\treturn path.slice(0, end);\n}\n\n/** The URL path in `mode`, or the path unchanged when `mode` keeps it. */\nfunction canonicalPath(path: string, mode: TrailingSlash): string {\n\tconst trimmed = trimTrailingSlashes(path);\n\tif (trimmed === \"\") {\n\t\treturn \"/\";\n\t}\n\tif (mode === \"never\") {\n\t\treturn trimmed;\n\t}\n\tif (mode === \"always\") {\n\t\treturn `${trimmed}/`;\n\t}\n\treturn path;\n}\n\n/**\n * Whether one of the app's own Hono routes matches the request. Why the\n * path: the plugins and the framework match at `/*`, and Hono matches a\n * route path strictly, so a redirect would move the request off its route.\n */\nfunction hasAppRoute(context: Context<AppServerEnv>): boolean {\n\treturn matchedRoutes(context).some((route) => route.path !== \"/*\");\n}\n\n/** Whether `path`, a decoded URL path, names a file in `files`, not a directory. */\nasync function isStaticFile(files: StaticFiles, path: string): Promise<boolean> {\n\treturn (await findStaticFile(files, path))?.path === path;\n}\n\n/**\n * Sends a 308 from a page URL to the same URL in `mode`, so each page has one\n * URL. It applies to rendered and prerendered pages, because the server cannot\n * tell which paths have a route. The redirect keeps the query string.\n *\n * It sends no redirect for `/`, a method other than GET or HEAD, a data\n * request of the framework, a path that one of the app's own Hono routes\n * matches, such as `app.get(\"/livez\")`, or a path that already has the\n * mode's form. `always` adds no slash to a file in the client build, such as\n * `/LICENSE`, or to a path whose last segment has a dot, such as `/llms.txt`.\n *\n * Set the same mode in the framework's router when it has one. Else the two\n * redirects loop: the server sends `/x` to `/x/`, and the router sends `/x/`\n * back to `/x`. For TanStack Start, check the mode against the router with\n * `RouterTrailingSlash` from `@ngrok/app-server/tanstack-start`. React Router\n * has no trailing-slash option, so it answers both forms itself.\n *\n * @example\n * createServer({ plugins: defaultPlugins({ trailingSlash: \"always\" }) });\n */\nexport function trailingSlash({ mode }: TrailingSlashOptions): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"trailing-slash\",\n\t\tsetup: (info) => {\n\t\t\tif (mode === \"preserve\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method } = context.req;\n\t\t\t\tif (\n\t\t\t\t\t(method !== \"GET\" && method !== \"HEAD\") ||\n\t\t\t\t\tinfo.isDataRequest(context.req.path) ||\n\t\t\t\t\thasAppRoute(context)\n\t\t\t\t) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\t// Why the raw URL: Hono decodes `path`, but a `Location` must keep the percent-encoding.\n\t\t\t\tconst url = new URL(context.req.url);\n\t\t\t\tconst path = canonicalPath(url.pathname, mode);\n\t\t\t\tconst location = `${path}${url.search}`;\n\t\t\t\t// Why the check: a path such as `//evil.com/` must not make a `Location` to another host.\n\t\t\t\tif (path === url.pathname || !isSafeLocalPath(location)) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\t// Why the decoded path: `/llms%2Etxt` names the file `/llms.txt`.\n\t\t\t\tif (\n\t\t\t\t\tmode === \"always\" &&\n\t\t\t\t\t(isFilePath(context.req.path) || (await isStaticFile(info.files, context.req.path)))\n\t\t\t\t) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\treturn context.redirect(location, 308);\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import type { Context, MiddlewareHandler } from \"hono\";\nimport { getPath } from \"hono/utils/url\";\nimport { manifestKey } from \"../build-manifest.js\";\nimport { writableHeaders } from \"../header-hook.js\";\nimport { prefersMarkdown } from \"../prefers-markdown.js\";\nimport { contentType, findStaticFile, isFilePath, staticResponse } from \"../static-files.js\";\nimport { withVary } from \"../vary.js\";\nimport type { StaticFile } from \"../static-files.js\";\nimport type { AppServerEnv, Plugin, StaticFiles } from \"../types.js\";\nimport { trimTrailingSlashes } from \"./trailing-slash.js\";\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/** The requests that the dev server answered. */\nconst devServerAnswers = new WeakSet<Context<AppServerEnv>>();\n\n/**\n * Whether the dev server answered the request, such as for a source module.\n * Why: the access log writes no line for such a request, because one page\n * load in development makes hundreds of them.\n *\n * @example\n * await next();\n * if (answeredByDevServer(context)) return;\n */\nexport function answeredByDevServer(context: Context<AppServerEnv>): boolean {\n\treturn devServerAnswers.has(context);\n}\n\n/**\n * Serves the hashed files under Vite's `build.assetsDir`, `/assets/` by\n * default, with a one-year immutable cache. The `appServer` Vite plugin\n * records the directory. A missing asset gets a plain 404 with\n * `Cache-Control: no-store`, not a rendered page. In development, the dev\n * server serves the source modules, the HMR client, and the CSS here instead.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });\n */\nexport function assets(): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"assets\",\n\t\tsetup: (info) => {\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\tconst { devServer } = info;\n\t\t\t\tstage = async (context, next) => {\n\t\t\t\t\tlet passed = false;\n\t\t\t\t\tconst answer = await devServer(context, async () => {\n\t\t\t\t\t\tpassed = true;\n\t\t\t\t\t\tawait next();\n\t\t\t\t\t});\n\t\t\t\t\tif (!passed) {\n\t\t\t\t\t\tdevServerAnswers.add(context);\n\t\t\t\t\t}\n\t\t\t\t\treturn answer;\n\t\t\t\t};\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { files, contentTypes, assetsPath } = info;\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method, path } = context.req;\n\t\t\t\tif (!path.startsWith(assetsPath) || (method !== \"GET\" && method !== \"HEAD\")) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst file = await findStaticFile(files, path);\n\t\t\t\tif (file == null) {\n\t\t\t\t\t// Why `no-store`: an old tab asks for the chunks of the build it runs, and a CDN must not keep the miss.\n\t\t\t\t\treturn context.text(\"Not Found\", 404, { \"Cache-Control\": \"no-store\" });\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, {\n\t\t\t\t\tfiles,\n\t\t\t\t\tfile,\n\t\t\t\t\theaders: { \"Cache-Control\": IMMUTABLE },\n\t\t\t\t\tcontentTypes,\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n\n/** Options for {@link prerendered}. */\nexport type PrerenderedOptions = {\n\t/**\n\t * Extra headers for a served file, by its URL path. They replace the\n\t * headers captured at build time.\n\t */\n\theaders?: (file: {\n\t\tpath: string;\n\t\tcontext: Context<AppServerEnv>;\n\t}) => Readonly<Record<string, string>> | undefined;\n\t/**\n\t * Maps a request path to the URL path of the file to serve, for content\n\t * negotiation. Return the path unchanged to serve the usual file. The\n\t * returned path follows the rules of a request path: one URL for each\n\t * file, no dotfiles, and nothing outside the client build. When the\n\t * answer depends on a request header, add a `Vary` for it in a plugin.\n\t * With `markdownTwins: true`, a request that `rewrite` changes gets no twin.\n\t */\n\trewrite?: (request: { path: string; context: Context<AppServerEnv> }) => string;\n\t/**\n\t * Serves the markdown twin of a page, such as `/docs/button.md` for\n\t * `/docs/button`, to a request that {@link prefersMarkdown} accepts. A\n\t * page has a twin when `twinOf` names a file in the client build. `twinOf`\n\t * gets the request path and the request's Hono context, the same as\n\t * `rewrite`. It returns `undefined` for a request with no twin.\n\t *\n\t * - A request that prefers markdown gets the twin, with the twin's\n\t * captured headers.\n\t * - Each answer for a path with a twin gets `Vary: Accept`: the twin, the\n\t * prerendered HTML, and the framework's answer. The server adds\n\t * `Accept` to the `Vary` header and keeps the values in it.\n\t * - Each answer for a path with a twin, except the twin, gets\n\t * `Link: <twin>; rel=\"alternate\"; type=\"text/markdown\"`, so a client can\n\t * find the twin.\n\t * - A path with no twin gets no `Vary: Accept` and no `Link`, so a request\n\t * for the twin's own URL gets none.\n\t * - In development, the client build has no twins. A request that prefers\n\t * markdown gets the framework's answer for the twin's URL, so an edit\n\t * shows at once. When the framework knows the paths that the build will\n\t * prerender, as React Router does, only those twins count. An error, or\n\t * an answer that is not markdown, gives the HTML.\n\t * - A plugin after `prerendered` does not see a twin, as it does not see\n\t * a prerendered file.\n\t *\n\t * `true` uses the default `twinOf`: the path with no trailing slash plus\n\t * `.md`, and `/index.md` for `/`. A request that `rewrite` changes gets no\n\t * twin, so it gets the same page as a browser. The returned path follows\n\t * the rules of a request path.\n\t *\n\t * @example\n\t * prerendered({ markdownTwins: { twinOf: ({ path }) => `/markdown${path}.md` } });\n\t */\n\tmarkdownTwins?: boolean | { twinOf: TwinOf };\n\t/**\n\t * Sends a request path to the next stage, with no file lookup. Use it for\n\t * private pages, so the auth check in the app or the framework runs for\n\t * them. A data request has its own path, such as `/app.data` in React\n\t * Router.\n\t *\n\t * @example\n\t * prerendered({ skip: (path) => path === \"/app\" || path.startsWith(\"/app/\") || path.startsWith(\"/app.\") });\n\t */\n\tskip?: (path: string) => boolean;\n\t/**\n\t * The `Cache-Control` of a served file, by the file's URL path, such as\n\t * `/about/index.html`. `undefined` sends none. A header that the build\n\t * captured, and the `headers` option, win over it.\n\t *\n\t * The default gives an HTML page, a markdown file, and a data file of the\n\t * framework `public, max-age=0, must-revalidate`, so a visitor always sees\n\t * the newest page and its markdown twin, and a 304 keeps it fast. It gives every other file\n\t * `public, max-age=3600, stale-while-revalidate=86400`.\n\t *\n\t * @example\n\t * prerendered({ cacheControl: (path) => (path.startsWith(\"/images/\") ? \"public, max-age=86400\" : undefined) });\n\t */\n\tcacheControl?: (path: string) => string | undefined;\n};\n\n/** Maps a request to the URL path of its markdown twin, or `undefined` when it has none. */\ntype TwinOf = (request: { path: string; context: Context<AppServerEnv> }) => string | undefined;\n\n/**\n * The twin of a request, from its path and the path that `rewrite` gives for\n * it, or `undefined` when it has none.\n */\ntype FindTwinPath = (\n\tpath: string,\n\trewritten: string,\n\tcontext: Context<AppServerEnv>,\n) => string | undefined;\n\nconst REVALIDATE = \"public, max-age=0, must-revalidate\";\nconst ONE_HOUR = \"public, max-age=3600, stale-while-revalidate=86400\";\n\n/**\n * The default markdown twin of a page: `/docs/button.md` for `/docs/button`,\n * and `/index.md` for `/`. Why none for a rewritten request: `rewrite` sends\n * it to another file or to the framework, so the page's twin does not match\n * its answer.\n */\nfunction defaultTwinOf(path: string, rewritten: string): string | undefined {\n\treturn rewritten === path ? `${trimTrailingSlashes(path) || \"/index\"}.md` : undefined;\n}\n\n/** The file of the markdown twin of the request, or `undefined` when the page has none. */\nasync function findTwin(\n\tfiles: StaticFiles,\n\tcontext: Context<AppServerEnv>,\n\t{ twinOf, rewritten }: { twinOf: FindTwinPath | undefined; rewritten: string },\n): Promise<{ path: string; file: StaticFile } | undefined> {\n\tconst twinPath = twinOf?.(context.req.path, rewritten, context);\n\tconst file = twinPath == null ? undefined : await findStaticFile(files, twinPath);\n\treturn twinPath == null || file == null ? undefined : { path: twinPath, file };\n}\n\n/** Adds `Vary: Accept` to the answer for a path with a twin, so a shared cache keeps both answers. */\nfunction varyOnAccept(context: Context<AppServerEnv>): void {\n\tconst vary = withVary(context.res.headers.get(\"Vary\"), \"Accept\");\n\tif (vary != null) {\n\t\twritableHeaders(context).set(\"Vary\", vary);\n\t}\n}\n\n/**\n * The percent-encoded URL path for a decoded path, so it holds no space,\n * `>`, or non-ASCII character. Why the replace: a URL removes a tab or a\n * newline, which a file name can hold.\n */\nfunction urlPath(path: string): string {\n\treturn new URL(\n\t\tpath.replaceAll(/[\\t\\n\\r]/gu, (character) => encodeURIComponent(character)),\n\t\t\"http://localhost\",\n\t).pathname;\n}\n\n/** Adds a `Link` to the twin at `twinPath`, so a client that does not ask for markdown can find it. */\nfunction linkToTwin(context: Context<AppServerEnv>, twinPath: string): void {\n\twritableHeaders(context).append(\n\t\t\"Link\",\n\t\t`<${urlPath(twinPath)}>; rel=\"alternate\"; type=\"text/markdown\"`,\n\t);\n}\n\n/**\n * The development stage of `markdownTwins`. The client build has no twins\n * then, so a request that prefers markdown gets the framework's answer for\n * the twin's URL: the route that prerenders the twin. A twin path that is not\n * in `prerenderedPaths`, an error, or an answer that is not markdown sends the\n * request on for the HTML.\n */\nfunction developmentTwins(\n\ttwinOf: FindTwinPath,\n\t{ rewrite, skip }: Pick<PrerenderedOptions, \"rewrite\" | \"skip\">,\n\tprerenderedPaths: ReadonlySet<string> | undefined,\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { method, path } = context.req;\n\t\tconst twinPath =\n\t\t\t(method === \"GET\" || method === \"HEAD\") &&\n\t\t\tskip?.(path) !== true &&\n\t\t\tprefersMarkdown(context.req.raw)\n\t\t\t\t? twinOf(path, rewrite?.({ path, context }) ?? path, context)\n\t\t\t\t: undefined;\n\t\t// Why both checks: production has no twin that the build does not prerender, or at a path that fails `isFilePath`.\n\t\tif (\n\t\t\ttwinPath == null ||\n\t\t\t(prerenderedPaths != null && !prerenderedPaths.has(twinPath)) ||\n\t\t\t!isFilePath(twinPath)\n\t\t) {\n\t\t\treturn next();\n\t\t}\n\t\tconst url = new URL(context.req.url);\n\t\turl.pathname = urlPath(twinPath);\n\t\t// Why: the URL can change the path, for example `%2e%2e` to `..`. Then the framework answers a path that `twinOf` did not name.\n\t\tif (getPath(new Request(url)) !== twinPath) {\n\t\t\treturn next();\n\t\t}\n\t\tconst { headers, signal } = context.req.raw;\n\t\t// Why no `Request` as the init: the Node.js listener's request is not one that `Request` can copy.\n\t\tconst twin = new Request(url, { method, headers, signal });\n\t\tconst response = await context.env.framework.fetch(twin, context);\n\t\t// Why only markdown: production serves a twin from a `.md` file, so an HTML page or an error is no twin.\n\t\t// A 304 has no body to check, and it answers a validator from the twin.\n\t\tconst markdown =\n\t\t\tresponse.headers.get(\"Content-Type\")?.toLowerCase().startsWith(\"text/markdown\") === true;\n\t\tif (response.status !== 304 && !(response.ok && markdown)) {\n\t\t\tawait response.body?.cancel();\n\t\t\treturn next();\n\t\t}\n\t\tcontext.res = response;\n\t\tvaryOnAccept(context);\n\t};\n}\n\n/** The twin lookup that the `markdownTwins` option selects, or `undefined` when it is off. */\nfunction twinOfOption(\n\tmarkdownTwins: PrerenderedOptions[\"markdownTwins\"],\n): FindTwinPath | undefined {\n\tif (markdownTwins === true) {\n\t\treturn defaultTwinOf;\n\t}\n\tif (markdownTwins == null || markdownTwins === false) {\n\t\treturn undefined;\n\t}\n\tconst { twinOf } = markdownTwins;\n\treturn (path, _rewritten, context) => twinOf({ path, context });\n}\n\n/**\n * Serves the client build: prerendered pages at their own URL with a 200,\n * plus every other file in it. It sends no redirect. The `trailingSlash`\n * plugin does. Each response gets\n * the headers its loader sent at build time (the `appServer` Vite plugin\n * captures them), a `Cache-Control` (see `cacheControl`), an ETag, and a 304\n * for a matching `If-None-Match`. A GET with one byte range gets a 206. A path\n * with no file goes on to the framework. In development, only\n * `markdownTwins` runs.\n *\n * At startup, it warns about each prerendered path that has no file.\n *\n * @example\n * prerendered({\n * \theaders: ({ path }) => (path.startsWith(\"/api/\") ? { \"Access-Control-Allow-Origin\": \"*\" } : undefined),\n * });\n */\nexport function prerendered(options: PrerenderedOptions = {}): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"prerendered\",\n\t\tsetup: async (info) => {\n\t\t\tconst twinOf = twinOfOption(options.markdownTwins);\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\tconst paths = info.prerenderedPaths;\n\t\t\t\tstage =\n\t\t\t\t\ttwinOf == null\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: developmentTwins(twinOf, options, paths == null ? undefined : new Set(paths));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { files, contentTypes, capturedHeaders } = info;\n\t\t\tconst missing: string[] = [];\n\t\t\tfor (const path of info.prerenderedPaths) {\n\t\t\t\tif ((await findStaticFile(files, path)) == null) {\n\t\t\t\t\tmissing.push(path);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (missing.length > 0) {\n\t\t\t\t// Why a warning: a path with no file falls through to the framework, which still answers.\n\t\t\t\tinfo.logger.log({\n\t\t\t\t\tlevel: \"warn\",\n\t\t\t\t\tmessage: \"prerendered paths with no file\",\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"app_server.missing_paths\": missing,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst cacheControl =\n\t\t\t\toptions.cacheControl ??\n\t\t\t\t((path: string) => {\n\t\t\t\t\tconst type = contentType(path, contentTypes);\n\t\t\t\t\treturn type.startsWith(\"text/html\") ||\n\t\t\t\t\t\ttype.startsWith(\"text/markdown\") ||\n\t\t\t\t\t\tinfo.isDataRequest(path)\n\t\t\t\t\t\t? REVALIDATE\n\t\t\t\t\t\t: ONE_HOUR;\n\t\t\t\t});\n\t\t\tconst serve = async (context: Context<AppServerEnv>, path: string, file: StaticFile) => {\n\t\t\t\tcontext.env.onServedFile?.(file.path);\n\t\t\t\tconst value = cacheControl(file.path);\n\t\t\t\tconst headers = new Headers(value == null ? undefined : { \"Cache-Control\": value });\n\t\t\t\t// Why `Headers`: the build captures lowercase names, and each layer must replace the one before it in any case.\n\t\t\t\tfor (const layer of [\n\t\t\t\t\tcapturedHeaders.get(manifestKey(path)),\n\t\t\t\t\toptions.headers?.({ path, context }),\n\t\t\t\t]) {\n\t\t\t\t\tfor (const [name, layerValue] of Object.entries(layer ?? {})) {\n\t\t\t\t\t\theaders.set(name, layerValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, {\n\t\t\t\t\tfiles,\n\t\t\t\t\tfile,\n\t\t\t\t\theaders: Object.fromEntries(headers),\n\t\t\t\t\tcontentTypes,\n\t\t\t\t});\n\t\t\t};\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method } = context.req;\n\t\t\t\tif ((method !== \"GET\" && method !== \"HEAD\") || options.skip?.(context.req.path) === true) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst rewritten =\n\t\t\t\t\toptions.rewrite?.({ path: context.req.path, context }) ?? context.req.path;\n\t\t\t\tconst twin = await findTwin(files, context, { twinOf, rewritten });\n\t\t\t\tconst preferred = twin != null && prefersMarkdown(context.req.raw) ? twin : undefined;\n\t\t\t\tconst path = preferred?.path ?? rewritten;\n\t\t\t\tconst file = preferred?.file ?? (await findStaticFile(files, path));\n\t\t\t\tif (file == null) {\n\t\t\t\t\tawait next();\n\t\t\t\t} else {\n\t\t\t\t\tcontext.res = await serve(context, path, file);\n\t\t\t\t}\n\t\t\t\tif (twin != null) {\n\t\t\t\t\tvaryOnAccept(context);\n\t\t\t\t}\n\t\t\t\tif (twin != null && preferred == null) {\n\t\t\t\t\tlinkToTwin(context, twin.path);\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import type { Context } from \"hono\";\nimport { withHeaderHook } from \"../header-hook.js\";\nimport { asError } from \"../log.js\";\nimport { onResponseSent } from \"../response-edge.js\";\nimport type { AppServerEnv, Plugin, SentResponse } from \"../types.js\";\nimport { answeredByDevServer } from \"./static.js\";\n\n/** Options for {@link accessLog}. */\nexport type AccessLogOptions = {\n\t/**\n\t * Replace each query value with `REDACTED`, so a single-use code in a URL\n\t * never reaches a log.\n\t * @default true\n\t */\n\tredactQuery?: boolean;\n\t/**\n\t * More attributes for each request line, such as the app's user ID. It\n\t * runs when the line goes out, with what went out. Read a response header\n\t * from `sent.headers`, not from `context.res`, which can lack the changes of the\n\t * header hooks.\n\t */\n\tattributes?: (response: {\n\t\tcontext: Context<AppServerEnv>;\n\t\tsent: SentResponse;\n\t}) => Readonly<Record<string, unknown>>;\n\t/**\n\t * Set `Server-Timing: app;dur=<ms>` on each HTML document: the time until\n\t * the response headers were ready. The browser's DevTools show it.\n\t * @default false\n\t */\n\tserverTiming?: boolean;\n};\n\n/**\n * A URL's path and query, with each query value replaced when `redact` is set.\n *\n * @example\n * loggedUrl(new URL(\"https://example.com/verify?code=123\"), { redact: true }); // => \"/verify?code=REDACTED\"\n */\nexport function loggedUrl(url: URL, { redact }: { redact: boolean }): string {\n\tif (!redact || url.search === \"\") {\n\t\treturn `${url.pathname}${url.search}`;\n\t}\n\tconst query = [...url.searchParams.keys()]\n\t\t.map((key) => `${encodeURIComponent(key)}=REDACTED`)\n\t\t.join(\"&\");\n\treturn `${url.pathname}?${query}`;\n}\n\n/** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */\nfunction loggedReferer(referer: string | undefined, { redact }: { redact: boolean }) {\n\tif (referer == null || !redact) {\n\t\treturn referer;\n\t}\n\tconst url = URL.parse(referer);\n\treturn url == null ? undefined : `${url.origin}${loggedUrl(url, { redact })}`;\n}\n\n/**\n * One log line per request, static hits included, with Datadog standard\n * attribute names. The line goes out when the response ends or the client\n * disconnects, so a streamed response logs its full duration and size. It\n * logs the response that leaves the server, after each stage. A listener\n * with an `edge`, such as the node listener, counts the bytes.\n *\n * - A 5xx line has the level `error`, and each other line has the level `info`.\n * - A line has `http.route` when the framework adapter gives the route\n * pattern that it matched, such as `/domains/:domainId`.\n * - In development, a request that Vite answers, such as a source module,\n * gets no line.\n * - A request of the build's check of the CDN pages gets no line.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });\n * // {\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200,\"network.bytes_written\":5120,\"duration\":1830000,...}\n */\nexport function accessLog({\n\tredactQuery = true,\n\tattributes,\n\tserverTiming = false,\n}: AccessLogOptions = {}): Plugin {\n\treturn {\n\t\tname: \"access-log\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst started = performance.now();\n\t\t\t// Why a hook: it runs when the head is ready, which is the time that the header gives.\n\t\t\tawait (serverTiming\n\t\t\t\t? withHeaderHook(context, next, (headers) => {\n\t\t\t\t\t\tif (headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) {\n\t\t\t\t\t\t\theaders.append(\n\t\t\t\t\t\t\t\t\"Server-Timing\",\n\t\t\t\t\t\t\t\t`app;dur=${(performance.now() - started).toFixed(1)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t: next());\n\t\t\t// Why skip the build's check of the CDN pages: its requests come from no visitor.\n\t\t\tif (answeredByDevServer(context) || context.env?.onServedFile != null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Why a catch: a log line must never change the response or stop its stream. The listener can\n\t\t\t// call the report from an event of its socket, where a throw stops the process.\n\t\t\tonResponseSent(context, (sent) => {\n\t\t\t\tconst line = lineAttributes(context, sent, started);\n\t\t\t\ttry {\n\t\t\t\t\t// Why `error` for a 5xx only: Datadog takes the status of a line from its level, and crawlers\n\t\t\t\t\t// make most 4xx responses.\n\t\t\t\t\tconst logger = context.get(\"logger\");\n\t\t\t\t\tlogger[sent.status >= 500 ? \"error\" : \"info\"](\n\t\t\t\t\t\t\"request\",\n\t\t\t\t\t\tattributes == null ? line : { ...line, ...attributes({ context, sent }) },\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontext.get(\"logger\").error(\"access log attributes failed\", {\n\t\t\t\t\t\t\t...line,\n\t\t\t\t\t\t\terror: asError(error),\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Why drop it: the sink failed twice, so no line can go out.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n\n\t/** `href` as {@link loggedUrl} logs it. */\n\tfunction requestUrl(href: string): string {\n\t\tconst start = href.indexOf(\"/\", href.indexOf(\"//\") + 2);\n\t\t// Why no parse for a path alone: a request URL is the `href` of a parsed URL, or one that the\n\t\t// Node.js listener checked holds no character that a parse changes. So its path is the `pathname`.\n\t\tif (start !== -1 && !href.includes(\"?\", start) && !href.includes(\"#\", start)) {\n\t\t\treturn href.slice(start);\n\t\t}\n\t\treturn loggedUrl(new URL(href), { redact: redactQuery });\n\t}\n\n\tfunction lineAttributes(\n\t\tcontext: Context<AppServerEnv>,\n\t\t{ status, bytes, aborted }: SentResponse,\n\t\tstarted: number,\n\t): Record<string, unknown> {\n\t\tconst line: Record<string, unknown> = {\n\t\t\t\"http.url\": requestUrl(context.req.url),\n\t\t\t\"http.status_code\": status,\n\t\t\t\"http.useragent\": context.req.header(\"User-Agent\"),\n\t\t\t\"http.referer\": loggedReferer(context.req.header(\"Referer\"), { redact: redactQuery }),\n\t\t\t\"network.client.ip\": context.get(\"clientAddress\"),\n\t\t\t\"network.bytes_written\": bytes,\n\t\t\t// Why nanoseconds: Datadog's standard `duration` attribute is in nanoseconds.\n\t\t\tduration: Math.round((performance.now() - started) * 1_000_000),\n\t\t};\n\t\tconst route = context.get(\"routePattern\");\n\t\tif (route != null) {\n\t\t\tline[\"http.route\"] = route;\n\t\t}\n\t\tif (aborted) {\n\t\t\tline[\"http.client_aborted\"] = true;\n\t\t}\n\t\treturn line;\n\t}\n}\n","import { HTTPException } from \"hono/http-exception\";\nimport { replaceResponse } from \"../header-hook.js\";\nimport type { Plugin } from \"../types.js\";\n\n// Why: GET and HEAD have no body, and the Fetch `Request` constructor rejects the other three.\nconst NO_BODY_METHODS = new Set([\"GET\", \"HEAD\", \"CONNECT\", \"TRACE\", \"TRACK\"]);\n\n/** Options for {@link bodyLimit}. */\nexport type BodyLimitOptions = {\n\t/** The largest request body, in bytes. */\n\tmaxBytes: number;\n};\n\n/** The 413 response. */\nfunction tooLarge(): Response {\n\treturn new Response(\"Payload Too Large\", { status: 413 });\n}\n\n/**\n * Sends a 413 for a request body that is larger than `maxBytes`. A request\n * whose `Content-Length` is too large gets the 413 before the app reads the\n * body, and a request whose `Content-Length` fits goes on unchanged. A\n * streamed body with no `Content-Length` errors when it passes the limit. When the app reads the body before it answers, the response\n * becomes a 413. When the app streams the body into its response, the\n * response stream errors. A `maxBytes` that is not a whole number of 0 or\n * more stops startup.\n *\n * Why not `hono/body-limit`: it reads a streamed body into memory before the\n * next stage runs, so an upload cannot stream.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 })] });\n */\nexport function bodyLimit({ maxBytes }: BodyLimitOptions): Plugin {\n\tif (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {\n\t\tthrow new RangeError(`bodyLimit needs a maxBytes of 0 or more whole bytes, not ${maxBytes}.`);\n\t}\n\treturn {\n\t\tname: \"body-limit\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { raw } = context.req;\n\t\t\tif (NO_BODY_METHODS.has(raw.method)) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tconst length = context.req.header(\"Content-Length\");\n\t\t\t// Why no stream count: the host's HTTP parser ends the body at its `Content-Length`. The\n\t\t\t// original request also keeps the fast body reads of `@hono/node-server`.\n\t\t\tif (\n\t\t\t\tlength != null &&\n\t\t\t\t/^\\d+$/u.test(length) &&\n\t\t\t\tcontext.req.header(\"Transfer-Encoding\") == null\n\t\t\t) {\n\t\t\t\treturn Number(length) > maxBytes ? tooLarge() : next();\n\t\t\t}\n\t\t\tlet bytes = 0;\n\t\t\tlet exceeded = false;\n\t\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t\t\tconst limited = new ReadableStream<Uint8Array>(\n\t\t\t\t{\n\t\t\t\t\tasync pull(controller) {\n\t\t\t\t\t\t// Why on the first read: on Node, `raw.body` starts to read the socket, and a dev\n\t\t\t\t\t\t// server middleware that answers the request reads it there.\n\t\t\t\t\t\treader ??= raw.body?.getReader();\n\t\t\t\t\t\tconst chunk = await reader?.read();\n\t\t\t\t\t\tif (chunk == null || chunk.done) {\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbytes += chunk.value.byteLength;\n\t\t\t\t\t\tif (bytes > maxBytes) {\n\t\t\t\t\t\t\texceeded = true;\n\t\t\t\t\t\t\t// Why an `HTTPException`: `onError` sends its 413 and logs no error.\n\t\t\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\t\t\tnew HTTPException(413, {\n\t\t\t\t\t\t\t\t\tmessage: \"The request body is larger than the body limit.\",\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait reader?.cancel();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(chunk.value);\n\t\t\t\t\t},\n\t\t\t\t\t// Why `raw.body`: if the app cancels before its first read, no reader exists yet.\n\t\t\t\t\tcancel: async (reason) => (reader ?? raw.body)?.cancel(reason),\n\t\t\t\t},\n\t\t\t\t// Why 0: the stream reads nothing until the app reads it.\n\t\t\t\t{ highWaterMark: 0 },\n\t\t\t);\n\t\t\t// Why a new request from its parts: `new Request(raw)` reads `raw.body` on Node. `duplex`: a\n\t\t\t// request with a stream body needs it, and the DOM types lack it.\n\t\t\tconst init: RequestInit & { duplex: \"half\" } = {\n\t\t\t\tmethod: raw.method,\n\t\t\t\theaders: raw.headers,\n\t\t\t\tsignal: raw.signal,\n\t\t\t\tbody: limited,\n\t\t\t\tduplex: \"half\",\n\t\t\t};\n\t\t\tcontext.req.raw = new Request(raw.url, init);\n\t\t\tawait next();\n\t\t\tif (exceeded) {\n\t\t\t\tawait context.res.body?.cancel();\n\t\t\t\treplaceResponse(context, tooLarge());\n\t\t\t}\n\t\t},\n\t};\n}\n","let controller = new AbortController();\nlet stopping = false;\n\n/**\n * A signal that aborts when the server starts to shut down. Read it for each\n * request: each start of a server makes a new one. A handler that\n * holds a response open, such as an event stream, stops on it so that the\n * drain does not wait for the deadline.\n *\n * @example\n * const timer = setInterval(sendUpdate, 1_000);\n * shutdownSignal().addEventListener(\"abort\", () => clearInterval(timer), { once: true });\n */\nexport function shutdownSignal(): AbortSignal {\n\treturn controller.signal;\n}\n\n/** Replaces {@link shutdownSignal} with a new one that has not aborted, and clears {@link isStopping}. */\nexport function renewShutdownSignal(): void {\n\tcontroller = new AbortController();\n\tstopping = false;\n}\n\n/** Marks the server as stopping, before the shutdown delay and the drain. */\nexport function markStopping(): void {\n\tstopping = true;\n}\n\n/** Whether the server got a stop signal. It is true during the shutdown delay, before {@link shutdownSignal} aborts. */\nexport function isStopping(): boolean {\n\treturn stopping;\n}\n\n/** Aborts {@link shutdownSignal}. */\nexport function abortShutdownSignal(): void {\n\tcontroller.abort();\n}\n","import { asError } from \"../log.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport { isStopping } from \"../shutdown.js\";\nimport type { Plugin, RequestLogger } from \"../types.js\";\n\n/** Options for {@link health}. */\nexport type HealthOptions = {\n\t/** @default \"/livez\" */\n\tlivePath?: string;\n\t/** @default \"/readyz\" */\n\treadyPath?: string;\n\t/**\n\t * An app check for readiness, such as a database ping. A `false` or a\n\t * throw makes the server not ready. When the check starts to fail, one\n\t * warn line goes to the log, and when it passes again, one info line.\n\t */\n\tready?: () => boolean | Promise<boolean>;\n};\n\n/** A probe answer that no cache keeps. */\nfunction probe(text: string, status: 200 | 503): Response {\n\treturn new Response(text, {\n\t\tstatus,\n\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\", \"Cache-Control\": \"no-store\" },\n\t});\n}\n\n/**\n * Answers the liveness and readiness probes of a load balancer or\n * Kubernetes. `livePath` always answers 200. `readyPath` answers 200 until\n * the server gets a stop signal, then 503. With `shutdownDelayMs` on\n * `createServer`, the listeners serve on for that time, so the load\n * balancer removes the server before the drain starts.\n *\n * `defaultPlugins()` runs it first, so a probe skips the access log. Its\n * `health` option takes these options, and `false` turns it off.\n *\n * @example\n * createServer({\n * \tplugins: defaultPlugins({ health: { ready: async () => db.ping() } }),\n * \tshutdownDelayMs: 5_000,\n * });\n */\nexport function health({\n\tlivePath = \"/livez\",\n\treadyPath = \"/readyz\",\n\tready,\n}: HealthOptions = {}): Plugin {\n\t// Why log on a change only: a probe comes every few seconds.\n\tlet appFailing = false;\n\tconst appCheck = async (logger: RequestLogger): Promise<boolean> => {\n\t\tif (ready == null) {\n\t\t\treturn true;\n\t\t}\n\t\tlet passed = false;\n\t\tlet failure: Record<string, unknown> = {};\n\t\ttry {\n\t\t\tpassed = await ready();\n\t\t} catch (error) {\n\t\t\tfailure = { error: asError(error) };\n\t\t}\n\t\tif (!passed && !appFailing) {\n\t\t\tlogger.warn(\"readiness check failed\", failure);\n\t\t} else if (passed && appFailing) {\n\t\t\tlogger.info(\"readiness check passed\");\n\t\t}\n\t\tappFailing = !passed;\n\t\treturn passed;\n\t};\n\tconst isReady = async (logger: RequestLogger) => {\n\t\tif (isStopping()) {\n\t\t\treturn false;\n\t\t}\n\t\tconst appReady = await appCheck(logger);\n\t\t// Why check again: a stop signal can come while the app check runs.\n\t\treturn appReady && !isStopping();\n\t};\n\treturn optionPlugin(\"health\", {\n\t\tname: \"health\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { method, path } = context.req;\n\t\t\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tif (path === livePath) {\n\t\t\t\treturn probe(\"ok\", 200);\n\t\t\t}\n\t\t\tif (path === readyPath) {\n\t\t\t\treturn (await isReady(context.get(\"logger\"))) ? probe(\"ok\", 200) : probe(\"not ready\", 503);\n\t\t\t}\n\t\t\treturn next();\n\t\t},\n\t});\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin, presenceHeaders } from \"../plugin-options.js\";\nimport type { Plugin } from \"../types.js\";\nimport { withVary } from \"../vary.js\";\n\n/** Options for {@link noindex}. With no options, each response gets `X-Robots-Tag`. */\nexport type NoindexOptions = {\n\t/**\n\t * A request with this header gets no `X-Robots-Tag`, and each response\n\t * gets the header in `Vary`. The `vercel` host can then serve a\n\t * prerendered page from the CDN, which picks the answer by the same header.\n\t */\n\tunlessHeader: string;\n};\n\n/**\n * Sets `X-Robots-Tag: noindex, nofollow` on each response, or on each\n * response to a request with no `unlessHeader`, so a search engine does not\n * index a preview deploy.\n *\n * The `noindex` option of `defaultPlugins()` puts it\n * before the static stages, so it also sees prerendered pages.\n *\n * @example\n * defaultPlugins({ noindex: process.env.PREVIEW === \"1\" });\n * defaultPlugins({ noindex: { unlessHeader: \"x-ngrok-edge\" } });\n */\nexport function noindex(options?: NoindexOptions): Plugin {\n\tconst unlessHeader = options?.unlessHeader;\n\tconst plugin = optionPlugin(\"noindex\", {\n\t\tname: \"noindex\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst hidden = unlessHeader == null || context.req.header(unlessHeader) == null;\n\t\t\tawait withHeaderHook(context, next, (response) => {\n\t\t\t\tif (hidden) {\n\t\t\t\t\tresponse.set(\"X-Robots-Tag\", \"noindex, nofollow\");\n\t\t\t\t}\n\t\t\t\tif (unlessHeader != null) {\n\t\t\t\t\tconst vary = withVary(response.get(\"Vary\"), unlessHeader);\n\t\t\t\t\tif (vary != null) {\n\t\t\t\t\t\tresponse.set(\"Vary\", vary);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t});\n\treturn unlessHeader == null ? plugin : presenceHeaders([unlessHeader], plugin);\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport type { Plugin, SetupInfo } from \"../types.js\";\n\n/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/**\n * Sets `Cache-Control: private, no-cache` on each HTML document and each\n * framework data response, such as a React Router `.data` request, that has\n * no `Cache-Control`. A shared cache then never keeps a page or loader data\n * that the server rendered for one user. A response with its own\n * `Cache-Control` keeps it. A resource route that sends per-user JSON sets\n * its own `Cache-Control`.\n *\n * Put it after the static stages, so it sees only the responses of the app's\n * routes and the framework. `defaultPlugins()` puts it last.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), assets(), prerendered(), privateDocuments()] });\n */\nexport function privateDocuments(): Plugin {\n\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn {\n\t\tname: \"private-documents\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t},\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (headers) => {\n\t\t\t\tif (\n\t\t\t\t\t!headers.has(\"Cache-Control\") &&\n\t\t\t\t\t((headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) ||\n\t\t\t\t\t\tisDataRequest(context.req.path))\n\t\t\t\t) {\n\t\t\t\t\theaders.set(\"Cache-Control\", \"private, no-cache\");\n\t\t\t\t}\n\t\t\t}),\n\t};\n}\n","import { isSafeLocalPath } from \"../safe-local-path.js\";\nimport type { Plugin } from \"../types.js\";\nimport { trimTrailingSlashes } from \"./trailing-slash.js\";\nimport type { TrailingSlash } from \"./trailing-slash.js\";\n\n/** One redirect of a {@link redirects} table. */\nexport type RedirectRule = {\n\t/**\n\t * The old URL path. A `:name` segment matches one path segment, and a `*`\n\t * last segment matches the rest of the path, or nothing: `/docs/*` also\n\t * matches `/docs`. A trailing slash does not change the match. Write the\n\t * path as it is in the URL, percent-encoded.\n\t */\n\tfrom: string;\n\t/**\n\t * The new URL: a local path, or an absolute `http` or `https` URL. It can\n\t * use each `:name` and the `*` of `from`. An absolute URL is\n\t * percent-encoded as UTF-8.\n\t */\n\tto: string;\n\t/** @default 301 */\n\tstatus?: 301 | 308;\n};\n\n/** A rule, compiled at startup. */\ntype CompiledRule = {\n\t/** The `from` path with no trailing slash. */\n\tkey: string;\n\tpattern: RegExp | undefined;\n\tto: string;\n\tstatus: 301 | 308;\n\t/** The origin of an absolute `to`, else `undefined`. */\n\torigin: string | undefined;\n\t/** The position of the rule in the table. */\n\tindex: number;\n};\n\nconst PARAM = /^:(?<name>[A-Za-z_]\\w*)$/u;\nconst TARGET_TOKEN = /:(?<name>[A-Za-z_]\\w*)|\\*/gu;\n\n/** `path` with no trailing slashes, and `/` for the root. */\nfunction matchKey(path: string): string {\n\treturn trimTrailingSlashes(path) || \"/\";\n}\n\n/** The pattern of `from`, with a named group for each `:name` and for `*`, or `undefined` for an exact path. */\nfunction compilePattern(from: string): { pattern: RegExp | undefined; names: Set<string> } {\n\tconst segments = matchKey(from).split(\"/\").slice(1);\n\tconst names = new Set<string>();\n\tconst parts = segments.map((segment, index) => {\n\t\tconst name = PARAM.exec(segment)?.groups?.name;\n\t\tif (name != null) {\n\t\t\tif (names.has(name)) {\n\t\t\t\tthrow new Error(`The redirect from ${from} uses :${name} twice.`);\n\t\t\t}\n\t\t\tnames.add(name);\n\t\t\treturn `/(?<${name}>[^/]+)`;\n\t\t}\n\t\tif (segment === \"*\") {\n\t\t\tif (index !== segments.length - 1) {\n\t\t\t\tthrow new Error(`The redirect from ${from} has a * that is not the last segment.`);\n\t\t\t}\n\t\t\tnames.add(\"*\");\n\t\t\t// Why `$`: a `:name` cannot have it, so the group name is free. Why optional: `/docs/*`\n\t\t\t// also moves `/docs`.\n\t\t\treturn \"(?:/(?<$splat>.*))?\";\n\t\t}\n\t\treturn `/${segment.replaceAll(/[$()*+.?[\\\\\\]^{|}]/gu, String.raw`\\$&`)}`;\n\t});\n\treturn {\n\t\tpattern: names.size === 0 ? undefined : new RegExp(`^${parts.join(\"\")}$`, \"u\"),\n\t\tnames,\n\t};\n}\n\n/** Compiles a rule, and throws for a rule that is not valid, so a bad table stops startup. */\nfunction compileRule({ from, to, status = 301 }: RedirectRule, index: number): CompiledRule {\n\tif (!from.startsWith(\"/\")) {\n\t\tthrow new Error(`A redirect must be from a path that starts with \"/\", not ${from}.`);\n\t}\n\tconst { pattern, names } = compilePattern(from);\n\tfor (const token of to.matchAll(TARGET_TOKEN)) {\n\t\tconst name = token.groups?.name ?? \"*\";\n\t\tif (!names.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The redirect from ${from} to ${to} uses ${token[0]}, which ${from} does not have.`,\n\t\t\t);\n\t\t}\n\t}\n\tif (to.startsWith(\"/\")) {\n\t\tif (!isSafeLocalPath(to)) {\n\t\t\tthrow new Error(`The redirect from ${from} goes to ${to}, which is not a safe local path.`);\n\t\t}\n\t\treturn { key: matchKey(from), pattern, to, status, origin: undefined, index };\n\t}\n\tconst url = URL.parse(to);\n\tif (url == null || (url.protocol !== \"https:\" && url.protocol !== \"http:\")) {\n\t\tthrow new Error(`A redirect must go to a local path or an http(s) URL, not ${to}.`);\n\t}\n\t// Why `href`: a `Location` must be ASCII, and it percent-encodes the rest as UTF-8.\n\treturn { key: matchKey(from), pattern, to: url.href, status, origin: url.origin, index };\n}\n\n/** The target of `rule` for the values that its pattern matched. */\nfunction fill(to: string, groups: Readonly<Record<string, string | undefined>>): string {\n\tconst queryStart = to.indexOf(\"?\");\n\treturn to.replaceAll(TARGET_TOKEN, (token, name: string | undefined, offset: number) => {\n\t\tconst value = name == null ? (groups.$splat ?? \"\") : (groups[name] ?? token);\n\t\t// Why: a path segment can have `&`, `=`, and `+`, but in a query they split or change the value.\n\t\treturn queryStart !== -1 && offset > queryStart\n\t\t\t? value.replaceAll(/[&+=]/gu, (char) => encodeURIComponent(char))\n\t\t\t: value;\n\t});\n}\n\n/** `target` with no trailing slash on its path, as the `never` mode of `trailingSlash` wants. */\nfunction withoutTrailingSlash(target: string): string {\n\tconst pathEnd = target.search(/[#?]/u);\n\tconst path = pathEnd === -1 ? target : target.slice(0, pathEnd);\n\tconst rest = pathEnd === -1 ? \"\" : target.slice(pathEnd);\n\treturn `${trimTrailingSlashes(path) || \"/\"}${rest}`;\n}\n\n/** `target` with the query string of the request added, before the fragment of `target`. */\nfunction withQuery(target: string, search: string): string {\n\tif (search === \"\") {\n\t\treturn target;\n\t}\n\tconst hashIndex = target.indexOf(\"#\");\n\tconst path = hashIndex === -1 ? target : target.slice(0, hashIndex);\n\tconst hash = hashIndex === -1 ? \"\" : target.slice(hashIndex);\n\treturn `${path}${path.includes(\"?\") ? `&${search.slice(1)}` : search}${hash}`;\n}\n\n/**\n * Sends a redirect from each old URL path in `rules` to its new URL, with\n * the query string. The first rule that matches wins. An exact path is a\n * map lookup. A rule with `:name` or `*` is a pattern.\n *\n * The rules compile at startup, and a rule that is not valid stops startup.\n * A local target must be a safe local path. An absolute target must keep the\n * origin that its rule names. A request whose values break either check goes\n * on to the next stage, and so does a request that is already at its\n * target. It applies to GET and HEAD only.\n *\n * Put it before `trailingSlash`, so `/old/` gets one redirect to the final\n * URL, and give it the same `trailingSlash` mode. In `never` mode, a local\n * target loses its trailing slash, so `trailingSlash` does not redirect it\n * again. `defaultPlugins({ redirects })` does both.\n *\n * @example\n * redirects([\n * \t{ from: \"/blog/:slug\", to: \"/articles/:slug\" },\n * \t{ from: \"/docs/*\", to: \"https://docs.example.com/*\", status: 308 },\n * ]);\n */\nexport function redirects(\n\trules: readonly RedirectRule[],\n\t{ trailingSlash = \"preserve\" }: { trailingSlash?: TrailingSlash } = {},\n): Plugin {\n\tconst compiled = rules.map((rule, index) => compileRule(rule, index));\n\tconst exact = new Map<string, CompiledRule>();\n\tfor (const rule of compiled.toReversed()) {\n\t\t// Why reversed: the first rule for a path wins.\n\t\tif (rule.pattern == null) {\n\t\t\texact.set(rule.key, rule);\n\t\t}\n\t}\n\tconst patterns = compiled.filter((rule) => rule.pattern != null);\n\tconst find = (path: string): { rule: CompiledRule; target: string } | undefined => {\n\t\tconst exactRule = exact.get(path);\n\t\tfor (const rule of patterns) {\n\t\t\tif (exactRule != null && rule.index > exactRule.index) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst groups = rule.pattern?.exec(path)?.groups;\n\t\t\tif (groups != null) {\n\t\t\t\treturn { rule, target: fill(rule.to, groups) };\n\t\t\t}\n\t\t}\n\t\treturn exactRule == null ? undefined : { rule: exactRule, target: exactRule.to };\n\t};\n\treturn {\n\t\tname: \"redirects\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { method } = context.req;\n\t\t\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\t// Why the raw URL: Hono decodes `path`, but a `Location` must keep the percent-encoding.\n\t\t\tconst url = new URL(context.req.url);\n\t\t\tconst found = find(matchKey(url.pathname));\n\t\t\tif (found == null) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tconst target =\n\t\t\t\ttrailingSlash === \"never\" && found.rule.origin == null\n\t\t\t\t\t? withoutTrailingSlash(found.target)\n\t\t\t\t\t: found.target;\n\t\t\tconst location = withQuery(target, url.search);\n\t\t\t// Why: a rule such as `/tags/:tag` to `/tags/:tag/` also matches its own target.\n\t\t\tif (new URL(location, url).href === url.href) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tconst safe =\n\t\t\t\tfound.rule.origin == null\n\t\t\t\t\t? isSafeLocalPath(location)\n\t\t\t\t\t: URL.parse(location)?.origin === found.rule.origin;\n\t\t\treturn safe ? context.redirect(location, found.rule.status) : next();\n\t\t},\n\t};\n}\n","import type { Context } from \"hono\";\nimport { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { AppServerEnv, Plugin } from \"../types.js\";\n\n/** The headers that {@link securityHeaders} sets, by name. */\nexport type SecurityHeaderValues = {\n\t\"X-Content-Type-Options\"?: string | false;\n\t\"Referrer-Policy\"?: string | false;\n\t\"Cross-Origin-Opener-Policy\"?: string | false;\n\t/** Sent on an HTTPS request only. */\n\t\"Strict-Transport-Security\"?: string | false;\n\t/**\n\t * A policy that the plugin adds to each response, next to the app's own\n\t * policy. It has no default.\n\t */\n\t\"Content-Security-Policy\"?: string | false;\n\t/**\n\t * The browser features that the page and its frames can use, such as\n\t * `camera=(), microphone=(), geolocation=()`. It has no default.\n\t */\n\t\"Permissions-Policy\"?: string | false;\n};\n\n// Why no `includeSubDomains`: a browser keeps HSTS for a year, and on an apex domain it would force\n// HTTPS on each subdomain. An app adds it when it knows each subdomain serves HTTPS.\nconst DEFAULT_SECURITY_HEADERS: SecurityHeaderValues = {\n\t\"X-Content-Type-Options\": \"nosniff\",\n\t\"Referrer-Policy\": \"strict-origin-when-cross-origin\",\n\t\"Cross-Origin-Opener-Policy\": \"same-origin\",\n\t\"Strict-Transport-Security\": \"max-age=31536000\",\n};\n\n/** Options for {@link securityHeaders}. */\nexport type SecurityHeadersOptions = {\n\t/** Values that replace the defaults. `false` turns a header off. */\n\theaders?: SecurityHeaderValues;\n};\n\n/**\n * Sets safe default security headers on each response:\n *\n * - `X-Content-Type-Options: nosniff`\n * - `Referrer-Policy: strict-origin-when-cross-origin`\n * - `Cross-Origin-Opener-Policy: same-origin`\n * - `Strict-Transport-Security: max-age=31536000`, on an HTTPS request only\n *\n * `Content-Security-Policy` and `Permissions-Policy` have no default. A\n * response that has a header keeps its own value. The exception is\n * `Content-Security-Policy`: the plugin adds a set value as a second policy,\n * and a browser enforces both.\n * `defaultPlugins()` puts it before the static stages, so it also sees\n * prerendered pages.\n *\n * @example\n * defaultPlugins({\n * \tsecurityHeaders: {\n * \t\theaders: {\n * \t\t\t\"Cross-Origin-Opener-Policy\": \"same-origin-allow-popups\",\n * \t\t\t\"Content-Security-Policy\": \"frame-ancestors 'none'\",\n * \t\t\t\"Permissions-Policy\": \"camera=(), microphone=(), geolocation=()\",\n * \t\t},\n * \t},\n * });\n */\nexport function securityHeaders({ headers = {} }: SecurityHeadersOptions = {}): Plugin {\n\tconst values = Object.entries({ ...DEFAULT_SECURITY_HEADERS, ...headers })\n\t\t.filter((entry): entry is [string, string] => typeof entry[1] === \"string\")\n\t\t.map(([name, value]) => [name, oneLine(value)] as const);\n\treturn {\n\t\tname: \"security-headers\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst isHttps = context.req.url.startsWith(\"https:\");\n\t\t\tawait withHeaderHook(context, next, (response) => {\n\t\t\t\tfor (const [name, value] of values) {\n\t\t\t\t\tif (name === \"Content-Security-Policy\") {\n\t\t\t\t\t\tresponse.append(name, value);\n\t\t\t\t\t} else if (!response.has(name) && (name !== \"Strict-Transport-Security\" || isHttps)) {\n\t\t\t\t\t\tresponse.set(name, value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * `value` on one line. Why: a header value cannot hold a line break, and a\n * policy written over several lines treats each run of whitespace as one space.\n */\nfunction oneLine(value: string): string {\n\treturn value.replaceAll(/\\s+/gu, \" \").trim();\n}\n\n/** Options for {@link contentSecurityPolicy}. */\nexport type ContentSecurityPolicyOptions = {\n\t/**\n\t * The `Content-Security-Policy` of an HTML document. `scriptSrc` is the\n\t * source list that trusts the document's scripts. Put it in `script-src`.\n\t * `context` is the request, so the policy can change by path. It runs in a\n\t * header hook, so it can run more than once for one request.\n\t */\n\tpolicy: (document: { scriptSrc: string; context: Context<AppServerEnv> }) => string;\n};\n\n/** A new random nonce: 16 bytes in base64. */\nfunction randomNonce(): string {\n\treturn btoa(String.fromCodePoint(...crypto.getRandomValues(new Uint8Array(16))));\n}\n\n/**\n * Sets the `Content-Security-Policy` from `policy` on each HTML document. The\n * policy trusts the document's scripts, and only them:\n *\n * - A rendered document gets `'nonce-…' 'strict-dynamic'` with a new nonce\n * for each request. The app reads the nonce from `requestContext()` and\n * gives it to the framework's render, so each inline script gets it.\n * - A prerendered document gets `'self'` and the hash of each of its inline\n * scripts, which the Vite plugin records. Its file has one nonce for every\n * visitor, so a nonce protects nothing. Why no `'strict-dynamic'`: a hash,\n * unlike a nonce, does not carry to the imports of an inline module script.\n *\n * The `contentSecurityPolicy` option of `defaultPlugins()` takes these\n * options, and puts the plugin before the static stages, so it sees the\n * prerendered documents. A response that has a `Content-Security-Policy`\n * keeps it.\n *\n * @example\n * defaultPlugins({\n * \tcontentSecurityPolicy: {\n * \t\tpolicy: ({ scriptSrc }) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,\n * \t},\n * });\n */\nexport function contentSecurityPolicy({ policy }: ContentSecurityPolicyOptions): Plugin {\n\tlet scriptHashes: ReadonlyMap<string, readonly string[]> = new Map();\n\treturn optionPlugin(\"contentSecurityPolicy\", {\n\t\tname: \"content-security-policy\",\n\t\tsetup: (info) => {\n\t\t\t({ scriptHashes } = info);\n\t\t},\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst nonce = randomNonce();\n\t\t\tcontext.set(\"cspNonce\", nonce);\n\t\t\t// Why a header hook: in development, the dev server sends its own response, such as a file of\n\t\t\t// Vite's public directory, and runs the hooks before it sends the head.\n\t\t\tawait withHeaderHook(context, next, (headers) => {\n\t\t\t\t// Why `staticDocument` too: a 304 has no `Content-Type`, and a browser replaces the cached policy with its policy.\n\t\t\t\tconst file = context.get(\"staticDocument\");\n\t\t\t\tconst hashes =\n\t\t\t\t\tcontext.get(\"documentScriptHashes\") ??\n\t\t\t\t\t(file == null ? undefined : (scriptHashes.get(file) ?? []));\n\t\t\t\tif (\n\t\t\t\t\theaders.has(\"Content-Security-Policy\") ||\n\t\t\t\t\t(hashes == null && !(headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false))\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Why `'self'` only for a file with no hashes: the policy fails closed, so a missed script shows in a test.\n\t\t\t\tconst scriptSrc =\n\t\t\t\t\thashes == null\n\t\t\t\t\t\t? `'nonce-${nonce}' 'strict-dynamic'`\n\t\t\t\t\t\t: [\"'self'\", ...hashes.map((hash) => `'sha256-${hash}'`)].join(\" \");\n\t\t\t\theaders.set(\"Content-Security-Policy\", oneLine(policy({ scriptSrc, context })));\n\t\t\t});\n\t\t},\n\t});\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport type { Plugin } from \"../types.js\";\n\n/** Options for {@link requestId}. */\nexport type RequestIdOptions = {\n\t/** @default \"X-Request-Id\" */\n\theaderName?: string;\n\t/**\n\t * Also log the trace IDs as `dd.trace_id` and `dd.span_id`, the lower 64\n\t * bits in decimal, so Datadog connects each log line to its trace.\n\t * @default false\n\t */\n\tdatadogTraceIds?: boolean;\n};\n\n/** An incoming request ID that the plugin keeps: up to 255 word characters, `-`, and `=`. */\nconst VALID_ID = /^[\\w\\-=]{1,255}$/u;\n\n/** A W3C `traceparent`: version, trace ID, parent ID, and flags, in lowercase hex. */\nconst TRACEPARENT =\n\t/^(?<version>[\\da-f]{2})-(?<traceId>[\\da-f]{32})-(?<spanId>[\\da-f]{16})-[\\da-f]{2}(?<rest>-.*)?$/u;\n\n/**\n * The trace IDs of a valid W3C `traceparent` header, else `undefined`. A\n * version `ff`, an ID of all zeros, and extra fields in version `00` are not valid.\n *\n * @example\n * parseTraceparent(\"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\");\n * // => { traceId: \"4bf92f3577b34da6a3ce929d0e0e4736\", spanId: \"00f067aa0ba902b7\" }\n */\nexport function parseTraceparent(\n\theader: string | undefined,\n): { traceId: string; spanId: string } | undefined {\n\tconst groups = TRACEPARENT.exec(header?.trim() ?? \"\")?.groups;\n\tif (\n\t\tgroups?.version == null ||\n\t\tgroups.traceId == null ||\n\t\tgroups.spanId == null ||\n\t\tgroups.version === \"ff\" ||\n\t\t(groups.version === \"00\" && groups.rest != null) ||\n\t\t/^0+$/u.test(groups.traceId) ||\n\t\t/^0+$/u.test(groups.spanId)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn { traceId: groups.traceId, spanId: groups.spanId };\n}\n\n/** The log attributes for the trace IDs. */\nfunction traceAttributes(\n\t{ traceId, spanId }: { traceId: string; spanId: string },\n\t{ datadog }: { datadog: boolean },\n): Record<string, string> {\n\treturn {\n\t\ttrace_id: traceId,\n\t\tspan_id: spanId,\n\t\t...(datadog\n\t\t\t? {\n\t\t\t\t\t\"dd.trace_id\": BigInt(`0x${traceId.slice(16)}`).toString(),\n\t\t\t\t\t\"dd.span_id\": BigInt(`0x${spanId}`).toString(),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Gives each request an ID: a valid incoming header (up to 255 word\n * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on\n * every log line, and into the framework's context.\n *\n * A valid W3C `traceparent` header adds `trace_id` and `span_id` to each log\n * line of the request.\n *\n * @example\n * const app = createServer({ plugins: [requestId()] });\n * const response = await app.request(\"/\", { headers: { \"X-Request-Id\": \"abc-123\" } });\n * response.headers.get(\"X-Request-Id\"); // => \"abc-123\"\n */\nexport function requestId({\n\theaderName = \"X-Request-Id\",\n\tdatadogTraceIds = false,\n}: RequestIdOptions = {}): Plugin {\n\treturn {\n\t\tname: \"request-id\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst trace = parseTraceparent(context.req.header(\"traceparent\"));\n\t\t\tif (trace != null) {\n\t\t\t\tcontext.set(\"logAttributes\", {\n\t\t\t\t\t...context.get(\"logAttributes\"),\n\t\t\t\t\t...traceAttributes(trace, { datadog: datadogTraceIds }),\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst incoming = context.req.header(headerName);\n\t\t\tconst id = incoming != null && VALID_ID.test(incoming) ? incoming : crypto.randomUUID();\n\t\t\tcontext.set(\"requestId\", id);\n\t\t\t// Why a header hook: a dev server middleware sends its own response, and runs the hooks first.\n\t\t\tawait withHeaderHook(context, next, (headers) => {\n\t\t\t\theaders.set(headerName, id);\n\t\t\t});\n\t\t},\n\t};\n}\n","import {\n\tforbidsTransform,\n\tisCompressible,\n\tMIN_COMPRESS_BYTES,\n\tpreferredEncoding,\n\treadIfQueued,\n} from \"../compression.js\";\nimport type { Encoding, ReadResult } from \"../compression.js\";\nimport { hookedHeaders, replaceResponse, withHeaderHook } from \"../header-hook.js\";\nimport type { Plugin } from \"../types.js\";\nimport { withVary } from \"../vary.js\";\n\n/** The chunks that a body has queued, and the read that is still open, if any. */\ntype Queued = { chunks: Uint8Array[]; done: boolean; pending: Promise<ReadResult> | undefined };\n\n/**\n * The most bytes that one pull of {@link replay} joins. Why 64 KiB: each\n * zlib write costs a trip to the thread pool, and the node host compresses a\n * body of one chunk up to 64 KiB with a pooled stream in one trip. A source\n * that makes a chunk on each read looks queued, so the join can read ahead of\n * the client by this size.\n */\nexport const MAX_JOINED_BYTES = 64 * 1024;\n\n/**\n * Reads at most two chunks that `reader` has queued, and never waits for\n * more. Why two: a body from a string or a buffer queues its bytes and its\n * end, so the plugin can see that it is small. `@hono/node-server` reads a\n * body the same way to find its length.\n */\nasync function readQueued(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<Queued> {\n\tconst chunks: Uint8Array[] = [];\n\tfor (let count = 0; count < 2; count += 1) {\n\t\tconst next = await readIfQueued(reader);\n\t\tif (\"pending\" in next) {\n\t\t\treturn { chunks, done: false, pending: next.pending };\n\t\t}\n\t\tif (next.result.done) {\n\t\t\treturn { chunks, done: true, pending: undefined };\n\t\t}\n\t\tchunks.push(next.result.value);\n\t}\n\treturn { chunks, done: false, pending: undefined };\n}\n\nfunction join(chunks: Uint8Array[], size: number): Uint8Array {\n\tconst [first] = chunks;\n\tif (chunks.length === 1 && first != null) {\n\t\treturn first;\n\t}\n\tconst joined = new Uint8Array(size);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tjoined.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn joined;\n}\n\n/**\n * The body again: the queued chunks, then the rest of `reader`. Each pull\n * waits for one chunk at most, and joins it with the chunks that are queued\n * after it, up to {@link MAX_JOINED_BYTES}. Why join: zlib flushes after each\n * chunk, and each flush costs more than the bytes. A renderer such as React\n * queues many small chunks at once. A chunk that comes later still goes out on\n * its own. A chunk that does not fit waits for the next pull, and an empty\n * chunk ends the join. When `queued` has the end, the first pull sends the\n * chunks and closes.\n */\nfunction replay(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tqueued: Queued,\n): ReadableStream<Uint8Array> {\n\tconst chunks = [...queued.chunks];\n\tlet { pending, done } = queued;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\tconst parts: Uint8Array[] = [];\n\t\t\t\tlet size = 0;\n\t\t\t\tconst fits = (chunk: Uint8Array) =>\n\t\t\t\t\tparts.length === 0 || size + chunk.byteLength <= MAX_JOINED_BYTES;\n\t\t\t\tfor (let [chunk] = chunks; chunk != null && fits(chunk); [chunk] = chunks) {\n\t\t\t\t\tchunks.shift();\n\t\t\t\t\tparts.push(chunk);\n\t\t\t\t\tsize += chunk.byteLength;\n\t\t\t\t}\n\t\t\t\tif (parts.length === 0) {\n\t\t\t\t\tconst result = await (pending ?? reader.read());\n\t\t\t\t\tpending = undefined;\n\t\t\t\t\tif (result.done) {\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\tparts.push(result.value);\n\t\t\t\t\tsize = result.value.byteLength;\n\t\t\t\t}\n\t\t\t\t// Why no read when `done`: the host reads a body the same way as `readQueued`, and it sends\n\t\t\t\t// a body with its `Content-Length` only when the body ends within that read.\n\t\t\t\twhile (chunks.length === 0 && pending == null && !done && size < MAX_JOINED_BYTES) {\n\t\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- each read takes only a chunk that is queued already.\n\t\t\t\t\tconst next = await readIfQueued(reader);\n\t\t\t\t\tif (\"pending\" in next) {\n\t\t\t\t\t\t({ pending } = next);\n\t\t\t\t\t} else if (next.result.done) {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (next.result.value.byteLength === 0) {\n\t\t\t\t\t\t// Why stop: empty chunks add no bytes, so a source of them would hold the join open.\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (fits(next.result.value)) {\n\t\t\t\t\t\tparts.push(next.result.value);\n\t\t\t\t\t\tsize += next.result.value.byteLength;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchunks.push(next.result.value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontroller.enqueue(join(parts, size));\n\t\t\t\tif (done && chunks.length === 0) {\n\t\t\t\t\tcontroller.close();\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 consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** A host stream that compresses a byte stream. */\ntype Compress = (source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>;\n\n/**\n * `response` with the compressed `body` and its headers. Why not in a header\n * hook: the body and its headers go together, also to the code that an outer\n * stage runs after its `next()`.\n */\nfunction compressed(\n\tresponse: Response,\n\tbody: ReadableStream<Uint8Array>,\n\t{ encoding, hasLength }: { encoding: Encoding; hasLength: boolean },\n): Response {\n\tconst replacement = new Response(body, response);\n\treplacement.headers.set(\"Content-Encoding\", encoding);\n\t// Why the flag: a delete costs as much as a set, and a streamed page has no length.\n\tif (hasLength) {\n\t\treplacement.headers.delete(\"Content-Length\");\n\t}\n\t// Why: a range of the compressed bytes cannot be served, because each response compresses again.\n\treplacement.headers.delete(\"Accept-Ranges\");\n\treturn replacement;\n}\n\n/**\n * Compresses text responses with brotli or gzip, and flushes after each\n * chunk, so a streamed page shell or a server-sent event reaches the client\n * at once. A client gets brotli when its `Accept-Encoding` ranks `br` at\n * least as high as `gzip`. Chunks that the body has queued together are one\n * chunk, up to 64 KiB. `hono/compress` holds a stream until it ends. Skips a\n * response that is already encoded, a partial response, one marked\n * `no-transform`, and one whose `Content-Length` is under 1 KiB. It adds\n * `Accept-Encoding` to the `Vary` of each response that it can compress. The\n * host gives the streams. On a host with none, the plugin does nothing.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });\n */\nexport function streamingCompress(): Plugin {\n\t/** The host's streams, in the order that the plugin prefers them. */\n\tlet streams = new Map<Encoding, Compress>();\n\tlet offered: readonly Encoding[] = [];\n\t/** The encoding that an `Accept-Encoding` header prefers, with its stream. */\n\tconst choose = (header: string | undefined) => {\n\t\tconst encoding = preferredEncoding(header, offered);\n\t\tconst stream = encoding == null ? undefined : streams.get(encoding);\n\t\treturn encoding == null || stream == null ? undefined : { encoding, stream };\n\t};\n\treturn {\n\t\tname: \"streaming-compress\",\n\t\tsetup: ({ brotli, gzip }) => {\n\t\t\tstreams = new Map();\n\t\t\t// Why brotli first: at quality 4 its output is smaller than gzip's, for the same CPU time.\n\t\t\tif (brotli != null) {\n\t\t\t\tstreams.set(\"br\", brotli);\n\t\t\t}\n\t\t\tif (gzip != null) {\n\t\t\t\tstreams.set(\"gzip\", gzip);\n\t\t\t}\n\t\t\toffered = [...streams.keys()];\n\t\t},\n\t\tmiddleware: async (context, next) => {\n\t\t\tif (offered.length === 0) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\t// Why a hook for `Vary`: the code after `next()` decides, and a response that the plugin does\n\t\t\t// not compress then needs no copy for it.\n\t\t\tlet compressing = false;\n\t\t\tawait withHeaderHook(context, next, (headers) => {\n\t\t\t\t// Why: the bytes of a type that the plugin never compresses, such as an image, do not vary by\n\t\t\t\t// `Accept-Encoding`. A response with no type, such as a 304, keeps the `Vary` of its 200.\n\t\t\t\tconst type = headers.get(\"Content-Type\");\n\t\t\t\tconst vary =\n\t\t\t\t\ttype == null || isCompressible(type)\n\t\t\t\t\t\t? withVary(headers.get(\"Vary\"), \"Accept-Encoding\")\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (vary != null) {\n\t\t\t\t\theaders.set(\"Vary\", vary);\n\t\t\t\t}\n\t\t\t\t// Why: the hook of an inner stage can set the length of the body before compression.\n\t\t\t\tif (compressing) {\n\t\t\t\t\theaders.delete(\"Content-Length\");\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst response = context.res;\n\t\t\tconst type = response.headers.get(\"Content-Type\");\n\t\t\tif (type != null && !isCompressible(type)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst length = response.headers.get(\"Content-Length\");\n\t\t\tconst { body } = response;\n\t\t\tconst chosen = choose(context.req.header(\"Accept-Encoding\"));\n\t\t\tif (\n\t\t\t\ttype == null ||\n\t\t\t\tbody == null ||\n\t\t\t\tcontext.req.method === \"HEAD\" ||\n\t\t\t\t(length != null && Number(length) < MIN_COMPRESS_BYTES) ||\n\t\t\t\tchosen == null ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: compression 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\tforbidsTransform(response.headers.get(\"Cache-Control\"))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet source: ReadableStream<Uint8Array> = body;\n\t\t\tlet compress = true;\n\t\t\tif (length == null) {\n\t\t\t\tconst reader = body.getReader();\n\t\t\t\tconst queued = await readQueued(reader);\n\t\t\t\tconst size = queued.chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n\t\t\t\t// Why: compression makes a small body larger, and a body from a string has no `Content-Length`.\n\t\t\t\tcompress = !queued.done || size >= MIN_COMPRESS_BYTES;\n\t\t\t\tsource = replay(reader, queued);\n\t\t\t}\n\t\t\t// Why the hooks: a header hook of a later stage can set these headers, and it runs only where\n\t\t\t// the response leaves.\n\t\t\tif (compress) {\n\t\t\t\tconst hooked = hookedHeaders(context, response.headers);\n\t\t\t\tcompress =\n\t\t\t\t\t!hooked.has(\"Content-Encoding\") &&\n\t\t\t\t\t!hooked.has(\"Content-Range\") &&\n\t\t\t\t\t!forbidsTransform(hooked.get(\"Cache-Control\"));\n\t\t\t}\n\t\t\tif (compress) {\n\t\t\t\tcompressing = true;\n\t\t\t\treplaceResponse(\n\t\t\t\t\tcontext,\n\t\t\t\t\tcompressed(response, chosen.stream(source), {\n\t\t\t\t\t\tencoding: chosen.encoding,\n\t\t\t\t\t\thasLength: length != null,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} else if (source !== body) {\n\t\t\t\treplaceResponse(context, new Response(source, response));\n\t\t\t}\n\t\t},\n\t};\n}\n","import { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport type { ErrorHandler, HTTPResponseError } from \"hono/types\";\nimport { asError, hookSink, jsonSink, requestLogger } from \"./log.js\";\nimport { accessLog } from \"./plugins/access-log.js\";\nimport type { AccessLogOptions } from \"./plugins/access-log.js\";\nimport { bodyLimit } from \"./plugins/body-limit.js\";\nimport { buildId } from \"./plugins/build-id.js\";\nimport type { BuildIdOptions } from \"./plugins/build-id.js\";\nimport { health } from \"./plugins/health.js\";\nimport type { HealthOptions } from \"./plugins/health.js\";\nimport { noindex } from \"./plugins/noindex.js\";\nimport type { NoindexOptions } from \"./plugins/noindex.js\";\nimport { privateDocuments } from \"./plugins/private-documents.js\";\nimport { redirects } from \"./plugins/redirects.js\";\nimport type { RedirectRule } from \"./plugins/redirects.js\";\nimport { contentSecurityPolicy, securityHeaders } from \"./plugins/security-headers.js\";\nimport type {\n\tContentSecurityPolicyOptions,\n\tSecurityHeadersOptions,\n} from \"./plugins/security-headers.js\";\nimport { requestId } from \"./plugins/request-id.js\";\nimport type { RequestIdOptions } from \"./plugins/request-id.js\";\nimport type { RuntimeEnv } from \"./plugins/runtime-env.js\";\nimport { assets, prerendered } from \"./plugins/static.js\";\nimport type { PrerenderedOptions } from \"./plugins/static.js\";\nimport { streamingCompress } from \"./plugins/streaming-compress.js\";\nimport { trailingSlash } from \"./plugins/trailing-slash.js\";\nimport type { TrailingSlash } from \"./plugins/trailing-slash.js\";\nimport { checkOptionPlugins, presenceHeadersOf } from \"./plugin-options.js\";\nimport { setProcessSink, withRequestContext } from \"./request-context.js\";\nimport { finishResponse } from \"./response-edge.js\";\nimport { abortShutdownSignal, markStopping, renewShutdownSignal } from \"./shutdown.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHeaderHook,\n\tListener,\n\tLogOptions,\n\tLogSink,\n\tPlugin,\n\tRequestStore,\n\tSentResponse,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The response for `error`, as `onError` gives it for a stage that throws. */\nfunction answerError(error: Error | HTTPResponseError, context: Context<AppServerEnv>): Response {\n\t// Why no `instanceof`: the app's routes can throw an `HTTPException` from another copy of Hono.\n\tif (\"getResponse\" in error && typeof error.getResponse === \"function\") {\n\t\tconst response: unknown = error.getResponse();\n\t\tif (response instanceof Response) {\n\t\t\treturn response;\n\t\t}\n\t}\n\tcontext.get(\"logger\").error(\"unhandled error\", { error });\n\treturn context.text(\"Internal Server Error\", 500);\n}\n\n// Why a WeakMap: only this copy of the package reads an app's internals, through `createEntry`.\nconst appInternals = new WeakMap<AppServer, ServerInternals>();\n\n/** A Hono app from {@link createServer}. Add routes to it before you export it. */\nexport type AppServer = Hono<AppServerEnv>;\n\n/** A server that listens. */\nexport type RunningServer = {\n\t/** The URL of each listener. */\n\turls: readonly string[];\n\t/**\n\t * Marks the server as not ready, and waits for the shutdown delay. Then it\n\t * aborts `shutdownSignal()` and runs each plugin's `onShutdown` while the\n\t * listeners stop and drain open requests. Both stop at the deadline.\n\t */\n\tshutdown: () => Promise<void>;\n};\n\n/** What `createEntry` calls on an app. */\nexport type ServerInternals = {\n\tlogger: LogSink;\n\t/** The request headers whose presence alone changes the answer of a plugin. See `presenceHeaders`. */\n\tpresenceHeaders: readonly string[];\n\t/** Runs each plugin's `setup` once and adds the framework handler after the app's routes. */\n\tprepare: (info: SetupInfo) => Promise<void>;\n\t/**\n\t * Starts the app's listeners, else `defaultListeners`, the host's. Call\n\t * `prepare` first. Throws when neither has a listener.\n\t */\n\tlisten: (\n\t\tframework: FrameworkRuntime,\n\t\tdefaultListeners: readonly Listener[] | undefined,\n\t) => Promise<RunningServer>;\n\t/** Runs each plugin's `onShutdown` once, and stops waiting for them at the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Sets the storage for `requestContext()` in this app's requests. `createEntry` sets the host's. */\n\tsetRequestStore: (store: RequestStore | undefined) => void;\n};\n\n/** Why 10 MiB: a form or an avatar upload fits, and a body cannot fill the memory. */\nconst DEFAULT_BODY_LIMIT = 10 * 1024 * 1024;\n\n/** Options for {@link defaultPlugins}. */\nexport type DefaultPluginsOptions = {\n\t/**\n\t * The options of the liveness and readiness probes. `false` turns them\n\t * off, such as for an app with its own `/livez` route. See {@link health}.\n\t * @default {}\n\t */\n\thealth?: HealthOptions | false;\n\trequestId?: RequestIdOptions;\n\taccessLog?: AccessLogOptions;\n\tprerendered?: PrerenderedOptions;\n\t/**\n\t * Redirects from old URL paths to new URLs. They run before\n\t * `trailingSlash`, so an old URL gets one redirect. See {@link redirects}.\n\t */\n\tredirects?: readonly RedirectRule[];\n\t/**\n\t * How a page URL ends. Set the same mode in the framework's router when it\n\t * has one, else the redirects loop. See {@link trailingSlash}.\n\t * @default \"never\"\n\t */\n\ttrailingSlash?: TrailingSlash;\n\t/**\n\t * The largest request body, in bytes. A larger body gets a 413. `false`\n\t * turns the limit off. See {@link bodyLimit}.\n\t * @default 10485760 (10 MiB)\n\t */\n\tbodyLimit?: number | false;\n\t/**\n\t * The options of the security headers. `false` turns them off. See\n\t * {@link securityHeaders}.\n\t */\n\tsecurityHeaders?: SecurityHeadersOptions | false;\n\t/**\n\t * Sets `X-Robots-Tag: noindex, nofollow` on each response, such as on a\n\t * preview deploy. The options decide for each request. See {@link noindex}.\n\t * @default false\n\t */\n\tnoindex?: boolean | NoindexOptions;\n\t/**\n\t * The options of the build ID on each document and data response. `false`\n\t * turns it off. See {@link buildId}.\n\t * @default {}, with the ID that the `appServer` Vite plugin derives from the client build\n\t */\n\tbuildId?: BuildIdOptions | false;\n\t/**\n\t * The options of the `Content-Security-Policy` of each HTML document. It\n\t * has no default. See {@link contentSecurityPolicy}.\n\t */\n\tcontentSecurityPolicy?: ContentSecurityPolicyOptions;\n\t/**\n\t * The plugin from `runtimeEnv(schema)`. It writes the public values into\n\t * each HTML document, prerendered pages included.\n\t */\n\tenv?: RuntimeEnv<unknown>;\n\t/**\n\t * The app's own plugins that see every response, prerendered pages\n\t * included, such as an auth check. They go after the plugins of the\n\t * options above and before the static stages.\n\t */\n\tbeforeStatic?: readonly Plugin[];\n};\n\n/**\n * The default pipeline, in order: `health`, `requestId`, `accessLog`,\n * `streamingCompress`, `securityHeaders`, `bodyLimit`, `noindex` (when\n * set), `buildId`, `contentSecurityPolicy` (when set), `env` (when set), the\n * `beforeStatic` plugins, `assets`, `redirects` (when the option has rules),\n * `trailingSlash`, `prerendered`, and `privateDocuments`. It is a plain\n * array, so an app can filter it or splice into it.\n *\n * @example\n * createServer({\n * \tplugins: defaultPlugins({ env, noindex: process.env.PREVIEW === \"1\", health: { ready: async () => db.ping() } }),\n * });\n */\nexport function defaultPlugins(options: DefaultPluginsOptions = {}): Plugin[] {\n\tconst maxBytes = options.bodyLimit ?? DEFAULT_BODY_LIMIT;\n\treturn [\n\t\t// Why first: a probe skips the access log, and a load balancer gets its answer with no other work.\n\t\t...(options.health === false ? [] : [health(options.health)]),\n\t\trequestId(options.requestId),\n\t\taccessLog(options.accessLog),\n\t\tstreamingCompress(),\n\t\t// Why before `bodyLimit`: its 413 must also get the security headers.\n\t\t...(options.securityHeaders === false ? [] : [securityHeaders(options.securityHeaders)]),\n\t\t...(maxBytes === false ? [] : [bodyLimit({ maxBytes })]),\n\t\t// Why before the static stages: these plugins must see the prerendered pages. Why before\n\t\t// `beforeStatic`: an app plugin, such as an auth check, then gets the CSP nonce, and its own\n\t\t// responses get these headers. Their order among themselves changes no response.\n\t\t...(options.noindex == null || options.noindex === false\n\t\t\t? []\n\t\t\t: [options.noindex === true ? noindex() : noindex(options.noindex)]),\n\t\t...(options.buildId === false ? [] : [buildId(options.buildId)]),\n\t\t...(options.contentSecurityPolicy == null\n\t\t\t? []\n\t\t\t: [contentSecurityPolicy(options.contentSecurityPolicy)]),\n\t\t...(options.env == null ? [] : [options.env]),\n\t\t...(options.beforeStatic ?? []),\n\t\tassets(),\n\t\t...(options.redirects == null || options.redirects.length === 0\n\t\t\t? []\n\t\t\t: [redirects(options.redirects, { trailingSlash: options.trailingSlash ?? \"never\" })]),\n\t\t// Why after `assets`: in development, the dev server there answers Vite's paths, such as `/@vite/client`.\n\t\ttrailingSlash({ mode: options.trailingSlash ?? \"never\" }),\n\t\tprerendered(options.prerendered),\n\t\t// Why last: it must see only the responses of the app's routes and the framework.\n\t\tprivateDocuments(),\n\t];\n}\n\n/** Options for {@link createServer}. */\nexport type CreateServerOptions = {\n\t/** @default defaultPlugins() */\n\tplugins?: readonly Plugin[];\n\t/** @default jsonSink() */\n\tlogger?: LogSink;\n\t/**\n\t * Hooks that change each log line of the server and of `logger()`, such\n\t * as to redact a field.\n\t */\n\tlog?: LogOptions;\n\t/** @default the host's listeners, such as `[tcp()]` on the node host */\n\tlisteners?: readonly Listener[];\n\t/**\n\t * Read the request scheme from `X-Forwarded-Proto`. Set it only behind a\n\t * proxy that overwrites that header, else a client can spoof it.\n\t * @default false\n\t */\n\ttrustForwardedProto?: boolean;\n\t/**\n\t * How many proxies in front of the server add the address they got a\n\t * request from to `X-Forwarded-For`. With N, the client address is the\n\t * Nth address from the right of that header. A header with fewer\n\t * addresses gives its leftmost address. Set it only to the number of\n\t * proxies that you run, else a client can spoof its address.\n\t * @default 0, the address of the socket\n\t */\n\ttrustedProxyHops?: number;\n\t/**\n\t * How long the listeners serve on after a stop signal, before the drain\n\t * starts. During this time, the `health` plugin's readiness probe answers\n\t * 503, so a load balancer stops sending requests first. The drain deadline\n\t * starts after the delay.\n\t * @default 0\n\t */\n\tshutdownDelayMs?: number;\n\t/**\n\t * How long open requests get to finish after the drain starts.\n\t * @default 10000\n\t */\n\tshutdownDeadlineMs?: number;\n};\n\n/**\n * The client address in an `X-Forwarded-For` header, with `hops` trusted\n * proxies, or `undefined` when the header has no address.\n */\nfunction forwardedClient(header: string | undefined, hops: number): string | undefined {\n\tconst addresses = (header ?? \"\")\n\t\t.split(\",\")\n\t\t.map((address) => address.trim())\n\t\t.filter((address) => address !== \"\");\n\treturn addresses[Math.max(0, addresses.length - hops)];\n}\n\n/** Why: `setTimeout` turns a longer delay into 1 ms. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\n/** Throws for a value that is not an integer from 0 to `max`, so a bad option stops startup. */\nfunction checkCount(name: string, value: number, max = Number.MAX_SAFE_INTEGER): void {\n\tif (!Number.isInteger(value) || value < 0 || value > max) {\n\t\tconst range = max === Number.MAX_SAFE_INTEGER ? \"of 0 or more\" : `from 0 to ${max}`;\n\t\tthrow new Error(`${name} must be an integer ${range}, not ${value}.`);\n\t}\n}\n\n/**\n * The request with the scheme from `X-Forwarded-Proto`, when that header holds one.\n *\n * @example\n * withForwardedProto(new Request(\"http://example.com/\", { headers: { \"X-Forwarded-Proto\": \"https\" } })).url;\n * // => \"https://example.com/\"\n */\nexport function withForwardedProto(request: Request): Request {\n\tconst proto = request.headers.get(\"X-Forwarded-Proto\");\n\t// Why check the scheme first: a new `Request` costs a copy of the request on each call.\n\tif ((proto !== \"http\" && proto !== \"https\") || request.url.startsWith(`${proto}:`)) {\n\t\treturn request;\n\t}\n\tconst url = new URL(request.url);\n\turl.protocol = `${proto}:`;\n\t// Why copy it first: the Node listener gives a light request, which `new Request` copies only as\n\t// its first argument. As the second, its getters throw \"Illegal invocation\".\n\tconst copy = new Request(url, new Request(request));\n\t// Why: a `Request` cannot hold TRACE, so the Node listener gives a GET request that says TRACE.\n\t// The copy must say TRACE too, or a GET route answers it.\n\tif (copy.method !== request.method) {\n\t\tObject.defineProperty(copy, \"method\", { value: request.method });\n\t}\n\treturn copy;\n}\n\n/** Whether `work` settles before `ms` pass. */\nasync function settlesWithin(work: Promise<void>, ms: number): Promise<boolean> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst settled = await Promise.race([\n\t\twork.then(() => true),\n\t\tnew Promise<boolean>((resolve) => {\n\t\t\ttimer = setTimeout(resolve, ms, false);\n\t\t}),\n\t]);\n\tclearTimeout(timer);\n\treturn settled;\n}\n\n/**\n * Builds an app server: a Hono app that runs the plugins in list order, then\n * the app's own routes, then the framework. It does not listen; the\n * `app-server` CLI starts it.\n *\n * Two plugins of one option of `defaultPlugins()`, such as two `buildId()`,\n * stop startup.\n *\n * @example\n * // server.ts\n * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ env }) });\n * app.get(\"/api/status\", (c) => c.json({ ok: true }));\n * export default app;\n */\nexport function createServer({\n\tplugins = defaultPlugins(),\n\tlogger: sink = jsonSink(),\n\tlog,\n\tlisteners,\n\ttrustForwardedProto = false,\n\ttrustedProxyHops = 0,\n\tshutdownDelayMs = 0,\n\tshutdownDeadlineMs = 10_000,\n}: CreateServerOptions = {}): AppServer {\n\tcheckOptionPlugins(plugins);\n\tcheckCount(\"trustedProxyHops\", trustedProxyHops);\n\tcheckCount(\"shutdownDelayMs\", shutdownDelayMs, MAX_TIMER_MS);\n\tcheckCount(\"shutdownDeadlineMs\", shutdownDeadlineMs, MAX_TIMER_MS);\n\tconst logger = hookSink(sink, log);\n\tsetProcessSink(logger);\n\tconst app = new Hono<AppServerEnv>();\n\t// Why keep the handler: a header hook that throws gets the app's `onError` answer, as a stage does.\n\tlet onError: ErrorHandler<AppServerEnv> = answerError;\n\tconst setOnError = app.onError.bind(app);\n\tapp.onError = (handler) => {\n\t\tonError = handler;\n\t\treturn setOnError(handler);\n\t};\n\tapp.onError(answerError);\n\tconst answerThrown = async (thrown: unknown, context: Context<AppServerEnv>) =>\n\t\tonError(asError(thrown), context);\n\tlet requestStore: RequestStore | undefined;\n\tif (trustForwardedProto) {\n\t\t// Why wrap `fetch`: every plugin and route, not only the framework, must see the trusted scheme.\n\t\tconst dispatch = app.fetch;\n\t\tapp.fetch = async (request, ...rest) => dispatch(withForwardedProto(request), ...rest);\n\t}\n\tapp.use(async (context, next) => {\n\t\tconst requestLog = requestLogger(logger, context);\n\t\tcontext.set(\"logger\", requestLog);\n\t\tconst remoteAddress = context.env?.remoteAddress;\n\t\tcontext.set(\n\t\t\t\"clientAddress\",\n\t\t\ttrustedProxyHops === 0\n\t\t\t\t? remoteAddress\n\t\t\t\t: (forwardedClient(context.req.header(\"X-Forwarded-For\"), trustedProxyHops) ??\n\t\t\t\t\t\tremoteAddress),\n\t\t);\n\t\t// Why lists here: each stage's header hook then changes the head once, where the response\n\t\t// leaves, and each report gets the response that leaves.\n\t\tconst hooks: HeaderHook[] = [];\n\t\tconst reports: ((sent: SentResponse) => void)[] = [];\n\t\tcontext.set(\"headerHooks\", hooks);\n\t\tcontext.set(\"sentReports\", reports);\n\t\tconst given = context.env?.edge;\n\t\t// Why claim before the stages: a request that the app sends through itself again with `c.env`\n\t\t// gets the same edge, and must change its own response.\n\t\tconst edge = given?.claim(requestLog) === true ? given : undefined;\n\t\t// Why finish in the request context: a header hook can read `requestContext()`.\n\t\tawait withRequestContext(requestStore, context, async () => {\n\t\t\tawait next();\n\t\t\tconst finishing = finishResponse(context, { hooks, reports, edge, fail: answerThrown });\n\t\t\tif (finishing != null) {\n\t\t\t\tawait finishing;\n\t\t\t}\n\t\t});\n\t\t// Why cancel: Hono drops the body of a HEAD response without a cancel, so a stream would run on.\n\t\tif (context.req.method === \"HEAD\") {\n\t\t\tawait context.res.body?.cancel();\n\t\t}\n\t});\n\t// Why `asError` at each step: a value that is not an `Error` becomes one where it is thrown,\n\t// so `onError` answers at once and each earlier plugin still sees the 500 after its `next`.\n\tfor (const { middleware, etagPart } of plugins) {\n\t\tapp.use(async (context, next) => {\n\t\t\tconst part = etagPart?.();\n\t\t\tif (part != null) {\n\t\t\t\tcontext.set(\"etagParts\", [...(context.get(\"etagParts\") ?? []), part]);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await (middleware == null ? next() : middleware(context, next));\n\t\t\t} catch (error) {\n\t\t\t\tthrow asError(error);\n\t\t\t}\n\t\t});\n\t}\n\tapp.use(async (_, next) => {\n\t\ttry {\n\t\t\tawait next();\n\t\t} catch (error) {\n\t\t\tthrow asError(error);\n\t\t}\n\t});\n\n\tlet prepared: Promise<void> | undefined;\n\tlet running: RunningServer | undefined;\n\tlet stoppingPlugins: Promise<void> | undefined;\n\tconst internals: ServerInternals = {\n\t\tlogger,\n\t\tpresenceHeaders: presenceHeadersOf(plugins),\n\t\tsetRequestStore: (store) => {\n\t\t\trequestStore = store;\n\t\t},\n\t\tprepare: async (info) => {\n\t\t\tprepared ??= (async () => {\n\t\t\t\tfor (const plugin of plugins) {\n\t\t\t\t\tawait plugin.setup?.(info);\n\t\t\t\t}\n\t\t\t\tapp.all(\"*\", async (context) => context.env.framework.fetch(context.req.raw, context));\n\t\t\t})().catch((error: unknown) => {\n\t\t\t\t// Why: the next request on a serverless host runs each `setup` again.\n\t\t\t\tprepared = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn prepared;\n\t\t},\n\t\tlisten: async (framework, defaultListeners) => {\n\t\t\tif (running != null) {\n\t\t\t\tthrow new Error(\"This app server is already listening.\");\n\t\t\t}\n\t\t\tconst chosen = listeners ?? defaultListeners ?? [];\n\t\t\tif (chosen.length === 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"This app server has no listener: the app sets none, and the host has none. A serverless host calls the entry's `fetch`.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\trenewShutdownSignal();\n\t\t\tlet deadlinePassed = false;\n\t\t\tconst fetch: FetchHandler = async (request, bindings) => {\n\t\t\t\tconst response = await app.fetch(request, { ...bindings, framework });\n\t\t\t\t// Why: after the drain deadline, the listener closed the connection, so no one reads this\n\t\t\t\t// body. A cancel stops its producer, which can otherwise keep the process alive.\n\t\t\t\tif (deadlinePassed) {\n\t\t\t\t\tawait response.body?.cancel();\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t};\n\t\t\tconst starts = await Promise.allSettled(\n\t\t\t\tchosen.map(async (listener) => listener.start(fetch, { trustForwardedProto })),\n\t\t\t);\n\t\t\tconst started = starts.flatMap((start) =>\n\t\t\t\tstart.status === \"fulfilled\" ? [start.value] : [],\n\t\t\t);\n\t\t\tconst failed = starts.find((start) => start.status === \"rejected\");\n\t\t\tif (failed != null) {\n\t\t\t\t// Why stop the others: the caller gets no handle to stop them.\n\t\t\t\tawait Promise.all(started.map(async (listener) => listener.stop({ deadlineMs: 0 })));\n\t\t\t\tthrow failed.reason;\n\t\t\t}\n\t\t\tconst urls = started.map((listener) => listener.url);\n\t\t\tlogger.log({ level: \"info\", message: \"listening\", attributes: { \"app_server.urls\": urls } });\n\t\t\tlet stopping: Promise<void> | undefined;\n\t\t\trunning = {\n\t\t\t\turls,\n\t\t\t\tshutdown: async () => {\n\t\t\t\t\tstopping ??= (async () => {\n\t\t\t\t\t\tmarkStopping();\n\t\t\t\t\t\tif (shutdownDelayMs > 0) {\n\t\t\t\t\t\t\tlogger.log({\n\t\t\t\t\t\t\t\tlevel: \"info\",\n\t\t\t\t\t\t\t\tmessage: \"waiting before the drain\",\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"app_server.delay_ms\": shutdownDelayMs,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tawait new Promise((resolve) => {\n\t\t\t\t\t\t\t\tsetTimeout(resolve, shutdownDelayMs);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger.log({\n\t\t\t\t\t\t\tlevel: \"info\",\n\t\t\t\t\t\t\tmessage: \"draining\",\n\t\t\t\t\t\t\tattributes: { \"app_server.deadline_ms\": shutdownDeadlineMs },\n\t\t\t\t\t\t});\n\t\t\t\t\t\tabortShutdownSignal();\n\t\t\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\t\t\tdeadlinePassed = true;\n\t\t\t\t\t\t}, shutdownDeadlineMs);\n\t\t\t\t\t\t// Why at the same time: a plugin that hangs must not keep the listeners open.\n\t\t\t\t\t\t// Why settle all: the process exits after shutdown, so one failed stop must not cut\n\t\t\t\t\t\t// the other stops short.\n\t\t\t\t\t\tconst results = await Promise.allSettled([\n\t\t\t\t\t\t\tinternals.stopPlugins(),\n\t\t\t\t\t\t\t...started.map(async (listener) => listener.stop({ deadlineMs: shutdownDeadlineMs })),\n\t\t\t\t\t\t]);\n\t\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\t\tconst rejected = results.find((result) => result.status === \"rejected\");\n\t\t\t\t\t\tif (rejected != null) {\n\t\t\t\t\t\t\tthrow rejected.reason;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger.log({ level: \"info\", message: \"stopped\", attributes: {} });\n\t\t\t\t\t})();\n\t\t\t\t\treturn stopping;\n\t\t\t\t},\n\t\t\t};\n\t\t\treturn running;\n\t\t},\n\t\tstopPlugins: async () => {\n\t\t\tstoppingPlugins ??= (async () => {\n\t\t\t\tconst hooks = (async () => {\n\t\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\t\tplugins.map(async (plugin) => plugin.onShutdown?.()),\n\t\t\t\t\t);\n\t\t\t\t\tfor (const result of results) {\n\t\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\t\tlogger.log({\n\t\t\t\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\t\t\t\tmessage: \"plugin shutdown failed\",\n\t\t\t\t\t\t\t\tattributes: { error: asError(result.reason) },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\tif (!(await settlesWithin(hooks, shutdownDeadlineMs))) {\n\t\t\t\t\tlogger.log({\n\t\t\t\t\t\tlevel: \"warn\",\n\t\t\t\t\t\tmessage: \"plugin shutdown passed the deadline\",\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\"app_server.deadline_ms\": shutdownDeadlineMs,\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\treturn stoppingPlugins;\n\t\t},\n\t};\n\tappInternals.set(app, internals);\n\treturn app;\n}\n\n/** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */\nexport function serverInternals(app: AppServer): ServerInternals | undefined {\n\treturn appInternals.get(app);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAM,SAAS;;AAIf,MAAM,UAAU;;;;;AAMhB,SAAS,mBAAmB,OAAe,WAA6B;CACvE,MAAM,QAAkB,CAAC;CACzB,IAAI,OAAO;CACX,IAAI,SAAS;CACb,IAAI,UAAU;CACd,KAAK,MAAM,aAAa,OACvB,IAAI,CAAC,UAAU,cAAc,WAAW;EACvC,MAAM,KAAK,IAAI;EACf,OAAO;CACR,OAAO;EACN,IAAI,SACH,UAAU;OACJ,IAAI,UAAU,cAAc,MAClC,UAAU;OACJ,IAAI,cAAc,MACxB,SAAS,CAAC;EAEX,QAAQ;CACT;CAED,MAAM,KAAK,IAAI;CACf,OAAO;AACR;;AAGA,SAAS,aAAa,YAAoD;CACzE,OAAO,IAAI,IACV,WAAW,KAAK,cAAc;EAC7B,MAAM,QAAQ,UAAU,QAAQ,GAAG;EACnC,MAAM,QAAQ,UAAU,KAAK,YAAY,UAAU,MAAM,GAAG,KAAK,EAAC,CAAE,KAAK,CAAC,CAAC,YAAY;EACvF,MAAM,QAAQ,UAAU,KAAK,KAAK,UAAU,MAAM,QAAQ,CAAC,CAAC,CAAC,KAAK;EAIlE,OAAO,CAAC,MAHS,WAAW,KAAK,KAAK,IACnC,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,WAAW,wBAAwB,cAAc,IACpE,KACmB;CACvB,CAAC,CACF;AACD;;;;;;AAOA,SAAS,YAAY,QAA8B;CAClD,OAAO,mBAAmB,QAAQ,GAAG,CAAC,CAAC,KAAK,UAAU;EACrD,MAAM,CAAC,OAAO,IAAI,GAAG,cAAc,mBAAmB,OAAO,GAAG;EAChE,MAAM,kBAAkB,a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;IACR;GACD;GACA,OAAO;EACR;EACA,aAAa,YAAY;GACxB,qBAAqB,YAAY;IAehC,IAAI,CAAE,MAAM,eAdG,YAAY;KAC1B,MAAM,UAAU,MAAM,QAAQ,WAC7B,QAAQ,IAAI,OAAO,WAAW,OAAO,aAAa,CAAC,CACpD;KACA,KAAK,MAAM,UAAU,SACpB,IAAI,OAAO,WAAW,YACrB,OAAO,IAAI;MACV,OAAO;MACP,SAAS;MACT,YAAY,EAAE,OAAO,QAAQ,OAAO,MAAM,EAAE;KAC7C,CAAC;IAGJ,EAAC,CAC6B,GAAG,kBAAkB,GAClD,OAAO,IAAI;KACV,OAAO;KACP,SAAS;KACT,YAAY,EACX,0BAA0B,mBAC3B;IACD,CAAC;GAEH,EAAC,CAAE;GACH,OAAO;EACR;CACD;CACA,aAAa,IAAI,KAAK,SAAS;CAC/B,OAAO;AACR;;AAGA,SAAgB,gBAAgB,KAA6C;CAC5E,OAAO,aAAa,IAAI,GAAG;AAC5B"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as TrailingSlash } from "./trailing-slash-
|
|
1
|
+
import { C as SentResponse, g as LogSink, h as LogOptions, t as AppServerEnv, u as Listener, v as Plugin } from "./types-C_I3i62n.js";
|
|
2
|
+
import { t as TrailingSlash } from "./trailing-slash-D_52DJaQ.js";
|
|
3
3
|
import { Context, Hono } from "hono";
|
|
4
4
|
/** Options for {@link accessLog}. */
|
|
5
5
|
type AccessLogOptions = {
|
|
@@ -12,10 +12,13 @@ type AccessLogOptions = {
|
|
|
12
12
|
/**
|
|
13
13
|
* More attributes for each request line, such as the app's user ID. It
|
|
14
14
|
* runs when the line goes out, with what went out. Read a response header
|
|
15
|
-
* from `sent.headers`, not from `
|
|
15
|
+
* from `sent.headers`, not from `context.res`, which can lack the changes of the
|
|
16
16
|
* header hooks.
|
|
17
17
|
*/
|
|
18
|
-
attributes?: (
|
|
18
|
+
attributes?: (response: {
|
|
19
|
+
context: Context<AppServerEnv>;
|
|
20
|
+
sent: SentResponse;
|
|
21
|
+
}) => Readonly<Record<string, unknown>>;
|
|
19
22
|
/**
|
|
20
23
|
* Set `Server-Timing: app;dur=<ms>` on each HTML document: the time until
|
|
21
24
|
* the response headers were ready. The browser's DevTools show it.
|
|
@@ -240,7 +243,10 @@ type ContentSecurityPolicyOptions = {
|
|
|
240
243
|
* `context` is the request, so the policy can change by path. It runs in a
|
|
241
244
|
* header hook, so it can run more than once for one request.
|
|
242
245
|
*/
|
|
243
|
-
policy: (
|
|
246
|
+
policy: (document: {
|
|
247
|
+
scriptSrc: string;
|
|
248
|
+
context: Context<AppServerEnv>;
|
|
249
|
+
}) => string;
|
|
244
250
|
};
|
|
245
251
|
/**
|
|
246
252
|
* Sets the `Content-Security-Policy` from `policy` on each HTML document. The
|
|
@@ -262,7 +268,7 @@ type ContentSecurityPolicyOptions = {
|
|
|
262
268
|
* @example
|
|
263
269
|
* defaultPlugins({
|
|
264
270
|
* contentSecurityPolicy: {
|
|
265
|
-
* policy: (scriptSrc) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
|
|
271
|
+
* policy: ({ scriptSrc }) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
|
|
266
272
|
* },
|
|
267
273
|
* });
|
|
268
274
|
*/
|
|
@@ -376,7 +382,10 @@ type PrerenderedOptions = {
|
|
|
376
382
|
* Extra headers for a served file, by its URL path. They replace the
|
|
377
383
|
* headers captured at build time.
|
|
378
384
|
*/
|
|
379
|
-
headers?: (
|
|
385
|
+
headers?: (file: {
|
|
386
|
+
path: string;
|
|
387
|
+
context: Context<AppServerEnv>;
|
|
388
|
+
}) => Readonly<Record<string, string>> | undefined;
|
|
380
389
|
/**
|
|
381
390
|
* Maps a request path to the URL path of the file to serve, for content
|
|
382
391
|
* negotiation. Return the path unchanged to serve the usual file. The
|
|
@@ -385,7 +394,10 @@ type PrerenderedOptions = {
|
|
|
385
394
|
* answer depends on a request header, add a `Vary` for it in a plugin.
|
|
386
395
|
* With `markdownTwins: true`, a request that `rewrite` changes gets no twin.
|
|
387
396
|
*/
|
|
388
|
-
rewrite?: (
|
|
397
|
+
rewrite?: (request: {
|
|
398
|
+
path: string;
|
|
399
|
+
context: Context<AppServerEnv>;
|
|
400
|
+
}) => string;
|
|
389
401
|
/**
|
|
390
402
|
* Serves the markdown twin of a page, such as `/docs/button.md` for
|
|
391
403
|
* `/docs/button`, to a request that {@link prefersMarkdown} accepts. A
|
|
@@ -417,7 +429,7 @@ type PrerenderedOptions = {
|
|
|
417
429
|
* the rules of a request path.
|
|
418
430
|
*
|
|
419
431
|
* @example
|
|
420
|
-
* prerendered({ markdownTwins: { twinOf: (path) => `/markdown${path}.md` } });
|
|
432
|
+
* prerendered({ markdownTwins: { twinOf: ({ path }) => `/markdown${path}.md` } });
|
|
421
433
|
*/
|
|
422
434
|
markdownTwins?: boolean | {
|
|
423
435
|
twinOf: TwinOf;
|
|
@@ -448,7 +460,10 @@ type PrerenderedOptions = {
|
|
|
448
460
|
cacheControl?: (path: string) => string | undefined;
|
|
449
461
|
};
|
|
450
462
|
/** Maps a request to the URL path of its markdown twin, or `undefined` when it has none. */
|
|
451
|
-
type TwinOf = (
|
|
463
|
+
type TwinOf = (request: {
|
|
464
|
+
path: string;
|
|
465
|
+
context: Context<AppServerEnv>;
|
|
466
|
+
}) => string | undefined;
|
|
452
467
|
/**
|
|
453
468
|
* Serves the client build: prerendered pages at their own URL with a 200,
|
|
454
469
|
* plus every other file in it. It sends no redirect. The `trailingSlash`
|
|
@@ -463,7 +478,7 @@ type TwinOf = (path: string, context: Context<AppServerEnv>) => string | undefin
|
|
|
463
478
|
*
|
|
464
479
|
* @example
|
|
465
480
|
* prerendered({
|
|
466
|
-
* headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
|
|
481
|
+
* headers: ({ path }) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
|
|
467
482
|
* });
|
|
468
483
|
*/
|
|
469
484
|
declare function prerendered(options?: PrerenderedOptions): Plugin;
|
|
@@ -562,6 +577,11 @@ type CreateServerOptions = {
|
|
|
562
577
|
plugins?: readonly Plugin[];
|
|
563
578
|
/** @default jsonSink() */
|
|
564
579
|
logger?: LogSink;
|
|
580
|
+
/**
|
|
581
|
+
* Hooks that change each log line of the server and of `logger()`, such
|
|
582
|
+
* as to redact a field.
|
|
583
|
+
*/
|
|
584
|
+
log?: LogOptions;
|
|
565
585
|
/** @default the host's listeners, such as `[tcp()]` on the node host */
|
|
566
586
|
listeners?: readonly Listener[];
|
|
567
587
|
/**
|
|
@@ -607,6 +627,6 @@ type CreateServerOptions = {
|
|
|
607
627
|
* app.get("/api/status", (c) => c.json({ ok: true }));
|
|
608
628
|
* export default app;
|
|
609
629
|
*/
|
|
610
|
-
declare function createServer({ plugins, logger, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
|
|
630
|
+
declare function createServer({ plugins, logger: sink, log, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
|
|
611
631
|
export { buildId as A, RedirectRule as C, HealthOptions as D, noindex as E, accessLog as M, health as O, securityHeaders as S, NoindexOptions as T, requestId as _, createServer as a, SecurityHeadersOptions as b, assets as c, PUBLIC_ENV_SCRIPT_ID as d, RuntimeEnv as f, RequestIdOptions as g, runtimeEnv as h, RunningServer as i, AccessLogOptions as j, BuildIdOptions as k, prerendered as l, StandardSchemaV1 as m, CreateServerOptions as n, defaultPlugins as o, RuntimeEnvOptions as p, DefaultPluginsOptions as r, PrerenderedOptions as s, AppServer as t, InferOutput as u, ContentSecurityPolicyOptions as v, redirects as w, contentSecurityPolicy as x, SecurityHeaderValues as y };
|
|
612
|
-
//# sourceMappingURL=create-server-
|
|
632
|
+
//# sourceMappingURL=create-server-DKJ0wASH.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as
|
|
1
|
+
import { t as asError } from "./log-CW_g1pWk.js";
|
|
2
2
|
import { i as readBuildManifest, n as DEFAULT_ASSETS_PATH } from "./build-manifest-DBMWe3Lx.js";
|
|
3
|
-
import { p as abortShutdownSignal, r as serverInternals } from "./create-server-
|
|
3
|
+
import { p as abortShutdownSignal, r as serverInternals } from "./create-server-C63luLkn.js";
|
|
4
4
|
import { a as keptFiles } from "./static-files-C2ea8KQ6.js";
|
|
5
5
|
|
|
6
6
|
// src/core/static-pages.ts
|
|
@@ -297,13 +297,21 @@ function createEntry({ app, host, framework, clientDirectory }) {
|
|
|
297
297
|
const runtime = await production();
|
|
298
298
|
const server = await internals.listen(runtime, host.listeners?.());
|
|
299
299
|
host.lifecycle?.onStop(async () => server.shutdown().catch((error) => {
|
|
300
|
-
internals.logger.log(
|
|
300
|
+
internals.logger.log({
|
|
301
|
+
level: "error",
|
|
302
|
+
message: "shutdown failed",
|
|
303
|
+
attributes: { error: asError(error) }
|
|
304
|
+
});
|
|
301
305
|
throw error;
|
|
302
306
|
}));
|
|
303
307
|
},
|
|
304
308
|
fetch: async (request, bindings) => {
|
|
305
309
|
const runtime = await production().catch((error) => {
|
|
306
|
-
internals.logger.log(
|
|
310
|
+
internals.logger.log({
|
|
311
|
+
level: "error",
|
|
312
|
+
message: "setup failed",
|
|
313
|
+
attributes: { error: asError(error) }
|
|
314
|
+
});
|
|
307
315
|
throw error;
|
|
308
316
|
});
|
|
309
317
|
return app.fetch(request, {
|
|
@@ -349,4 +357,4 @@ function isAppServerEntry(value) {
|
|
|
349
357
|
}
|
|
350
358
|
|
|
351
359
|
export { isAppServerEntry as n, createEntry as t };
|
|
352
|
-
//# sourceMappingURL=entry-
|
|
360
|
+
//# sourceMappingURL=entry-BSbsQ_kq.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entry-BSbsQ_kq.js","names":[],"sources":["../src/core/static-pages.ts","../src/core/entry.ts"],"sourcesContent":["/** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */\nexport type CdnPage = {\n\t/** The URL path of the client build's file that the answer comes from, such as `/about/index.html`. */\n\tfile: string;\n\t/** The body that the pipeline sent. It can differ from the file, such as with `runtimeEnv` values. */\n\tbody: Uint8Array;\n\t/**\n\t * The response headers for each case of the presence headers. `present`\n\t * lists the headers that the request has. With no presence headers, there\n\t * is one case.\n\t */\n\tanswers: { present: readonly string[]; headers: Readonly<Record<string, string>> }[];\n\t/**\n\t * The path of the page's markdown twin. A request whose `Accept` names\n\t * `text/markdown` must reach the server, which negotiates the answer.\n\t */\n\ttwin?: string;\n};\n\n/** A prerendered path, with its CDN answer, or with the reason that the server must answer it. */\nexport type StaticPage = { path: string } & ({ cdn: CdnPage } | { reason: string });\n\n/**\n * Sends a request through the pipeline as a client at `remoteAddress`. The\n * pipeline calls `onServedFile` with the URL path of the client build's file\n * that `prerendered()` sends, if it sends one.\n */\nexport type PipelineFetch = (\n\trequest: Request,\n\tbindings: { remoteAddress: string; onServedFile: (path: string) => void },\n) => Promise<Response>;\n\n/** The headers that change with each request, such as the request ID. A CDN answer drops them. */\nconst PER_REQUEST = new Set([\"x-request-id\", \"date\"]);\n\n/** The headers that the CDN sets for each file itself. */\nconst CDN_OWN = new Set([\n\t\"content-length\",\n\t\"etag\",\n\t\"last-modified\",\n\t\"accept-ranges\",\n\t\"transfer-encoding\",\n\t\"connection\",\n\t\"keep-alive\",\n]);\n\n/** A browser's `Accept`. A browser never names `text/markdown`, so it gets the HTML. */\nconst BROWSER_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\";\n\n/**\n * A URL path that a CDN route matches as it is. Why only these characters: a\n * CDN can match a path before or after it decodes it, and these two forms\n * are the same. Why a slash after each segment but the last: the match then\n * takes linear time.\n */\nconst PLAIN_PATH = /^\\/(?:[\\w.~-]+\\/)*[\\w.~-]*$/u;\n\n/** The most presence headers. Why: each one doubles the requests and the CDN routes. */\nconst MAX_PRESENCE_HEADERS = 3;\n\n/** One answer of the pipeline. */\ntype Answer = {\n\tstatus: number;\n\theaders: Headers;\n\tbody: Uint8Array;\n\tfile: string | undefined;\n};\n\n/**\n * The two clients of each check. The first is an anonymous browser. The\n * second differs in each value that a CDN route does not match on: the host,\n * the address, the query, the value of a presence header, and the request\n * headers that a plugin reads most often to choose an answer. Why a cookie\n * and `Authorization`: a plugin that sends a signed-in visitor to another\n * page must keep its pages on the server. Why the geo headers: Vercel adds\n * them, and a plugin can redirect by country.\n */\nconst CLIENTS = [\n\t{\n\t\torigin: \"https://localhost\",\n\t\tquery: \"\",\n\t\taddress: \"203.0.113.1\",\n\t\tpresentValue: \"1\",\n\t\theaders: { Accept: BROWSER_ACCEPT, \"User-Agent\": \"app-server-build\" },\n\t},\n\t{\n\t\torigin: \"https://app-server-check.example\",\n\t\tquery: \"?app-server-check=1\",\n\t\taddress: \"198.51.100.2\",\n\t\tpresentValue: \"2\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\t\"Accept-Language\": \"de-DE\",\n\t\t\tAuthorization: \"Bearer app-server-check\",\n\t\t\tCookie: \"session=app-server-check\",\n\t\t\tReferer: \"https://app-server-check.example/\",\n\t\t\t\"User-Agent\": \"app-server-build-check\",\n\t\t\t\"X-Vercel-IP-City\": \"Berlin\",\n\t\t\t\"X-Vercel-IP-Country\": \"DE\",\n\t\t\t\"X-Vercel-IP-Country-Region\": \"BE\",\n\t\t},\n\t},\n] as const;\n\n/**\n * The answer of the pipeline for `path`. The request has each of `presence`\n * that is in `present`, and no other of `presence`.\n */\nasync function answer(\n\tfetch: PipelineFetch,\n\tpath: string,\n\t{\n\t\tclient,\n\t\tpresence,\n\t\tpresent,\n\t}: {\n\t\tclient: (typeof CLIENTS)[number];\n\t\tpresence: readonly string[];\n\t\tpresent: readonly string[];\n\t},\n): Promise<Answer> {\n\t// Why `Host`: a listener gives it to each request, and a plugin can read it.\n\tconst headers = new Headers({ ...client.headers, Host: new URL(client.origin).host });\n\tfor (const name of presence) {\n\t\tif (present.includes(name)) {\n\t\t\theaders.set(name, client.presentValue);\n\t\t} else {\n\t\t\theaders.delete(name);\n\t\t}\n\t}\n\tconst request = new Request(`${client.origin}${path}${client.query}`, { headers });\n\tlet file: string | undefined;\n\tconst response = await fetch(request, {\n\t\tremoteAddress: client.address,\n\t\tonServedFile: (served) => {\n\t\t\tfile = served;\n\t\t},\n\t});\n\tif (file == null) {\n\t\t// Why cancel: only the answer of a file can go on a CDN, and another body can stream with no end.\n\t\tawait response.body?.cancel();\n\t}\n\treturn {\n\t\tstatus: response.status,\n\t\theaders: response.headers,\n\t\tbody: file == null ? new Uint8Array() : new Uint8Array(await response.arrayBuffer()),\n\t\tfile,\n\t};\n}\n\nfunction sameBytes(first: Uint8Array, second: Uint8Array): boolean {\n\treturn first.length === second.length && first.every((byte, index) => byte === second[index]);\n}\n\n/** The headers of `headers` that a CDN answer keeps, sorted by name. */\nfunction keptHeaders(headers: Headers): [string, string][] {\n\treturn [...headers]\n\t\t.filter(([name]) => !PER_REQUEST.has(name) && !CDN_OWN.has(name))\n\t\t.toSorted(([first], [second]) => (first < second ? -1 : 1));\n}\n\n/** The path of the markdown twin in a `Link` header, if any. */\nfunction twinIn(link: string | null): string | undefined {\n\treturn /<(?<path>[^>]+)>;\\s*rel=\"alternate\";\\s*type=\"text\\/markdown\"/u.exec(link ?? \"\")?.groups\n\t\t?.path;\n}\n\n/** Why a CDN cannot keep `first`, or `undefined` when it can. */\nfunction uncacheable(first: Answer, allowedVary: ReadonlySet<string>): string | undefined {\n\tif (first.status !== 200) {\n\t\treturn `the status is ${first.status}`;\n\t}\n\tif (first.file == null) {\n\t\treturn \"the answer does not come from a prerendered file\";\n\t}\n\tif (!PLAIN_PATH.test(first.file)) {\n\t\treturn \"the file path has a character that a CDN route can match two ways\";\n\t}\n\tif (first.headers.has(\"set-cookie\")) {\n\t\treturn \"the answer sets a cookie\";\n\t}\n\t// Why each `CDN-Cache-Control` field: a CDN obeys it before `Cache-Control` (RFC 9213).\n\tfor (const [name, value] of first.headers) {\n\t\t// Why `i`: cache directives are case-insensitive.\n\t\tconst blocked = /\\b(?:private|no-store|no-cache)\\b/iu.exec(value);\n\t\tif (blocked != null && (name === \"cache-control\" || name.endsWith(\"cdn-cache-control\"))) {\n\t\t\treturn `the ${name} header has ${blocked[0]}`;\n\t\t}\n\t}\n\tif (first.headers.has(\"content-encoding\")) {\n\t\treturn \"the answer has a Content-Encoding\";\n\t}\n\tconst vary = (first.headers.get(\"vary\") ?? \"\")\n\t\t.split(\",\")\n\t\t.map((name) => name.trim().toLowerCase())\n\t\t.find((name) => name !== \"\" && !allowedVary.has(name));\n\treturn vary == null ? undefined : `the answer varies on ${vary}`;\n}\n\n/** Why `second` differs from `first`, or `undefined` when they match. */\nfunction difference(first: Answer, second: Answer): string | undefined {\n\tif (first.status !== second.status || first.file !== second.file) {\n\t\treturn \"the status or the file changes with the request\";\n\t}\n\tconst names = new Set(\n\t\t[...keptHeaders(first.headers), ...keptHeaders(second.headers)].map(([name]) => name),\n\t);\n\tconst changed = [...names].find((name) => first.headers.get(name) !== second.headers.get(name));\n\tif (changed != null) {\n\t\treturn `the ${changed} header changes with the request`;\n\t}\n\treturn sameBytes(first.body, second.body) ? undefined : \"the body changes with the request\";\n}\n\n/** Each subset of `names`, the empty one first. */\nfunction subsets(names: readonly string[]): string[][] {\n\tconst all: string[][] = [[]];\n\tfor (const name of names) {\n\t\tall.push(...all.map((subset) => [...subset, name]));\n\t}\n\treturn all;\n}\n\n/** The CDN answer of one path, or the reason that the server must answer it. */\nasync function staticPage(\n\tfetch: PipelineFetch,\n\tpath: string,\n\tpresence: readonly string[],\n): Promise<StaticPage> {\n\tif (!PLAIN_PATH.test(path)) {\n\t\treturn { path, reason: \"the path has a character that a CDN route can match two ways\" };\n\t}\n\t// Why: the build records a path with no trailing slash, and `trailingSlash: \"always\"` sends it on.\n\tconst probe = await answer(fetch, path, { client: CLIENTS[0], presence, present: [] });\n\tif (probe.status === 308 && probe.headers.get(\"location\") === `${path}/`) {\n\t\treturn staticPage(fetch, `${path}/`, presence);\n\t}\n\tif (presence.length > MAX_PRESENCE_HEADERS) {\n\t\treturn { path, reason: `more than ${MAX_PRESENCE_HEADERS} presence headers` };\n\t}\n\t// Why reuse the probe: it is the first client's answer with no presence header.\n\tconst firstAnswer = async (present: readonly string[]): Promise<Answer> =>\n\t\tpresent.length === 0 ? probe : answer(fetch, path, { client: CLIENTS[0], presence, present });\n\tconst answers: CdnPage[\"answers\"] = [];\n\tlet base: Answer | undefined;\n\tlet twin: string | undefined;\n\tfor (const present of subsets(presence)) {\n\t\tconst [first, second] = [\n\t\t\tawait firstAnswer(present),\n\t\t\tawait answer(fetch, path, { client: CLIENTS[1], presence, present }),\n\t\t];\n\t\tconst caseTwin = twinIn(first.headers.get(\"link\"));\n\t\tconst allowedVary = new Set([\n\t\t\t\"accept-encoding\",\n\t\t\t...presence,\n\t\t\t...(caseTwin == null ? [] : [\"accept\"]),\n\t\t]);\n\t\tconst reason = uncacheable(first, allowedVary) ?? difference(first, second);\n\t\tif (reason != null) {\n\t\t\treturn { path, reason };\n\t\t}\n\t\tif (base != null && (base.file !== first.file || !sameBytes(base.body, first.body))) {\n\t\t\treturn { path, reason: \"the body changes with a presence header\" };\n\t\t}\n\t\t// Why: the CDN routes send each markdown request of a page to the server, or none.\n\t\tif (base != null && caseTwin !== twin) {\n\t\t\treturn { path, reason: \"the markdown twin changes with a presence header\" };\n\t\t}\n\t\tbase ??= first;\n\t\ttwin = caseTwin;\n\t\tanswers.push({ present, headers: Object.fromEntries(keptHeaders(first.headers)) });\n\t}\n\tif (base?.file == null) {\n\t\treturn { path, reason: \"the answer does not come from a prerendered file\" };\n\t}\n\tif (twin != null && !PLAIN_PATH.test(twin)) {\n\t\treturn { path, reason: \"the twin path has a character that a CDN route can match two ways\" };\n\t}\n\treturn {\n\t\tpath,\n\t\tcdn: { file: base.file, body: base.body, answers, ...(twin == null ? {} : { twin }) },\n\t};\n}\n\n/**\n * Sends each prerendered path through the pipeline, and gives the paths that\n * a CDN can serve with no server. A path qualifies when its answer:\n *\n * - is a 200 from a prerendered file, with no cookie and no `private`,\n * `no-store`, or `no-cache`\n * - is the same, except for the request ID, for a second client with another\n * host, client address, query, and value of each presence header, and with\n * a cookie, `Authorization`, `Accept-Language`, and geo headers. Why: a CDN\n * route matches only the path, a markdown `Accept`, and the presence of\n * each presence header.\n * - varies only on `Accept-Encoding`, on `Accept` for a markdown twin, and on\n * the presence headers. Each case of the presence headers gets its own\n * headers, and all cases must send the same body.\n *\n * An auth check that refuses an anonymous request keeps its pages on the\n * server. Why: the first client sends no cookie and no `Authorization`.\n *\n * @yields Each path with its CDN answer, or with the reason that the server must answer it, in the order of `paths`.\n * @example\n * for await (const page of staticPages(fetch, [\"/\", \"/about\"], { presence: [\"x-ngrok-edge\"] })) {\n * \tconsole.log(page.path, \"cdn\" in page ? \"CDN\" : page.reason);\n * }\n */\nexport async function* staticPages(\n\tfetch: PipelineFetch,\n\tpaths: readonly string[],\n\t{ presence }: { presence: readonly string[] },\n): AsyncGenerator<StaticPage> {\n\tfor (const path of paths) {\n\t\tyield await staticPage(fetch, path, presence);\n\t}\n}\n","import type { MiddlewareHandler } from \"hono\";\nimport { DEFAULT_ASSETS_PATH, readBuildManifest } from \"./build-manifest.js\";\nimport { serverInternals } from \"./create-server.js\";\nimport type { AppServer } from \"./create-server.js\";\nimport { asError } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport { staticPages } from \"./static-pages.js\";\nimport type { StaticPage } from \"./static-pages.js\";\nimport { keptFiles } from \"./static-files.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHostRuntime,\n\tListenerBindings,\n\tMode,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 2;\n\n/**\n * What a server build exports as `appServer`. The CLI calls it, so the copy\n * of this package in the build runs the server, and the CLI's copy runs\n * nothing.\n */\nexport type AppServerEntry = {\n\t/** The CLI refuses an entry with another version. */\n\tprotocol: typeof ENTRY_PROTOCOL;\n\t/** The app. Two entries with the same app share its plugins. */\n\tapp: AppServer;\n\t/**\n\t * Production: runs each plugin's `setup` and listens. When the host's\n\t * lifecycle stops, such as on `SIGTERM`, it shuts down.\n\t */\n\tstart: () => Promise<void>;\n\t/**\n\t * Production, for a serverless host: answers one request, and does not\n\t * listen. The first call runs each plugin's `setup`.\n\t */\n\tfetch: FetchHandler;\n\t/** Development: answers one request with the dev server inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tdevServer: MiddlewareHandler<AppServerEnv>,\n\t) => Promise<Response>;\n\t/**\n\t * Production, for a build step: each prerendered path, with the answer\n\t * that a content delivery network (CDN) can send with no server, or the\n\t * reason that the server must answer it. The first call runs each\n\t * plugin's `setup`. See `staticPages`.\n\t */\n\tstaticPages: () => AsyncGenerator<StaticPage>;\n\t/** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Aborts `shutdownSignal()` of this copy of the package. */\n\tabortShutdownSignal: () => void;\n};\n\n/** Options for {@link createEntry}. */\nexport type CreateEntryOptions = {\n\t/** The app from `createServer`. */\n\tapp: AppServer;\n\t/** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */\n\thost: HostRuntime;\n\t/** Makes the run side of the framework adapter for a mode. */\n\tframework: (mode: Mode) => FrameworkRuntime;\n\t/**\n\t * The client build, as a file path or a `file:` URL. The entry that the\n\t * Vite plugin generates sets it.\n\t * @default the framework's `clientDirectory`\n\t */\n\tclientDirectory?: string;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer`, the\n * host, and the framework adapter for each mode. The `appServer` Vite plugin\n * generates this export. Call this for a build without the plugin.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport function createEntry({\n\tapp,\n\thost,\n\tframework,\n\tclientDirectory,\n}: CreateEntryOptions): AppServerEntry {\n\tconst internals = serverInternals(app);\n\tif (internals == null) {\n\t\tthrow new Error(\n\t\t\t\"The app is not from `createServer()` of the copy of @ngrok/app-server in this build.\",\n\t\t);\n\t}\n\tinternals.setRequestStore(host.storage);\n\tconst setupInfo = async (runtime: FrameworkRuntime) => {\n\t\tconst directory = clientDirectory ?? runtime.clientDirectory;\n\t\tif (directory == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`,\n\t\t\t);\n\t\t}\n\t\tconst files = host.files(directory);\n\t\treturn {\n\t\t\tfiles,\n\t\t\tisDataRequest: runtime.isDataRequest ?? (() => false),\n\t\t\tcontentTypes: runtime.contentTypes ?? {},\n\t\t\tgzip: host.gzip,\n\t\t\tbrotli: host.brotli,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\tlet prerenderedPaths: readonly string[] = [];\n\t/** Runs each plugin's `setup` for production, and gives the framework's run side. */\n\tconst prepareProduction = async (): Promise<FrameworkRuntime> => {\n\t\tconst runtime = framework(\"production\");\n\t\tconst shared = await setupInfo(runtime);\n\t\tconst snapshot = await shared.files.snapshot?.();\n\t\t// Why only with a snapshot: it promises that the client build does not change while the server runs.\n\t\tconst files = snapshot == null ? shared.files : keptFiles(snapshot);\n\t\tconst manifest = await readBuildManifest(files);\n\t\tconst info: SetupInfo = {\n\t\t\t...shared,\n\t\t\tfiles,\n\t\t\tmode: \"production\",\n\t\t\tprerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,\n\t\t\tcapturedHeaders: new Map(Object.entries(manifest.headers)),\n\t\t\tscriptHashes: new Map(Object.entries(manifest.scriptHashes)),\n\t\t\tbuildId: manifest.buildId,\n\t\t\tassetsPath: manifest.assetsPath ?? DEFAULT_ASSETS_PATH,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\t({ prerenderedPaths } = info);\n\t\treturn runtime;\n\t};\n\tlet preparing: Promise<FrameworkRuntime> | undefined;\n\t/**\n\t * The production run side, set up once. Why forget a failure: a serverless\n\t * instance stays up, so the next request runs each `setup` again.\n\t */\n\tconst production = async (): Promise<FrameworkRuntime> => {\n\t\tpreparing ??= prepareProduction().catch((error: unknown) => {\n\t\t\tpreparing = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\treturn preparing;\n\t};\n\tlet development: FrameworkRuntime | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst runtime = await production();\n\t\t\tconst server = await internals.listen(runtime, host.listeners?.());\n\t\t\thost.lifecycle?.onStop(async () =>\n\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\tinternals.logger.log({\n\t\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\t\tmessage: \"shutdown failed\",\n\t\t\t\t\t\tattributes: { error: asError(error) },\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tfetch: async (request, bindings) => {\n\t\t\t// Why log it: the host sends a 500 with no log, and no app handler runs before setup ends.\n\t\t\tconst runtime = await production().catch((error: unknown) => {\n\t\t\t\tinternals.logger.log({\n\t\t\t\t\tlevel: \"error\",\n\t\t\t\t\tmessage: \"setup failed\",\n\t\t\t\t\tattributes: { error: asError(error) },\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: runtime });\n\t\t},\n\t\tfetchDev: async (request, bindings, devServer) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\t...(await setupInfo(development)),\n\t\t\t\tmode: \"development\",\n\t\t\t\tdevServer,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tcapturedHeaders: new Map(),\n\t\t\t\tscriptHashes: new Map(),\n\t\t\t\t// Why none: development has no client build, and Vite's HMR updates an open tab after each edit.\n\t\t\t\tbuildId: undefined,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tasync *staticPages() {\n\t\t\tconst runtime = await production();\n\t\t\tyield* staticPages(\n\t\t\t\tasync (request, bindings) => app.fetch(request, { ...bindings, framework: runtime }),\n\t\t\t\tprerenderedPaths,\n\t\t\t\t{ presence: internals.presenceHeaders },\n\t\t\t);\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\n/**\n * Whether a value is an entry of this protocol version.\n *\n * @example\n * isAppServerEntry((await import(\"./build/server/app-server.js\")).appServer); // => true\n */\nexport function isAppServerEntry(value: unknown): value is AppServerEntry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"protocol\" in value &&\n\t\tvalue.protocol === ENTRY_PROTOCOL\n\t);\n}\n"],"mappings":";;;;;;;AAiCA,MAAM,8BAAc,IAAI,IAAI,CAAC,gBAAgB,MAAM,CAAC;;AAGpD,MAAM,0BAAU,IAAI,IAAI;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,aAAa;;AAGnB,MAAM,uBAAuB;;;;;;;;;;AAmB7B,MAAM,UAAU,CACf;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EAAE,QAAQ;EAAgB,cAAc;CAAmB;AACrE,GACA;CACC,QAAQ;CACR,OAAO;CACP,SAAS;CACT,cAAc;CACd,SAAS;EACR,QAAQ;EACR,mBAAmB;EACnB,eAAe;EACf,QAAQ;EACR,SAAS;EACT,cAAc;EACd,oBAAoB;EACpB,uBAAuB;EACvB,8BAA8B;CAC/B;AACD,CACD;;;;;AAMA,eAAe,OACd,OACA,MACA,EACC,QACA,UACA,WAMiB;CAElB,MAAM,UAAU,IAAI,QAAQ;EAAE,GAAG,OAAO;EAAS,MAAM,IAAI,IAAI,OAAO,MAAM,CAA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;GACD,OAAO,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAY,CAAC;EAClE;EACA,OAAO,cAAc;GACpB,MAAM,UAAU,MAAM,WAAW;GACjC,OAAO,YACN,OAAO,SAAS,aAAa,IAAI,MAAM,SAAS;IAAE,GAAG;IAAU,WAAW;GAAQ,CAAC,GACnF,kBACA,EAAE,UAAU,UAAU,gBAAgB,CACvC;EACD;EACA,aAAa,UAAU;EACvB;CACD;AACD;;;;;;;AAQA,SAAgB,iBAAiB,OAAyC;CACzE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings,
|
|
2
|
-
import { t as AppServer } from "./create-server-
|
|
1
|
+
import { _ as Mode, a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, r as FetchHandler, t as AppServerEnv } from "./types-C_I3i62n.js";
|
|
2
|
+
import { t as AppServer } from "./create-server-DKJ0wASH.js";
|
|
3
3
|
import { MiddlewareHandler } from "hono";
|
|
4
4
|
/** What a content delivery network (CDN) sends for a prerendered path that it can serve with no server. */
|
|
5
5
|
type CdnPage = {
|
|
@@ -91,4 +91,4 @@ type CreateEntryOptions = {
|
|
|
91
91
|
*/
|
|
92
92
|
declare function createEntry({ app, host, framework, clientDirectory }: CreateEntryOptions): AppServerEntry;
|
|
93
93
|
export { CreateEntryOptions as n, createEntry as r, AppServerEntry as t };
|
|
94
|
-
//# sourceMappingURL=entry-
|
|
94
|
+
//# sourceMappingURL=entry-C9bBcYeP.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as
|
|
2
|
-
import { A as buildId, C as RedirectRule, D as HealthOptions, E as noindex, M as accessLog, O as health, S as securityHeaders, T as NoindexOptions, _ as requestId, a as createServer, b as SecurityHeadersOptions, c as assets, d as PUBLIC_ENV_SCRIPT_ID, f as RuntimeEnv, g as RequestIdOptions, h as runtimeEnv, i as RunningServer, j as AccessLogOptions, k as BuildIdOptions, l as prerendered, m as StandardSchemaV1, n as CreateServerOptions, o as defaultPlugins, p as RuntimeEnvOptions, r as DefaultPluginsOptions, s as PrerenderedOptions, t as AppServer, u as InferOutput, v as ContentSecurityPolicyOptions, w as redirects, x as contentSecurityPolicy, y as SecurityHeaderValues } from "./create-server-
|
|
3
|
-
import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-
|
|
4
|
-
import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-
|
|
1
|
+
import { C as SentResponse, D as StaticFiles, E as StartedListener, O as ResponseEdge, S as ResponseHeaders, T as SetupInfo, _ as Mode, a as FrameworkRuntime, b as RequestLogger, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as LogSink, h as LogOptions, i as FileInfo, l as Lifecycle, m as LogLine, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as Plugin, w as ServerBindings, x as RequestStore, y as RequestContext } from "./types-C_I3i62n.js";
|
|
2
|
+
import { A as buildId, C as RedirectRule, D as HealthOptions, E as noindex, M as accessLog, O as health, S as securityHeaders, T as NoindexOptions, _ as requestId, a as createServer, b as SecurityHeadersOptions, c as assets, d as PUBLIC_ENV_SCRIPT_ID, f as RuntimeEnv, g as RequestIdOptions, h as runtimeEnv, i as RunningServer, j as AccessLogOptions, k as BuildIdOptions, l as prerendered, m as StandardSchemaV1, n as CreateServerOptions, o as defaultPlugins, p as RuntimeEnvOptions, r as DefaultPluginsOptions, s as PrerenderedOptions, t as AppServer, u as InferOutput, v as ContentSecurityPolicyOptions, w as redirects, x as contentSecurityPolicy, y as SecurityHeaderValues } from "./create-server-DKJ0wASH.js";
|
|
3
|
+
import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-D_52DJaQ.js";
|
|
4
|
+
import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-C9bBcYeP.js";
|
|
5
5
|
import { Context, Next } from "hono";
|
|
6
6
|
/** One server-sent event. */
|
|
7
7
|
type ServerSentEvent = {
|
|
@@ -168,6 +168,19 @@ export declare function prefersMarkdown(request: Request): boolean;
|
|
|
168
168
|
* }
|
|
169
169
|
*/
|
|
170
170
|
export declare function requestContext(): RequestContext | undefined;
|
|
171
|
+
/**
|
|
172
|
+
* The logger of the request that runs. Outside a request, such as at module
|
|
173
|
+
* load or in a prerender pass, it gives a logger that writes to the sink and
|
|
174
|
+
* the hooks of the last `createServer` call, else to `jsonSink()`.
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* import { logger } from "@ngrok/app-server";
|
|
178
|
+
*
|
|
179
|
+
* export async function loader() {
|
|
180
|
+
* logger().info("loading the dashboard", { "usr.id": userId });
|
|
181
|
+
* }
|
|
182
|
+
*/
|
|
183
|
+
export declare function logger(): RequestLogger;
|
|
171
184
|
/**
|
|
172
185
|
* A signal that aborts when the server starts to shut down. Read it for each
|
|
173
186
|
* request: each start of a server makes a new one. A handler that
|
|
@@ -179,5 +192,5 @@ export declare function requestContext(): RequestContext | undefined;
|
|
|
179
192
|
* shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
|
|
180
193
|
*/
|
|
181
194
|
export declare function shutdownSignal(): AbortSignal;
|
|
182
|
-
export { type AccessLogOptions, type AppServer, type AppServerEntry, type AppServerEnv, type BodyLimitOptions, type BuildIdOptions, type ByteRange, type ContentSecurityPolicyOptions, type CreateEntryOptions, type CreateServerOptions, type DefaultPluginsOptions, type EventStreamOptions, type EventStreamSink, type FetchHandler, type FileInfo, type FrameworkRuntime, type FrameworkRuntimeFactory, type HeaderHook, type HealthOptions, type HostRuntime, type InferOutput, type Lifecycle, type Listener, type ListenerBindings, type ListenerStartOptions, type LogLevel, type LogSink, type Mode, type NoindexOptions, PUBLIC_ENV_SCRIPT_ID, type Plugin, type PrerenderedOptions, type RedirectRule, type RequestContext, type RequestIdOptions, type RequestLogger, type RequestStore, ResponseEdge, type ResponseHeaders, type RunningServer, type RuntimeEnv, type RuntimeEnvOptions, type SecurityHeaderValues, type SecurityHeadersOptions, type SentResponse, type ServerBindings, type ServerSentEvent, type SetupInfo, type StandardSchemaV1, type StartedListener, type StaticFiles, type TrailingSlash, type TrailingSlashOptions, accessLog, assets, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, health, noindex, prerendered, redirects, requestId, runtimeEnv, securityHeaders, trailingSlash };
|
|
195
|
+
export { type AccessLogOptions, type AppServer, type AppServerEntry, type AppServerEnv, type BodyLimitOptions, type BuildIdOptions, type ByteRange, type ContentSecurityPolicyOptions, type CreateEntryOptions, type CreateServerOptions, type DefaultPluginsOptions, type EventStreamOptions, type EventStreamSink, type FetchHandler, type FileInfo, type FrameworkRuntime, type FrameworkRuntimeFactory, type HeaderHook, type HealthOptions, type HostRuntime, type InferOutput, type Lifecycle, type Listener, type ListenerBindings, type ListenerStartOptions, type LogLevel, type LogLine, type LogOptions, type LogSink, type Mode, type NoindexOptions, PUBLIC_ENV_SCRIPT_ID, type Plugin, type PrerenderedOptions, type RedirectRule, type RequestContext, type RequestIdOptions, type RequestLogger, type RequestStore, ResponseEdge, type ResponseHeaders, type RunningServer, type RuntimeEnv, type RuntimeEnvOptions, type SecurityHeaderValues, type SecurityHeadersOptions, type SentResponse, type ServerBindings, type ServerSentEvent, type SetupInfo, type StandardSchemaV1, type StartedListener, type StaticFiles, type TrailingSlash, type TrailingSlashOptions, accessLog, assets, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, health, noindex, prerendered, redirects, requestId, runtimeEnv, securityHeaders, trailingSlash };
|
|
183
196
|
//# sourceMappingURL=index.d.ts.map
|