@ngrok/app-server 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +63 -23
  2. package/dist/brotli-only-DrA29Ecw.js +97 -0
  3. package/dist/brotli-only-DrA29Ecw.js.map +1 -0
  4. package/dist/{build-id-C6sYO9Yp.js → build-id-B0448vZH.js} +27 -2
  5. package/dist/build-id-B0448vZH.js.map +1 -0
  6. package/dist/{build-manifest-UDNk81Ce.js → build-manifest-DBMWe3Lx.js} +12 -2
  7. package/dist/build-manifest-DBMWe3Lx.js.map +1 -0
  8. package/dist/cli.js +3 -3
  9. package/dist/client-browser.js +1 -1
  10. package/dist/client.js +1 -1
  11. package/dist/compress-JuJf2HaO.js +377 -0
  12. package/dist/compress-JuJf2HaO.js.map +1 -0
  13. package/dist/{compression-7_gToa8R.js → compression-CT2mWlKM.js} +9 -2
  14. package/dist/compression-CT2mWlKM.js.map +1 -0
  15. package/dist/{create-server-D0De6R7Q.js → create-server-BX2rH6-E.js} +616 -547
  16. package/dist/create-server-BX2rH6-E.js.map +1 -0
  17. package/dist/{create-server-kzZWd_Lo.d.ts → create-server-kxyhCdhv.d.ts} +50 -13
  18. package/dist/{entry-DuGgSKeB.d.ts → entry-CNL4OsEn.d.ts} +39 -3
  19. package/dist/entry-ChHgs269.js +352 -0
  20. package/dist/entry-ChHgs269.js.map +1 -0
  21. package/dist/{index-Bo5G9LuQ.d.ts → index-B8LsM6Mh.d.ts} +26 -1
  22. package/dist/index.d.ts +14 -23
  23. package/dist/index.js +3 -3
  24. package/dist/{load-entry-Bodyd2Ok.js → load-entry-BOgJPt1I.js} +4 -4
  25. package/dist/{load-entry-Bodyd2Ok.js.map → load-entry-BOgJPt1I.js.map} +1 -1
  26. package/dist/{node-C1qudLs_.js → node-B0AYf_IA.js} +5 -4
  27. package/dist/{node-C1qudLs_.js.map → node-B0AYf_IA.js.map} +1 -1
  28. package/dist/{node-tBVQPjQv.js → node-C0Ad7CVL.js} +2 -2
  29. package/dist/{node-tBVQPjQv.js.map → node-C0Ad7CVL.js.map} +1 -1
  30. package/dist/node-vite.d.ts +1 -1
  31. package/dist/node.d.ts +1 -1
  32. package/dist/node.js +2 -2
  33. package/dist/react-router-vite.d.ts +1 -1
  34. package/dist/react-router.d.ts +3 -2
  35. package/dist/react-router.js +31 -2
  36. package/dist/react-router.js.map +1 -1
  37. package/dist/{response-writer-B7FoJjEE.js → response-writer-DzvUAz9x.js} +3 -3
  38. package/dist/response-writer-DzvUAz9x.js.map +1 -0
  39. package/dist/{script-hashes-C6hQ5XnP.js → script-hashes-CU7P9oZU.js} +2 -2
  40. package/dist/{script-hashes-C6hQ5XnP.js.map → script-hashes-CU7P9oZU.js.map} +1 -1
  41. package/dist/{serve-caOkS3o5.js → serve-BUJ7ZonG.js} +2 -2
  42. package/dist/{serve-caOkS3o5.js.map → serve-BUJ7ZonG.js.map} +1 -1
  43. package/dist/{stale-build-navigation-PnMLtTF8.js → stale-build-navigation-rg5xxmTr.js} +2 -2
  44. package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map} +1 -1
  45. package/dist/{start-DREqYrZh.js → start-DiQf9ttp.js} +36 -8
  46. package/dist/start-DiQf9ttp.js.map +1 -0
  47. package/dist/{static-files-Beju9riB.js → static-files-C2ea8KQ6.js} +11 -3
  48. package/dist/static-files-C2ea8KQ6.js.map +1 -0
  49. package/dist/tanstack-start-vite.d.ts +1 -1
  50. package/dist/tanstack-start.d.ts +2 -2
  51. package/dist/{tcp-Dd1Mt6sN.js → tcp-Bws6oEau.js} +2 -2
  52. package/dist/{tcp-Dd1Mt6sN.js.map → tcp-Bws6oEau.js.map} +1 -1
  53. package/dist/testing.d.ts +2 -2
  54. package/dist/testing.js +4 -4
  55. package/dist/{trailing-slash-BrymAEGv.d.ts → trailing-slash-DeOUxMYo.d.ts} +2 -2
  56. package/dist/{types-CEvzAmcn.d.ts → types-BKJxtIuj.d.ts} +24 -3
  57. package/dist/vercel-pages.d.ts +32 -0
  58. package/dist/vercel-pages.js +54 -0
  59. package/dist/vercel-pages.js.map +1 -0
  60. package/dist/vercel-vite.d.ts +30 -9
  61. package/dist/vercel-vite.js +183 -20
  62. package/dist/vercel-vite.js.map +1 -1
  63. package/dist/vercel.d.ts +4 -3
  64. package/dist/vercel.js +7 -5
  65. package/dist/vercel.js.map +1 -1
  66. package/dist/{vite-tTxVimP6.js → vite-DPiSKHDn.js} +182 -51
  67. package/dist/vite-DPiSKHDn.js.map +1 -0
  68. package/dist/vite.d.ts +1 -1
  69. package/dist/vite.js +1 -1
  70. package/package.json +2 -1
  71. package/dist/build-id-C6sYO9Yp.js.map +0 -1
  72. package/dist/build-manifest-UDNk81Ce.js.map +0 -1
  73. package/dist/compression-7_gToa8R.js.map +0 -1
  74. package/dist/create-server-D0De6R7Q.js.map +0 -1
  75. package/dist/entry-UDsxuqBC.js +0 -116
  76. package/dist/entry-UDsxuqBC.js.map +0 -1
  77. package/dist/gzip-Doi4wqjX.js +0 -294
  78. package/dist/gzip-Doi4wqjX.js.map +0 -1
  79. package/dist/response-writer-B7FoJjEE.js.map +0 -1
  80. package/dist/start-DREqYrZh.js.map +0 -1
  81. package/dist/static-files-Beju9riB.js.map +0 -1
  82. package/dist/vite-tTxVimP6.js.map +0 -1
package/README.md CHANGED
@@ -36,7 +36,7 @@ How we measured:
36
36
  - Each page has one URL. A page URL with the other trailing-slash form gets a 308 to it, for rendered and prerendered pages. A prerendered page answers at its own URL with a 200.
37
37
  - A prerendered resource route (`llms.txt`, `sitemap.xml`, a JSON API file) and each `.data` file keep the headers their loader sent: `Content-Type`, `Cache-Control`, CORS.
38
38
  - A static file gets the brotli or gzip copy that the build wrote. `compression()` compresses each response again for each request.
39
- - A streamed page under gzip reaches the client chunk by chunk.
39
+ - A streamed page under brotli or gzip reaches the client chunk by chunk.
40
40
  - Each request gets one JSON log line in your format, static files included, and an `X-Request-Id`.
41
41
  - Shutdown drains open requests with a deadline, and the keep-alive timeout outlasts the proxy's idle pool. `@react-router/serve` closes the server on `SIGTERM`, with no deadline and no readiness probe.
42
42
 
@@ -122,11 +122,12 @@ export default defineConfig({
122
122
  });
123
123
  ```
124
124
 
125
- `appServer` has three options. Each one has a default:
125
+ `appServer` has four options. Each one has a default:
126
126
 
127
127
  - `framework`: the framework adapter. Default: the adapter of the framework plugin in the Vite config. The plugin of React Router is `reactRouter()`, and the plugin of TanStack Start is `tanstackStart()`. If the config has neither plugin or both, Vite stops with an error. Then pass `reactRouterAdapter()` from `@ngrok/app-server/react-router/vite` or `tanstackStartAdapter()` from `@ngrok/app-server/tanstack-start/vite`.
128
128
  - `host`: the host adapter. Default: `node()` from `@ngrok/app-server/node/vite`.
129
129
  - `app`: the module whose default export is the app, relative to the Vite root. Default: `server.ts`, else `server.js`, in the Vite root. If neither file exists, the server uses the default plugins.
130
+ - `externals`: how the server build copies the packages that stay external. `whole` lists packages that keep each file, and `omit` lists packages that the build does not copy. Default: no package in either list. See [Deploy](#deploy).
130
131
 
131
132
  An option that you set replaces its default. Set it for a third-party adapter or for an app in another file:
132
133
 
@@ -158,7 +159,7 @@ Run it:
158
159
 
159
160
  `appServer` adds `server/app-server.js` to the server build, next to the framework's own entry, which does not change. The file bundles `server.ts` with the framework's server module, so the server gets the app's path aliases and its one copy of the framework. The build also bundles the dependencies, so the build directory runs with no install. See [Deploy](#deploy).
160
161
 
161
- After the build and after the prerender pass, `appServer` writes a gzip copy (`.<file>.gz`) and a brotli copy (`.<file>.br`) next to each text file of 1 kibibyte (KiB) or more in the client build, HTML pages included. It writes the gzip copy when it is smaller than the file, and the brotli copy when it is smaller than the gzip copy. `app-server serve` sends the copy that the client's `Accept-Encoding` prefers, brotli before gzip, so it does not compress the file for each request. Each copy is a dotfile, so it has no URL of its own: a `skip` rule or an auth check for the file also blocks its copies. The build does not change a `.gz` or `.br` file of the app. The copies include the prerendered files, in any plugin order. The brotli copies use quality 9, not 11: on a docs build with 70 megabytes (MB) of text, quality 11 adds 46 s to the build, and quality 9 adds 0.6 s for copies that are 9% larger. `appServer` gives a list of Vite plugins, so put it in `plugins` as it is.
162
+ After the build and after the prerender pass, `appServer` writes a gzip copy (`.<file>.gz`) and a brotli copy (`.<file>.br`) next to each compressible file of 1 kibibyte (KiB) or more in the client build, HTML pages included. A compressible file has a text type, a type with a `+json` or `+xml` suffix (such as an RSS feed), or another type that compresses well: JSON, JavaScript, WebAssembly, YAML, a shell script, an icon (`.ico`, `.bmp`), or a TrueType, OpenType, or Embedded OpenType font. A WOFF or WOFF2 font is compressed already, so it gets no copy. It writes the gzip copy when it is smaller than the file, and the brotli copy when it is smaller than the gzip copy. `app-server serve` sends the copy that the client's `Accept-Encoding` prefers, brotli before gzip, so it does not compress the file for each request. Each copy is a dotfile, so it has no URL of its own: a `skip` rule or an auth check for the file also blocks its copies. The build does not change a `.gz` or `.br` file of the app. A link, and a file in a linked directory, get no copy, so the build writes only inside the client build. The copies include the prerendered files, in any plugin order. The brotli copies use quality 9, not 11: on a docs build with 70 megabytes (MB) of text, quality 11 adds 46 s to the build, and quality 9 adds 0.6 s for copies that are 9% larger. `appServer` gives a list of Vite plugins, so put it in `plugins` as it is.
162
163
 
163
164
  The build exports `appServer`, and the CLI calls it. So the copy of this package in the build runs the server, and the CLI's copy runs nothing. The CLI refuses a build from a version of this package with another entry protocol.
164
165
 
@@ -166,7 +167,7 @@ A React Router app with no Vite plugin also works: `app-server serve build/serve
166
167
 
