@ngrok/app-server 0.3.1 → 0.3.3

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 (65) hide show
  1. package/README.md +83 -27
  2. package/dist/{build-id-C6sYO9Yp.js → build-id-B0448vZH.js} +27 -2
  3. package/dist/build-id-B0448vZH.js.map +1 -0
  4. package/dist/{build-manifest-UDNk81Ce.js → build-manifest-DBMWe3Lx.js} +12 -2
  5. package/dist/build-manifest-DBMWe3Lx.js.map +1 -0
  6. package/dist/cli.js +2 -2
  7. package/dist/client-browser.js +1 -1
  8. package/dist/client.js +1 -1
  9. package/dist/{entry-CM6Ma-Tv.d.ts → create-server-D4-nVOVJ.d.ts} +56 -70
  10. package/dist/{create-server-DkTeIJ8L.js → create-server-jMl2ltHD.js} +454 -394
  11. package/dist/create-server-jMl2ltHD.js.map +1 -0
  12. package/dist/entry-BPrgE_6K.d.ts +94 -0
  13. package/dist/entry-D9H4LA9c.js +351 -0
  14. package/dist/entry-D9H4LA9c.js.map +1 -0
  15. package/dist/{index-Bo5G9LuQ.d.ts → index-Db7dspq6.d.ts} +6 -1
  16. package/dist/index.d.ts +5 -14
  17. package/dist/index.js +3 -3
  18. package/dist/{load-entry-CmkdlmDX.js → load-entry-D7r0mjEp.js} +4 -4
  19. package/dist/{load-entry-CmkdlmDX.js.map → load-entry-D7r0mjEp.js.map} +1 -1
  20. package/dist/{node-BFH82eeL.js → node-C1qudLs_.js} +2 -2
  21. package/dist/{node-BFH82eeL.js.map → node-C1qudLs_.js.map} +1 -1
  22. package/dist/node-vite.d.ts +1 -1
  23. package/dist/node.d.ts +1 -1
  24. package/dist/node.js +1 -1
  25. package/dist/react-router-vite.d.ts +1 -1
  26. package/dist/react-router.d.ts +3 -2
  27. package/dist/react-router.js +31 -2
  28. package/dist/react-router.js.map +1 -1
  29. package/dist/request-context-BtQ87VYb.js.map +1 -1
  30. package/dist/{script-hashes-hqUk6kG7.js → script-hashes-C6hQ5XnP.js} +22 -4
  31. package/dist/script-hashes-C6hQ5XnP.js.map +1 -0
  32. package/dist/{serve-Cc-ADdhZ.js → serve-E0hSGe6_.js} +2 -2
  33. package/dist/{serve-Cc-ADdhZ.js.map → serve-E0hSGe6_.js.map} +1 -1
  34. package/dist/{stale-build-navigation-PnMLtTF8.js → stale-build-navigation-rg5xxmTr.js} +2 -2
  35. package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map} +1 -1
  36. package/dist/{start-Cb3kknlF.js → start-CifYPRq1.js} +34 -6
  37. package/dist/start-CifYPRq1.js.map +1 -0
  38. package/dist/tanstack-start-vite.d.ts +1 -1
  39. package/dist/tanstack-start.d.ts +2 -2
  40. package/dist/testing.d.ts +56 -0
  41. package/dist/testing.js +114 -0
  42. package/dist/testing.js.map +1 -0
  43. package/dist/{trailing-slash-DX7NB88H.d.ts → trailing-slash-CFSv_Gzx.d.ts} +2 -2
  44. package/dist/{types-DLYxYS6M.d.ts → types-j29vspx_.d.ts} +16 -2
  45. package/dist/vercel-pages.d.ts +32 -0
  46. package/dist/vercel-pages.js +54 -0
  47. package/dist/vercel-pages.js.map +1 -0
  48. package/dist/vercel-vite.d.ts +30 -9
  49. package/dist/vercel-vite.js +160 -17
  50. package/dist/vercel-vite.js.map +1 -1
  51. package/dist/vercel.d.ts +2 -2
  52. package/dist/vercel.js +2 -2
  53. package/dist/{vite-iioAoxSt.js → vite-BDREIgiH.js} +45 -33
  54. package/dist/vite-BDREIgiH.js.map +1 -0
  55. package/dist/vite.d.ts +1 -1
  56. package/dist/vite.js +1 -1
  57. package/package.json +5 -1
  58. package/dist/build-id-C6sYO9Yp.js.map +0 -1
  59. package/dist/build-manifest-UDNk81Ce.js.map +0 -1
  60. package/dist/create-server-DkTeIJ8L.js.map +0 -1
  61. package/dist/entry-CenmvESk.js +0 -116
  62. package/dist/entry-CenmvESk.js.map +0 -1
  63. package/dist/script-hashes-hqUk6kG7.js.map +0 -1
  64. package/dist/start-Cb3kknlF.js.map +0 -1
  65. package/dist/vite-iioAoxSt.js.map +0 -1
