@ngrok/app-server 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +223 -64
  2. package/dist/brotli-only-BVAagKt3.js +63 -0
  3. package/dist/build-id-CwMbED1n.js +245 -0
  4. package/dist/{build-manifest-DBMWe3Lx.js → build-manifest-CoBztw_6.js} +13 -4
  5. package/dist/bun-BCz6K_Xv.js +1 -2
  6. package/dist/check-count-DQl5z_qe.js +17 -0
  7. package/dist/cli.js +9 -6
  8. package/dist/client-browser.d.ts +2 -3
  9. package/dist/client-browser.js +1 -1
  10. package/dist/client.d.ts +5 -4
  11. package/dist/client.js +9 -6
  12. package/dist/{compress-Cp5NfXCC.js → compress-2w3jqBh7.js} +2 -3
  13. package/dist/{compression-CT2mWlKM.js → compression-uJxu0JVb.js} +32 -5
  14. package/dist/content-types-Le-5BNEC.js +10 -0
  15. package/dist/{create-server-Bp1yILQk.js → create-server-DVTZun6D.js} +617 -306
  16. package/dist/create-server-PA0qniaK.js +3 -0
  17. package/dist/{create-server-X2GR-U6t.d.ts → create-server-UVsHFQyK.d.ts} +116 -54
  18. package/dist/deno-aqhikNMG.js +1 -2
  19. package/dist/{entry-BoxCqc6w.js → entry-CMhX3yf8.js} +85 -65
  20. package/dist/entry-CvZ4U0ia.js +3 -0
  21. package/dist/{entry-DZTCaL3d.d.ts → entry-DBq_3s8X.d.ts} +10 -36
  22. package/dist/entry-protocol-C30UPXzy.js +14 -0
  23. package/dist/entry-source-DSE5NAJu.js +70 -0
  24. package/dist/entry-source-SHoE-DUP.js +3 -0
  25. package/dist/exit-Hh-O3gp4.js +83 -0
  26. package/dist/{header-hook-Vzw9J9BY.js → header-hook-JfqaTt34.js} +69 -23
  27. package/dist/{index-B8LsM6Mh.d.ts → index-gzGs53Ue.d.ts} +43 -38
  28. package/dist/index.d.ts +88 -44
  29. package/dist/index.js +216 -84
  30. package/dist/listen-options-7TaXjyrk.js +1 -2
  31. package/dist/{load-entry-CCPWbsrj.js → load-entry-Bgq1_HDV.js} +11 -12
  32. package/dist/{log-DQAS5gGT.js → log-DfC9D5_T.js} +70 -49
  33. package/dist/{node-D6m6e6EI.js → node-DQPrMFyc.js} +20 -8
  34. package/dist/node-DyKDFII0.js +263 -0
  35. package/dist/node-vite.d.ts +2 -3
  36. package/dist/node-vite.js +1 -1
  37. package/dist/node.d.ts +41 -64
  38. package/dist/node.js +3 -3
  39. package/dist/react-router-vite.d.ts +2 -3
  40. package/dist/react-router-vite.js +1 -1
  41. package/dist/react-router.d.ts +6 -17
  42. package/dist/react-router.js +9 -14
  43. package/dist/request-context-Cslbrscf.js +163 -0
  44. package/dist/{response-edge-CU8ZvL_F.js → response-edge-Ow5Pi5qF.js} +13 -10
  45. package/dist/{response-writer-D7KHfr8n.js → response-writer-Dd4Ey99f.js} +57 -21
  46. package/dist/{script-hashes-CU7P9oZU.js → script-hashes-BdvJ0QI_.js} +2 -3
  47. package/dist/serve-AatMo9k6.js +26 -0
  48. package/dist/{stale-build-navigation-rg5xxmTr.js → stale-build-navigation-Qf_Lem39.js} +4 -5
  49. package/dist/{stale-build-navigation-ypV7Ow4o.d.ts → stale-build-navigation-WjhD8zHi.d.ts} +4 -4
  50. package/dist/start-DYFyGKsM.js +470 -0
  51. package/dist/static-files-BdTPam5b.js +438 -0
  52. package/dist/static-pages-6IBHdYQc.d.ts +30 -0
  53. package/dist/tanstack-start-vite.d.ts +2 -3
  54. package/dist/tanstack-start-vite.js +1 -1
  55. package/dist/tanstack-start.d.ts +3 -4
  56. package/dist/tanstack-start.js +2 -3
  57. package/dist/tcp-3v4pmnYU.js +58 -0
  58. package/dist/testing.d.ts +8 -6
  59. package/dist/testing.js +19 -17
  60. package/dist/{trailing-slash-D2QWKWEu.d.ts → trailing-slash-C-yBKCib.d.ts} +2 -3
  61. package/dist/{types-MgFtkNQW.d.ts → types-KsKRDwAv.d.ts} +97 -46
  62. package/dist/vercel-pages.d.ts +3 -16
  63. package/dist/vercel-pages.js +1 -2
  64. package/dist/vercel-vite.d.ts +4 -5
  65. package/dist/vercel-vite.js +48 -44
  66. package/dist/vercel.d.ts +13 -10
  67. package/dist/vercel.js +48 -35
  68. package/dist/{vite-D4hfj3ph.js → vite-Brb8YR9I.js} +2 -7
  69. package/dist/{vite-B-GfswoH.js → vite-CHppJWp_.js} +5 -7
  70. package/dist/{vite-DyrhyKEr.js → vite-DjlHdyTM.js} +2 -7
  71. package/dist/vite.d.ts +2 -2
  72. package/dist/vite.js +885 -2
  73. package/package.json +13 -12
  74. package/dist/brotli-only-DrA29Ecw.js +0 -97
  75. package/dist/brotli-only-DrA29Ecw.js.map +0 -1
  76. package/dist/build-id-B0448vZH.js +0 -151
  77. package/dist/build-id-B0448vZH.js.map +0 -1
  78. package/dist/build-manifest-DBMWe3Lx.js.map +0 -1
  79. package/dist/bun-BCz6K_Xv.js.map +0 -1
  80. package/dist/cli.js.map +0 -1
  81. package/dist/client.js.map +0 -1
  82. package/dist/compress-Cp5NfXCC.js.map +0 -1
  83. package/dist/compression-CT2mWlKM.js.map +0 -1
  84. package/dist/create-server-Bp1yILQk.js.map +0 -1
  85. package/dist/deno-aqhikNMG.js.map +0 -1
  86. package/dist/entry-BoxCqc6w.js.map +0 -1
  87. package/dist/header-hook-Vzw9J9BY.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/listen-options-7TaXjyrk.js.map +0 -1
  90. package/dist/load-entry-CCPWbsrj.js.map +0 -1
  91. package/dist/log-DQAS5gGT.js.map +0 -1
  92. package/dist/node-CVVdk2N6.js +0 -334
  93. package/dist/node-CVVdk2N6.js.map +0 -1
  94. package/dist/node-D6m6e6EI.js.map +0 -1
  95. package/dist/react-router.js.map +0 -1
  96. package/dist/request-context-Bxdbk5P1.js +0 -80
  97. package/dist/request-context-Bxdbk5P1.js.map +0 -1
  98. package/dist/response-edge-CU8ZvL_F.js.map +0 -1
  99. package/dist/response-writer-D7KHfr8n.js.map +0 -1
  100. package/dist/script-hashes-CU7P9oZU.js.map +0 -1
  101. package/dist/serve-W4WacdOw.js +0 -29
  102. package/dist/serve-W4WacdOw.js.map +0 -1
  103. package/dist/stale-build-navigation-rg5xxmTr.js.map +0 -1
  104. package/dist/start-j0VlxeiI.js +0 -324
  105. package/dist/start-j0VlxeiI.js.map +0 -1
  106. package/dist/static-files-C2ea8KQ6.js +0 -310
  107. package/dist/static-files-C2ea8KQ6.js.map +0 -1
  108. package/dist/tanstack-start.js.map +0 -1
  109. package/dist/tcp-BgDXbjOG.js +0 -42
  110. package/dist/tcp-BgDXbjOG.js.map +0 -1
  111. package/dist/testing.js.map +0 -1
  112. package/dist/vercel-pages.js.map +0 -1
  113. package/dist/vercel-vite.js.map +0 -1
  114. package/dist/vercel.js.map +0 -1
  115. package/dist/vite-B-GfswoH.js.map +0 -1
  116. package/dist/vite-D4hfj3ph.js.map +0 -1
  117. package/dist/vite-DPiSKHDn.js +0 -870
  118. package/dist/vite-DPiSKHDn.js.map +0 -1
  119. package/dist/vite-DyrhyKEr.js.map +0 -1