167
168
  ## Commands
168
169
 
169
- - `app-server start`: development. Vite in middleware mode inside the pipeline, with HMR on the same port. It needs the `appServer` plugin. Each request loads the latest server entry, so an edit to a route or to `server.ts` applies at once. The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, `start` tries each next port, unless Vite's `server.strictPort` is true. The host is `HOST`, else Vite's `server.host`. On `SIGTERM` or `SIGINT`, it stops Vite and the server, then exits.
170
+ - `app-server start`: development. Vite in middleware mode inside the pipeline, with HMR on the same port. It needs the `appServer` plugin. Each request loads the latest server entry, so an edit to a route or to `server.ts` applies at once. A Vite plugin gets the CLI's HTTP server as `server.httpServer` in its `configureServer` hook, so it can wait for `listening` and `close`. A Vite restart, such as after an edit to `vite.config.ts`, keeps that server open. So a new plugin instance gets no `listening`, and the old instance gets `close` only at exit. To clean up for each instance, use Vite's `closeServer` hook. The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, `start` tries each next port, unless Vite's `server.strictPort` is true. The host is `HOST`, else Vite's `server.host`. On `SIGTERM` or `SIGINT`, it stops Vite and the server, then exits.
170
171
  - `node build/server/app-server.js`: production, with no install. Use `dist/server/app-server.js` for TanStack Start. It reads `PORT` and `HOST`, and it drains on `SIGTERM` or `SIGINT`, as `app-server serve` does. It has no `--port`. It sets `NODE_ENV` to `production` when `NODE_ENV` has no value.
171
172
  - `app-server serve [path]`: production. With no path, it runs the first of `build/server/app-server.js` (React Router), `dist/server/app-server.js` (TanStack Start), and `build/server/index.js` (a plain React Router build). The port is `--port`, else `PORT`, else 3000. The host is `HOST`, else every interface. A port in use stops startup at once. On `SIGTERM` or `SIGINT`, it drains, then exits, even when the app left a timer. A server process serves the client build that was there at start. A deploy starts a new process.
172
173
 