package/README.md CHANGED
@@ -158,7 +158,7 @@ Run it:
158
158
 
159
159
  `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
160
 
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.
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. 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
162
 
163
163
  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
164
 
@@ -166,7 +166,7 @@ A React Router app with no Vite plugin also works: `app-server serve build/serve
166
166
 
167
167
  ## Commands
168
168
 
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.
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. 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
170
  - `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
171
  - `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
172
 
@@ -206,7 +206,7 @@ For TanStack Start, copy `dist`, and run `dist/server/app-server.js`.
206
206
 
207
207
  ## Deploy to Vercel
208
208
 
209
- The `vercel` host runs the pipeline in one Node.js Vercel Function. Vercel's content delivery network (CDN) serves the hashed files.
209
+ 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
210
 
211
211
  Use `vercel()` as the host:
212
212
 
@@ -221,16 +221,39 @@ After the build, `vercel()` writes `.vercel/output` (the Build Output API, versi
221
221
 
222
222
  The output has two parts:
223
223
 
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.
224
+ - `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
225
  - `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
226
 
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.
227
+ ### Prerendered pages on the CDN
228
+
229
+ 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.
230
+
231
+ 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:
232
+
233
+ - It is a 200 from the page's file.
234
+ - 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`.
235
+ - 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.
236
+ - It varies only on `Accept-Encoding`, on `Accept` for a [markdown twin](#content-negotiation), and on the header of `noindex: { unlessHeader }`.
237
+
238
+ 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.
239
+
240
+ The function serves each other prerendered page, and the CDN never keeps its answer:
241
+
242
+ - 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.
243
+ - 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.
244
+ - A request that names `text/markdown` in `Accept` goes to the function, which negotiates the twin.
245
+ - 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.
246
+ - 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.
247
+ - A request with another method, such as a form's `POST`, goes to the function.
248
+
249
+ 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
250
 
229
251
  `vercel()` takes:
230
252
 
231
253
  - `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.
254
+ - `cdnHeaders`: headers for each file of `cdnPaths` and `build.assetsDir`, such as CORS headers. Default none.
255
+ - `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.
256
+ - `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
257
 
235
258
  The function differs from a long-lived process:
236
259
 
@@ -246,17 +269,17 @@ The function differs from a long-lived process:
246
269
 
247
270
  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
271
  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.
272
+ 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.
250
273
  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.
251
274
  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
275
  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
276
  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).