@@ -1,13 +1,15 @@
1
- import { a as requestLogger, i as jsonSink, r as hookSink, t as asError } from "./log-DQAS5gGT.js";
2
- import { a as setProcessSink, o as withRequestContext } from "./request-context-Bxdbk5P1.js";
3
- import { a as replaceResponse, o as withHeaderHook, r as hookedHeaders, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
4
- import { c as presenceHeaders, l as presenceHeadersOf, o as checkOptionPlugins, r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
5
- import { n as finishResponse, r as onResponseSent } from "./response-edge-CU8ZvL_F.js";
6
- import { r as manifestKey } from "./build-manifest-DBMWe3Lx.js";
7
- import { a as isCompressible, i as forbidsTransform, n as MIN_COMPRESS_BYTES, o as preferredEncoding, s as readIfQueued } from "./compression-CT2mWlKM.js";
8
- import { i as isFilePath$1, n as findStaticFile, o as staticResponse, s as withVary, t as contentType } from "./static-files-C2ea8KQ6.js";
1
+ import { a as requestLogger, c as textSink, i as jsonSink, r as hookSink, t as asError } from "./log-DfC9D5_T.js";
2
+ import { i as hookedView, o as replaceResponse, r as headerList, s as withBuiltInHeaderHook, t as bodyHooks } from "./header-hook-JfqaTt34.js";
3
+ import { c as checkOptionPlugins, d as perRequestHeadersOf, f as presenceHeaders, l as optionPlugin, o as checkHeaderName, p as presenceHeadersOf, r as buildId, s as checkHeaderValue, u as perRequestHeaders } from "./build-id-CwMbED1n.js";
4
+ import { n as finishResponse, r as onResponseSent } from "./response-edge-Ow5Pi5qF.js";
5
+ import { a as manifestKey, r as IMMUTABLE } from "./build-manifest-CoBztw_6.js";
6
+ import { c as withVary, i as isFilePath$1, n as findStaticFile, s as staticResponse, t as contentType } from "./static-files-BdTPam5b.js";
7
+ import { a as forbidsTransform, c as readIfQueued, n as MIN_COMPRESS_BYTES, o as isCompressible, s as preferredEncoding } from "./compression-uJxu0JVb.js";
8
+ import { n as checkCount, t as MAX_TIMER_MS } from "./check-count-DQl5z_qe.js";
9
+ import { c as withRequestContext, i as releaseContext, s as setProcessSink, t as currentShutdown } from "./request-context-Cslbrscf.js";
9
10
  import { Hono } from "hono";
10
11
  import { getPath } from "hono/utils/url";
12
+ import { parseAccept } from "hono/utils/accept";
11
13
  import { matchedRoutes } from "hono/route";
12
14
  import { HTTPException } from "hono/http-exception";
13
15
 
@@ -17,49 +19,21 @@ const QVALUE = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;
17
19
  /** The charset of each answer that a caller of {@link prefersMarkdown} sends. */
18
20
  const CHARSET = "utf-8";
19
21
  /**
20
- * The parts of `value` between each `separator`. Why a scan, not `split`: a
21
- * quoted parameter value can hold a `,` or a `;`.
22
- */
23
- function splitOutsideQuotes(value, separator) {
24
- const parts = [];
25
- let part = "";
26
- let quoted = false;
27
- let escaped = false;
28
- for (const character of value) if (!quoted && character === separator) {
29
- parts.push(part);
30
- part = "";
31
- } else {
32
- if (escaped) escaped = false;
33
- else if (quoted && character === "\\") escaped = true;
34
- else if (character === "\"") quoted = !quoted;
35
- part += character;
36
- }
37
- parts.push(part);
38
- return parts;
39
- }
40
- /** The parameters of a media range, by lowercase name, with quotes removed. */
41
- function parameterMap(parameters) {
42
- return new Map(parameters.map((parameter) => {
43
- const index = parameter.indexOf("=");
44
- const name = (index === -1 ? parameter : parameter.slice(0, index)).trim().toLowerCase();
45
- const value = index === -1 ? "" : parameter.slice(index + 1).trim();
46
- return [name, /^".*"$/su.test(value) ? value.slice(1, -1).replaceAll(/\\(?<character>.)/gsu, "$<character>") : value];
47
- }));
48
- }
49
- /**
50
22
  * The media ranges of an `Accept` header. A missing `q` counts as 1, the RFC
51
23
  * 9110 default. Why a malformed `q` also counts as 1: the client still named
52
- * the media type.
24
+ * the media type. Hono drops a parameter with no value or with text after its
25
+ * closing quote, so such a `charset` counts as no charset.
53
26
  */
54
27
  function mediaRanges(accept) {
55
- return splitOutsideQuotes(accept, ",").map((entry) => {
56
- const [type = "", ...parameters] = splitOutsideQuotes(entry, ";");
57
- const parameterValues = parameterMap(parameters);
58
- const quality = parameterValues.get("q") ?? "1";
28
+ return parseAccept(accept).map(({ type, params }) => {
29
+ let quality = "1";
30
+ let charset;
31
+ for (const name in params) if (name.toLowerCase() === "q") quality = params[name] ?? quality;
32
+ else if (name.toLowerCase() === "charset") charset = params[name]?.toLowerCase();
59
33
  return {
60
- type: type.trim().toLowerCase(),
34
+ type: type.toLowerCase(),
61
35
  quality: QVALUE.test(quality) ? Number(quality) : 1,
62
- charset: parameterValues.get("charset")?.toLowerCase()
36
+ charset
63
37
  };
64
38
  });
65
39
  }
@@ -93,7 +67,8 @@ function qualityOf(ranges, type) {
93
67
  * the client named it.
94
68
  * - Both answers are UTF-8. A range with `charset=utf-8` is more specific
95
69
  * than a range with no charset, and a range with another charset does not
96
- * match. Other parameters, such as `variant`, do not change the match.
70
+ * match. A `charset` with no value counts as no charset. Other parameters,
71
+ * such as `variant`, do not change the match.
97
72
  * - Media types and parameter names are not case-sensitive. A quoted
98
73
  * parameter value can hold a `,` or a `;`.
99
74
  *
@@ -163,6 +138,17 @@ function canonicalPath(path, mode) {
163
138
  return path;
164
139
  }
165
140
  /**
141
+ * Whether `path`, the path that Hono decoded, proves with no URL parse that
142
+ * the URL path has the form of `mode`. Hono keeps `%2F`, so `path` has the
143
+ * slashes of the request URL. Why `false` for a last segment that ends with
144
+ * `\` or `.`: Deno gives the URL as the client sent it, and a URL parse makes
145
+ * a `/` from a `\` and from a dot segment, such as `/a/..`.
146
+ */
147
+ function hasModeForm(path, mode) {
148
+ const last = trimTrailingSlashes(path).at(-1);
149
+ return last !== "\\" && last !== "." && canonicalPath(path, mode) === path;
150
+ }
151
+ /**
166
152
  * Whether one of the app's own Hono routes matches the request. Why the
167
153
  * path: the plugins and the framework match at `/*`, and Hono matches a
168
154
  * route path strictly, so a redirect would move the request off its route.
@@ -195,28 +181,33 @@ async function isStaticFile(files, path) {
195
181
  * createServer({ plugins: defaultPlugins({ trailingSlash: "always" }) });
196
182
  */
197
183
  function trailingSlash({ mode }) {
198
- let stage;
199
- return {
184
+ if (mode === "preserve") return optionPlugin("trailingSlash", { name: "trailing-slash" });
185
+ /** Answers a request whose path does not have the form of `mode`. `setup` makes it. */
186
+ let redirect;
187
+ return optionPlugin("trailingSlash", {
200
188
  name: "trailing-slash",
201
- setup: (info) => {
202
- if (mode === "preserve") return;
203
- stage = async (context, next) => {
204
- const { method } = context.req;
205
- if (method !== "GET" && method !== "HEAD" || info.isDataRequest(context.req.path) || hasAppRoute(context)) return next();
189
+ setup: ({ isDataRequest, files }) => {
190
+ redirect = async (context, next) => {
191
+ const { path } = context.req;
192
+ if (isDataRequest(path) || hasAppRoute(context)) return next();
206
193
  const url = new URL(context.req.url);
207
- const path = canonicalPath(url.pathname, mode);
208
- const location = `${path}${url.search}`;
209
- if (path === url.pathname || !isSafeLocalPath(location)) return next();
210
- if (mode === "always" && (isFilePath(context.req.path) || await isStaticFile(info.files, context.req.path))) return next();
194
+ const canonical = canonicalPath(url.pathname, mode);
195
+ const location = `${canonical}${url.search}`;
196
+ if (canonical === url.pathname || !isSafeLocalPath(location)) return next();
197
+ if (mode === "always" && (isFilePath(path) || await isStaticFile(files, path))) return next();
211
198
  return context.redirect(location, 308);
212
199
  };
213
200
  },
214
- middleware: async (context, next) => stage == null ? next() : stage(context, next)
215
- };
201
+ middleware: (context, next) => {
202
+ const { method, path } = context.req;
203
+ return redirect == null || method !== "GET" && method !== "HEAD" || hasModeForm(path, mode) ? next() : redirect(context, next);
204
+ }
205
+ });
216
206
  }
217
207
 
218
208
  // src/core/plugins/static.ts
219
- const IMMUTABLE = "public, max-age=31536000, immutable";
209
+ /** The headers of a hashed asset. Why one list for all responses: `staticResponse` only reads it. */
210
+ const ASSET_HEADERS = [{ "Cache-Control": IMMUTABLE }];
220
211
  /** The requests that the dev server answered. */
221
212
  const devServerAnswers = /* @__PURE__ */ new WeakSet();
222
213
  /**
@@ -236,7 +227,8 @@ function answeredByDevServer(context) {
236
227
  * default, with a one-year immutable cache. The `appServer` Vite plugin
237
228
  * records the directory. A missing asset gets a plain 404 with
238
229
  * `Cache-Control: no-store`, not a rendered page. In development, the dev
239
- * server serves the source modules, the HMR client, and the CSS here instead.
230
+ * server serves the source modules, the HMR client, and the CSS here instead,
231
+ * so a development plugin list needs this plugin.
240
232
  *
241
233
  * @example
242
234
  * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
@@ -268,7 +260,7 @@ function assets() {
268
260
  return staticResponse(context, {
269
261
  files,
270
262
  file,
271
- headers: { "Cache-Control": IMMUTABLE },
263
+ headers: ASSET_HEADERS,
272
264
  contentTypes
273
265
  });
274
266
  };
@@ -296,11 +288,6 @@ async function findTwin(files, context, { twinOf, rewritten }) {
296
288
  file
297
289
  };
298
290
  }
299
- /** Adds `Vary: Accept` to the answer for a path with a twin, so a shared cache keeps both answers. */
300
- function varyOnAccept(context) {
301
- const vary = withVary(context.res.headers.get("Vary"), "Accept");
302
- if (vary != null) writableHeaders(context).set("Vary", vary);
303
- }
304
291
  /**
305
292
  * The percent-encoded URL path for a decoded path, so it holds no space,
306
293
  * `>`, or non-ASCII character. Why the replace: a URL removes a tab or a
@@ -309,9 +296,25 @@ function varyOnAccept(context) {
309
296
  function urlPath(path) {
310
297
  return new URL(path.replaceAll(/[\t\n\r]/gu, (character) => encodeURIComponent(character)), "http://localhost").pathname;
311
298
  }
312
- /** Adds a `Link` to the twin at `twinPath`, so a client that does not ask for markdown can find it. */
313
- function linkToTwin(context, twinPath) {
314
- writableHeaders(context).append("Link", `<${urlPath(twinPath)}>; rel="alternate"; type="text/markdown"`);
299
+ /** The later stages of a stage that adds a header hook after its answer: none. */
300
+ async function noLaterStage() {}
301
+ /**
302
+ * Adds `Vary: Accept` to the answer for a path with a twin, so a shared
303
+ * cache keeps both answers. With `twinPath`, it also adds a `Link` to the
304
+ * twin, so a client that does not ask for markdown can find it. Why a header
305
+ * hook: the answer then needs no copy for the two headers.
306
+ */
307
+ async function negotiate(context, twinPath) {
308
+ const link = twinPath == null ? void 0 : `<${urlPath(twinPath)}>; rel="alternate"; type="text/markdown"`;
309
+ await withBuiltInHeaderHook({
310
+ context,
311
+ next: noLaterStage,
312
+ hook: (headers) => {
313
+ const vary = withVary(headers.get("Vary"), "Accept");
314
+ if (vary != null) headers.set("Vary", vary);
315
+ if (link != null) headers.append("Link", link);
316
+ }
317
+ });
315
318
  }
316
319
  /**
317
320
  * The development stage of `markdownTwins`. The client build has no twins
@@ -344,7 +347,7 @@ function developmentTwins(twinOf, { rewrite, skip }, prerenderedPaths) {
344
347
  return next();
345
348
  }
346
349
  context.res = response;
347
- varyOnAccept(context);
350
+ await negotiate(context);
348
351
  };
349
352
  }
350
353
  /** The twin lookup that the `markdownTwins` option selects, or `undefined` when it is off. */
@@ -376,7 +379,7 @@ function twinOfOption(markdownTwins) {
376
379
  */
377
380
  function prerendered(options = {}) {
378
381
  let stage;
379
- return {
382
+ return optionPlugin("prerendered", {
380
383
  name: "prerendered",
381
384
  setup: async (info) => {
382
385
  const twinOf = twinOfOption(options.markdownTwins);
@@ -385,30 +388,31 @@ function prerendered(options = {}) {
385
388
  stage = twinOf == null ? void 0 : developmentTwins(twinOf, options, paths == null ? void 0 : new Set(paths));
386
389
  return;
387
390
  }
388
- const { files, contentTypes, capturedHeaders } = info;
391
+ const { files, contentTypes, capturedHeaders, isDataRequest } = info;
389
392
  const missing = [];
390
393
  for (const path of info.prerenderedPaths) if (await findStaticFile(files, path) == null) missing.push(path);
391
- if (missing.length > 0) info.logger.log({
392
- level: "warn",
393
- message: "prerendered paths with no file",
394
- attributes: { "app_server.missing_paths": missing }
395
- });
396
- const cacheControl = options.cacheControl ?? ((path) => {
397
- const type = contentType(path, contentTypes);
398
- return type.startsWith("text/html") || type.startsWith("text/markdown") || info.isDataRequest(path) ? REVALIDATE : ONE_HOUR;
394
+ if (missing.length > 0) info.logger.warn("prerendered paths with no file", {
395
+ "app_server.missing_count": missing.length,
396
+ "app_server.missing_paths": missing.slice(0, 20)
399
397
  });
398
+ const defaultCacheControl = (file) => {
399
+ const type = contentType(file, contentTypes);
400
+ return type.startsWith("text/html") || type.startsWith("text/markdown") || isDataRequest(file) ? REVALIDATE : ONE_HOUR;
401
+ };
400
402
  const serve = async (context, path, file) => {
401
403
  context.env.onServedFile?.(file.path);
402
- const value = cacheControl(file.path);
403
- const headers = new Headers(value == null ? void 0 : { "Cache-Control": value });
404
- for (const layer of [capturedHeaders.get(manifestKey(path)), options.headers?.({
405
- path,
406
- context
407
- })]) for (const [name, layerValue] of Object.entries(layer ?? {})) headers.set(name, layerValue);
408
404
  return staticResponse(context, {
409
405
  files,
410
406
  file,
411
- headers: Object.fromEntries(headers),
407
+ headers: [
408
+ { "Cache-Control": options.cacheControl?.(file.path) ?? defaultCacheControl(file.path) },
409
+ capturedHeaders.get(manifestKey(path)),
410
+ options.headers?.({
411
+ path,
412
+ file: file.path,
413
+ context
414
+ })
415
+ ],
412
416
  contentTypes
413
417
  });
414
418
  };
@@ -428,16 +432,24 @@ function prerendered(options = {}) {
428
432
  const file = preferred?.file ?? await findStaticFile(files, path);
429
433
  if (file == null) await next();
430
434
  else context.res = await serve(context, path, file);
431
- if (twin != null) varyOnAccept(context);
432
- if (twin != null && preferred == null) linkToTwin(context, twin.path);
435
+ if (twin != null) await negotiate(context, preferred == null ? twin.path : void 0);
433
436
  };
434
437
  },
435
438
  middleware: async (context, next) => stage == null ? next() : stage(context, next)
436
- };
439
+ });
437
440
  }
438
441
 
439
442
  // src/core/plugins/access-log.ts
440
443
  /**
444
+ * A query in which each part is a key, an `=`, and a value, and each key has
445
+ * only characters that a URL parse and `encodeURIComponent` keep. Why:
446
+ * {@link loggedUrl} gives such a key as it is, so the redacted query needs no
447
+ * parse.
448
+ */
449
+ const PLAIN_QUERY = /^[\w!'()*\-.~]+=[^&]*(?:&[\w!'()*\-.~]+=[^&]*)*$/u;
450
+ /** The `=` and the value of each part of a {@link PLAIN_QUERY}. */
451
+ const QUERY_VALUE = /[=][^&]*/gu;
452
+ /**
441
453
  * A URL's path and query, with each query value replaced when `redact` is set.
442
454
  *
443
455
  * @example
@@ -462,29 +474,43 @@ function loggedReferer(referer, { redact }) {
462
474
  * with an `edge`, such as the node listener, counts the bytes.
463
475
  *
464
476
  * - A 5xx line has the level `error`, and each other line has the level `info`.
477
+ * - A 5xx whose client went away before the app answered has the status
478
+ * `499` and the level `info`.
465
479
  * - A line has `http.route` when the framework adapter gives the route
466
480
  * pattern that it matched, such as `/domains/:domainId`.
481
+ * - A line has `http.aborted: true` when the body stopped before its end: the
482
+ * client left, the body failed, or the server closed the connection.
467
483
  * - In development, a request that Vite answers, such as a source module,
468
484
  * gets no line.
469
485
  * - A request of the build's check of the CDN pages gets no line.
470
486
  *
471
487
  * @example
472
- * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
488
+ * createServer({ plugins: [requestId(), accessLog({ redactQuery: false }), assets()] });
473
489
  * // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
474
490
  */
475
491
  function accessLog({ redactQuery = true, attributes, serverTiming = false } = {}) {
476
- return {
492
+ return optionPlugin("accessLog", {
477
493
  name: "access-log",
478
494
  middleware: async (context, next) => {
479
495
  const started = performance.now();
480
- await (serverTiming ? withHeaderHook(context, next, (headers) => {
481
- if (headers.get("Content-Type")?.startsWith("text/html") ?? false) headers.append("Server-Timing", `app;dur=${(performance.now() - started).toFixed(1)}`);
482
- }) : next());
496
+ let clientLeft = false;
497
+ await withBuiltInHeaderHook({
498
+ context,
499
+ next,
500
+ hook: (headers) => {
501
+ clientLeft = context.req.raw.signal.aborted;
502
+ if (serverTiming && (headers.get("Content-Type")?.startsWith("text/html") ?? false)) headers.append("Server-Timing", `app;dur=${(performance.now() - started).toFixed(1)}`);
503
+ }
504
+ });
483
505
  if (answeredByDevServer(context) || context.env?.onServedFile != null) return;
484
506
  onResponseSent(context, (sent) => {
485
- const line = lineAttributes(context, sent, started);
507
+ const status = clientLeft && sent.status >= 500 ? 499 : sent.status;
508
+ const line = lineAttributes(context, {
509
+ ...sent,
510
+ status
511
+ }, started);
486
512
  try {
487
- context.get("logger")[sent.status >= 500 ? "error" : "info"]("request", attributes == null ? line : {
513
+ context.get("logger")[status >= 500 ? "error" : "info"]("request", attributes == null ? line : {
488
514
  ...line,
489
515
  ...attributes({
490
516
  context,
@@ -501,11 +527,16 @@ function accessLog({ redactQuery = true, attributes, serverTiming = false } = {}
501
527
  }
502
528
  });
503
529
  }
504
- };
530
+ });
505
531
  /** `href` as {@link loggedUrl} logs it. */
506
532
  function requestUrl(href) {
507
533
  const start = href.indexOf("/", href.indexOf("//") + 2);
508
- if (start !== -1 && !href.includes("?", start) && !href.includes("#", start)) return href.slice(start);
534
+ if (start !== -1 && !href.includes("#", start)) {
535
+ const query = href.indexOf("?", start);
536
+ if (query === -1) return href.slice(start);
537
+ const search = href.slice(query + 1);
538
+ if (redactQuery && PLAIN_QUERY.test(search)) return `${href.slice(start, query)}?${search.replaceAll(QUERY_VALUE, "=REDACTED")}`;
539
+ }
509
540
  return loggedUrl(new URL(href), { redact: redactQuery });
510
541
  }
511
542
  function lineAttributes(context, { status, bytes, aborted }, started) {
@@ -520,7 +551,7 @@ function accessLog({ redactQuery = true, attributes, serverTiming = false } = {}
520
551
  };
521
552
  const route = context.get("routePattern");
522
553
  if (route != null) line["http.route"] = route;
523
- if (aborted) line["http.client_aborted"] = true;
554
+ if (aborted) line["http.aborted"] = true;
524
555
  return line;
525
556
  }
526
557
  }
@@ -550,88 +581,55 @@ function tooLarge() {
550
581
  * next stage runs, so an upload cannot stream.
551
582
  *
552
583
  * @example
553
- * createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 })] });
584
+ * createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 }), assets()] });
554
585
  */
555
586
  function bodyLimit({ maxBytes }) {
556
587
  if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError(`bodyLimit needs a maxBytes of 0 or more whole bytes, not ${maxBytes}.`);
557
- return {
558
- name: "body-limit",
559
- middleware: async (context, next) => {
560
- const { raw } = context.req;
561
- if (NO_BODY_METHODS.has(raw.method)) return next();
562
- const length = context.req.header("Content-Length");
563
- if (length != null && /^\d+$/u.test(length) && context.req.header("Transfer-Encoding") == null) return Number(length) > maxBytes ? tooLarge() : next();
564
- let bytes = 0;
565
- let exceeded = false;
566
- let reader;
567
- const limited = new ReadableStream({
568
- async pull(controller) {
569
- reader ??= raw.body?.getReader();
570
- const chunk = await reader?.read();
571
- if (chunk == null || chunk.done) {
572
- controller.close();
573
- return;
574
- }
575
- bytes += chunk.value.byteLength;
576
- if (bytes > maxBytes) {
577
- exceeded = true;
578
- controller.error(new HTTPException(413, { message: "The request body is larger than the body limit." }));
579
- await reader?.cancel();
580
- return;
581
- }
582
- controller.enqueue(chunk.value);
583
- },
584
- cancel: async (reason) => (reader ?? raw.body)?.cancel(reason)
585
- }, { highWaterMark: 0 });
586
- const init = {
587
- method: raw.method,
588
- headers: raw.headers,
589
- signal: raw.signal,
590
- body: limited,
591
- duplex: "half"
592
- };
593
- context.req.raw = new Request(raw.url, init);
594
- await next();
595
- if (exceeded) {
596
- await context.res.body?.cancel();
597
- replaceResponse(context, tooLarge());
598
- }
588
+ /** The stage for a method that can have a body. */
589
+ const limit = async (context, next) => {
590
+ const { raw } = context.req;
591
+ const length = context.req.header("Content-Length");
592
+ if (length != null && /^\d+$/u.test(length) && context.req.header("Transfer-Encoding") == null) return Number(length) > maxBytes ? tooLarge() : next();
593
+ let bytes = 0;
594
+ let exceeded = false;
595
+ let reader;
596
+ const limited = new ReadableStream({
597
+ async pull(controller) {
598
+ reader ??= raw.body?.getReader();
599
+ const chunk = await reader?.read();
600
+ if (chunk == null || chunk.done) {
601
+ controller.close();
602
+ return;
603
+ }
604
+ bytes += chunk.value.byteLength;
605
+ if (bytes > maxBytes) {
606
+ exceeded = true;
607
+ controller.error(new HTTPException(413, { message: "The request body is larger than the body limit." }));
608
+ await reader?.cancel();
609
+ return;
610
+ }
611
+ controller.enqueue(chunk.value);
612
+ },
613
+ cancel: async (reason) => (reader ?? raw.body)?.cancel(reason)
614
+ }, { highWaterMark: 0 });
615
+ const init = {
616
+ method: raw.method,
617
+ headers: raw.headers,
618
+ signal: raw.signal,
619
+ body: limited,
620
+ duplex: "half"
621
+ };
622
+ context.req.raw = new Request(raw.url, init);
623
+ await next();
624
+ if (exceeded) {
625
+ await context.res.body?.cancel();
626
+ replaceResponse(context, tooLarge());
599
627
  }
600
628
  };
601
- }
602
-
603
- // src/core/shutdown.ts
604
- let controller = new AbortController();
605
- let stopping = false;
606
- /**
607
- * A signal that aborts when the server starts to shut down. Read it for each
608
- * request: each start of a server makes a new one. A handler that
609
- * holds a response open, such as an event stream, stops on it so that the
610
- * drain does not wait for the deadline.
611
- *
612
- * @example
613
- * const timer = setInterval(sendUpdate, 1_000);
614
- * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
615
- */
616
- function shutdownSignal() {
617
- return controller.signal;
618
- }
619
- /** Replaces {@link shutdownSignal} with a new one that has not aborted, and clears {@link isStopping}. */
620
- function renewShutdownSignal() {
621
- controller = new AbortController();
622
- stopping = false;
623
- }
624
- /** Marks the server as stopping, before the shutdown delay and the drain. */
625
- function markStopping() {
626
- stopping = true;
627
- }
628
- /** Whether the server got a stop signal. It is true during the shutdown delay, before {@link shutdownSignal} aborts. */
629
- function isStopping() {
630
- return stopping;
631
- }
632
- /** Aborts {@link shutdownSignal}. */
633
- function abortShutdownSignal() {
634
- controller.abort();
629
+ return optionPlugin("bodyLimit", {
630
+ name: "body-limit",
631
+ middleware: (context, next) => NO_BODY_METHODS.has(context.req.raw.method) ? next() : limit(context, next)
632
+ });
635
633
  }
636
634
 
637
635
  // src/core/plugins/health.ts
@@ -655,6 +653,10 @@ function probe(text, status) {
655
653
  * `defaultPlugins()` runs it first, so a probe skips the access log. Its
656
654
  * `health` option takes these options, and `false` turns it off.
657
655
  *
656
+ * A path that does not start with `/`, a path with `?` or `#`, or one path
657
+ * for both probes stops startup. For a platform with one health URL, set only
658
+ * `readyPath`.
659
+ *
658
660
  * @example
659
661
  * createServer({
660
662
  * plugins: defaultPlugins({ health: { ready: async () => db.ping() } }),
@@ -662,6 +664,14 @@ function probe(text, status) {
662
664
  * });
663
665
  */
664
666
  function health({ livePath = "/livez", readyPath = "/readyz", ready } = {}) {
667
+ for (const [option, path] of Object.entries({
668
+ livePath,
669
+ readyPath
670
+ })) {
671
+ if (!path.startsWith("/")) throw new Error(`health needs a ${option} that starts with "/", not ${JSON.stringify(path)}.`);
672
+ if (/[?#]/u.test(path)) throw new Error(`health needs a ${option} with no "?" and no "#", not ${JSON.stringify(path)}. A probe path matches the path of the request only.`);
673
+ }
674
+ if (livePath === readyPath) throw new Error(`health needs a livePath and a readyPath that differ. Both are ${JSON.stringify(livePath)}, so the readiness check would never run. For one health URL, set only readyPath.`);
665
675
  let appFailing = false;
666
676
  const appCheck = async (logger) => {
667
677
  if (ready == null) return true;
@@ -677,18 +687,18 @@ function health({ livePath = "/livez", readyPath = "/readyz", ready } = {}) {
677
687
  appFailing = !passed;
678
688
  return passed;
679
689
  };
680
- const isReady = async (logger) => {
681
- if (isStopping()) return false;
682
- return await appCheck(logger) && !isStopping();
690
+ const isReady = async (context) => {
691
+ const stopping = () => context.get("shutdown")?.stopping === true;
692
+ if (stopping()) return false;
693
+ return await appCheck(context.get("logger")) && !stopping();
683
694
  };
695
+ /** The answer to the probe at `path`, which is `livePath` or `readyPath`. */
696
+ const answer = async (path, context) => path === livePath || await isReady(context) ? probe("ok", 200) : probe("not ready", 503);
684
697
  return optionPlugin("health", {
685
698
  name: "health",
686
- middleware: async (context, next) => {
699
+ middleware: (context, next) => {
687
700
  const { method, path } = context.req;
688
- if (method !== "GET" && method !== "HEAD") return next();
689
- if (path === livePath) return probe("ok", 200);
690
- if (path === readyPath) return await isReady(context.get("logger")) ? probe("ok", 200) : probe("not ready", 503);
691
- return next();
701
+ return (method === "GET" || method === "HEAD") && (path === livePath || path === readyPath) ? answer(path, context) : next();
692
702
  }
693
703
  });
694
704
  }
@@ -708,15 +718,24 @@ function health({ livePath = "/livez", readyPath = "/readyz", ready } = {}) {
708
718
  */
709
719
  function noindex(options) {
710
720
  const unlessHeader = options?.unlessHeader;
721
+ if (unlessHeader != null) checkHeaderName({
722
+ plugin: "noindex",
723
+ option: "unlessHeader",
724
+ name: unlessHeader
725
+ });
711
726
  const plugin = optionPlugin("noindex", {
712
727
  name: "noindex",
713
- middleware: async (context, next) => {
728
+ middleware: (context, next) => {
714
729
  const hidden = unlessHeader == null || context.req.header(unlessHeader) == null;
715
- await withHeaderHook(context, next, (response) => {
716
- if (hidden) response.set("X-Robots-Tag", "noindex, nofollow");
717
- if (unlessHeader != null) {
718
- const vary = withVary(response.get("Vary"), unlessHeader);
719
- if (vary != null) response.set("Vary", vary);
730
+ return withBuiltInHeaderHook({
731
+ context,
732
+ next,
733
+ hook: (response) => {
734
+ if (hidden) response.set("X-Robots-Tag", "noindex, nofollow");
735
+ if (unlessHeader != null) {
736
+ const vary = withVary(response.get("Vary"), unlessHeader);
737
+ if (vary != null) response.set("Vary", vary);
738
+ }
720
739
  }
721
740
  });
722
741
  }
@@ -750,8 +769,12 @@ function privateDocuments() {
750
769
  setup: (info) => {
751
770
  ({isDataRequest} = info);
752
771
  },
753
- middleware: async (context, next) => withHeaderHook(context, next, (headers) => {
754
- if (!headers.has("Cache-Control") && ((headers.get("Content-Type")?.startsWith("text/html") ?? false) || isDataRequest(context.req.path))) headers.set("Cache-Control", "private, no-cache");
772
+ middleware: (context, next) => withBuiltInHeaderHook({
773
+ context,
774
+ next,
775
+ hook: (headers) => {
776
+ if (!headers.has("Cache-Control") && ((headers.get("Content-Type")?.startsWith("text/html") ?? false) || isDataRequest(context.req.path))) headers.set("Cache-Control", "private, no-cache");
777
+ }
755
778
  })
756
779
  };
757
780
  }
@@ -759,14 +782,40 @@ function privateDocuments() {
759
782
  // src/core/plugins/redirects.ts
760
783
  const PARAM = /^:(?<name>[A-Za-z_]\w*)$/u;
761
784
  const TARGET_TOKEN = /:(?<name>[A-Za-z_]\w*)|\*/gu;
785
+ const NO_RULES = [];
786
+ /**
787
+ * A part of a URL path that a URL parse changes: a character that the parse
788
+ * encodes or removes, a `\`, or a dot segment. It also matches a `%`,
789
+ * because Hono does not decode each escape.
790
+ */
791
+ const PARSE_CHANGES = /[^!$&-;=@-[\]_a-z|~]|\/\.\.?(?:\/|$)/u;
792
+ /**
793
+ * Whether `path`, the path that Hono gives for the URL `href`, is the
794
+ * `pathname` of that URL. Why not always: Hono decodes most escapes of the
795
+ * path, and Deno gives the URL as the client sent it, with no parse.
796
+ */
797
+ function isPathname(path, href) {
798
+ const escape = href.indexOf("%");
799
+ return !(escape !== -1 && href.lastIndexOf("?", escape) === -1) && !PARSE_CHANGES.test(path);
800
+ }
762
801
  /** `path` with no trailing slashes, and `/` for the root. */
763
802
  function matchKey(path) {
764
803
  return trimTrailingSlashes(path) || "/";
765
804
  }
766
- /** The pattern of `from`, with a named group for each `:name` and for `*`, or `undefined` for an exact path. */
805
+ /** The first segment of `path`, a path with no trailing slash: `docs` for `/docs/a`, and an empty string for `/`. */
806
+ function firstSegment(path) {
807
+ const end = path.indexOf("/", 1);
808
+ return end === -1 ? path.slice(1) : path.slice(1, end);
809
+ }
810
+ /**
811
+ * The pattern of `from`, with a named group for each `:name` and for `*`, or
812
+ * `undefined` for an exact path. It also gives the first segment of `from`,
813
+ * and the names that `to` can use.
814
+ */
767
815
  function compilePattern(from) {
768
816
  const segments = matchKey(from).split("/").slice(1);
769
817
  const names = /* @__PURE__ */ new Set();
818
+ let first;
770
819
  const parts = segments.map((segment, index) => {
771
820
  const name = PARAM.exec(segment)?.groups?.name;
772
821
  if (name != null) {
@@ -779,17 +828,22 @@ function compilePattern(from) {
779
828
  names.add("*");
780
829
  return "(?:/(?<$splat>.*))?";
781
830
  }
831
+ if (segment.startsWith(":") || segment.includes("*")) throw new Error(`The redirect from ${from} has the segment ${segment}, which is not valid. Use :name for one whole segment, or * as the whole last segment. A literal segment cannot start with ":" or have "*".`);
832
+ if (index === 0) first = segment;
782
833
  return `/${segment.replaceAll(/[$()*+.?[\\\]^{|}]/gu, String.raw`\$&`)}`;
783
834
  });
784
835
  return {
785
836
  pattern: names.size === 0 ? void 0 : new RegExp(`^${parts.join("")}$`, "u"),
837
+ first,
786
838
  names
787
839
  };
788
840
  }
789
841
  /** Compiles a rule, and throws for a rule that is not valid, so a bad table stops startup. */
790
842
  function compileRule({ from, to, status = 301 }, index) {
791
843
  if (!from.startsWith("/")) throw new Error(`A redirect must be from a path that starts with "/", not ${from}.`);
792
- const { pattern, names } = compilePattern(from);
844
+ const { pattern, first, names } = compilePattern(from);
845
+ const pathname = URL.parse(`http://localhost${from}`)?.pathname;
846
+ if (pathname !== from) throw new Error(`The redirect from ${from} can never match. A rule matches the path only. Write it percent-encoded, with no query and no fragment: ${pathname}.`);
793
847
  for (const token of to.matchAll(TARGET_TOKEN)) {
794
848
  const name = token.groups?.name ?? "*";
795
849
  if (!names.has(name)) throw new Error(`The redirect from ${from} to ${to} uses ${token[0]}, which ${from} does not have.`);
@@ -799,6 +853,7 @@ function compileRule({ from, to, status = 301 }, index) {
799
853
  return {
800
854
  key: matchKey(from),
801
855
  pattern,
856
+ first,
802
857
  to,
803
858
  status,
804
859
  origin: void 0,
@@ -810,12 +865,28 @@ function compileRule({ from, to, status = 301 }, index) {
810
865
  return {
811
866
  key: matchKey(from),
812
867
  pattern,
868
+ first,
813
869
  to: url.href,
814
870
  status,
815
871
  origin: url.origin,
816
872
  index
817
873
  };
818
874
  }
875
+ /**
876
+ * The first of `rules`, which are in table order, whose pattern matches
877
+ * `path`, with the values that it matched. With `before`, it tests only the
878
+ * rules before that position of the table.
879
+ */
880
+ function firstMatch(rules, path, before = 1e400) {
881
+ for (const rule of rules ?? NO_RULES) {
882
+ if (rule.index > before) break;
883
+ const groups = rule.pattern?.exec(path)?.groups;
884
+ if (groups != null) return {
885
+ rule,
886
+ groups
887
+ };
888
+ }
889
+ }
819
890
  /** The target of `rule` for the values that its pattern matched. */
820
891
  function fill(to, groups) {
821
892
  const queryStart = to.indexOf("?");
@@ -842,7 +913,9 @@ function withQuery(target, search) {
842
913
  /**
843
914
  * Sends a redirect from each old URL path in `rules` to its new URL, with
844
915
  * the query string. The first rule that matches wins. An exact path is a
845
- * map lookup. A rule with `:name` or `*` is a pattern.
916
+ * map lookup. A rule with `:name` or `*` is a pattern. A request tests only
917
+ * the patterns that start with its first path segment, and the patterns
918
+ * whose first segment is `:name` or `*`.
846
919
  *
847
920
  * The rules compile at startup, and a rule that is not valid stops startup.
848
921
  * A local target must be a safe local path. An absolute target must keep the
@@ -851,9 +924,10 @@ function withQuery(target, search) {
851
924
  * target. It applies to GET and HEAD only.
852
925
  *
853
926
  * Put it before `trailingSlash`, so `/old/` gets one redirect to the final
854
- * URL, and give it the same `trailingSlash` mode. In `never` mode, a local
855
- * target loses its trailing slash, so `trailingSlash` does not redirect it
856
- * again. `defaultPlugins({ redirects })` does both.
927
+ * URL, and give it the same `trailingSlash` mode. Its default is
928
+ * `"preserve"`, which is not the `"never"` of `defaultPlugins()`. In `never`
929
+ * mode, a local target loses its trailing slash, so `trailingSlash` does not
930
+ * redirect it again. `defaultPlugins({ redirects })` does both.
857
931
  *
858
932
  * @example
859
933
  * redirects([
@@ -865,33 +939,37 @@ function redirects(rules, { trailingSlash = "preserve" } = {}) {
865
939
  const compiled = rules.map((rule, index) => compileRule(rule, index));
866
940
  const exact = /* @__PURE__ */ new Map();
867
941
  for (const rule of compiled.toReversed()) if (rule.pattern == null) exact.set(rule.key, rule);
868
- const patterns = compiled.filter((rule) => rule.pattern != null);
942
+ const patterns = Map.groupBy(compiled.filter((rule) => rule.pattern != null), (rule) => rule.first);
943
+ /** The first pattern before the table position `before` that matches `path`. */
944
+ const matchPattern = (path, before) => {
945
+ const own = firstMatch(patterns.get(firstSegment(path)), path, before);
946
+ return firstMatch(patterns.get(void 0), path, own?.rule.index ?? before) ?? own;
947
+ };
869
948
  const find = (path) => {
870
949
  const exactRule = exact.get(path);
871
- for (const rule of patterns) {
872
- if (exactRule != null && rule.index > exactRule.index) break;
873
- const groups = rule.pattern?.exec(path)?.groups;
874
- if (groups != null) return {
875
- rule,
876
- target: fill(rule.to, groups)
877
- };
878
- }
950
+ const matched = patterns.size === 0 ? void 0 : matchPattern(path, exactRule?.index);
951
+ if (matched != null) return {
952
+ rule: matched.rule,
953
+ target: fill(matched.rule.to, matched.groups)
954
+ };
879
955
  return exactRule == null ? void 0 : {
880
956
  rule: exactRule,
881
957
  target: exactRule.to
882
958
  };
883
959
  };
960
+ const redirect = async (context, next) => {
961
+ const url = new URL(context.req.url);
962
+ const found = find(matchKey(url.pathname));
963
+ if (found == null) return next();
964
+ const location = withQuery(trailingSlash === "never" && found.rule.origin == null ? withoutTrailingSlash(found.target) : found.target, url.search);
965
+ if (URL.parse(location, url)?.href === url.href) return next();
966
+ return (found.rule.origin == null ? isSafeLocalPath(location) : URL.parse(location)?.origin === found.rule.origin) ? context.redirect(location, found.rule.status) : next();
967
+ };
884
968
  return {
885
969
  name: "redirects",
886
- middleware: async (context, next) => {
887
- const { method } = context.req;
888
- if (method !== "GET" && method !== "HEAD") return next();
889
- const url = new URL(context.req.url);
890
- const found = find(matchKey(url.pathname));
891
- if (found == null) return next();
892
- const location = withQuery(trailingSlash === "never" && found.rule.origin == null ? withoutTrailingSlash(found.target) : found.target, url.search);
893
- if (new URL(location, url).href === url.href) return next();
894
- return (found.rule.origin == null ? isSafeLocalPath(location) : URL.parse(location)?.origin === found.rule.origin) ? context.redirect(location, found.rule.status) : next();
970
+ middleware: (context, next) => {
971
+ const { method, path } = context.req;
972
+ return method !== "GET" && method !== "HEAD" || isPathname(path, context.req.url) && find(matchKey(path)) == null ? next() : redirect(context, next);
895
973
  }
896
974
  };
897
975
  }
@@ -934,16 +1012,25 @@ function securityHeaders({ headers = {} } = {}) {
934
1012
  ...DEFAULT_SECURITY_HEADERS,
935
1013
  ...headers
936
1014
  }).filter((entry) => typeof entry[1] === "string").map(([name, value]) => [name, oneLine(value)]);
937
- return {
1015
+ for (const [name, value] of values) checkHeaderValue({
1016
+ plugin: "securityHeaders",
1017
+ option: name,
1018
+ value
1019
+ });
1020
+ return optionPlugin("securityHeaders", {
938
1021
  name: "security-headers",
939
- middleware: async (context, next) => {
1022
+ middleware: (context, next) => {
940
1023
  const isHttps = context.req.url.startsWith("https:");
941
- await withHeaderHook(context, next, (response) => {
942
- for (const [name, value] of values) if (name === "Content-Security-Policy") response.append(name, value);
943
- else if (!response.has(name) && (name !== "Strict-Transport-Security" || isHttps)) response.set(name, value);
1024
+ return withBuiltInHeaderHook({
1025
+ context,
1026
+ next,
1027
+ hook: (response) => {
1028
+ for (const [name, value] of values) if (name === "Content-Security-Policy") response.append(name, value);
1029
+ else if (!response.has(name) && (name !== "Strict-Transport-Security" || isHttps)) response.set(name, value);
1030
+ }
944
1031
  });
945
1032
  }
946
- };
1033
+ });
947
1034
  }
948
1035
  /**
949
1036
  * `value` on one line. Why: a header value cannot hold a line break, and a
@@ -952,17 +1039,46 @@ function securityHeaders({ headers = {} } = {}) {
952
1039
  function oneLine(value) {
953
1040
  return value.replaceAll(/\s+/gu, " ").trim();
954
1041
  }
1042
+ /** The `script-src` source list that trusts `'self'` and each inline script with one of `hashes`. */
1043
+ function hashSources(hashes) {
1044
+ return ["'self'", ...hashes.map((hash) => `'sha256-${hash}'`)].join(" ");
1045
+ }
1046
+ /** The bytes of one nonce. Why 16: a nonce must have 128 bits or more. */
1047
+ const NONCE_BYTES = 16;
1048
+ /**
1049
+ * Random bytes for 64 nonces. Why a pool: on Node.js, one
1050
+ * `crypto.getRandomValues` call costs more than the rest of a nonce. Each
1051
+ * nonce takes its own 16 bytes, so no two nonces share a byte. The bytes
1052
+ * that no nonce took yet stay in memory. So each process that starts from a
1053
+ * copy of that memory, such as an image of a virtual machine or a Node.js
1054
+ * startup snapshot, gives the same next nonces, 63 at most.
1055
+ */
1056
+ const noncePool = /* @__PURE__ */ new Uint8Array(1024);
1057
+ /**
1058
+ * How many bytes of {@link noncePool} the nonces took. Why all of them at
1059
+ * the start: the first nonce fills the pool, so a process holds no random
1060
+ * bytes before its first request.
1061
+ */
1062
+ let takenBytes = noncePool.length;
955
1063
  /** A new random nonce: 16 bytes in base64. */
956
1064
  function randomNonce() {
957
- return btoa(String.fromCodePoint(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
1065
+ if (takenBytes === noncePool.length) {
1066
+ crypto.getRandomValues(noncePool);
1067
+ takenBytes = 0;
1068
+ }
1069
+ let bytes = "";
1070
+ for (const byte of noncePool.subarray(takenBytes, takenBytes + NONCE_BYTES)) bytes += String.fromCodePoint(byte);
1071
+ takenBytes += NONCE_BYTES;
1072
+ return btoa(bytes);
958
1073
  }
959
1074
  /**
960
1075
  * Sets the `Content-Security-Policy` from `policy` on each HTML document. The
961
1076
  * policy trusts the document's scripts, and only them:
962
1077
  *
963
1078
  * - A rendered document gets `'nonce-…' 'strict-dynamic'` with a new nonce
964
- * for each request. The app reads the nonce from `requestContext()` and
965
- * gives it to the framework's render, so each inline script gets it.
1079
+ * for each request. The app gives `cspNonce()` from
1080
+ * `@ngrok/app-server/client` to the framework's render, so each inline
1081
+ * script gets the nonce.
966
1082
  * - A prerendered document gets `'self'` and the hash of each of its inline
967
1083
  * scripts, which the Vite plugin records. Its file has one nonce for every
968
1084
  * visitor, so a nonce protects nothing. Why no `'strict-dynamic'`: a hash,
@@ -981,24 +1097,31 @@ function randomNonce() {
981
1097
  * });
982
1098
  */
983
1099
  function contentSecurityPolicy({ policy }) {
984
- let scriptHashes = /* @__PURE__ */ new Map();
1100
+ /** The source list of each HTML file of the client build that has hashes, by the file's URL path. */
1101
+ let fileSources = /* @__PURE__ */ new Map();
985
1102
  return optionPlugin("contentSecurityPolicy", {
986
1103
  name: "content-security-policy",
987
1104
  setup: (info) => {
988
- ({scriptHashes} = info);
1105
+ fileSources = new Map(Array.from(info.scriptHashes, ([file, hashes]) => [file, hashSources(hashes)]));
989
1106
  },
990
- middleware: async (context, next) => {
1107
+ middleware: (context, next) => {
991
1108
  const nonce = randomNonce();
992
1109
  context.set("cspNonce", nonce);
993
- await withHeaderHook(context, next, (headers) => {
994
- const file = context.get("staticDocument");
995
- const hashes = context.get("documentScriptHashes") ?? (file == null ? void 0 : scriptHashes.get(file) ?? []);
996
- if (headers.has("Content-Security-Policy") || hashes == null && !(headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
997
- const scriptSrc = hashes == null ? `'nonce-${nonce}' 'strict-dynamic'` : ["'self'", ...hashes.map((hash) => `'sha256-${hash}'`)].join(" ");
998
- headers.set("Content-Security-Policy", oneLine(policy({
999
- scriptSrc,
1000
- context
1001
- })));
1110
+ return withBuiltInHeaderHook({
1111
+ context,
1112
+ next,
1113
+ hook: (headers) => {
1114
+ const file = context.get("staticDocument");
1115
+ const devHashes = context.get("documentScriptHashes");
1116
+ const fileSource = file == null ? void 0 : fileSources.get(file) ?? "'self'";
1117
+ const hashSource = devHashes == null ? fileSource : hashSources(devHashes);
1118
+ if (headers.has("Content-Security-Policy") || hashSource == null && !(headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
1119
+ const scriptSrc = hashSource ?? `'nonce-${nonce}' 'strict-dynamic'`;
1120
+ headers.set("Content-Security-Policy", oneLine(policy({
1121
+ scriptSrc,
1122
+ context
1123
+ })));
1124
+ }
1002
1125
  });
1003
1126
  }
1004
1127
  });
@@ -1045,14 +1168,19 @@ function traceAttributes({ traceId, spanId }, { datadog }) {
1045
1168
  * line of the request.
1046
1169
  *
1047
1170
  * @example
1048
- * const app = createServer({ plugins: [requestId()] });
1171
+ * const app = createServer({ plugins: [requestId(), assets()] });
1049
1172
  * const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
1050
1173
  * response.headers.get("X-Request-Id"); // => "abc-123"
1051
1174
  */
1052
1175
  function requestId({ headerName = "X-Request-Id", datadogTraceIds = false } = {}) {
1053
- return {
1176
+ checkHeaderName({
1177
+ plugin: "requestId",
1178
+ option: "headerName",
1179
+ name: headerName
1180
+ });
1181
+ const plugin = optionPlugin("requestId", {
1054
1182
  name: "request-id",
1055
- middleware: async (context, next) => {
1183
+ middleware: (context, next) => {
1056
1184
  const trace = parseTraceparent(context.req.header("traceparent"));
1057
1185
  if (trace != null) context.set("logAttributes", {
1058
1186
  ...context.get("logAttributes"),
@@ -1061,11 +1189,16 @@ function requestId({ headerName = "X-Request-Id", datadogTraceIds = false } = {}
1061
1189
  const incoming = context.req.header(headerName);
1062
1190
  const id = incoming != null && VALID_ID.test(incoming) ? incoming : crypto.randomUUID();
1063
1191
  context.set("requestId", id);
1064
- await withHeaderHook(context, next, (headers) => {
1065
- headers.set(headerName, id);
1192
+ return withBuiltInHeaderHook({
1193
+ context,
1194
+ next,
1195
+ hook: (headers) => {
1196
+ headers.set(headerName, id);
1197
+ }
1066
1198
  });
1067
1199
  }
1068
- };
1200
+ });
1201
+ return perRequestHeaders([headerName], plugin);
1069
1202
  }
1070
1203
 
1071
1204
  // src/core/plugins/streaming-compress.ts
@@ -1178,6 +1311,13 @@ function compressed(response, body, { encoding, hasLength }) {
1178
1311
  return replacement;
1179
1312
  }
1180
1313
  /**
1314
+ * Whether `headers` keep the body as it is: the body has an encoding, it is
1315
+ * a part of a file, or it is marked `no-transform`.
1316
+ */
1317
+ function keepsBody(headers) {
1318
+ return headers.has("Content-Encoding") || headers.has("Content-Range") || forbidsTransform(headers.get("Cache-Control"));
1319
+ }
1320
+ /**
1181
1321
  * Compresses text responses with brotli or gzip, and flushes after each
1182
1322
  * chunk, so a streamed page shell or a server-sent event reaches the client
1183
1323
  * at once. A client gets brotli when its `Accept-Encoding` ranks `br` at
@@ -1189,7 +1329,7 @@ function compressed(response, body, { encoding, hasLength }) {
1189
1329
  * host gives the streams. On a host with none, the plugin does nothing.
1190
1330
  *
1191
1331
  * @example
1192
- * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
1332
+ * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets()] });
1193
1333
  */
1194
1334
  function streamingCompress() {
1195
1335
  /** The host's streams, in the order that the plugin prefers them. */
@@ -1215,19 +1355,25 @@ function streamingCompress() {
1215
1355
  middleware: async (context, next) => {
1216
1356
  if (offered.length === 0) return next();
1217
1357
  let compressing = false;
1218
- await withHeaderHook(context, next, (headers) => {
1219
- const type = headers.get("Content-Type");
1220
- const vary = type == null || isCompressible(type) ? withVary(headers.get("Vary"), "Accept-Encoding") : void 0;
1221
- if (vary != null) headers.set("Vary", vary);
1222
- if (compressing) headers.delete("Content-Length");
1358
+ await withBuiltInHeaderHook({
1359
+ context,
1360
+ next,
1361
+ hook: (headers) => {
1362
+ const type = headers.get("Content-Type");
1363
+ const vary = type == null || isCompressible(type) ? withVary(headers.get("Vary"), "Accept-Encoding") : void 0;
1364
+ if (vary != null) headers.set("Vary", vary);
1365
+ if (compressing) headers.delete("Content-Length");
1366
+ }
1223
1367
  });
1224
1368
  const response = context.res;
1225
1369
  const type = response.headers.get("Content-Type");
1226
1370
  if (type != null && !isCompressible(type)) return;
1227
1371
  const length = response.headers.get("Content-Length");
1228
1372
  const { body } = response;
1229
- const chosen = choose(context.req.header("Accept-Encoding"));
1230
- if (type == null || body == null || context.req.method === "HEAD" || length != null && Number(length) < 1024 || chosen == null || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || forbidsTransform(response.headers.get("Cache-Control"))) return;
1373
+ const accept = context.req.header("Accept-Encoding");
1374
+ if (accept == null || type == null || body == null || context.req.method === "HEAD" || length != null && Number(length) < 1024 || keepsBody(response.headers)) return;
1375
+ const chosen = choose(accept);
1376
+ if (chosen == null) return;
1231
1377
  let source = body;
1232
1378
  let compress = true;
1233
1379
  if (length == null) {
@@ -1237,10 +1383,8 @@ function streamingCompress() {
1237
1383
  compress = !queued.done || size >= 1024;
1238
1384
  source = replay(reader, queued);
1239
1385
  }
1240
- if (compress) {
1241
- const hooked = hookedHeaders(context, response.headers);
1242
- compress = !hooked.has("Content-Encoding") && !hooked.has("Content-Range") && !forbidsTransform(hooked.get("Cache-Control"));
1243
- }
1386
+ const hooks = compress ? bodyHooks(context) : void 0;
1387
+ if (hooks != null) compress = !keepsBody(hookedView(hooks, headerList(response.headers)));
1244
1388
  if (compress) {
1245
1389
  compressing = true;
1246
1390
  replaceResponse(context, compressed(response, chosen.stream(source), {
@@ -1252,6 +1396,62 @@ function streamingCompress() {
1252
1396
  };
1253
1397
  }
1254
1398
 
1399
+ // src/core/shutdown.ts
1400
+ /**
1401
+ * The stop state of each app server of this copy of the package, for
1402
+ * {@link abortShutdownSignal}. Why not weak: a module can keep the signal of an
1403
+ * app server that no other code keeps, such as one that a `server.ts` edit
1404
+ * replaced.
1405
+ */
1406
+ const states = /* @__PURE__ */ new Set();
1407
+ function newState() {
1408
+ const state = {
1409
+ controller: new AbortController(),
1410
+ stopping: false
1411
+ };
1412
+ states.add(state);
1413
+ return state;
1414
+ }
1415
+ /**
1416
+ * The state that the first `createServer` call takes. Why: a signal that a
1417
+ * module reads before that call then aborts when that server shuts down.
1418
+ */
1419
+ let unclaimed = newState();
1420
+ /** The state of the last `createServer` call, which {@link shutdownSignal} reads outside a request. */
1421
+ let latest = unclaimed;
1422
+ /** The stop state of a new app server. Each `createServer` call takes one. */
1423
+ function createShutdownState() {
1424
+ latest = unclaimed ?? newState();
1425
+ unclaimed = void 0;
1426
+ return latest;
1427
+ }
1428
+ /**
1429
+ * A signal that aborts when the server starts to shut down. A handler that
1430
+ * holds a response open, such as an event stream, stops on it so that the
1431
+ * drain does not wait for the deadline.
1432
+ *
1433
+ * In a request, and in work that the request started, it is the signal of the
1434
+ * app server that serves the request. Outside a request, and on a host with
1435
+ * no request storage, it is the signal of the last `createServer` call, as
1436
+ * the sink of `logger()` is.
1437
+ *
1438
+ * @example
1439
+ * const timer = setInterval(sendUpdate, 1_000);
1440
+ * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
1441
+ */
1442
+ function shutdownSignal() {
1443
+ return (currentShutdown() ?? latest).controller.signal;
1444
+ }
1445
+ /**
1446
+ * Aborts the {@link shutdownSignal} of each app server of this copy of the
1447
+ * package, for the exit of `app-server start`. Why each one: an edit to
1448
+ * `server.ts` makes a new app server, and a signal of the app server before
1449
+ * it must abort too.
1450
+ */
1451
+ function abortShutdownSignal() {
1452
+ for (const { controller } of states) controller.abort();
1453
+ }
1454
+
1255
1455
  // src/core/create-server.ts
1256
1456
  /** The response for `error`, as `onError` gives it for a stage that throws. */
1257
1457
  function answerError(error, context) {
@@ -1262,6 +1462,44 @@ function answerError(error, context) {
1262
1462
  context.get("logger").error("unhandled error", { error });
1263
1463
  return context.text("Internal Server Error", 500);
1264
1464
  }
1465
+ /**
1466
+ * The app's `onError` handler, with a 500 for an error that `handler` returns
1467
+ * no `Response` for. Why: Hono turns a falsy response into an empty 200, so
1468
+ * such a handler would answer each of those errors with a 200.
1469
+ */
1470
+ function checkedOnError(handler) {
1471
+ return async (error, context) => {
1472
+ const answer = await handler(error, context);
1473
+ if (answer) return answer;
1474
+ return answerError(new TypeError("The app's onError returned no Response. It must return a Response for each error.", { cause: error }), context);
1475
+ };
1476
+ }
1477
+ /**
1478
+ * Throws for a `plugins` value that is not a list, and for an entry of it that
1479
+ * is a function, a list, a promise, or not an object, so a wrong plugin list
1480
+ * stops startup. Why: such an entry has no `middleware`, so the server would
1481
+ * start and never run it. Why `unknown`: the `Plugin` type rejects these
1482
+ * values, but a build can skip the type check, as Vite's does.
1483
+ */
1484
+ function checkPluginObjects(plugins) {
1485
+ if (!Array.isArray(plugins)) throw new TypeError("plugins is not a list of plugins. Give a list, such as defaultPlugins() or [requestId()].");
1486
+ const entries = plugins;
1487
+ for (const [index, plugin] of entries.entries()) {
1488
+ if (typeof plugin === "function") {
1489
+ const value = plugin.name === "" ? "a function" : `the function ${plugin.name}`;
1490
+ throw new TypeError(`plugins[${index}] is ${value}, not a plugin. Call a plugin factory, such as requestId(). Put a Hono middleware in a plugin, such as { name: "auth", middleware: basicAuth() }.`);
1491
+ }
1492
+ if (typeof plugin !== "object" || plugin == null) throw new TypeError(`plugins[${index}] is ${String(plugin)}, not a plugin. Remove it. To add a plugin on a condition, spread a list: ...(condition ? [plugin] : []).`);
1493
+ if (Array.isArray(plugin)) throw new TypeError(`plugins[${index}] is a list, not a plugin. Spread the list, such as ...defaultPlugins().`);
1494
+ if ("then" in plugin && typeof plugin.then === "function") throw new TypeError(`plugins[${index}] is a promise, not a plugin. Wait for the plugin with await, such as await auth().`);
1495
+ }
1496
+ }
1497
+ /**
1498
+ * Answers a request that no plugin or route answers. Why at module scope: a
1499
+ * function made in `prepare` keeps the `SetupInfo`, and so the script hashes
1500
+ * of each page, for the life of the server.
1501
+ */
1502
+ const frameworkRoute = async (context) => context.env.framework.fetch(context.req.raw, context);
1265
1503
  const appInternals = /* @__PURE__ */ new WeakMap();
1266
1504
  /** Why 10 MiB: a form or an avatar upload fits, and a body cannot fill the memory. */
1267
1505
  const DEFAULT_BODY_LIMIT = 10485760;
@@ -1271,12 +1509,20 @@ const DEFAULT_BODY_LIMIT = 10485760;
1271
1509
  * set), `buildId`, `contentSecurityPolicy` (when set), `env` (when set), the
1272
1510
  * `beforeStatic` plugins, `assets`, `redirects` (when the option has rules),
1273
1511
  * `trailingSlash`, `prerendered`, and `privateDocuments`. It is a plain
1274
- * array, so an app can filter it or splice into it.
1512
+ * array, so an app can filter it or splice into it. To find a plugin in the
1513
+ * array, compare its `name`: the name of its function in kebab-case, such as
1514
+ * `streaming-compress`. A filter on a name that no plugin has removes nothing.
1275
1515
  *
1276
1516
  * @example
1277
1517
  * createServer({
1278
1518
  * plugins: defaultPlugins({ env, noindex: process.env.PREVIEW === "1", health: { ready: async () => db.ping() } }),
1279
1519
  * });
1520
+ *
1521
+ * @example
1522
+ * // Behind a proxy that compresses each response.
1523
+ * createServer({
1524
+ * plugins: defaultPlugins().filter((plugin) => plugin.name !== "streaming-compress"),
1525
+ * });
1280
1526
  */
1281
1527
  function defaultPlugins(options = {}) {
1282
1528
  const maxBytes = options.bodyLimit ?? DEFAULT_BODY_LIMIT;
@@ -1307,15 +1553,6 @@ function forwardedClient(header, hops) {
1307
1553
  const addresses = (header ?? "").split(",").map((address) => address.trim()).filter((address) => address !== "");
1308
1554
  return addresses[Math.max(0, addresses.length - hops)];
1309
1555
  }
1310
- /** Why: `setTimeout` turns a longer delay into 1 ms. */
1311
- const MAX_TIMER_MS = 2147483647;
1312
- /** Throws for a value that is not an integer from 0 to `max`, so a bad option stops startup. */
1313
- function checkCount(name, value, max = Number.MAX_SAFE_INTEGER) {
1314
- if (!Number.isInteger(value) || value < 0 || value > max) {
1315
- const range = max === Number.MAX_SAFE_INTEGER ? "of 0 or more" : `from 0 to ${max}`;
1316
- throw new Error(`${name} must be an integer ${range}, not ${value}.`);
1317
- }
1318
- }
1319
1556
  /**
1320
1557
  * The request with the scheme from `X-Forwarded-Proto`, when that header holds one.
1321
1558
  *
@@ -1346,8 +1583,9 @@ async function settlesWithin(work, ms) {
1346
1583
  * the app's own routes, then the framework. It does not listen; the
1347
1584
  * `app-server` CLI starts it.
1348
1585
  *
1349
- * Two plugins of one option of `defaultPlugins()`, such as two `buildId()`,
1350
- * stop startup.
1586
+ * A plugin list with an entry that is not a plugin, a second plugin of one
1587
+ * option, or a plugin that the prerendered pages need after `prerendered()`
1588
+ * stops startup. The README section "The pipeline" gives each rule.
1351
1589
  *
1352
1590
  * @example
1353
1591
  * // server.ts
@@ -1355,30 +1593,71 @@ async function settlesWithin(work, ms) {
1355
1593
  * app.get("/api/status", (c) => c.json({ ok: true }));
1356
1594
  * export default app;
1357
1595
  */
1358
- function createServer({ plugins = defaultPlugins(), logger: sink = jsonSink(), log, listeners, trustForwardedProto = false, trustedProxyHops = 0, shutdownDelayMs = 0, shutdownDeadlineMs = 1e4 } = {}) {
1596
+ function createServer({ plugins = defaultPlugins(), logger: appSink, log, listeners, trustForwardedProto = false, trustedProxyHops = 0, shutdownDelayMs = 0, shutdownDeadlineMs = 1e4 } = {}) {
1597
+ checkPluginObjects(plugins);
1359
1598
  checkOptionPlugins(plugins);
1360
1599
  checkCount("trustedProxyHops", trustedProxyHops);
1361
1600
  checkCount("shutdownDelayMs", shutdownDelayMs, MAX_TIMER_MS);
1362
1601
  checkCount("shutdownDeadlineMs", shutdownDeadlineMs, MAX_TIMER_MS);
1602
+ const sink = appSink ?? jsonSink();
1363
1603
  const logger = hookSink(sink, log);
1364
1604
  setProcessSink(logger);
1605
+ const shutdown = createShutdownState();
1365
1606
  const app = new Hono();
1366
1607
  let onError = answerError;
1367
1608
  const setOnError = app.onError.bind(app);
1609
+ setOnError(answerError);
1368
1610
  app.onError = (handler) => {
1369
- onError = handler;
1370
- return setOnError(handler);
1611
+ onError = checkedOnError(handler);
1612
+ return setOnError(onError);
1371
1613
  };
1372
- app.onError(answerError);
1373
1614
  const answerThrown = async (thrown, context) => onError(asError(thrown), context);
1374
1615
  let requestStore;
1375
1616
  if (trustForwardedProto) {
1376
1617
  const dispatch = app.fetch;
1377
1618
  app.fetch = async (request, ...rest) => dispatch(withForwardedProto(request), ...rest);
1378
1619
  }
1620
+ const stages = plugins.flatMap(({ middleware, etagPart }) => middleware == null && etagPart == null ? [] : [{
1621
+ middleware,
1622
+ etagPart
1623
+ }]);
1624
+ /**
1625
+ * Runs the stage at `index` for the request of `run`. The stage runs each
1626
+ * later stage through its `next`. After the last stage, `run.rest` runs the
1627
+ * app's routes and the framework. `run.reached` is the last stage that
1628
+ * started, so a second `next()` in one stage throws, as in Hono.
1629
+ *
1630
+ * Why not one Hono middleware for each plugin: Hono runs an async function
1631
+ * for each one, and a second one must turn a thrown value that is not an
1632
+ * `Error` into one. This function does both jobs. As Hono does for an
1633
+ * `Error`, it answers each thrown value with `onError` at the stage that
1634
+ * threw, so each earlier plugin sees that answer after its `next()`.
1635
+ */
1636
+ const runStage = async (run, index) => {
1637
+ if (index <= run.reached) throw new Error("next() called multiple times");
1638
+ run.reached = index;
1639
+ const { context } = run;
1640
+ const stage = stages[index];
1641
+ try {
1642
+ if (stage == null) {
1643
+ await run.rest();
1644
+ return;
1645
+ }
1646
+ const { middleware, etagPart } = stage;
1647
+ const part = etagPart?.();
1648
+ if (part != null) context.set("etagParts", [...context.get("etagParts") ?? [], part]);
1649
+ const next = () => runStage(run, index + 1);
1650
+ const answer = await (middleware == null ? next() : middleware(context, next));
1651
+ if (answer && !context.finalized) context.res = answer;
1652
+ } catch (error) {
1653
+ context.error = asError(error);
1654
+ context.res = await onError(context.error, context);
1655
+ }
1656
+ };
1379
1657
  app.use(async (context, next) => {
1380
1658
  const requestLog = requestLogger(logger, context);
1381
1659
  context.set("logger", requestLog);
1660
+ context.set("shutdown", shutdown);
1382
1661
  const remoteAddress = context.env?.remoteAddress;
1383
1662
  context.set("clientAddress", trustedProxyHops === 0 ? remoteAddress : forwardedClient(context.req.header("X-Forwarded-For"), trustedProxyHops) ?? remoteAddress);
1384
1663
  const hooks = [];
@@ -1387,8 +1666,20 @@ function createServer({ plugins = defaultPlugins(), logger: sink = jsonSink(), l
1387
1666
  context.set("sentReports", reports);
1388
1667
  const given = context.env?.edge;
1389
1668
  const edge = given?.claim(requestLog) === true ? given : void 0;
1390
- await withRequestContext(requestStore, context, async () => {
1391
- await next();
1669
+ const scope = {
1670
+ context,
1671
+ values: void 0
1672
+ };
1673
+ await withRequestContext(requestStore, scope, async () => {
1674
+ await runStage({
1675
+ context,
1676
+ rest: next,
1677
+ reached: -1
1678
+ }, 0);
1679
+ if (!context.finalized) context.res = await answerThrown(/* @__PURE__ */ new Error("The request has no answer. A middleware must return a Response or call `await next()`."), context);
1680
+ if (requestStore != null && (edge != null || reports.length > 0)) reports.push(() => {
1681
+ releaseContext(scope, logger, requestLog);
1682
+ });
1392
1683
  const finishing = finishResponse(context, {
1393
1684
  hooks,
1394
1685
  reports,
@@ -1399,35 +1690,30 @@ function createServer({ plugins = defaultPlugins(), logger: sink = jsonSink(), l
1399
1690
  });
1400
1691
  if (context.req.method === "HEAD") await context.res.body?.cancel();
1401
1692
  });
1402
- for (const { middleware, etagPart } of plugins) app.use(async (context, next) => {
1403
- const part = etagPart?.();
1404
- if (part != null) context.set("etagParts", [...context.get("etagParts") ?? [], part]);
1405
- try {
1406
- return await (middleware == null ? next() : middleware(context, next));
1407
- } catch (error) {
1408
- throw asError(error);
1409
- }
1410
- });
1411
- app.use(async (_, next) => {
1412
- try {
1413
- await next();
1414
- } catch (error) {
1415
- throw asError(error);
1416
- }
1417
- });
1418
1693
  let prepared;
1419
1694
  let running;
1420
1695
  let stoppingPlugins;
1421
1696
  const internals = {
1422
1697
  logger,
1423
1698
  presenceHeaders: presenceHeadersOf(plugins),
1699
+ perRequestHeaders: perRequestHeadersOf(plugins),
1424
1700
  setRequestStore: (store) => {
1425
1701
  requestStore = store;
1426
1702
  },
1427
1703
  prepare: async (info) => {
1428
1704
  prepared ??= (async () => {
1429
- for (const plugin of plugins) await plugin.setup?.(info);
1430
- app.all("*", async (context) => context.env.framework.fetch(context.req.raw, context));
1705
+ if (appSink == null && info.mode === "development") sink.log = textSink().log;
1706
+ let devServerTaken = info.mode !== "development";
1707
+ const seen = info.mode === "development" ? {
1708
+ ...info,
1709
+ get devServer() {
1710
+ devServerTaken = true;
1711
+ return info.devServer;
1712
+ }
1713
+ } : info;
1714
+ for (const plugin of plugins) await plugin.setup?.(seen);
1715
+ if (!devServerTaken) throw new Error("No plugin runs the dev server, so Vite serves no source module, HMR client, or CSS. Add assets() to the plugin list.");
1716
+ app.all("*", frameworkRoute);
1431
1717
  })().catch((error) => {
1432
1718
  prepared = void 0;
1433
1719
  throw error;
@@ -1438,7 +1724,6 @@ function createServer({ plugins = defaultPlugins(), logger: sink = jsonSink(), l
1438
1724
  if (running != null) throw new Error("This app server is already listening.");
1439
1725
  const chosen = listeners ?? defaultListeners ?? [];
1440
1726
  if (chosen.length === 0) throw new Error("This app server has no listener: the app sets none, and the host has none. A serverless host calls the entry's `fetch`.");
1441
- renewShutdownSignal();
1442
1727
  let deadlinePassed = false;
1443
1728
  const fetch = async (request, bindings) => {
1444
1729
  const response = await app.fetch(request, {
@@ -1466,7 +1751,7 @@ function createServer({ plugins = defaultPlugins(), logger: sink = jsonSink(), l
1466
1751
  urls,
1467
1752
  shutdown: async () => {
1468
1753
  stopping ??= (async () => {
1469
- markStopping();
1754
+ shutdown.stopping = true;
1470
1755
  if (shutdownDelayMs > 0) {
1471
1756
  logger.log({
1472
1757
  level: "info",
@@ -1482,11 +1767,23 @@ function createServer({ plugins = defaultPlugins(), logger: sink = jsonSink(), l
1482
1767
  message: "draining",
1483
1768
  attributes: { "app_server.deadline_ms": shutdownDeadlineMs }
1484
1769
  });
1485
- abortShutdownSignal();
1770
+ shutdown.controller.abort();
1771
+ let openListeners = started.length;
1486
1772
  const deadline = setTimeout(() => {
1487
1773
  deadlinePassed = true;
1774
+ if (openListeners > 0) logger.log({
1775
+ level: "warn",
1776
+ message: "the drain deadline passed with open requests",
1777
+ attributes: { "app_server.deadline_ms": shutdownDeadlineMs }
1778
+ });
1488
1779
  }, shutdownDeadlineMs);
1489
- const results = await Promise.allSettled([internals.stopPlugins(), ...started.map(async (listener) => listener.stop({ deadlineMs: shutdownDeadlineMs }))]);
1780
+ const results = await Promise.allSettled([internals.stopPlugins(), ...started.map(async (listener) => {
1781
+ try {
1782
+ await listener.stop({ deadlineMs: shutdownDeadlineMs });
1783
+ } finally {
1784
+ openListeners -= 1;
1785
+ }
1786
+ })]);
1490
1787
  clearTimeout(deadline);
1491
1788
  const rejected = results.find((result) => result.status === "rejected");
1492
1789
  if (rejected != null) throw rejected.reason;
@@ -1503,17 +1800,32 @@ function createServer({ plugins = defaultPlugins(), logger: sink = jsonSink(), l
1503
1800
  },
1504
1801
  stopPlugins: async () => {
1505
1802
  stoppingPlugins ??= (async () => {
1803
+ const open = /* @__PURE__ */ new Set();
1506
1804
  if (!await settlesWithin((async () => {
1507
- const results = await Promise.allSettled(plugins.map(async (plugin) => plugin.onShutdown?.()));
1508
- for (const result of results) if (result.status === "rejected") logger.log({
1509
- level: "error",
1510
- message: "plugin shutdown failed",
1511
- attributes: { error: asError(result.reason) }
1512
- });
1805
+ await Promise.all(plugins.map(async (plugin, index) => {
1806
+ if (plugin.onShutdown == null) return;
1807
+ open.add(index);
1808
+ try {
1809
+ await plugin.onShutdown();
1810
+ } catch (error) {
1811
+ logger.log({
1812
+ level: "error",
1813
+ message: "plugin shutdown failed",
1814
+ attributes: {
1815
+ "app_server.plugin": plugin.name,
1816
+ error: asError(error)
1817
+ }
1818
+ });
1819
+ }
1820
+ open.delete(index);
1821
+ }));
1513
1822
  })(), shutdownDeadlineMs)) logger.log({
1514
1823
  level: "warn",
1515
1824
  message: "plugin shutdown passed the deadline",
1516
- attributes: { "app_server.deadline_ms": shutdownDeadlineMs }
1825
+ attributes: {
1826
+ "app_server.deadline_ms": shutdownDeadlineMs,
1827
+ "app_server.plugins": [...open].map((index) => plugins[index]?.name)
1828
+ }
1517
1829
  });
1518
1830
  })();
1519
1831
  return stoppingPlugins;
@@ -1527,5 +1839,4 @@ function serverInternals(app) {
1527
1839
  return appInternals.get(app);
1528
1840
  }
1529
1841
 
1530
- export { assets as _, streamingCompress as a, prefersMarkdown as b, securityHeaders as c, noindex as d, health as f, accessLog as g, bodyLimit as h, withForwardedProto as i, redirects as l, shutdownSignal as m, defaultPlugins as n, requestId as o, abortShutdownSignal as p, serverInternals as r, contentSecurityPolicy as s, createServer as t, privateDocuments as u, prerendered as v, trailingSlash as y };
1531
- //# sourceMappingURL=create-server-Bp1yILQk.js.map
1842
+ export { assets as _, abortShutdownSignal as a, prefersMarkdown as b, requestId as c, redirects as d, privateDocuments as f, accessLog as g, bodyLimit as h, withForwardedProto as i, contentSecurityPolicy as l, health as m, defaultPlugins as n, shutdownSignal as o, noindex as p, serverInternals as r, streamingCompress as s, createServer as t, securityHeaders as u, prerendered as v, trailingSlash as y };