@@ -180,7 +181,9 @@ On Bun, run `bun build/server/app-server.js`, or `bun node_modules/@ngrok/app-se
180
181
 
181
182
  - `appServer` bundles each dependency into the server build. For the build, it sets `ssr.noExternal: true`, unless the app sets its own `ssr.noExternal` or sets `ssr.external: true`.
182
183
  - Some packages stay external: each package in the app's `ssr.external` or in the bundler's `external` option, the whole package of an external subpath, each peer dependency of a package that the app keeps external, the peers of each peer, each native package, and each package that reads a file next to its own module. So the bundle and an external package use one copy of a package, such as `react` for a component library. For a `RegExp` or a function in the bundler's `external` option, the build tests the name of each package in the `dependencies`, `optionalDependencies`, and `devDependencies` of the app. It keeps the peers of each match external too. A package is native when a `.node` file is in it, or in a package of its `dependencies` or `optionalDependencies`. For example, `oxc-parser` gets its addon from `@oxc-parser/binding-linux-x64-gnu`. A package reads a file next to its module when the file that an import resolves to has `new URL("./…", import.meta.url)`, `fileURLToPath(import.meta.url)`, or `import.meta.dirname`. For example, `@vercel/og` reads `resvg.wasm` so.
183
- - The build copies each external package, whole, with its installed dependencies, into `node_modules` in the server build. Each file stays where its package expects it, so CommonJS, a file read through `__dirname`, and a `.node` addon work.
184
+ - The build copies each external package, with its installed dependencies, into `node_modules` in the server build. Each file stays where its package expects it, so CommonJS, a file read through `__dirname`, and a `.node` addon work.
185
+ - The build then removes each copied file that the server build cannot load, as [`@vercel/nft`](https://github.com/vercel/nft) traces it from the modules of the build, with the export conditions of Node, Bun, and Deno. So a source map, an edge build, or a dependency that a package bundled into its own file does not reach the deploy. For `@vercel/og` 1.0.1, the copy goes from 42.9 MB in 453 files to 23.6 MB. Five kinds of package keep each file: a native package and each package that it depends on (a native package can load a library, such as libvips, that a trace cannot see), each package in `ssr.external`, each package that the app gives to `require.resolve()` or `import.meta.resolve()`, each package that the trace misses files of, with each package that it depends on, and each package in `externals.whole`. The trace misses files of a package when its loaded code has `import.meta.dirname` or `import.meta.filename`, or when it cannot parse a loaded module, such as a TypeScript entry for Bun. It also misses a file that a loaded module gives to `require.resolve()` or `import.meta.resolve()` through the `exports` of a package, so that package keeps each file too. Add a package to `externals.whole` when it reads a file whose path the trace cannot find.
186
+ - The build does not copy a package in `externals.omit`. Use it for an optional dependency that a package loads in a `try`. For example, `@vercel/og` uses `sharp` when it is installed, else `resvg.wasm`. `appServer({ externals: { omit: ["sharp"] } })` makes the `@vercel/og` copy 3.0 MB. The server fails when it loads an omitted package with no `try`.
184
187
  - The build copies each package in `ssr.external`, also when no code imports it. It also copies each package that the app's code gives to `require.resolve()` or `import.meta.resolve()` as a string, such as `require.resolve("@fontsource/inter/files/inter-latin-400-normal.woff")`. When the code makes the name at run time, add the package to `ssr.external`.
185
188
  - The build writes a `package.json` with `"type": "module"` into the server build, so Node, Bun, and Deno load it as ES modules and find its `node_modules`.
186
189
 
@@ -206,7 +209,7 @@ For TanStack Start, copy `dist`, and run `dist/server/app-server.js`.
206
209
 
207
210
  ## Deploy to Vercel
208
211
 
209
- The `vercel` host runs the pipeline in one Node.js Vercel Function. Vercel's content delivery network (CDN) serves the hashed files.
212
+ The `vercel` host runs the pipeline in one Node.js Vercel Function. Vercel's content delivery network (CDN) serves the hashed files, and with `cdnPages`, each public prerendered page.
210
213
 
211
214
  Use `vercel()` as the host:
212
215
 
@@ -221,22 +224,46 @@ After the build, `vercel()` writes `.vercel/output` (the Build Output API, versi
221
224
 
222
225
  The output has two parts:
223
226
 
224
- - `static/`: the files under `/assets/` and the other `cdnPaths`. The CDN serves them. Each file under `/assets/` gets `Cache-Control: public, max-age=31536000, immutable`. A request under `/assets/` with no file goes to the function, which sends a 404 with `Cache-Control: no-store`. A request under another CDN path with no file goes through the pipeline, as on the node host.
227
+ - `static/`: the files of Vite's `build.assetsDir` (`/assets/` by default), the other `cdnPaths`, and with `cdnPages`, the public prerendered pages. The CDN serves them. Each file of `build.assetsDir` gets `Cache-Control: public, max-age=31536000, immutable`. A request under `build.assetsDir` with no file goes to the function, which sends a 404 with `Cache-Control: no-store`. A request under another CDN path with no file goes through the pipeline, as on the node host.
225
228
  - `functions/index.func/`: the function for each other request. It has the whole server build, which runs with no install (see [Deploy](#deploy)), and the rest of the client build. The Node.js version of the function is the version that ran the build.
226
229
 
227
- Prerendered pages come from the function, so they get the same pipeline as rendered pages: the security headers, the CSP, the redirects, and the markdown twins. To let the CDN keep a page, send `s-maxage` or `CDN-Cache-Control` in its headers, such as with the `headers` option of [`prerendered`](#prerendered-headers). Then a page calls the function only on a CDN miss.
230
+ ### Prerendered pages on the CDN
231
+
232
+ By default, the function serves each prerendered page, so a page gets the same pipeline as a rendered page. To let the CDN keep a page, send `s-maxage` or `CDN-Cache-Control` in its headers, such as with the `headers` option of [`prerendered`](#prerendered-headers). Then a page calls the function only on a CDN miss.
233
+
234
+ With `vercel({ cdnPages: true })`, the CDN serves each public prerendered page with no function. After the build, `vercel()` starts the server build once, with no listener, and sends each prerendered path through the pipeline. The first request comes from an anonymous client, with no cookie and no `Authorization`. The CDN serves a page when its answer meets all of these conditions:
235
+
236
+ - It is a 200 from the page's file.
237
+ - It has no `Set-Cookie`. It has no `private`, `no-store`, or `no-cache`, in any case, in `Cache-Control` or in a CDN field such as `Vercel-CDN-Cache-Control`.
238
+ - It is the same for a second client with another host, client address, user agent, query, `Accept` with no markdown, and value of the `unlessHeader` header. The second client also sends a cookie, `Authorization`, `Referer`, `Accept-Language`, and Vercel's `X-Vercel-IP-Country`, `X-Vercel-IP-Country-Region`, and `X-Vercel-IP-City`. So a plugin that sends a signed-in visitor or a country to another answer keeps its pages in the function. Only `X-Request-Id` and `Date` can change.
239
+ - It varies only on `Accept-Encoding`, on `Accept` for a [markdown twin](#content-negotiation), and on the header of `noindex: { unlessHeader }`.
240
+
241
+ The CDN then sends the pipeline's body and headers: the security headers, the CSP, the build ID, and the `runtimeEnv` values. The function also keeps the page's file, for a request that no CDN route matches, such as `/about/` for `/about`. A browser gets `Cache-Control: public, max-age=0, must-revalidate` and the CDN's ETag, so it revalidates each page. Vercel keeps the CDN's copies for one deployment, so a deploy never serves an old page. The build log names each path that the function serves, with the reason.
242
+
243
+ The function serves each other prerendered page, and the CDN never keeps its answer:
244
+
245
+ - A page that an auth check in `beforeStatic` protects stays in the function, because the check refuses the anonymous request. So the CDN never keeps a page behind auth.
246
+ - A page whose answer changes with the query or the host stays in the function, such as with a `prerendered({ rewrite })` that reads the query.
247
+ - A request that names `text/markdown` in `Accept` goes to the function, which negotiates the twin.
248
+ - Vercel allows 2,048 routes for each deployment. A page uses one route for each case of the `unlessHeader` header, and one more for a twin. If the pages need more routes, the function serves the rest.
249
+ - A page with a `$` in a response header stays in the function, because a Vercel route reads `$1` or `$name` in a header as a capture.
250
+ - A request with another method, such as a form's `POST`, goes to the function.
251
+
252
+ The build cannot see a check that both clients pass but another client fails, such as a check of a real session, an allowlist of client addresses, or a rule on one query key. Keep such a page in the function with a `cdnPages` function. A page that the CDN serves writes no access log line, and neither do the build's requests. The build also needs the app's environment, because it runs each plugin's `setup`.
228
253
 
229
254
  `vercel()` takes:
230
255
 
231
256
  - `cdnPaths`: more URL path prefixes for the CDN, such as `["/blog-assets/"]`. Each starts and ends with `/`. Their files skip the pipeline, and the function does not carry them. Vercel limits a function to 250 MB, so put a large directory of the client build here. Default none.
232
- - `cdnHeaders`: headers for each CDN file, such as CORS headers. Default none.
233
- - `regions`, `memory`, and `maxDuration`: the function's Vercel config. Default the project's.
257
+ - `cdnHeaders`: headers for each file of `cdnPaths` and `build.assetsDir`, such as CORS headers. Default none.
258
+ - `cdnPages`: which prerendered pages the CDN can serve. `true` gives the CDN each page that qualifies. A function gives the CDN each page that qualifies and that it accepts, such as `(path) => path !== "/"` for a page that renders a filtered view for one query key. A page that it refuses in either trailing-slash form stays in the function. Default `false`: the function serves each page.
259
+ - `regions`, `memory`, and `maxDuration`: the function's Vercel config. Default the project's. One function serves each route, so the values apply to each request. A route module's `config` export, such as `export const config = { maxDuration: 60 }` for `@vercel/react-router`, does nothing.
234
260
 
235
261
  The function differs from a long-lived process:
236
262
 
237
263
  - Vercel starts and stops it. Each plugin's `setup` runs on the first request of each instance. If a `setup` throws, that request fails, and the next request runs each `setup` again. `onShutdown` never runs, and `shutdownSignal()` never aborts.
238
264
  - The request scheme comes from `X-Forwarded-Proto`, and the client address comes from `X-Real-IP`, because Vercel sets both headers. Do not set `trustForwardedProto` or `trustedProxyHops`. Behind another proxy, such as the ngrok edge, the client address is the proxy's.
239
- - The function does not gzip a response, because the CDN compresses each response. It still sends the build's `.<file>.br` and `.<file>.gz` copies.
265
+ - The function does not compress a response, because the CDN compresses each response.
266
+ - The function keeps only the brotli copy of a file that has one, so it holds one copy of each text file, not three. For a blog with 265 prerendered pages, that makes the function about 50 MB smaller. A client that accepts brotli, as each browser does, gets the copy. For any other client, the function decompresses the copy, and the CDN compresses the response.
240
267
  - The deploy gives each file of the function one fixed modification time. So the function uses the time of the build for each file, and the ETag of each file it sends changes with each build.
241
268
  - `app-server serve` cannot run the build. Use `app-server start` for development, as with the node host.
242
269
 
@@ -246,20 +273,20 @@ The function differs from a long-lived process:
246
273
 
247
274
  1. `health()`: the liveness and readiness probes at `/livez` and `/readyz`. A probe skips the access log. `defaultPlugins({ health })` changes them, and `false` turns them off. See [Health checks](#health-checks).
248
275
  2. `requestId()`: reuses a valid incoming `X-Request-Id`, else makes a UUID, and echoes it.
249
- 3. `accessLog({ redactQuery })`: one line per request when the response ends, for the response that leaves the server, with Datadog standard attributes (`http.status_code`, `network.bytes_written`, `duration` in nanoseconds). Query values are `REDACTED` by default.
250
- 4. `streamingCompress()`: gzip that flushes after each chunk. Chunks that the body has queued together go out as one, up to 16 KiB, so a rendered page costs fewer flushes. When the body ends by the time the gzip stream finishes its last chunk, that chunk and the gzip trailer go out together. On the node host, a body that ends with its first chunk, up to 64 KiB, uses a zlib stream from a pool, so a small page costs no new zlib stream. The pool keeps up to 16 streams between responses, about 4.3 MiB in all. A stream takes only such a body, and only one at least as long as each earlier body of that stream, so the gzip bytes of a body depend on that body alone. It skips encoded, partial, and `no-transform` responses, and a body under 1,024 bytes: by its `Content-Length`, or a body from a string. It adds `Accept-Encoding` to `Vary` only on a type that it can gzip. A static file with a compressed copy from the build gets that copy, and this plugin skips it. It follows the `q` values of `Accept-Encoding`, and `q=0` refuses gzip. The host gives the gzip stream. On a host with none, the plugin does nothing.
276
+ 3. `accessLog({ redactQuery })`: one line per request when the response ends, for the response that leaves the server, with Datadog standard attributes (`http.status_code`, `network.bytes_written`, `duration` in nanoseconds). Query values are `REDACTED` by default. A 5xx line has the level `error`, and each other line has the level `info`. With React Router, a line for a request that React Router answers has the route pattern that it matched as `http.route`, such as `/domains/:domainId`. A prerendered page that the server sends from its file has no `http.route`. In development, a request that Vite answers, such as a source module or `/@vite/client`, gets no line. A request of the `vercel` build's check of the CDN pages gets no line.
277
+ 4. `streamingCompress()`: brotli or gzip that flushes after each chunk. A client gets brotli, at quality 4, when its `Accept-Encoding` ranks `br` at least as high as `gzip`. For HTML, brotli at quality 4 is smaller than gzip, for the same CPU time. For example, a page of 149 KiB in 10 chunks takes 0.60 ms and 7.7 KiB as brotli, and 0.68 ms and 10.6 KiB as gzip, on an Apple M3 Max. The `compression` middleware of Express also uses quality 4. Chunks that the body has queued together go out as one, up to 16 KiB, so a rendered page costs fewer flushes. When the body ends by the time the stream finishes its last chunk, that chunk and the end of the stream go out together. On the node host, a body that ends with its first chunk, up to 64 KiB, uses a zlib stream from a pool, so a small page costs no new zlib stream. Each encoding keeps up to 16 streams between responses. The gzip streams hold about 4.3 MiB in all. A gzip stream takes only such a body, and only one at least as long as each earlier body of that stream, so the gzip bytes of a body depend on that body alone. A reset gives a brotli stream a new encoder, so its bytes also depend on the body alone. On Bun and Deno, each brotli body gets a new stream, because a reset there loses the quality or gives no bytes. It skips encoded, partial, and `no-transform` responses, and a body under 1,024 bytes: by its `Content-Length`, or a body from a string. It adds `Accept-Encoding` to `Vary` only on a compressible type, the same types that get a copy from the build. A static file with a compressed copy from the build gets that copy, and this plugin skips it. It follows the `q` values of `Accept-Encoding`, and `q=0` refuses an encoding. The host gives the streams. On a host with neither, the plugin does nothing.
251
278
  5. `securityHeaders()`: safe default security headers on each response, prerendered pages included. `defaultPlugins({ securityHeaders })` changes them, and `false` turns them off. See [Security headers](#security-headers).
252
279
  6. `bodyLimit({ maxBytes })`: a 413 for a request body over `defaultPlugins({ bodyLimit })`, 10 mebibytes (MiB) by default. `false` turns it off. A `Content-Length` that is too large gets the 413 before the app runs. A streamed body errors when it passes the limit. When the app reads the body before it answers, the response becomes a 413. When the app streams the body into its response, the response stream errors. A `bodyLimit` that is not a whole number of 0 or more stops startup. The body streams. The plugin does not read it into memory.
253
280
  7. The plugins of the named options. They see every response, prerendered pages included:
254
- - `noindex()`, with `defaultPlugins({ noindex: true })`. See [Preview deploys](#preview-deploys).
281
+ - `noindex()`, with `defaultPlugins({ noindex })`. See [Preview deploys](#preview-deploys).
255
282
  - `buildId()`, on by default. `defaultPlugins({ buildId })` changes it, and `false` turns it off. See [Deploys and open tabs](#deploys-and-open-tabs).
256
283
  - `contentSecurityPolicy()`, with `defaultPlugins({ contentSecurityPolicy })`. See [A CSP for each document](#a-csp-for-each-document).
257
284
  - The plugin from `runtimeEnv()`, with `defaultPlugins({ env })`. See [Environment](#environment).
258
285
  8. The `beforeStatic` plugins: the app's own plugins that see every response, prerendered pages included, such as an auth check. They come after the plugins of the named options, so they get the CSP nonce, and their responses get the headers of those plugins.
259
- 9. `assets()`: `/assets/*` with a one-year immutable cache. A missing asset gets a plain 404 with `Cache-Control: no-store`. In development, Vite serves here. See [Deploys and open tabs](#deploys-and-open-tabs).
286
+ 9. `assets()`: the files of Vite's `build.assetsDir` (`/assets/*` by default) with a one-year immutable cache. The `appServer` Vite plugin records the directory in `.app-server.json`. A missing asset gets a plain 404 with `Cache-Control: no-store`. In development, Vite serves here. See [Deploys and open tabs](#deploys-and-open-tabs).
260
287
  10. `redirects(rules)`, when `defaultPlugins({ redirects })` has rules: a redirect from each old URL to its new URL. See [Redirects](#redirects).
261
288
  11. `trailingSlash({ mode })`: a 308 from a page URL to the same URL in the site's trailing-slash form. See [Trailing slashes](#trailing-slashes).
262
- 12. `prerendered({ headers, rewrite, skip, cacheControl })`: every file in the client build, with an ETag, a 304 for a matching `If-None-Match`, and a 206 for one byte range of a file that is not HTML. An HTML page, a markdown file, and a data file of the framework get `Cache-Control: public, max-age=0, must-revalidate`, and every other file gets `public, max-age=3600, stale-while-revalidate=86400`. A captured header, the `headers` option, and `cacheControl` change it. A file with a compressed copy from the build gets `Vary: Accept-Encoding`. A client gets the copy that its `Accept-Encoding` prefers, brotli before gzip, with no byte ranges and an ETag for that encoding. A `no-transform` response never gets a copy, and an HTML page gets none when `runtimeEnv` adds values to it. A directory answers with its `index.html`. Each file has one URL: `/a//b`, `/a/index.html`, and `/a%2Fb` go on to the framework. Dotfiles stay private, except `/.well-known/`. A path with no file, or a path that `skip` matches, goes on to the framework.
289
+ 12. `prerendered({ headers, rewrite, skip, cacheControl })`: every file in the client build, with its content type, an ETag, a 304 for a matching `If-None-Match`, and a 206 for one byte range of a file that is not HTML. An HTML page, a markdown file, and a data file of the framework get `Cache-Control: public, max-age=0, must-revalidate`, and every other file gets `public, max-age=3600, stale-while-revalidate=86400`. A captured header, the `headers` option, and `cacheControl` change it. A file with a compressed copy from the build gets `Vary: Accept-Encoding`. A client gets the copy that its `Accept-Encoding` prefers, brotli before gzip, with no byte ranges and an ETag for that encoding. A `no-transform` response never gets a copy, and an HTML page gets none when `runtimeEnv` adds values to it. A directory answers with its `index.html`. Each file has one URL: `/a//b`, `/a/index.html`, and `/a%2Fb` go on to the framework. Dotfiles stay private, except `/.well-known/`. A path with no file, or a path that `skip` matches, goes on to the framework. The content type comes from the file's extension. Besides the types that Hono knows, `.sh` gets `application/x-sh`, `.yaml` and `.yml` get `text/yaml`, `.rss` gets `application/rss+xml`, `.atom` gets `application/atom+xml`, and `.pem` gets `application/x-pem-file`, as with `express.static`. An unknown extension gets `application/octet-stream`.
263
290
  13. `privateDocuments()`: `Cache-Control: private, no-cache` on each HTML document and each framework data response (such as a React Router `.data` request) from the app's routes or the framework that has no `Cache-Control`. A shared cache then never keeps a page or loader data that the server rendered for one user. A response with its own `Cache-Control` keeps it. A resource route that sends per-user JSON sets its own `Cache-Control`.
264
291
 
265
292
  A route that takes a body larger than the limit needs a higher `bodyLimit` for the whole app, because each request passes the limit before it reaches a route.
@@ -342,7 +369,7 @@ export default createServer({ plugins: defaultPlugins({ beforeStatic: [auth] })
342
369
  - `Cross-Origin-Opener-Policy: same-origin`
343
370
  - `Strict-Transport-Security: max-age=31536000`, on an HTTPS request only
344
371
 
345
- A response that has one of these headers keeps its own value. `false` turns a header off, and `defaultPlugins({ securityHeaders: false })` turns them all off.
372
+ `Content-Security-Policy` and `Permissions-Policy` have no default. A response that has one of these headers keeps its own value. `false` turns a header off, and `defaultPlugins({ securityHeaders: false })` turns them all off.
346
373
 
347
374
  ```ts
348
375
  defaultPlugins({
@@ -351,6 +378,7 @@ defaultPlugins({
351
378
  "Cross-Origin-Opener-Policy": "same-origin-allow-popups",
352
379
  "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
353
380
  "Content-Security-Policy": "frame-ancestors 'none'",
381
+ "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
354
382
  },
355
383
  },
356
384
  });
@@ -433,7 +461,7 @@ export function getRouter() {
433
461
 
434
462
  After a deploy, an open tab still runs the old build. Two things can then go wrong:
435
463
 
436
- - **Old assets.** The tab asks for a chunk of its own build, such as `/assets/route-3f9a1c.js`, and the new server does not have it. Keep the `/assets/*` files of each build, with their `.<file>.gz` and `.<file>.br` copies, in storage that a deploy never deletes, such as an object store behind the CDN. File names are content hashes, so the builds never collide. The server sends `Cache-Control: no-store` with a missing asset, so a CDN does not keep the 404.
464
+ - **Old assets.** The tab asks for a chunk of its own build, such as `/assets/route-3f9a1c.js`, and the new server does not have it. Keep the files of Vite's `build.assetsDir` (`/assets/*` by default) of each build, with their `.<file>.gz` and `.<file>.br` copies, in storage that a deploy never deletes, such as an object store behind the CDN. File names are content hashes, so the builds never collide. The server sends `Cache-Control: no-store` with a missing asset, so a CDN does not keep the 404.
437
465
  - **New data for old code.** The router fetches data from the new server, such as a React Router `.data` file or a TanStack Start server function, and the old code renders it. A changed loader can break the page.
438
466
 
439
467
  `buildId()` and the client module fix the second problem at the next navigation, and the page that the visitor reads never reloads. For React Router, create the module once, and give its three hooks to the router:
@@ -600,6 +628,14 @@ defaultPlugins({
600
628
  defaultPlugins({ noindex: process.env.PREVIEW === "1" });
601
629
  ```
602
630
 
631
+ To allow indexing only for a request with a header, give `unlessHeader`. Each response gets the header in `Vary`, so a CDN keeps one answer for each case. For example, to allow indexing only for a request through the ngrok edge, which adds `x-ngrok-edge`:
632
+
633
+ ```ts
634
+ defaultPlugins({ noindex: { unlessHeader: "x-ngrok-edge" } });
635
+ ```
636
+
637
+ On the `vercel` host with `cdnPages`, the CDN serves the page and picks the answer by the header. See [Prerendered pages on the CDN](#prerendered-pages-on-the-cdn).
638
+
603
639
  ## Content negotiation
604
640
 
605
641
  One URL can answer HTML to a browser and markdown to an agent, per [acceptmarkdown.com](https://acceptmarkdown.com). `prefersMarkdown(request)` decides which answer a request gets. Use it in the server, in a plugin, and in the app, so each place answers one request the same way.
@@ -708,7 +744,7 @@ A resource route, or a TanStack Start server route, gets the same `Request`. Cal
708
744
 
709
745
  During the framework's prerender pass, `appServer` records each prerendered path and the response headers of each prerendered file that is not an HTML document into `.app-server.json` in the client build. `prerendered()` replays the headers. It leaves out `Set-Cookie`, `Vary`, and the headers of one transfer, such as `Content-Length`. When the framework does not list its prerendered paths, as with TanStack Start, the server reads them from this file.
710
746
 
711
- A document's headers are not recorded, because the framework sets them for each request (a CSP nonce, the host). Set the headers of a prerendered page with the `headers` option or a plugin. The file also records the hash of each inline script of each HTML file in the client build, so `contentSecurityPolicy()` can give a prerendered page a CSP. See [A CSP for each document](#a-csp-for-each-document). It also holds the build ID. See [Deploys and open tabs](#deploys-and-open-tabs).
747
+ A document's headers are not recorded, because the framework sets them for each request (a CSP nonce, the host). Set the headers of a prerendered page with the `headers` option or a plugin. The file also records the hash of each inline script of each HTML file in the client build, so `contentSecurityPolicy()` can give a prerendered page a CSP. See [A CSP for each document](#a-csp-for-each-document). It also holds the build ID (see [Deploys and open tabs](#deploys-and-open-tabs)) and the URL path of Vite's `build.assetsDir`.
712
748
 
713
749
  ## Logs
714
750
 
@@ -808,7 +844,7 @@ The values whose names start with `PUBLIC_` go into each HTML document at serve
808
844
  const publicEnv = JSON.parse(document.getElementById("app-server-public-env")?.textContent ?? "{}");
809
845
  ```
810
846
 
811
- When there are public values, the server sends each prerendered page from its file, not from its compressed copy, because the values change the bytes of the page. `streamingCompress()` then gzips the page for each request.
847
+ When there are public values, the server sends each prerendered page from its file, not from its compressed copy, because the values change the bytes of the page. `streamingCompress()` then compresses the page for each request.
812
848
 
813
849
  ## Long-lived responses
814
850
 
@@ -860,9 +896,9 @@ const html = await withRequestContext({ cspNonce: "test-nonce" }, () => renderTo
860
896
  A framework adapter or a host adapter is two small objects. A third-party adapter uses the same contract.
861
897
 
862
898
  - `FrameworkBuild` (from `@ngrok/app-server/vite`): the framework's server module, the module of the run side, how to detect the prerender pass, and a check of the Vite config.
863
- - `FrameworkRuntime` (from `@ngrok/app-server`): `fetch(request, context)`, plus, when the framework has them, its client build, its prerendered paths, its data requests, and the content types that `mime` lacks. The run-side module exports `runtime(serverModule, { mode })`.
864
- - `HostBuild` (from `@ngrok/app-server/vite`): the module of the run side, the file name of the server entry, and an optional `output` that writes the host's deploy output after the build, such as `.vercel/output`.
865
- - `HostRuntime` (from `@ngrok/app-server`): the client build's files, the default listeners (a serverless host has none), request storage for `requestContext()`, a gzip stream, and a lifecycle for a long-lived process. The run-side module exports `host`. `files(...).open(path, range)` must honor `range`, because the static stages send those bytes in a 206. An optional `files(...).snapshot()` lists the client build once. The production server calls it at start, answers each lookup from that list, and keeps each file up to 256 KiB in memory after the first read, up to 32 MiB in all. The `.<file>.gz` and `.<file>.br` copies count in that limit. A client that accepts brotli reads only the `.br` copies, so the copies make the memory that a site needs smaller. If clients read each file in all three forms, a large site can need more than 32 MiB. Then the files that the server reads last stream from disk. Restart the server after you change the client build. A file that you remove while it runs gets a 500, unless it is in memory.
899
+ - `FrameworkRuntime` (from `@ngrok/app-server`): `fetch(request, context)`, plus, when the framework has them, its client build, its prerendered paths, its data requests, and the content types that `mime` lacks. The run-side module exports `runtime(serverModule, { mode })`. To give the access log `http.route`, `fetch` sets `routePattern` on the Hono context to the route pattern that the request matched.
900
+ - `HostBuild` (from `@ngrok/app-server/vite`): the module of the run side, the file name of the server entry, and an optional `output` that writes the host's deploy output after the build, such as `.vercel/output`. `output` gets the paths of the build and the URL path of Vite's `build.assetsDir`.
901
+ - `HostRuntime` (from `@ngrok/app-server`): the client build's files, the default listeners (a serverless host has none), request storage for `requestContext()`, gzip and brotli streams, and a lifecycle for a long-lived process. The run-side module exports `host`. `files(...).open(path, range)` must honor `range`, because the static stages send those bytes in a 206. An optional `files(...).snapshot()` lists the client build once. The production server calls it at start, answers each lookup from that list, and keeps each file up to 256 KiB in memory after the first read, up to 32 MiB in all. The `.<file>.gz` and `.<file>.br` copies count in that limit. A client that accepts brotli reads only the `.br` copies, so the copies make the memory that a site needs smaller. If clients read each file in all three forms, a large site can need more than 32 MiB. Then the files that the server reads last stream from disk. Restart the server after you change the client build. A file that you remove while it runs gets a 500, unless it is in memory.
866
902
  - `ResponseEdge` (from `@ngrok/app-server`): for a listener that writes each response itself. The listener makes one for each request and gives it as the `edge` binding. The server runs the header hooks on a list of the headers and keeps the list in the edge, so it copies no response for them. The listener writes `edge.headersFor(response)` in place of the headers of the response, adds each body byte to `edge.bytes`, gives an error that stops the response to `edge.fail`, and calls `edge.close(status, aborted, head)` once, with the status and the header list that it sent. The access log takes its line from that report. Only the first request that gets an edge uses it: a request that the app sends through itself again with `c.env` changes its own response. The node host's listener on Node.js and the vercel handler give one. Without it, as on Bun and Deno, the server makes one new response with the headers after the hooks and a body that counts its bytes.
867
903
 
868
904
  ## Options
@@ -885,3 +921,7 @@ A framework adapter or a host adapter is two small objects. A third-party adapte
885
921
  - One server process uses one CPU core. To use more cores, run one replica or one container for each core behind the load balancer.
886
922
  - The package has two host adapters, `node` and `vercel`. Another host, such as Cloudflare Workers, needs its own adapter. See `HostRuntime` and `HostBuild`. A serverless host calls the `fetch` of the build's `appServer` export for each request. The build also exports `hostModule`, the host's run-side module, so a function file can call it through the bundle's copy.
887
923
  - On Deno, `Deno.serve` logs a notice about its legacy `request.signal` behavior.
924
+
925
+ ## Contributing
926
+
927
+ Each change meets the six goals of the [north star](./docs/north-star.md): correct, least surprising, fast, delightful, clean, and efficient. [AGENTS.md](./AGENTS.md) is the guide for humans and agents. It lists the goals, the [principles](./docs/principles/README.md) that serve them, and the checks to run before a pull request.
@@ -0,0 +1,97 @@
1
+ import { r as copyName } from "./compression-CT2mWlKM.js";
2
+ import { createBrotliDecompress } from "node:zlib";
3
+ import { Duplex } from "node:stream";
4
+
5
+ // src/vercel/brotli-only.ts
6
+ /**
7
+ * The URL path of the list that `vercel()` writes in the function's client
8
+ * build: the size of each file whose only copy in the function is its brotli
9
+ * copy, by the URL path of the file. Why a dotfile: the static stages never
10
+ * serve one.
11
+ */
12
+ const BROTLI_ONLY_LIST = "/.app-server-brotli.json";
13
+ /** The URL path of the brotli copy of the file at `path`. */
14
+ function brotliCopy(path) {
15
+ const slash = path.lastIndexOf("/");
16
+ return `${path.slice(0, slash + 1)}${copyName(path.slice(slash + 1), "br")}`;
17
+ }
18
+ /** The bytes of `range` in `stream`. It cancels `stream` after the last byte. */
19
+ function sliced(stream, { start, end }) {
20
+ let position = 0;
21
+ return stream.pipeThrough(new TransformStream({ transform(chunk, controller) {
22
+ const from = Math.max(start - position, 0);
23
+ const to = Math.min(end + 1 - position, chunk.byteLength);
24
+ position += chunk.byteLength;
25
+ if (to > from) controller.enqueue(chunk.subarray(from, to));
26
+ if (position > end) controller.terminate();
27
+ } }));
28
+ }
29
+ /**
30
+ * The bytes of the stream that `open` gives, with `open` called on the first
31
+ * read. Why: a pipe reads its source at once, and a stage can drop a response
32
+ * that no one reads.
33
+ */
34
+ function decodedOnRead(open) {
35
+ let reader;
36
+ return new ReadableStream({
37
+ async pull(controller) {
38
+ reader ??= open().then((stream) => stream.getReader());
39
+ const { done, value } = await (await reader).read();
40
+ if (done) controller.close();
41
+ else controller.enqueue(value);
42
+ },
43
+ async cancel(reason) {
44
+ await (await reader)?.cancel(reason);
45
+ }
46
+ }, { highWaterMark: 0 });
47
+ }
48
+ /**
49
+ * `files` that also find each file in {@link BROTLI_ONLY_LIST}, with the
50
+ * size from the list and the time of its brotli copy. Each read of such a
51
+ * file decompresses its brotli copy. Why: a function then keeps one copy of
52
+ * the file, not three, and a client that accepts brotli, as each browser
53
+ * does, gets the copy with no work.
54
+ *
55
+ * @example
56
+ * brotliOnlyFiles(nodeFiles("build/client")).open("/blog/index.html");
57
+ */
58
+ function brotliOnlyFiles(files) {
59
+ let sizes;
60
+ const readSizes = async () => {
61
+ sizes ??= files.stat(BROTLI_ONLY_LIST).then(async (info) => {
62
+ if (info?.kind !== "file") return /* @__PURE__ */ new Map();
63
+ const text = await new Response(await files.open(BROTLI_ONLY_LIST)).text();
64
+ return new Map(Object.entries(JSON.parse(text)));
65
+ });
66
+ return sizes;
67
+ };
68
+ const wrap = (inner) => {
69
+ const { snapshot } = inner;
70
+ return {
71
+ stat: async (path) => {
72
+ const info = await inner.stat(path);
73
+ const size = info == null ? (await readSizes()).get(path) : void 0;
74
+ if (size == null) return info;
75
+ const copy = await inner.stat(brotliCopy(path));
76
+ return copy?.kind === "file" ? {
77
+ kind: "file",
78
+ size,
79
+ mtimeMs: copy.mtimeMs
80
+ } : void 0;
81
+ },
82
+ open: async (path, range) => {
83
+ if (!(await readSizes()).has(path)) return inner.open(path, range);
84
+ return decodedOnRead(async () => {
85
+ const decompress = Duplex.toWeb(createBrotliDecompress());
86
+ const decoded = (await inner.open(brotliCopy(path))).pipeThrough(decompress);
87
+ return range == null ? decoded : sliced(decoded, range);
88
+ });
89
+ },
90
+ ...snapshot == null ? {} : { snapshot: async () => wrap(await snapshot()) }
91
+ };
92
+ };
93
+ return wrap(files);
94
+ }
95
+
96
+ export { brotliOnlyFiles as n, BROTLI_ONLY_LIST as t };
97
+ //# sourceMappingURL=brotli-only-DrA29Ecw.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"brotli-only-DrA29Ecw.js","names":[],"sources":["../src/vercel/brotli-only.ts"],"sourcesContent":["import { Duplex } from \"node:stream\";\nimport { createBrotliDecompress } from \"node:zlib\";\nimport { copyName } from \"../core/compression.js\";\nimport type { ByteRange, StaticFiles } from \"../core/types.js\";\n\n/**\n * The URL path of the list that `vercel()` writes in the function's client\n * build: the size of each file whose only copy in the function is its brotli\n * copy, by the URL path of the file. Why a dotfile: the static stages never\n * serve one.\n */\nexport const BROTLI_ONLY_LIST = \"/.app-server-brotli.json\";\n\n/** The URL path of the brotli copy of the file at `path`. */\nfunction brotliCopy(path: string): string {\n\tconst slash = path.lastIndexOf(\"/\");\n\treturn `${path.slice(0, slash + 1)}${copyName(path.slice(slash + 1), \"br\")}`;\n}\n\n/** The bytes of `range` in `stream`. It cancels `stream` after the last byte. */\nfunction sliced(stream: ReadableStream<Uint8Array>, { start, end }: ByteRange) {\n\tlet position = 0;\n\treturn stream.pipeThrough(\n\t\tnew TransformStream<Uint8Array, Uint8Array>({\n\t\t\ttransform(chunk, controller) {\n\t\t\t\tconst from = Math.max(start - position, 0);\n\t\t\t\tconst to = Math.min(end + 1 - position, chunk.byteLength);\n\t\t\t\tposition += chunk.byteLength;\n\t\t\t\tif (to > from) {\n\t\t\t\t\tcontroller.enqueue(chunk.subarray(from, to));\n\t\t\t\t}\n\t\t\t\tif (position > end) {\n\t\t\t\t\tcontroller.terminate();\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t);\n}\n\n/**\n * The bytes of the stream that `open` gives, with `open` called on the first\n * read. Why: a pipe reads its source at once, and a stage can drop a response\n * that no one reads.\n */\nfunction decodedOnRead(\n\topen: () => Promise<ReadableStream<Uint8Array>>,\n): ReadableStream<Uint8Array> {\n\tlet reader: Promise<ReadableStreamDefaultReader<Uint8Array>> | undefined;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\treader ??= open().then((stream) => stream.getReader());\n\t\t\t\tconst { done, value } = await (await reader).read();\n\t\t\t\tif (done) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync cancel(reason) {\n\t\t\t\tawait (await reader)?.cancel(reason);\n\t\t\t},\n\t\t},\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * `files` that also find each file in {@link BROTLI_ONLY_LIST}, with the\n * size from the list and the time of its brotli copy. Each read of such a\n * file decompresses its brotli copy. Why: a function then keeps one copy of\n * the file, not three, and a client that accepts brotli, as each browser\n * does, gets the copy with no work.\n *\n * @example\n * brotliOnlyFiles(nodeFiles(\"build/client\")).open(\"/blog/index.html\");\n */\nexport function brotliOnlyFiles(files: StaticFiles): StaticFiles {\n\tlet sizes: Promise<ReadonlyMap<string, number>> | undefined;\n\t// Why once and late: the list does not change while the function runs, and a file found on\n\t// disk does not need it.\n\tconst readSizes = async () => {\n\t\tsizes ??= files.stat(BROTLI_ONLY_LIST).then(async (info) => {\n\t\t\tif (info?.kind !== \"file\") {\n\t\t\t\treturn new Map<string, number>();\n\t\t\t}\n\t\t\tconst text = await new Response(await files.open(BROTLI_ONLY_LIST)).text();\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `vercel()` of this package wrote the file.\n\t\t\treturn new Map(Object.entries(JSON.parse(text) as Record<string, number>));\n\t\t});\n\t\treturn sizes;\n\t};\n\tconst wrap = (inner: StaticFiles): StaticFiles => {\n\t\tconst { snapshot } = inner;\n\t\treturn {\n\t\t\tstat: async (path) => {\n\t\t\t\tconst info = await inner.stat(path);\n\t\t\t\tconst size = info == null ? (await readSizes()).get(path) : undefined;\n\t\t\t\tif (size == null) {\n\t\t\t\t\treturn info;\n\t\t\t\t}\n\t\t\t\tconst copy = await inner.stat(brotliCopy(path));\n\t\t\t\treturn copy?.kind === \"file\" ? { kind: \"file\", size, mtimeMs: copy.mtimeMs } : undefined;\n\t\t\t},\n\t\t\topen: async (path, range) => {\n\t\t\t\tif (!(await readSizes()).has(path)) {\n\t\t\t\t\treturn inner.open(path, range);\n\t\t\t\t}\n\t\t\t\treturn decodedOnRead(async () => {\n\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Node.js types its web streams apart from the global ones.\n\t\t\t\t\tconst decompress = Duplex.toWeb(createBrotliDecompress()) as ReadableWritablePair<\n\t\t\t\t\t\tUint8Array,\n\t\t\t\t\t\tUint8Array\n\t\t\t\t\t>;\n\t\t\t\t\tconst decoded = (await inner.open(brotliCopy(path))).pipeThrough(decompress);\n\t\t\t\t\treturn range == null ? decoded : sliced(decoded, range);\n\t\t\t\t});\n\t\t\t},\n\t\t\t...(snapshot == null ? {} : { snapshot: async () => wrap(await snapshot()) }),\n\t\t};\n\t};\n\treturn wrap(files);\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,mBAAmB;;AAGhC,SAAS,WAAW,MAAsB;CACzC,MAAM,QAAQ,KAAK,YAAY,GAAG;CAClC,OAAO,GAAG,KAAK,MAAM,GAAG,QAAQ,CAAC,IAAI,SAAS,KAAK,MAAM,QAAQ,CAAC,GAAG,IAAI;AAC1E;;AAGA,SAAS,OAAO,QAAoC,EAAE,OAAO,OAAkB;CAC9E,IAAI,WAAW;CACf,OAAO,OAAO,YACb,IAAI,gBAAwC,EAC3C,UAAU,OAAO,YAAY;EAC5B,MAAM,OAAO,KAAK,IAAI,QAAQ,UAAU,CAAC;EACzC,MAAM,KAAK,KAAK,IAAI,MAAM,IAAI,UAAU,MAAM,UAAU;EACxD,YAAY,MAAM;EAClB,IAAI,KAAK,MACR,WAAW,QAAQ,MAAM,SAAS,MAAM,EAAE,CAAC;EAE5C,IAAI,WAAW,KACd,WAAW,UAAU;CAEvB,EACD,CAAC,CACF;AACD;;;;;;AAOA,SAAS,cACR,MAC6B;CAC7B,IAAI;CACJ,OAAO,IAAI,eACV;EACC,MAAM,KAAK,YAAY;GACtB,WAAW,KAAK,CAAC,CAAC,MAAM,WAAW,OAAO,UAAU,CAAC;GACrD,MAAM,EAAE,MAAM,UAAU,OAAO,MAAM,OAAM,CAAE,KAAK;GAClD,IAAI,MACH,WAAW,MAAM;QAEjB,WAAW,QAAQ,KAAK;EAE1B;EACA,MAAM,OAAO,QAAQ;GACpB,OAAO,MAAM,OAAM,EAAG,OAAO,MAAM;EACpC;CACD,GACA,EAAE,eAAe,EAAE,CACpB;AACD;;;;;;;;;;;AAYA,SAAgB,gBAAg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(option != null) seen.add(option);
34
34
  }