277
+ - `noindex()`, with `defaultPlugins({ noindex })`. See [Preview deploys](#preview-deploys).
255
278
  - `buildId()`, on by default. `defaultPlugins({ buildId })` changes it, and `false` turns it off. See [Deploys and open tabs](#deploys-and-open-tabs).
256
279
  - `contentSecurityPolicy()`, with `defaultPlugins({ contentSecurityPolicy })`. See [A CSP for each document](#a-csp-for-each-document).
257
280
  - The plugin from `runtimeEnv()`, with `defaultPlugins({ env })`. See [Environment](#environment).
258
281
  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).
282
+ 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
283
  10. `redirects(rules)`, when `defaultPlugins({ redirects })` has rules: a redirect from each old URL to its new URL. See [Redirects](#redirects).
261
284
  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
285
  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.
@@ -342,7 +365,7 @@ export default createServer({ plugins: defaultPlugins({ beforeStatic: [auth] })
342
365
  - `Cross-Origin-Opener-Policy: same-origin`
343
366
  - `Strict-Transport-Security: max-age=31536000`, on an HTTPS request only
344
367
 
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.
368
+ `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
369
 
347
370
  ```ts
348
371
  defaultPlugins({
@@ -351,6 +374,7 @@ defaultPlugins({
351
374
  "Cross-Origin-Opener-Policy": "same-origin-allow-popups",
352
375
  "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
353
376
  "Content-Security-Policy": "frame-ancestors 'none'",
377
+ "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
354
378
  },
355
379
  },
356
380
  });
@@ -433,7 +457,7 @@ export function getRouter() {
433
457
 
434
458
  After a deploy, an open tab still runs the old build. Two things can then go wrong:
435
459
 
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.
460
+ - **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
461
  - **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
462
 
439
463
  `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 +624,14 @@ defaultPlugins({
600
624
  defaultPlugins({ noindex: process.env.PREVIEW === "1" });
601
625
  ```
602
626
 
627
+ 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`:
628
+
629
+ ```ts
630
+ defaultPlugins({ noindex: { unlessHeader: "x-ngrok-edge" } });
631
+ ```
632
+
633
+ 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).
634
+
603
635
  ## Content negotiation
604
636
 
605
637
  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.
@@ -641,22 +673,15 @@ createServer({ plugins: defaultPlugins({ prerendered: { markdownTwins: true } })
641
673
  - In development, React Router gives only the twins in its `prerender` config, as the build does. TanStack Start finds its prerendered pages only during the build, so in development each twin route that answers markdown counts.
642
674
  - A plugin after `prerendered` does not see a twin, in development or in production, because a twin is a prerendered file. Put an auth check for a twin in `beforeStatic` or in the twin's route.
643
675
 
644
- The default twin is the path with no trailing slash plus `.md`, and `/index.md` for `/`. A different mapping goes in `twinOf`. Its path follows the same rules as a request path:
676
+ The default twin is the path with no trailing slash plus `.md`, and `/index.md` for `/`. A request that `rewrite` changes gets no twin. `rewrite` sends that request to another file or to the framework, so it gets the same answer as a browser. For example, when `rewrite` sends `/?q=h100` to the framework, `/?q=h100` gets no twin, and `/gpu/h100` gets `/gpu/h100.md`.
677
+
678
+ A different mapping goes in `twinOf`. Its path follows the same rules as a request path, and it can give a twin to a request that `rewrite` changes:
645
679
 
646
680
  ```ts
647
681
  prerendered({ markdownTwins: { twinOf: (path) => (path === "/" ? "/llms.md" : `${path}.md`) } });
648
682
  ```
649
683
 
650
- `twinOf` also gets the request's Hono context, the same as `rewrite`. If it gives `undefined`, the request gets no twin, `rewrite` runs, and the answer gets no `Vary: Accept` and no `Link`. For example, when the framework renders a page for each query, keep a request with a query off the prerendered twin:
651
-
652
- ```ts
653
- prerendered({
654
- markdownTwins: {
655
- twinOf: (path, c) =>
656
- new URL(c.req.url).search === "" ? `${path === "/" ? "/index" : path}.md` : undefined,
657
- },
658
- });
659
- ```
684
+ `twinOf` also gets the request's Hono context, the same as `rewrite`. If it gives `undefined`, the request gets no twin, and the answer gets no `Vary: Accept` and no `Link`.
660
685
 
661
686
  The framework makes the twins. In React Router, one splat resource route can answer every twin. Prerender each twin URL, and point `twinOf` at the route. `markdownFor` stands for the app's own lookup:
662
687
 
@@ -683,7 +708,7 @@ createServer({ plugins: defaultPlugins({ prerendered: { markdownTwins: { twinOf
683
708
 
684
709
  The same route answers the twins in development.
685
710
 
686
- For other negotiation, `rewrite` maps a request path to the file to serve. It does not run for a request that gets the twin. To keep a request off the twin, give `undefined` from `twinOf`. When its answer depends on a request header, add a `Vary` for that header in a plugin.
711
+ For other negotiation, `rewrite` maps a request path to the file to serve. A request that gets the twin gets the twin's file. When its answer depends on a request header, add a `Vary` for that header in a plugin.
687
712
 
688
713
  ### A rendered page
689
714
 
@@ -715,7 +740,7 @@ A resource route, or a TanStack Start server route, gets the same `Request`. Cal
715
740
 
716
741
  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.
717
742
 
718
- 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).
743
+ 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`.
719
744
 
720
745
  ## Logs
721
746
 
@@ -835,13 +860,40 @@ export async function loader({ request }: Route.LoaderArgs) {
835
860
 
836
861
  For other long work, stop on `shutdownSignal()`.
837
862
 
863
+ ## Testing
864
+
865
+ `@ngrok/app-server/testing` runs an app in a test, with no build and no listener.
866
+
867
+ `createTestServer({ app, files, framework })` starts the app in production mode over a client build of `files`. It records the hashes of the inline scripts of each HTML file, as the build does. `framework` answers each request that no stage answers. The default is a 404. Give each test server a new app, because an app runs the `setup` of its plugins one time. `close()` cancels each body that the test did not read, runs each plugin's `onShutdown`, and removes the files.
868
+
869
+ ```ts
870
+ import { createTestServer } from "@ngrok/app-server/testing";
871
+
872
+ const server = await createTestServer({
873
+ app: createServer({ plugins: defaultPlugins({ contentSecurityPolicy: { policy } }) }),
874
+ files: { "providers/index.html": "<!doctype html><script>…</script>" },
875
+ framework: async () => new Response("rendered", { headers: { "Content-Type": "text/html" } }),
876
+ });
877
+ const response = await server.request("/providers");
878
+ response.headers.get("Content-Security-Policy"); // => "script-src 'self' 'sha256-…'"
879
+ await server.close();
880
+ ```
881
+
882
+ `withRequestContext(values, work)` runs `work` as in a server request, so `requestContext()` and `cspNonce()` give `values`. Use it to test a render with no mock. With no `logger`, the log lines go nowhere.
883
+
884
+ ```tsx
885
+ import { withRequestContext } from "@ngrok/app-server/testing";
886
+
887
+ const html = await withRequestContext({ cspNonce: "test-nonce" }, () => renderToString(<App />));
888
+ ```
889
+
838
890
  ## Adapters
839
891
 
840
892
  A framework adapter or a host adapter is two small objects. A third-party adapter uses the same contract.
841
893
 
842
894
  - `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.
843
- - `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 })`.
844
- - `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`.
895
+ - `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.
896
+ - `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`.
845
897
  - `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.
846
898
  - `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.
847
899
 
@@ -865,3 +917,7 @@ A framework adapter or a host adapter is two small objects. A third-party adapte
865
917
  - One server process uses one CPU core. To use more cores, run one replica or one container for each core behind the load balancer.
866
918
  - 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.
867
919
  - On Deno, `Deno.serve` logs a notice about its legacy `request.signal` behavior.
920
+
921
+ ## Contributing
922
+
923
+ 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.
@@ -33,6 +33,31 @@ function checkOptionPlugins(plugins) {
33
33
  if (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,MAAM,0BAAU,IAAI,QAAwB;;;;;;;;AAS5C,SAAgB,aAA+B,QAAgB,QAAc;CAC5E,QAAQ,IAAI,QAAQ,MAAM;CAC1B,OAAO;AACR;;;;;;;;;AAUA,SAAgB,mBAAmB,SAAkC;CACpE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,UAAU,SAAS;EAC7B,MAAM,SAAS,QAAQ,IAAI,MAAM;EACjC,IAAI,UAAU,QAAQ,KAAK,IAAI,MAAM,GACpC,MAAM,IAAI,MACT,2BAA2B,OAAO,KAAK,mEAAmE,OAAO,8DAClH;EAED,IAAI,UAAU,MACb,KAAK,IAAI,MAAM;CAEjB;AACD;;AAGA,MAAM,2BAAW,IAAI,QAAmC;;;;;;;;;;AAWxD,SAAgB,gBAAkC,SAA4B,QAAc;CAC3F,SAAS,IAAI,QAAQ,OAAO;CAC5B,OAAO;AACR;;;;;;;;AASA,SAAgB,kBAAkB,SAAsC;CACvE,OAAO,CACN,GAAG,IAAI,IACN,QAAQ,SAAS,WAAW,SAAS,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,KAAK,YAAY,CAAC,CACzF,CACD;AACD;;;;ACpEA,MAAa,kBAAkB;;;;;;AAO/B,MAAa,kBAAkB;;;;;AAgC/B,SAAS,WAAW,UAAoC;CACvD,MAAM,eAAe,SAAS,IAAI,eAAe,KAAK;CACtD,IAAI,8BAA8B,KAAK,YAAY,GAClD,OAAO;CAER,OACC,iFAAiF,KAChF,YACD,KACA,eAAe,KAAK,YAAY,KAChC,KAAK,MAAM,SAAS,IAAI,SAAS,KAAK,EAAE,IAAI,KAAK,IAAI,KACrD,SAAS,IAAI,eAAe;AAE9B;;AAGA,SAAgB,oBAAoB,QAAiC;CAEpE,QAAQ,QAAQ,MAAM,gCAAgC,KAAK,CAAC,EAAC,CAC3D,KAAK,WAAW,OAAO,KAAK,CAAC,CAAC,CAC9B,QAAQ,WAAW,WAAW,EAAE;AACnC;;AAGA,SAAgB,cAAc,QAAyB;CACtD,OAAO,OAAO,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,YAAY,MAAM;AACvD;;AAGA,SAAS,aAAa,QAAiC;CACtD,OAAO,oBAAoB,MAAM,CAAC,CAAC,QAAQ,WAAW,CAAC,cAAc,MAAM,CAAC;AAC7E;;AAGA,SAAS,iBAA0B;CAClC,OAAO;AACR;;AAGA,SAAS,OAAO,OAAuB;CACtC,OAAO,IAAI,MAAM,WAAW,WAAW,OAAO,GAAG,KAAK,EAAE;AACzD;;AAGA,SAAS,YAAY,OAA+C;CACnE,OAAO,SAAS,OAAO,SAAY,GAAG,gBAAgB,QAAQ,OAAO,KAAK;AAC3E;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,QAAQ,EACvB,SAAS,iBACT,OAAO,OACP,UACmB,CAAC,GAAW;CAE/B,MAAM,WAAW,UAAU,KAAK,SAAY;CAC5C,IAAI,QAAQ;CACZ,IAAI,SAAS,YAAY,KAAK;CAC9B,IAAI,gBAA4C;CAChD,OAAO,aAAa,WAAW;EAC9B,MAAM;EACN,QAAQ,SAAS;GAChB,CAAC,CAAE,iBAAkB;GACrB,QAAQ,YAAY,KAAK;GACzB,SAAS,YAAY,KAAK;EAC3B;EAGA,gBAAgB;EAChB,YAAY,OAAO,SAAS,SAC3B,eAAe,SAAS,OAAO,aAAa;GAC3C,MAAM,EAAE,SAAS,QAAQ;GACzB,MAAM,YACJ,SAAS,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,UAAU,cAAc,IAAI;GACvF,MAAM,YAAY,YAAa,QAAQ,IAAI,MAAM,QAAQ,CAAC,WAAW,QAAQ;GAE7E,MAAM,SAAS,SAAS,IAAI,eAAe;GAC3C,MAAM,UAAU,CACf,GAAG,aAAa,MAAM,GACtB,GAAI,aAAa,UAAU,OAAO,CAAC,MAAM,IAAI,CAAC,CAC/C,CAAC,CAAC,KAAK,IAAI;GACX,IAAI,YAAY,IACf,SAAS,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,UAC/B,MAAM,IAAI,UAAU,GAAG,oBAAoB,kCAAkC;CAE9E,OAAO,EAAE,SAAS,SAAS,QAAQ;AACpC;;AAGA,SAAS,aAAa,UAAqD;CAC1E,IAAI,EAAE,gBAAgB,WACrB,OAAO,CAAC;CAET,MAAM,EAAE,eAAe;CACvB,IACC,OAAO,eAAe,YACtB,eAAe,OACf,CAAC,WAAW,WAAW,GAAG,KAC1B,CAAC,WAAW,SAAS,GAAG,GAExB,MAAM,IAAI,UACT,GAAG,oBAAoB,qEACxB;CAED,OAAO,EAAE,WAAW;AACrB;;;;;AAMA,eAAsB,kBAAkB,OAA4C;CACnF,MAAM,OAAO,IAAI;CACjB,KAAK,MAAM,MAAM,KAAK,IAAI,EAAC,EAAG,SAAS,QACtC,OAAO;EAAE,aAAa,CAAC;EAAG,SAAS,CAAC;EAAG,cAAc,CAAC;CAAE;CAEzD,MAAM,SAAkB,MAAM,IAAI,SAAS,MAAM,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK;CACxE,IACC,OAAO,WAAW,YAClB,UAAU,QACV,EAAE,iBAAiB,WACnB,CAAC,aAAa,OAAO,WAAW,KAChC,EAAE,aAAa,WACf,OAAO,OAAO,YAAY,YAC1B,OAAO,WAAW,QAClB,EAAE,kBAAkB,WACpB,OAAO,OAAO,iBAAiB,YAC/B,OAAO,gBAAgB,MAEvB,MAAM,IAAI,MACT,GAAG,oBAAoB,8EACxB;CAED,MAAM,UAAkD,CAAC;CACzD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,OAAO,GAAG;EAC1D,IAAI,CAAC,eAAe,KAAK,GACxB,MAAM,IAAI,MAAM,GAAG,oBAAoB,oBAAoB,IAAI,kBAAkB;EAElF,QAAQ,OAAO;CAChB;CACA,MAAM,eAAyC,CAAC;CAChD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,YAAY,GAAG;EAC/D,IAAI,CAAC,aAAa,KAAK,GACtB,MAAM,IAAI,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
@@ -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-Cb3kknlF.js");
45
+ const { start } = await import("./start-CifYPRq1.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-Cc-ADdhZ.js");
50
+ const { serve } = await import("./serve-E0hSGe6_.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
  /**
@@ -1,6 +1,6 @@
1
- import { a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, g as Plugin, h as Mode, m as LogSink, r as FetchHandler, t as AppServerEnv, u as Listener, x as SentResponse } from "./types-DLYxYS6M.js";
2
- import { t as TrailingSlash } from "./trailing-slash-DX7NB88H.js";
3
- import { Context, Hono, MiddlewareHandler } from "hono";
1
+ import { g as Plugin, m as LogSink, t as AppServerEnv, u as Listener, x as SentResponse } from "./types-j29vspx_.js";
2
+ import { t as TrailingSlash } from "./trailing-slash-CFSv_Gzx.js";
3
+ import { Context, Hono } from "hono";
4
4
  /** Options for {@link accessLog}. */
5
5
  type AccessLogOptions = {
6
6
  /**
@@ -30,6 +30,13 @@ type AccessLogOptions = {
30
30
  * logs the response that leaves the server, after each stage. A listener
31
31
  * with an `edge`, such as the node listener, counts the bytes.
32
32
  *
33
+ * - A 5xx line has the level `error`, and each other line has the level `info`.
34
+ * - A line has `http.route` when the framework adapter gives the route
35
+ * pattern that it matched, such as `/domains/:domainId`.
36
+ * - In development, a request that Vite answers, such as a source module,
37
+ * gets no line.
38
+ * - A request of the build's check of the CDN pages gets no line.
39
+ *
33
40
  * @example
34
41
  * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
35
42
  * // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
@@ -110,6 +117,28 @@ type HealthOptions = {
110
117
  * });
111
118
  */
112
119
  declare function health({ livePath, readyPath, ready }?: HealthOptions): Plugin;
120
+ /** Options for {@link noindex}. With no options, each response gets `X-Robots-Tag`. */
121
+ type NoindexOptions = {
122
+ /**
123
+ * A request with this header gets no `X-Robots-Tag`, and each response
124
+ * gets the header in `Vary`. The `vercel` host can then serve a
125
+ * prerendered page from the CDN, which picks the answer by the same header.
126
+ */
127
+ unlessHeader: string;
128
+ };
129
+ /**
130
+ * Sets `X-Robots-Tag: noindex, nofollow` on each response, or on each
131
+ * response to a request with no `unlessHeader`, so a search engine does not
132
+ * index a preview deploy.
133
+ *
134
+ * The `noindex` option of `defaultPlugins()` puts it
135
+ * before the static stages, so it also sees prerendered pages.
136
+ *
137
+ * @example
138
+ * defaultPlugins({ noindex: process.env.PREVIEW === "1" });
139
+ * defaultPlugins({ noindex: { unlessHeader: "x-ngrok-edge" } });
140
+ */
141
+ declare function noindex(options?: NoindexOptions): Plugin;
113
142
  /** One redirect of a {@link redirects} table. */
114
143
  type RedirectRule = {
115
144
  /**
@@ -165,6 +194,11 @@ type SecurityHeaderValues = {
165
194
  * policy. It has no default.
166
195
  */
167
196
  "Content-Security-Policy"?: string | false;
197
+ /**
198
+ * The browser features that the page and its frames can use, such as
199
+ * `camera=(), microphone=(), geolocation=()`. It has no default.
200
+ */
201
+ "Permissions-Policy"?: string | false;
168
202
  };
169
203
  /** Options for {@link securityHeaders}. */
170
204
  type SecurityHeadersOptions = {
@@ -179,9 +213,10 @@ type SecurityHeadersOptions = {
179
213
  * - `Cross-Origin-Opener-Policy: same-origin`
180
214
  * - `Strict-Transport-Security: max-age=31536000`, on an HTTPS request only
181
215
  *
182
- * A response that has a header keeps its own value. The exception is
183
- * `Content-Security-Policy`, which has no default: the plugin adds a set
184
- * value as a second policy, and a browser enforces both.
216
+ * `Content-Security-Policy` and `Permissions-Policy` have no default. A
217
+ * response that has a header keeps its own value. The exception is
218
+ * `Content-Security-Policy`: the plugin adds a set value as a second policy,
219
+ * and a browser enforces both.
185
220
  * `defaultPlugins()` puts it before the static stages, so it also sees
186
221
  * prerendered pages.
187
222
  *
@@ -191,6 +226,7 @@ type SecurityHeadersOptions = {
191
226
  * headers: {
192
227
  * "Cross-Origin-Opener-Policy": "same-origin-allow-popups",
193
228
  * "Content-Security-Policy": "frame-ancestors 'none'",
229
+ * "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
194
230
  * },
195
231
  * },
196
232
  * });
@@ -324,10 +360,11 @@ type RuntimeEnv<Values> = Plugin & {
324
360
  */
325
361
  declare function runtimeEnv<Schema extends StandardSchemaV1>(schema: Schema, { source, publicPrefix }?: RuntimeEnvOptions): RuntimeEnv<InferOutput<Schema>>;
326
362
  /**
327
- * Serves the hashed files under `/assets/` with a one-year immutable cache.
328
- * A missing asset gets a plain 404 with `Cache-Control: no-store`, not a
329
- * rendered page. In development, the dev server serves the source modules,
330
- * the HMR client, and the CSS here instead.
363
+ * Serves the hashed files under Vite's `build.assetsDir`, `/assets/` by
364
+ * default, with a one-year immutable cache. The `appServer` Vite plugin
365
+ * records the directory. A missing asset gets a plain 404 with
366
+ * `Cache-Control: no-store`, not a rendered page. In development, the dev
367
+ * server serves the source modules, the HMR client, and the CSS here instead.
331
368
  *
332
369
  * @example
333
370
  * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
@@ -346,6 +383,7 @@ type PrerenderedOptions = {
346
383
  * returned path follows the rules of a request path: one URL for each
347
384
  * file, no dotfiles, and nothing outside the client build. When the
348
385
  * answer depends on a request header, add a `Vary` for it in a plugin.
386
+ * With `markdownTwins: true`, a request that `rewrite` changes gets no twin.
349
387
  */
350
388
  rewrite?: (path: string, context: Context<AppServerEnv>) => string;
351
389
  /**
@@ -356,7 +394,7 @@ type PrerenderedOptions = {
356
394
  * `rewrite`. It returns `undefined` for a request with no twin.
357
395
  *
358
396
  * - A request that prefers markdown gets the twin, with the twin's
359
- * captured headers. `rewrite` does not run for it.
397
+ * captured headers.
360
398
  * - Each answer for a path with a twin gets `Vary: Accept`: the twin, the
361
399
  * prerendered HTML, and the framework's answer. The server adds
362
400
  * `Accept` to the `Vary` header and keeps the values in it.
@@ -374,8 +412,9 @@ type PrerenderedOptions = {
374
412
  * a prerendered file.
375
413
  *
376
414
  * `true` uses the default `twinOf`: the path with no trailing slash plus
377
- * `.md`, and `/index.md` for `/`. The returned path follows the rules of a
378
- * request path.
415
+ * `.md`, and `/index.md` for `/`. A request that `rewrite` changes gets no
416
+ * twin, so it gets the same page as a browser. The returned path follows
417
+ * the rules of a request path.
379
418
  *
380
419
  * @example
381
420
  * prerendered({ markdownTwins: { twinOf: (path) => `/markdown${path}.md` } });
@@ -476,10 +515,10 @@ type DefaultPluginsOptions = {
476
515
  securityHeaders?: SecurityHeadersOptions | false;
477
516
  /**
478
517
  * Sets `X-Robots-Tag: noindex, nofollow` on each response, such as on a
479
- * preview deploy. See {@link noindex}.
518
+ * preview deploy. The options decide for each request. See {@link noindex}.
480
519
  * @default false
481
520
  */
482
- noindex?: boolean;
521
+ noindex?: boolean | NoindexOptions;
483
522
  /**
484
523
  * The options of the build ID on each document and data response. `false`
485
524
  * turns it off. See {@link buildId}.
@@ -569,58 +608,5 @@ type CreateServerOptions = {
569
608
  * export default app;
570
609
  */
571
610
  declare function createServer({ plugins, logger, listeners, trustForwardedProto, trustedProxyHops, shutdownDelayMs, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
572
- /** The version of the contract between the CLI and the `appServer` export of a build. */
573
- declare const ENTRY_PROTOCOL = 2;
574
- /**
575
- * What a server build exports as `appServer`. The CLI calls it, so the copy
576
- * of this package in the build runs the server, and the CLI's copy runs
577
- * nothing.
578
- */
579
- type AppServerEntry = {
580
- /** The CLI refuses an entry with another version. */
581
- protocol: typeof ENTRY_PROTOCOL;
582
- /** The app. Two entries with the same app share its plugins. */
583
- app: AppServer;
584
- /**
585
- * Production: runs each plugin's `setup` and listens. When the host's
586
- * lifecycle stops, such as on `SIGTERM`, it shuts down.
587
- */
588
- start: () => Promise<void>;
589
- /**
590
- * Production, for a serverless host: answers one request, and does not
591
- * listen. The first call runs each plugin's `setup`.
592
- */
593
- fetch: FetchHandler;
594
- /** Development: answers one request with the dev server inside the pipeline. */
595
- fetchDev: (request: Request, bindings: ListenerBindings, devServer: MiddlewareHandler<AppServerEnv>) => Promise<Response>;
596
- /** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */
597
- stopPlugins: () => Promise<void>;
598
- /** Aborts `shutdownSignal()` of this copy of the package. */
599
- abortShutdownSignal: () => void;
600
- };
601
- /** Options for {@link createEntry}. */
602
- type CreateEntryOptions = {
603
- /** The app from `createServer`. */
604
- app: AppServer;
605
- /** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */
606
- host: HostRuntime;
607
- /** Makes the run side of the framework adapter for a mode. */
608
- framework: (mode: Mode) => FrameworkRuntime;
609
- /**
610
- * The client build, as a file path or a `file:` URL. The entry that the
611
- * Vite plugin generates sets it.
612
- * @default the framework's `clientDirectory`
613
- */
614
- clientDirectory?: string;
615
- };
616
- /**
617
- * The `appServer` export of a server build: an app from `createServer`, the
618
- * host, and the framework adapter for each mode. The `appServer` Vite plugin
619
- * generates this export. Call this for a build without the plugin.
620
- *
621
- * @example
622
- * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
623
- */
624
- declare function createEntry({ app, host, framework, clientDirectory }: CreateEntryOptions): AppServerEntry;
625
- export { BuildIdOptions as A, SecurityHeadersOptions as C, redirects as D, RedirectRule as E, AccessLogOptions as M, accessLog as N, HealthOptions as O, SecurityHeaderValues as S, securityHeaders as T, StandardSchemaV1 as _, CreateServerOptions as a, requestId as b, createServer as c, assets as d, prerendered as f, RuntimeEnvOptions as g, RuntimeEnv as h, AppServer as i, buildId as j, health as k, defaultPlugins as l, PUBLIC_ENV_SCRIPT_ID as m, CreateEntryOptions as n, DefaultPluginsOptions as o, InferOutput as p, createEntry as r, RunningServer as s, AppServerEntry as t, PrerenderedOptions as u, runtimeEnv as v, contentSecurityPolicy as w, ContentSecurityPolicyOptions as x, RequestIdOptions as y };
626
- //# sourceMappingURL=entry-CM6Ma-Tv.d.ts.map
611
+ export { buildId as A, RedirectRule as C, HealthOptions as D, noindex as E, accessLog as M, health as O, securityHeaders as S, NoindexOptions as T, requestId as _, createServer as a, SecurityHeadersOptions as b, assets as c, PUBLIC_ENV_SCRIPT_ID as d, RuntimeEnv as f, RequestIdOptions as g, runtimeEnv as h, RunningServer as i, AccessLogOptions as j, BuildIdOptions as k, prerendered as l, StandardSchemaV1 as m, CreateServerOptions as n, defaultPlugins as o, RuntimeEnvOptions as p, DefaultPluginsOptions as r, PrerenderedOptions as s, AppServer as t, InferOutput as u, ContentSecurityPolicyOptions as v, redirects as w, contentSecurityPolicy as x, SecurityHeaderValues as y };
612
+ //# sourceMappingURL=create-server-D4-nVOVJ.d.ts.map