35
35
  }
36
+ /** The request headers whose presence alone changes the answer of each plugin, by plugin object. */
37
+ const presence = /* @__PURE__ */ new WeakMap();
38
+ /**
39
+ * Marks `plugin` as one whose changes to a response depend only on whether
40
+ * each of `headers` is present in the request. Why: the build can then put
41
+ * one static answer for each case on a CDN, which picks the answer by the
42
+ * same headers.
43
+ *
44
+ * @example
45
+ * return presenceHeaders(["x-ngrok-edge"], { name: "noindex", middleware });
46
+ */
47
+ function presenceHeaders(headers, plugin) {
48
+ presence.set(plugin, headers);
49
+ return plugin;
50
+ }
51
+ /**
52
+ * The headers that {@link presenceHeaders} marked on `plugins`, in lowercase,
53
+ * once each.
54
+ *
55
+ * @example
56
+ * presenceHeadersOf(defaultPlugins({ noindex: { unlessHeader: "X-Ngrok-Edge" } })); // => ["x-ngrok-edge"]
57
+ */
58
+ function presenceHeadersOf(plugins) {
59
+ return [...new Set(plugins.flatMap((plugin) => presence.get(plugin) ?? []).map((name) => name.toLowerCase()))];
60
+ }
36
61
 
37
62
  // src/core/plugins/build-id.ts
38
63
  /** The header that {@link buildId} sets by default. */
@@ -122,5 +147,5 @@ function buildId({ header = BUILD_ID_HEADER, value: given, paths } = {}) {
122
147
  });
123
148
  }
124
149
 
125
- export { serverTimingMetrics as a, isBuildMetric as i, BUILD_ID_METRIC as n, checkOptionPlugins as o, buildId as r, optionPlugin as s, BUILD_ID_HEADER as t };
126
- //# sourceMappingURL=build-id-C6sYO9Yp.js.map
150
+ export { serverTimingMetrics as a, presenceHeaders as c, isBuildMetric as i, presenceHeadersOf as l, BUILD_ID_METRIC as n, checkOptionPlugins as o, buildId as r, optionPlugin as s, BUILD_ID_HEADER as t };
151
+ //# sourceMappingURL=build-id-B0448vZH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-id-B0448vZH.js","names":[],"sources":["../src/core/plugin-options.ts","../src/core/plugins/build-id.ts"],"sourcesContent":["import type { Plugin } from \"./types.js\";\n\n/**\n * The option of `defaultPlugins()` that places each plugin, by plugin\n * object. Why the object, not the name: an app plugin can have any name.\n */\nconst options = new WeakMap<Plugin, string>();\n\n/**\n * Marks `plugin` as the plugin of the `option` of `defaultPlugins()`, so\n * `createServer` finds it in the plugin list.\n *\n * @example\n * return optionPlugin(\"noindex\", { name: \"noindex\", middleware });\n */\nexport function optionPlugin<P extends Plugin>(option: string, plugin: P): P {\n\toptions.set(plugin, option);\n\treturn plugin;\n}\n\n/**\n * Stops startup when `plugins` has two plugins of one option of\n * `defaultPlugins()`, such as two `buildId()`. Why: two copies do not fail.\n * One sets its headers over the other, so a value that the app gave is lost.\n *\n * @example\n * checkOptionPlugins([...defaultPlugins(), buildId({ value: \"v42\" })]); // throws\n */\nexport function checkOptionPlugins(plugins: readonly Plugin[]): void {\n\tconst seen = new Set<string>();\n\tfor (const plugin of plugins) {\n\t\tconst option = options.get(plugin);\n\t\tif (option != null && seen.has(option)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The plugin list has the ${plugin.name} plugin two times, so one replaces the other. Keep one: set the \"${option}\" option of defaultPlugins(), and do not also add the plugin.`,\n\t\t\t);\n\t\t}\n\t\tif (option != null) {\n\t\t\tseen.add(option);\n\t\t}\n\t}\n}\n\n/** The request headers whose presence alone changes the answer of each plugin, by plugin object. */\nconst presence = new WeakMap<Plugin, readonly string[]>();\n\n/**\n * Marks `plugin` as one whose changes to a response depend only on whether\n * each of `headers` is present in the request. Why: the build can then put\n * one static answer for each case on a CDN, which picks the answer by the\n * same headers.\n *\n * @example\n * return presenceHeaders([\"x-ngrok-edge\"], { name: \"noindex\", middleware });\n */\nexport function presenceHeaders<P extends Plugin>(headers: readonly string[], plugin: P): P {\n\tpresence.set(plugin, headers);\n\treturn plugin;\n}\n\n/**\n * The headers that {@link presenceHeaders} marked on `plugins`, in lowercase,\n * once each.\n *\n * @example\n * presenceHeadersOf(defaultPlugins({ noindex: { unlessHeader: \"X-Ngrok-Edge\" } })); // => [\"x-ngrok-edge\"]\n */\nexport function presenceHeadersOf(plugins: readonly Plugin[]): string[] {\n\treturn [\n\t\t...new Set(\n\t\t\tplugins.flatMap((plugin) => presence.get(plugin) ?? []).map((name) => name.toLowerCase()),\n\t\t),\n\t];\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { Plugin, ResponseHeaders, SetupInfo } from \"../types.js\";\n\n/** The header that {@link buildId} sets by default. */\nexport const BUILD_ID_HEADER = \"X-Build-Id\";\n\n/**\n * The `Server-Timing` metric that holds the build of a response. Why\n * `Server-Timing`: a script can read it from the performance entries, with no\n * request and no change to the document's HTML.\n */\nexport const BUILD_ID_METRIC = \"build\";\n\n/** Options for {@link buildId}. */\nexport type BuildIdOptions = {\n\t/** @default \"X-Build-Id\" */\n\theader?: string;\n\t/**\n\t * The deployed build, such as the image tag. With no value or `\"\"`, the\n\t * plugin sends the ID that the `appServer` Vite plugin derives from the\n\t * client build. In development, it then sends no build.\n\t * @default the `buildId` of `.app-server.json` in the client build\n\t */\n\tvalue?: string | undefined;\n\t/**\n\t * More request paths whose responses carry the build in `Server-Timing`,\n\t * such as the app's proxy routes to its API. A tab then finds a new build\n\t * in the requests that it already sends. They get no build header, because\n\t * the header marks the router's own responses. A response that a cache can\n\t * use again without the server gets no build, so a cached copy never\n\t * reports an old build. It runs in a header hook, so it can run more than\n\t * once for one request.\n\t *\n\t * @example\n\t * buildId({ paths: (path) => path.startsWith(\"/api/\") });\n\t */\n\tpaths?: (path: string) => boolean;\n};\n\n/**\n * Whether a cache can use the response again without the server: it has a\n * fresh time, a stale time, or a date that a cache can guess a fresh time from.\n */\nfunction isReusable(response: ResponseHeaders): boolean {\n\tconst cacheControl = response.get(\"Cache-Control\") ?? \"\";\n\tif (/\\b(?:no-store|no-cache)\\b/iu.test(cacheControl)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t/\\b(?:max-age|s-maxage|stale-while-revalidate|stale-if-error)\\s*=\\s*\"?0*[1-9]/iu.test(\n\t\t\tcacheControl,\n\t\t) ||\n\t\t/\\bpublic\\b/iu.test(cacheControl) ||\n\t\tDate.parse(response.get(\"Expires\") ?? \"\") > Date.now() ||\n\t\tresponse.has(\"Last-Modified\")\n\t);\n}\n\n/** The metrics of a `Server-Timing` header, such as `build;desc=\"v42\"`. */\nexport function serverTimingMetrics(header: string | null): string[] {\n\t// Why match the quoted strings: a comma or an escaped quote in a description does not end a metric.\n\treturn (header?.match(/(?:[^\",]|\"(?:[^\"\\\\]|\\\\.)*\")+/gu) ?? [])\n\t\t.map((metric) => metric.trim())\n\t\t.filter((metric) => metric !== \"\");\n}\n\n/** Whether a `Server-Timing` metric is a build. */\nexport function isBuildMetric(metric: string): boolean {\n\treturn metric.split(\";\")[0]?.trim().toLowerCase() === BUILD_ID_METRIC;\n}\n\n/** The `Server-Timing` metrics of `header` that are not a build. */\nfunction otherMetrics(header: string | null): string[] {\n\treturn serverTimingMetrics(header).filter((metric) => !isBuildMetric(metric));\n}\n\n/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/** A `Server-Timing` quoted string with the characters of `value`. */\nfunction quoted(value: string): string {\n\treturn `\"${value.replaceAll(/[\"\\\\]/gu, String.raw`\\$&`)}\"`;\n}\n\n/** The `build` metric of `value`, or `undefined` for no build. */\nfunction buildMetric(value: string | undefined): string | undefined {\n\treturn value == null ? undefined : `${BUILD_ID_METRIC};desc=${quoted(value)}`;\n}\n\n/**\n * Sets a build ID header on documents and on the framework's data responses,\n * such as React Router `.data` files, so a client can see that a deploy\n * happened under it. Each of them also gets the build as\n * `Server-Timing: build;desc=\"<value>\"`. The `paths` option adds the metric\n * to more routes, such as API proxy routes. The plugin removes the build\n * header and the `build` metric of an upstream API from each other\n * response, so the client reads only this app's build.\n * `staleBuildReactRouter()` and `staleBuildTanStack()` from `@ngrok/app-server/client` read the metric\n * from the document, and from a response that the browser fetches with no\n * script, such as a prefetch.\n *\n * With no `value`, it sends the build ID that the `appServer` Vite plugin\n * derives from the client build. Development and a build with no\n * `.app-server.json` then get no build.\n *\n * @example\n * buildId({ value: process.env.IMAGE_TAG });\n */\nexport function buildId({\n\theader = BUILD_ID_HEADER,\n\tvalue: given,\n\tpaths,\n}: BuildIdOptions = {}): Plugin {\n\t// Why `\"\"` too: a deploy can set the variable with no value, such as `IMAGE_TAG=`.\n\tconst explicit = given === \"\" ? undefined : given;\n\tlet value = explicit;\n\tlet timing = buildMetric(value);\n\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn optionPlugin(\"buildId\", {\n\t\tname: \"build-id\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t\tvalue = explicit ?? info.buildId;\n\t\t\ttiming = buildMetric(value);\n\t\t},\n\t\t// Why: a 304 has no `Content-Type`, so a document that did not change on disk must still\n\t\t// answer 200 when the build ID changes.\n\t\tetagPart: () => value,\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (response) => {\n\t\t\t\tconst { path } = context.req;\n\t\t\t\tconst isRouter =\n\t\t\t\t\t(response.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) || isDataRequest(path);\n\t\t\t\tconst isStamped = isRouter || (paths?.(path) === true && !isReusable(response));\n\t\t\t\t// Why remove the build of an upstream API: the client must read only this app's build.\n\t\t\t\tconst before = response.get(\"Server-Timing\");\n\t\t\t\tconst metrics = [\n\t\t\t\t\t...otherMetrics(before),\n\t\t\t\t\t...(isStamped && timing != null ? [timing] : []),\n\t\t\t\t].join(\", \");\n\t\t\t\tif (metrics === \"\") {\n\t\t\t\t\tresponse.delete(\"Server-Timing\");\n\t\t\t\t} else if (metrics !== before) {\n\t\t\t\t\tresponse.set(\"Server-Timing\", metrics);\n\t\t\t\t}\n\t\t\t\tif (isRouter && value != null) {\n\t\t\t\t\tresponse.set(header, value);\n\t\t\t\t} else {\n\t\t\t\t\tresponse.delete(header);\n\t\t\t\t}\n\t\t\t}),\n\t});\n}\n"],"mappings":";;;;;;;AAMA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AS,OAAO,eAAe;QACzB,IAAI,YAAY,QACtB,SAAS,IAAI,iBAAiB,OAAO;GAEtC,IAAI,YAAY,SAAS,MACxB,SAAS,IAAI,QAAQ,KAAK;QAE1B,SAAS,OAAO,MAAM;EAExB,CAAC;CACH,CAAC;AACF"}
@@ -5,6 +5,8 @@
5
5
  * static stages never serve it.
6
6
  */
7
7
  const BUILD_MANIFEST_FILE = ".app-server.json";
8
+ /** The URL path of the hashed files of a build that records none: Vite's default `build.assetsDir`. */
9
+ const DEFAULT_ASSETS_PATH = "/assets/";
8
10
  /**
9
11
  * The key for a URL path in {@link BuildManifest}: the path with no trailing
10
12
  * slash, so `/a/` and `/a` share headers. The root stays `/`.
@@ -28,6 +30,13 @@ function buildIdOf(manifest) {
28
30
  if (typeof manifest.buildId !== "string") throw new TypeError(`${BUILD_MANIFEST_FILE}: the "buildId" must be a string.`);
29
31
  return { buildId: manifest.buildId };
30
32
  }
33
+ /** The `assetsPath` of a parsed manifest, which can have none. A value that is not a URL path prefix throws. */
34
+ function assetsPathOf(manifest) {
35
+ if (!("assetsPath" in manifest)) return {};
36
+ const { assetsPath } = manifest;
37
+ if (typeof assetsPath !== "string" || assetsPath === "/" || !assetsPath.startsWith("/") || !assetsPath.endsWith("/")) throw new TypeError(`${BUILD_MANIFEST_FILE}: the "assetsPath" must be a URL path that starts and ends with "/".`);
38
+ return { assetsPath };
39
+ }
31
40
  /**
32
41
  * Reads the build manifest of a client build. A build with no file has an
33
42
  * empty one. A file in any other shape throws, so a bad build stops startup.
@@ -53,11 +62,12 @@ async function readBuildManifest(files) {
53
62
  }
54
63
  return {
55
64
  ...buildIdOf(parsed),
65
+ ...assetsPathOf(parsed),
56
66
  prerendered: parsed.prerendered,
57
67
  headers,
58
68
  scriptHashes
59
69
  };
60
70
  }
61
71
 
62
- export { manifestKey as n, readBuildManifest as r, BUILD_MANIFEST_FILE as t };
63
- //# sourceMappingURL=build-manifest-UDNk81Ce.js.map
72
+ export { readBuildManifest as i, DEFAULT_ASSETS_PATH as n, manifestKey as r, BUILD_MANIFEST_FILE as t };
73
+ //# sourceMappingURL=build-manifest-DBMWe3Lx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-manifest-DBMWe3Lx.js","names":[],"sources":["../src/core/build-manifest.ts"],"sourcesContent":["import type { StaticFiles } from \"./types.js\";\n\n/**\n * The file under the client build that the Vite plugin writes after the\n * client build and again after the prerender pass. It is a dotfile, so the\n * static stages never serve it.\n */\nexport const BUILD_MANIFEST_FILE = \".app-server.json\";\n\n/** The URL path of the hashed files of a build that records none: Vite's default `build.assetsDir`. */\nexport const DEFAULT_ASSETS_PATH = \"/assets/\";\n\n/** What the Vite plugin records about the client build. */\nexport type BuildManifest = {\n\t/**\n\t * The ID of the client build: a hash of the files that the client build\n\t * writes. The `buildId` plugin sends it by default.\n\t */\n\tbuildId?: string;\n\t/**\n\t * The URL path of Vite's `build.assetsDir`, such as `/assets/`. It starts\n\t * and ends with `/`. The `assets` plugin serves its files with a one-year\n\t * immutable cache.\n\t */\n\tassetsPath?: string;\n\t/** The URL paths that answered with a 2xx, sorted. */\n\tprerendered: string[];\n\t/** The headers of each prerendered file that is not an HTML document, by URL path. */\n\theaders: Record<string, Record<string, string>>;\n\t/**\n\t * The base64 `SHA-256` of each inline script of each HTML file in the client\n\t * build, by the file's URL path, such as `/about/index.html`. A CSP trusts\n\t * the scripts of a prerendered page by these hashes.\n\t */\n\tscriptHashes: Record<string, string[]>;\n};\n\n/**\n * The key for a URL path in {@link BuildManifest}: the path with no trailing\n * slash, so `/a/` and `/a` share headers. The root stays `/`.\n *\n * @example\n * manifestKey(\"/components/button/\"); // => \"/components/button\"\n */\nexport function manifestKey(pathname: string): string {\n\tconst trimmed = pathname.replace(/\\/+$/u, \"\");\n\treturn trimmed === \"\" ? \"/\" : trimmed;\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t!Array.isArray(value) &&\n\t\tObject.values(value).every((entry) => typeof entry === \"string\")\n\t);\n}\n\nfunction isStringList(value: unknown): value is string[] {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n\n/** The `buildId` of a parsed manifest, which can have none. A value that is not a string throws. */\nfunction buildIdOf(manifest: object): Pick<BuildManifest, \"buildId\"> {\n\tif (!(\"buildId\" in manifest)) {\n\t\treturn {};\n\t}\n\tif (typeof manifest.buildId !== \"string\") {\n\t\tthrow new TypeError(`${BUILD_MANIFEST_FILE}: the \"buildId\" must be a string.`);\n\t}\n\treturn { buildId: manifest.buildId };\n}\n\n/** The `assetsPath` of a parsed manifest, which can have none. A value that is not a URL path prefix throws. */\nfunction assetsPathOf(manifest: object): Pick<BuildManifest, \"assetsPath\"> {\n\tif (!(\"assetsPath\" in manifest)) {\n\t\treturn {};\n\t}\n\tconst { assetsPath } = manifest;\n\tif (\n\t\ttypeof assetsPath !== \"string\" ||\n\t\tassetsPath === \"/\" ||\n\t\t!assetsPath.startsWith(\"/\") ||\n\t\t!assetsPath.endsWith(\"/\")\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${BUILD_MANIFEST_FILE}: the \"assetsPath\" must be a URL path that starts and ends with \"/\".`,\n\t\t);\n\t}\n\treturn { assetsPath };\n}\n\n/**\n * Reads the build manifest of a client build. A build with no file has an\n * empty one. A file in any other shape throws, so a bad build stops startup.\n */\nexport async function readBuildManifest(files: StaticFiles): Promise<BuildManifest> {\n\tconst path = `/${BUILD_MANIFEST_FILE}`;\n\tif ((await files.stat(path))?.kind !== \"file\") {\n\t\treturn { prerendered: [], headers: {}, scriptHashes: {} };\n\t}\n\tconst parsed: unknown = await new Response(await files.open(path)).json();\n\tif (\n\t\ttypeof parsed !== \"object\" ||\n\t\tparsed == null ||\n\t\t!(\"prerendered\" in parsed) ||\n\t\t!isStringList(parsed.prerendered) ||\n\t\t!(\"headers\" in parsed) ||\n\t\ttypeof parsed.headers !== \"object\" ||\n\t\tparsed.headers == null ||\n\t\t!(\"scriptHashes\" in parsed) ||\n\t\ttypeof parsed.scriptHashes !== \"object\" ||\n\t\tparsed.scriptHashes == null\n\t) {\n\t\tthrow new Error(\n\t\t\t`${BUILD_MANIFEST_FILE} must hold a \"prerendered\" list and the \"headers\" and \"scriptHashes\" objects.`,\n\t\t);\n\t}\n\tconst headers: Record<string, Record<string, string>> = {};\n\tfor (const [key, value] of Object.entries(parsed.headers)) {\n\t\tif (!isStringRecord(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the headers for ${key} must be strings.`);\n\t\t}\n\t\theaders[key] = value;\n\t}\n\tconst scriptHashes: Record<string, string[]> = {};\n\tfor (const [key, value] of Object.entries(parsed.scriptHashes)) {\n\t\tif (!isStringList(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the script hashes for ${key} must be strings.`);\n\t\t}\n\t\tscriptHashes[key] = value;\n\t}\n\treturn {\n\t\t...buildIdOf(parsed),\n\t\t...assetsPathOf(parsed),\n\t\tprerendered: parsed.prerendered,\n\t\theaders,\n\t\tscriptHashes,\n\t};\n}\n"],"mappings":";;;;;;AAOA,MAAa,sBAAsB;;AAGnC,MAAa,sBAAsB;;;;;;;;AAkCnC,SAAgB,YAAY,UAA0B;CACrD,MAAM,UAAU,SAAS,QAAQ,SAAS,EAAE;CAC5C,OAAO,YAAY,KAAK,MAAM;AAC/B;AAEA,SAAS,eAAe,OAAiD;CACxE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAO,OAAO,KAAK,CAAC,CAAC,OAAO,UAAU,OAAO,UAAU,QAAQ;AAEjE;AAEA,SAAS,aAAa,OAAmC;CACxD,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,UAAU,OAAO,UAAU,QAAQ;AAChF;;AAGA,SAAS,UAAU,UAAkD;CACpE,IAAI,EAAE,aAAa,WAClB,OAAO,CAAC;CAET,IAAI,OAAO,SAAS,YAAY,UA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,MAAM,GAAG,oBAAoB,0BAA0B,IAAI,kBAAkB;EAExF,aAAa,OAAO;CACrB;CACA,OAAO;EACN,GAAG,UAAU,MAAM;EACnB,GAAG,aAAa,MAAM;EACtB,aAAa,OAAO;EACpB;EACA;CACD;AACD"}
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as parsePort } from "./tcp-Dd1Mt6sN.js";
2
+ import { t as parsePort } from "./tcp-Bws6oEau.js";
3
3
  import process from "node:process";
4
4
  import { parseArgs } from "node:util";
5
5
 
@@ -42,12 +42,12 @@ try {
42
42
  if (args?.help === true) process.stdout.write(`${USAGE}\n`);
43
43
  else if (args?.command === "start") {
44
44
  process.env.NODE_ENV ??= "development";
45
- const { start } = await import("./start-DREqYrZh.js");
45
+ const { start } = await import("./start-DiQf9ttp.js");
46
46
  await start();
47
47
  } else if (args?.command === "serve") {
48
48
  process.env.NODE_ENV ??= "production";
49
49
  if (typeof process.setSourceMapsEnabled === "function") process.setSourceMapsEnabled(true);
50
- const { serve } = await import("./serve-caOkS3o5.js");
50
+ const { serve } = await import("./serve-BUJ7ZonG.js");
51
51
  await serve({ buildPath: args.buildPath });
52
52
  } else if (args != null) fail(args.command == null ? "Give a command." : `Unknown command: ${args.command}.`);
53
53
 
@@ -1,3 +1,3 @@
1
- import { n as staleBuildTanStack, r as documentNonce, t as staleBuildReactRouter } from "./stale-build-navigation-PnMLtTF8.js";
1
+ import { n as staleBuildTanStack, r as documentNonce, t as staleBuildReactRouter } from "./stale-build-navigation-rg5xxmTr.js";
2
2
 
3
3
  export { documentNonce as cspNonce, staleBuildReactRouter, staleBuildTanStack };
package/dist/client.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as requestContext } from "./request-context-BtQ87VYb.js";
2
- import { n as staleBuildTanStack, r as documentNonce, t as staleBuildReactRouter } from "./stale-build-navigation-PnMLtTF8.js";
2
+ import { n as staleBuildTanStack, r as documentNonce, t as staleBuildReactRouter } from "./stale-build-navigation-rg5xxmTr.js";
3
3
 
4
4
  // src/client/csp-nonce.ts
5
5
  /**