@ngrok/app-server 0.3.2 → 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 (57) hide show
  1. package/README.md +51 -15
  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/{create-server-kzZWd_Lo.d.ts → create-server-D4-nVOVJ.d.ts} +50 -13
  10. package/dist/{create-server-D0De6R7Q.js → create-server-jMl2ltHD.js} +572 -522
  11. package/dist/create-server-jMl2ltHD.js.map +1 -0
  12. package/dist/{entry-DuGgSKeB.d.ts → entry-BPrgE_6K.d.ts} +39 -3
  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 -15
  17. package/dist/index.js +3 -3
  18. package/dist/{load-entry-Bodyd2Ok.js → load-entry-D7r0mjEp.js} +3 -3
  19. package/dist/{load-entry-Bodyd2Ok.js.map → load-entry-D7r0mjEp.js.map} +1 -1
  20. package/dist/node-vite.d.ts +1 -1
  21. package/dist/node.d.ts +1 -1
  22. package/dist/react-router-vite.d.ts +1 -1
  23. package/dist/react-router.d.ts +3 -2
  24. package/dist/react-router.js +31 -2
  25. package/dist/react-router.js.map +1 -1
  26. package/dist/{serve-caOkS3o5.js → serve-E0hSGe6_.js} +2 -2
  27. package/dist/{serve-caOkS3o5.js.map → serve-E0hSGe6_.js.map} +1 -1
  28. package/dist/{stale-build-navigation-PnMLtTF8.js → stale-build-navigation-rg5xxmTr.js} +2 -2
  29. package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map} +1 -1
  30. package/dist/{start-DREqYrZh.js → start-CifYPRq1.js} +33 -5
  31. package/dist/start-CifYPRq1.js.map +1 -0
  32. package/dist/tanstack-start-vite.d.ts +1 -1
  33. package/dist/tanstack-start.d.ts +2 -2
  34. package/dist/testing.d.ts +2 -2
  35. package/dist/testing.js +2 -2
  36. package/dist/{trailing-slash-BrymAEGv.d.ts → trailing-slash-CFSv_Gzx.d.ts} +2 -2
  37. package/dist/{types-CEvzAmcn.d.ts → types-j29vspx_.d.ts} +15 -1
  38. package/dist/vercel-pages.d.ts +32 -0
  39. package/dist/vercel-pages.js +54 -0
  40. package/dist/vercel-pages.js.map +1 -0
  41. package/dist/vercel-vite.d.ts +30 -9
  42. package/dist/vercel-vite.js +160 -17
  43. package/dist/vercel-vite.js.map +1 -1
  44. package/dist/vercel.d.ts +2 -2
  45. package/dist/vercel.js +1 -1
  46. package/dist/{vite-tTxVimP6.js → vite-BDREIgiH.js} +44 -19
  47. package/dist/vite-BDREIgiH.js.map +1 -0
  48. package/dist/vite.d.ts +1 -1
  49. package/dist/vite.js +1 -1
  50. package/package.json +1 -1
  51. package/dist/build-id-C6sYO9Yp.js.map +0 -1
  52. package/dist/build-manifest-UDNk81Ce.js.map +0 -1
  53. package/dist/create-server-D0De6R7Q.js.map +0 -1
  54. package/dist/entry-UDsxuqBC.js +0 -116
  55. package/dist/entry-UDsxuqBC.js.map +0 -1
  56. package/dist/start-DREqYrZh.js.map +0 -1
  57. package/dist/vite-tTxVimP6.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"react-router.js","names":[],"sources":["../src/react-router/index.ts"],"sourcesContent":["import { createContext, createRequestHandler, RouterContextProvider } from \"react-router\";\nimport type { ServerBuild } from \"react-router\";\nimport { jsonSink, sinkLogger } from \"../core/log.js\";\nimport { requestContextValues } from \"../core/request-context.js\";\nimport type { FrameworkRuntime, Mode, RequestContext } from \"../core/types.js\";\n\n/** What the server puts in React Router's context for each request. */\nexport type AppServerContext = RequestContext;\n\n/**\n * The React Router context key for {@link AppServerContext}. Outside a server\n * request, such as in React Router's prerender pass, it holds no request ID\n * and a logger that writes to `jsonSink()`. `requestContext()` from\n * `@ngrok/app-server` gives the same values.\n *\n * @example\n * export async function loader({ context }: Route.LoaderArgs) {\n * \tcontext.get(appServerContext).logger.info(\"loading the dashboard\");\n * }\n */\nexport const appServerContext = createContext<AppServerContext>({\n\trequestId: undefined,\n\tlogger: sinkLogger(jsonSink()),\n\tcspNonce: undefined,\n\tclientAddress: undefined,\n});\n\n/**\n * Whether a module is a React Router server build.\n *\n * @example\n * isServerBuild(await import(\"./build/server/index.js\")); // => true\n */\nexport function isServerBuild(value: unknown): value is ServerBuild {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"routes\" in value &&\n\t\t\"entry\" in value &&\n\t\t\"assetsBuildDirectory\" in value &&\n\t\ttypeof value.assetsBuildDirectory === \"string\"\n\t);\n}\n\n/**\n * The run side of the React Router adapter, for a server build. Each request\n * gets a `RouterContextProvider` that holds {@link appServerContext}.\n *\n * @example\n * const framework = runtime(build, { mode: \"production\" });\n */\nexport function runtime(build: unknown, { mode }: { mode: Mode }): FrameworkRuntime {\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server module is not a React Router server build.\");\n\t}\n\t// Why also here: the Vite plugin checks the base, but a plain build skips the plugin.\n\tif (build.publicPath !== \"/\") {\n\t\tthrow new Error(\n\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this build has the publicPath \"${build.publicPath}\".`,\n\t\t);\n\t}\n\tconst handler = createRequestHandler(build, mode);\n\t// Why: lazy route discovery fetches this exact path, so a redirect breaks it.\n\tconst manifestPath =\n\t\tbuild.routeDiscovery.mode === \"lazy\"\n\t\t\t? [build.basename ?? \"\", build.routeDiscovery.manifestPath || \"/__manifest\"]\n\t\t\t\t\t.join(\"/\")\n\t\t\t\t\t.replaceAll(/\\/+/gu, \"/\")\n\t\t\t: undefined;\n\treturn {\n\t\tname: \"react-router\",\n\t\tclientDirectory: build.assetsBuildDirectory,\n\t\tprerenderedPaths: build.prerender,\n\t\tisDataRequest: (path) => path.endsWith(\".data\") || path === manifestPath,\n\t\tcontentTypes: { \".data\": \"text/x-script\" },\n\t\tfetch: async (request, context) => {\n\t\t\tconst routerContext = new RouterContextProvider();\n\t\t\trouterContext.set(appServerContext, requestContextValues(context));\n\t\t\treturn handler(request, routerContext);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAa,mBAAmB,cAAgC;CAC/D,WAAW;CACX,QAAQ,WAAW,SAAS,CAAC;CAC7B,UAAU;CACV,eAAe;AAChB,CAAC;;;;;;;AAQD,SAAgB,cAAc,OAAsC;CACnE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,YAAY,SACZ,WAAW,SACX,0BAA0B,SAC1B,OAAO,MAAM,yBAAyB;AAExC;;;;;;;;AASA,SAAgB,QAAQ,OAAgB,EAAE,QAA0C;CACnF,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,uDAAuD;CAGxE,IAAI,MAAM,eAAe,KACxB,MAAM,IAAI,MACT,oFAAoF,MAAM,WAAW,GACtG;CAED,MAAM,UAAU,qBAAqB,OAAO,IAAI;CAEhD,MAAM,eACL,MAAM,eAAe,SAAS,SAC3B,CAAC,MAAM,YAAY,IAAI,MAAM,eAAe,gBAAgB,aAAa,CAAC,CACzE,KAAK,GAAG,CAAC,CACT,WAAW,SAAS,GAAG,IACxB;CACJ,OAAO;EACN,MAAM;EACN,iBAAiB,MAAM;EACvB,kBAAkB,MAAM;EACxB,gBAAgB,SAAS,KAAK,SAAS,OAAO,KAAK,SAAS;EAC5D,cAAc,EAAE,SAAS,gBAAgB;EACzC,OAAO,OAAO,SAAS,YAAY;GAClC,MAAM,gBAAgB,IAAI,sBAAsB;GAChD,cAAc,IAAI,kBAAkB,qBAAqB,OAAO,CAAC;GACjE,OAAO,QAAQ,SAAS,aAAa;EACtC;CACD;AACD"}
1
+ {"version":3,"file":"react-router.js","names":[],"sources":["../src/react-router/index.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { createContext, createRequestHandler, RouterContextProvider } from \"react-router\";\nimport type { MiddlewareFunction, ServerBuild } from \"react-router\";\nimport { jsonSink, sinkLogger } from \"../core/log.js\";\nimport { requestContextValues } from \"../core/request-context.js\";\nimport type { AppServerEnv, FrameworkRuntime, Mode, RequestContext } from \"../core/types.js\";\n\n/** What the server puts in React Router's context for each request. */\nexport type AppServerContext = RequestContext;\n\n/**\n * The React Router context key for {@link AppServerContext}. Outside a server\n * request, such as in React Router's prerender pass, it holds no request ID\n * and a logger that writes to `jsonSink()`. `requestContext()` from\n * `@ngrok/app-server` gives the same values.\n *\n * @example\n * export async function loader({ context }: Route.LoaderArgs) {\n * \tcontext.get(appServerContext).logger.info(\"loading the dashboard\");\n * }\n */\nexport const appServerContext = createContext<AppServerContext>({\n\trequestId: undefined,\n\tlogger: sinkLogger(jsonSink()),\n\tcspNonce: undefined,\n\tclientAddress: undefined,\n});\n\n/** The Hono context of the request, for {@link recordRoutePattern}. */\nconst honoContext = createContext<Context<AppServerEnv>>();\n\n/**\n * Sets `routePattern` on the Hono context to the route pattern that React\n * Router matched, such as `/domains/:domainId`, so the access log writes\n * `http.route`. Why a root middleware: it runs for each document, data, and\n * resource request, and it costs less for each request than a request\n * handler instrumentation.\n */\nconst recordRoutePattern: MiddlewareFunction<Response> = async ({ pattern, context }, next) => {\n\tif (pattern !== \"\") {\n\t\t// Why the slash: React Router joins the relative paths of the routes, such as `domains/:domainId`.\n\t\tcontext.get(honoContext).set(\"routePattern\", pattern.startsWith(\"/\") ? pattern : `/${pattern}`);\n\t}\n\treturn next();\n};\n\n/** `build` with {@link recordRoutePattern} before the middleware of each root route. */\nfunction withRoutePattern(build: ServerBuild): ServerBuild {\n\tconst routes = Object.fromEntries(\n\t\tObject.entries(build.routes).map(([id, route]) => [\n\t\t\tid,\n\t\t\troute == null || route.parentId != null\n\t\t\t\t? route\n\t\t\t\t: {\n\t\t\t\t\t\t...route,\n\t\t\t\t\t\tmodule: {\n\t\t\t\t\t\t\t...route.module,\n\t\t\t\t\t\t\tmiddleware: [recordRoutePattern, ...(route.module.middleware ?? [])],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t]),\n\t);\n\treturn { ...build, routes };\n}\n\n/**\n * Whether a module is a React Router server build.\n *\n * @example\n * isServerBuild(await import(\"./build/server/index.js\")); // => true\n */\nexport function isServerBuild(value: unknown): value is ServerBuild {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"routes\" in value &&\n\t\t\"entry\" in value &&\n\t\t\"assetsBuildDirectory\" in value &&\n\t\ttypeof value.assetsBuildDirectory === \"string\"\n\t);\n}\n\n/**\n * The run side of the React Router adapter, for a server build. Each request\n * gets a `RouterContextProvider` that holds {@link appServerContext}. The\n * access log gets the route pattern that React Router matched.\n *\n * @example\n * const framework = runtime(build, { mode: \"production\" });\n */\nexport function runtime(build: unknown, { mode }: { mode: Mode }): FrameworkRuntime {\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server module is not a React Router server build.\");\n\t}\n\t// Why also here: the Vite plugin checks the base, but a plain build skips the plugin.\n\tif (build.publicPath !== \"/\") {\n\t\tthrow new Error(\n\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this build has the publicPath \"${build.publicPath}\".`,\n\t\t);\n\t}\n\tconst handler = createRequestHandler(withRoutePattern(build), mode);\n\t// Why: lazy route discovery fetches this exact path, so a redirect breaks it.\n\tconst manifestPath =\n\t\tbuild.routeDiscovery.mode === \"lazy\"\n\t\t\t? [build.basename ?? \"\", build.routeDiscovery.manifestPath || \"/__manifest\"]\n\t\t\t\t\t.join(\"/\")\n\t\t\t\t\t.replaceAll(/\\/+/gu, \"/\")\n\t\t\t: undefined;\n\treturn {\n\t\tname: \"react-router\",\n\t\tclientDirectory: build.assetsBuildDirectory,\n\t\tprerenderedPaths: build.prerender,\n\t\tisDataRequest: (path) => path.endsWith(\".data\") || path === manifestPath,\n\t\tcontentTypes: { \".data\": \"text/x-script\" },\n\t\tfetch: async (request, context) => {\n\t\t\tconst routerContext = new RouterContextProvider();\n\t\t\trouterContext.set(appServerContext, requestContextValues(context));\n\t\t\trouterContext.set(honoContext, context);\n\t\t\treturn handler(request, routerContext);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,MAAa,mBAAmB,cAAgC;CAC/D,WAAW;CACX,QAAQ,WAAW,SAAS,CAAC;CAC7B,UAAU;CACV,eAAe;AAChB,CAAC;;AAGD,MAAM,cAAc,cAAqC;;;;;;;;AASzD,MAAM,qBAAmD,OAAO,EAAE,SAAS,WAAW,SAAS;CAC9F,IAAI,YAAY,IAEf,QAAQ,IAAI,WAAW,CAAC,CAAC,IAAI,gBAAgB,QAAQ,WAAW,GAAG,IAAI,UAAU,IAAI,SAAS;CAE/F,OAAO,KAAK;AACb;;AAGA,SAAS,iBAAiB,OAAiC;CAC1D,MAAM,SAAS,OAAO,YACrB,OAAO,QAAQ,MAAM,MAAM,CAAC,CAAC,KAAK,CAAC,IAAI,WAAW,CACjD,IACA,SAAS,QAAQ,MAAM,YAAY,OAChC,QACA;EACA,GAAG;EACH,QAAQ;GACP,GAAG,MAAM;GACT,YAAY,CAAC,oBAAoB,GAAI,MAAM,OAAO,cAAc,CAAC,CAAE;EACpE;CACD,CACH,CAAC,CACF;CACA,OAAO;EAAE,GAAG;EAAO;CAAO;AAC3B;;;;;;;AAQA,SAAgB,cAAc,OAAsC;CACnE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,YAAY,SACZ,WAAW,SACX,0BAA0B,SAC1B,OAAO,MAAM,yBAAyB;AAExC;;;;;;;;;AAUA,SAAgB,QAAQ,OAAgB,EAAE,QAA0C;CACnF,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,uDAAuD;CAGxE,IAAI,MAAM,eAAe,KACxB,MAAM,IAAI,MACT,oFAAoF,MAAM,WAAW,GACtG;CAED,MAAM,UAAU,qBAAqB,iBAAiB,KAAK,GAAG,IAAI;CAElE,MAAM,eACL,MAAM,eAAe,SAAS,SAC3B,CAAC,MAAM,YAAY,IAAI,MAAM,eAAe,gBAAgB,aAAa,CAAC,CACzE,KAAK,GAAG,CAAC,CACT,WAAW,SAAS,GAAG,IACxB;CACJ,OAAO;EACN,MAAM;EACN,iBAAiB,MAAM;EACvB,kBAAkB,MAAM;EACxB,gBAAgB,SAAS,KAAK,SAAS,OAAO,KAAK,SAAS;EAC5D,cAAc,EAAE,SAAS,gBAAgB;EACzC,OAAO,OAAO,SAAS,YAAY;GAClC,MAAM,gBAAgB,IAAI,sBAAsB;GAChD,cAAc,IAAI,kBAAkB,qBAAqB,OAAO,CAAC;GACjE,cAAc,IAAI,aAAa,OAAO;GACtC,OAAO,QAAQ,SAAS,aAAa;EACtC;CACD;AACD"}
@@ -1,4 +1,4 @@
1
- import { t as loadEntry } from "./load-entry-Bodyd2Ok.js";
1
+ import { t as loadEntry } from "./load-entry-D7r0mjEp.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
@@ -26,4 +26,4 @@ async function serve({ buildPath }) {
26
26
  }
27
27
 
28
28
  export { serve };
29
- //# sourceMappingURL=serve-caOkS3o5.js.map
29
+ //# sourceMappingURL=serve-E0hSGe6_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve-caOkS3o5.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
1
+ {"version":3,"file":"serve-E0hSGe6_.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
@@ -1,4 +1,4 @@
1
- import { a as serverTimingMetrics, i as isBuildMetric, n as BUILD_ID_METRIC, t as BUILD_ID_HEADER } from "./build-id-C6sYO9Yp.js";
1
+ import { a as serverTimingMetrics, i as isBuildMetric, n as BUILD_ID_METRIC, t as BUILD_ID_HEADER } from "./build-id-B0448vZH.js";
2
2
 
3
3
  // src/client/document-nonce.ts
4
4
  /**
@@ -336,4 +336,4 @@ function staleBuildTanStack(router, options = {}) {
336
336
  }
337
337
 
338
338
  export { staleBuildTanStack as n, documentNonce as r, staleBuildReactRouter as t };
339
- //# sourceMappingURL=stale-build-navigation-PnMLtTF8.js.map
339
+ //# sourceMappingURL=stale-build-navigation-rg5xxmTr.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"stale-build-navigation-PnMLtTF8.js","names":[],"sources":["../src/client/document-nonce.ts","../src/client/stale-build-navigation.ts"],"sourcesContent":["/**\n * The CSP nonce of the document's first element with a nonce, or `undefined`\n * when it has none. The browser build of `@ngrok/app-server/client` exports it\n * as `cspNonce()`, so the browser bundle holds no server code.\n *\n * @example\n * documentNonce(); // => \"d2hhdCBhIG5vbmNl\"\n */\nexport function documentNonce(): string | undefined {\n\t// Why the property: a browser hides the value of the `nonce` attribute when the page's CSP applies.\n\treturn document.querySelector<HTMLElement>(\"[nonce]\")?.nonce;\n}\n","import {\n\tBUILD_ID_HEADER,\n\tBUILD_ID_METRIC,\n\tisBuildMetric,\n\tserverTimingMetrics,\n} from \"../core/plugins/build-id.js\";\n\n/** Options for {@link staleBuildReactRouter} and {@link staleBuildTanStack}. */\nexport type StaleBuildOptions = {\n\t/**\n\t * The header that `buildId()` sets on data responses.\n\t * @default \"X-Build-Id\"\n\t */\n\theader?: string;\n\t/**\n\t * The build that this document runs. Set it only when the server does not\n\t * send it.\n\t * @default the `build` metric of the document's `Server-Timing`, which `buildId()` sends\n\t */\n\tbuild?: string;\n\t/**\n\t * Runs once, when the tab first sees a response from another build. Use\n\t * it to count stale tabs in the app's RUM tool.\n\t */\n\tonNewBuild?: (served: string) => void;\n};\n\n/** The context that React Router gives `unstable_fetch` with each request. */\nexport type RouterFetchContext = {\n\t/** `\"navigation\"` for the data request of a navigation that the router started. */\n\ttype: string;\n\t/** `\"PUSH\"`, `\"REPLACE\"`, or `\"POP\"` for a navigation. */\n\tnavigationType?: string | null;\n\t/** The fetcher that sends the request, also in a navigation that revalidates it. */\n\tfetcherKey?: string | null;\n};\n\n/** The location in a TanStack Router event. */\ntype EventLocation = { pathname: string; searchStr: string };\n\n/** The part of a TanStack Router that {@link staleBuildTanStack} reads. */\nexport type NavigationEvents = {\n\thistory: { flush: () => void };\n\tclearCache: () => void;\n\tsubscribe: (\n\t\ttype: \"onBeforeNavigate\" | \"onResolved\",\n\t\tlistener: (event: { fromLocation?: EventLocation; toLocation: EventLocation }) => void,\n\t) => () => void;\n};\n\n/** Whether `url` is on the origin of this page. */\nfunction isOwn(url: string): boolean {\n\treturn new URL(url, location.href).origin === location.origin;\n}\n\n/** The build in the `Server-Timing` of the first of `entries` that has one, from this origin only. */\nfunction timingBuild(entries: PerformanceEntryList): string | undefined {\n\treturn (\n\t\tentries\n\t\t\t.filter(\n\t\t\t\t(entry): entry is PerformanceResourceTiming => \"serverTiming\" in entry && isOwn(entry.name),\n\t\t\t)\n\t\t\t// Why: a redirected resource keeps its first URL as its name, and the redirect can end on\n\t\t\t// another origin. A document entry has its final URL.\n\t\t\t.filter((entry) => entry.entryType !== \"resource\" || entry.redirectStart === 0)\n\t\t\t.flatMap((entry) => entry.serverTiming)\n\t\t\t.find((metric) => metric.name === BUILD_ID_METRIC)?.description\n\t);\n}\n\n/** The build in a `Server-Timing` header, as `buildId()` writes it. */\nfunction headerBuild(header: string | null): string | undefined {\n\tconst { quoted, token } =\n\t\tserverTimingMetrics(header)\n\t\t\t.find((metric) => isBuildMetric(metric))\n\t\t\t?.match(/;\\s*desc\\s*=\\s*(?:\"(?<quoted>(?:[^\"\\\\]|\\\\.)*)\"|(?<token>[^;\\s]*))/iu)?.groups ?? {};\n\treturn quoted?.replaceAll(/\\\\(?<char>.)/gu, \"$<char>\") ?? token;\n}\n\n/** The page of `url`: the router renders a new route for a new path or query, not for a new fragment. */\nfunction pageOf(url: string): string {\n\tconst { origin, pathname, search } = new URL(url, location.href);\n\treturn `${origin}${pathname}${search}`;\n}\n\n/** The page of a TanStack Router location, as {@link pageOf} reads a URL. */\nfunction eventPage({ pathname, searchStr }: EventLocation): string {\n\treturn `${pathname}${searchStr}`;\n}\n\n/** The URL of a `fetch` call. */\nfunction urlOf(input: RequestInfo | URL): string {\n\treturn input instanceof Request ? input.url : String(input);\n}\n\n/** The method of a `fetch` call. */\nfunction methodOf(input: RequestInfo | URL, init: RequestInit | undefined): string {\n\treturn (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n}\n\n/** The page that a React Router data request loads: `/a.data` loads `/a`, and `/a/_.data` loads `/a/`. */\nfunction targetOf(request: Request): string {\n\tconst url = new URL(request.url);\n\turl.pathname = url.pathname.replace(/\\/_\\.data$/u, \"/\").replace(/\\.data$/u, \"\");\n\turl.searchParams.delete(\"_routes\");\n\treturn url.href;\n}\n\n/**\n * Reloads a document that the back/forward cache shows again. Why: Back can\n * show the document that {@link loadDocument} left, with its router still in a\n * navigation that never ends. Why one function: the browser adds it once.\n */\nfunction reloadIfRestored(event: PageTransitionEvent): void {\n\tif (event.persisted) {\n\t\tlocation.reload();\n\t}\n}\n\n/**\n * Loads `target` as a document, so the old code never gets the new build's\n * data. It returns a promise that never settles, because the page unloads.\n */\nasync function loadDocument(\n\ttarget: string,\n\t{\n\t\tresponse,\n\t\tnavigationType,\n\t}: { response?: Response | undefined; navigationType?: string | null | undefined } = {},\n): Promise<never> {\n\t// Why no wait: the cancel of a cloned body waits for the other branch.\n\tresponse?.body?.cancel().catch(() => undefined);\n\t// Why reload on this page: the router can move history first, and `assign` to the same page\n\t// with a fragment scrolls with no document load. A history step already moved history. Why\n\t// not to remove a fragment: `assign` to a URL with no fragment loads the document.\n\tconst isSamePage = pageOf(target) === pageOf(location.href);\n\tconst removesFragment = new URL(target, location.href).hash === \"\" && location.hash !== \"\";\n\taddEventListener(\"pageshow\", reloadIfRestored, { once: true });\n\tif (navigationType === \"POP\" || (isSamePage && !removesFragment)) {\n\t\tlocation.reload();\n\t} else if (navigationType === \"REPLACE\") {\n\t\tlocation.replace(target);\n\t} else {\n\t\tlocation.assign(target);\n\t}\n\treturn new Promise<never>(() => {});\n}\n\n/**\n * Runs `clear` when `signal` aborts. Why: the router aborts a navigation when a\n * newer one starts, such as after the visitor stays on the page at a leave prompt.\n */\nfunction onAbort(signal: AbortSignal, clear: () => void): void {\n\tsignal.addEventListener(\"abort\", clear, { once: true });\n}\n\n/** Reads the build of each response, and tells when the server runs a new build. */\nfunction watchBuild({ header = BUILD_ID_HEADER, build, onNewBuild }: StaleBuildOptions) {\n\t// Why: on the server, such as in a router factory that runs for each request, there is no tab to move.\n\tif (typeof document === \"undefined\") {\n\t\treturn null;\n\t}\n\tconst current = build ?? timingBuild(performance.getEntriesByType(\"navigation\"));\n\tif (current == null) {\n\t\treturn null;\n\t}\n\tlet stale = false;\n\tconst see = (served: string | null | undefined) => {\n\t\tif (served == null || served === current || stale) {\n\t\t\treturn;\n\t\t}\n\t\tstale = true;\n\t\t// Why a catch: an error in the app's callback must not fail the request that found the build.\n\t\ttry {\n\t\t\tonNewBuild?.(served);\n\t\t} catch (error) {\n\t\t\treportError(error);\n\t\t}\n\t};\n\t// Why resource timing: it shows the build of a response that no script fetched, such as a\n\t// prefetch on hover, so the tab can find a new build before the click. Why buffered: a prefetch\n\t// can finish before this module runs.\n\tconst observer =\n\t\ttypeof PerformanceObserver === \"function\"\n\t\t\t? new PerformanceObserver((list) => {\n\t\t\t\t\t// Why each entry: one delivery can hold the old build first and the new build after it.\n\t\t\t\t\tfor (const entry of list.getEntries()) {\n\t\t\t\t\t\tsee(timingBuild([entry]));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: undefined;\n\tobserver?.observe({ type: \"resource\", buffered: true });\n\treturn {\n\t\tisStale: () => stale,\n\t\t/** Whether `response` comes from a new build of this origin. `url` is the URL of the request. */\n\t\tisNew: (response: Response, url: string) => {\n\t\t\t// Why the final URL: a redirect can end on another origin. Why `Server-Timing`: a proxy\n\t\t\t// route of `buildId({ paths })` sends no build header.\n\t\t\tconst served = isOwn(response.url === \"\" ? url : response.url)\n\t\t\t\t? (response.headers.get(header) ?? headerBuild(response.headers.get(\"Server-Timing\")))\n\t\t\t\t: null;\n\t\t\tsee(served);\n\t\t\treturn served != null && served !== current;\n\t\t},\n\t\tstop: () => observer?.disconnect(),\n\t};\n}\n\n/** The `navigate` call of a React Router instrumentation. */\ntype NavigateInfo = { to: string | number; formMethod?: string };\n\n/** The router instrumentations that {@link staleBuildReactRouter} adds. */\ntype RouterInstrumentations = {\n\tnavigate: (handler: () => Promise<unknown>, info: NavigateInfo) => Promise<void>;\n};\n\n/**\n * The arguments of a client middleware call. Why the `unstable_` fields: React\n * Router gives the middleware the arguments of its data strategy, which tell a\n * navigation from a fetcher and give its history action.\n */\ntype MiddlewareArgs = {\n\trequest: Request;\n\tunstable_initiator?: string;\n\tunstable_navigationType?: string | null;\n};\n\n/** The hooks that {@link staleBuildReactRouter} gives to React Router. */\nexport type StaleBuildReactRouter = {\n\t/** Give it to `HydratedRouter` as `unstable_fetch`. */\n\tfetch: (request: Request, context: RouterFetchContext) => Promise<Response>;\n\t/** Give it to `HydratedRouter` in `instrumentations`. */\n\tinstrumentation: {\n\t\trouter: (router: { instrument: (instrumentations: RouterInstrumentations) => void }) => void;\n\t};\n\t/** Export it from `app/root.tsx` in `clientMiddleware`. */\n\tmiddleware: <Result>(args: { request: Request }, next: () => Promise<Result>) => Promise<Result>;\n};\n\n/** The fragment of a `navigate` target, such as `#usage`, or `\"\"`. */\nfunction hashOf(to: string | number): string {\n\treturn typeof to === \"string\" && to.includes(\"#\") ? to.slice(to.indexOf(\"#\")) : \"\";\n}\n\n/**\n * Moves an open React Router tab to a new build at a navigation, so the old\n * client code never renders data from the new server, and the page that the\n * visitor reads never reloads. Create it in a module that the client entry\n * and `app/root.tsx` both import. It reads no browser state until React\n * Router calls it, so the server can import it.\n *\n * - When the data request of a navigation gets a response from a new build,\n * the browser loads the target URL as a document.\n * - When the tab already knows of a new build, a `navigate` call, such as a\n * link click, loads its target as a document before the router renders it\n * or sends a data request. The root middleware does this also for a route\n * with no loader.\n * - A revalidation, a fetcher, an action, and the loaders after an action\n * get their response. They only mark the tab, so the page that the visitor\n * reads never reloads.\n * - The router's blockers run first, and a canceled navigation never loads\n * its target.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n *\n * @example\n * // app/stale-build.ts\n * export const staleBuild = staleBuildReactRouter();\n *\n * // app/root.tsx\n * export const clientMiddleware = [staleBuild.middleware];\n *\n * // app/entry.client.tsx\n * startTransition(() => {\n * \thydrateRoot(\n * \t\tdocument,\n * \t\t<HydratedRouter\n * \t\t\tunstable_fetch={staleBuild.fetch}\n * \t\t\tinstrumentations={[staleBuild.instrumentation]}\n * \t\t/>,\n * \t);\n * });\n */\nexport function staleBuildReactRouter(options: StaleBuildOptions = {}): StaleBuildReactRouter {\n\t// Why lazy: `app/root.tsx` also runs on the server, which has no tab to watch.\n\tlet watched: { watch: ReturnType<typeof watchBuild> } | undefined;\n\tconst watch = () => {\n\t\twatched ??= { watch: watchBuild(options) };\n\t\treturn watched.watch;\n\t};\n\t/**\n\t * The path of the last action of a navigation, until its loaders run. The\n\t * router revalidates the page with one or more loader requests after it.\n\t * `loading` is true while they run.\n\t */\n\tlet action: { path: string; loading: boolean } | undefined;\n\t/** The target that the tab loads as a document now. */\n\tlet leaving: string | undefined;\n\t/**\n\t * The last `navigate` call. `claimed` is true when its first middleware call\n\t * already ran, or when it is not a page load. `page` is the target page of\n\t * that first call.\n\t */\n\tlet navigating: { hash: string; claimed: boolean; page?: string } | undefined;\n\tconst load = async (\n\t\trequest: Request,\n\t\ttarget: string,\n\t\t{ response, navigationType }: { response?: Response; navigationType?: string | null } = {},\n\t) => {\n\t\tif (leaving === target) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<never>(() => {});\n\t\t}\n\t\tleaving = target;\n\t\tonAbort(request.signal, () => {\n\t\t\tif (leaving === target) {\n\t\t\t\tleaving = undefined;\n\t\t\t}\n\t\t});\n\t\treturn loadDocument(target, { response, navigationType });\n\t};\n\treturn {\n\t\tfetch: async (request, context) => {\n\t\t\tconst navigationType =\n\t\t\t\tcontext.type === \"navigation\" && context.fetcherKey == null\n\t\t\t\t\t? context.navigationType\n\t\t\t\t\t: undefined;\n\t\t\t// Why the global at each call: an app can wrap `fetch` after this module, such as for RUM.\n\t\t\tconst send = async () => {\n\t\t\t\tconst response = await globalThis.fetch(request);\n\t\t\t\treturn { response, isNew: watch()?.isNew(response, request.url) === true };\n\t\t\t};\n\t\t\tif (watch() == null || navigationType == null) {\n\t\t\t\treturn (await send()).response;\n\t\t\t}\n\t\t\t// Why the hash of the `navigate` call: the router removes it from the data request. Why\n\t\t\t// its page only: a redirect goes to another page with no `navigate` call.\n\t\t\tconst page = targetOf(request);\n\t\t\tconst hash =\n\t\t\t\tnavigationType !== \"POP\" && navigating?.page === pageOf(page) ? navigating.hash : \"\";\n\t\t\tconst target = page + hash;\n\t\t\tconst path = new URL(target).pathname;\n\t\t\tconst isAfterAction = request.method === \"GET\" && action?.path === path;\n\t\t\t// Why check the signal: a canceled navigation must never load its target.\n\t\t\tconst isNavigation = () =>\n\t\t\t\trequest.method === \"GET\" && !isAfterAction && !request.signal.aborted;\n\t\t\tif (isNavigation() && watch()?.isStale() === true) {\n\t\t\t\treturn load(request, target, { navigationType });\n\t\t\t}\n\t\t\tconst { response, isNew } = await send();\n\t\t\tif (!isNew || !isNavigation()) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\treturn load(request, target, { response, navigationType });\n\t\t},\n\t\tinstrumentation: {\n\t\t\trouter: ({ instrument }) => {\n\t\t\t\twatch();\n\t\t\t\tinstrument({\n\t\t\t\t\tnavigate: async (handler, { to, formMethod }) => {\n\t\t\t\t\t\t// Why claimed: a history step and a form submission are not a page load to take over.\n\t\t\t\t\t\tconst current = {\n\t\t\t\t\t\t\thash: hashOf(to),\n\t\t\t\t\t\t\tclaimed: typeof to === \"number\" || (formMethod ?? \"GET\").toUpperCase() !== \"GET\",\n\t\t\t\t\t\t};\n\t\t\t\t\t\tnavigating = current;\n\t\t\t\t\t\tawait handler();\n\t\t\t\t\t\t// Why keep an unclaimed call: a blocker stops it, and `blocker.proceed()` starts it\n\t\t\t\t\t\t// again with no `navigate` call.\n\t\t\t\t\t\tif (navigating === current && current.claimed) {\n\t\t\t\t\t\t\tnavigating = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tmiddleware: async (args, next) => {\n\t\t\tconst {\n\t\t\t\trequest,\n\t\t\t\tunstable_initiator: initiator,\n\t\t\t\tunstable_navigationType: navigationType,\n\t\t\t} = args as MiddlewareArgs;\n\t\t\tconst current = navigating;\n\t\t\tif (initiator === \"navigation\") {\n\t\t\t\t// Why here: a `clientAction` sends no request, and the router runs the middleware once\n\t\t\t\t// for an action and once for all the loaders after it.\n\t\t\t\tconst path = new URL(request.url).pathname;\n\t\t\t\tconst mark = action;\n\t\t\t\tif (navigationType === \"POP\") {\n\t\t\t\t\taction = undefined;\n\t\t\t\t} else if (request.method !== \"GET\") {\n\t\t\t\t\tconst started = { path, loading: false };\n\t\t\t\t\taction = started;\n\t\t\t\t\tonAbort(request.signal, () => {\n\t\t\t\t\t\tif (action === started) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn next();\n\t\t\t\t} else if (mark?.path === path) {\n\t\t\t\t\tmark.loading = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await next();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (action === mark) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (mark?.loading === false) {\n\t\t\t\t\t// Why: a redirect after the action goes to another page, and its loaders never run.\n\t\t\t\t\t// Why not while they run: the router revalidates the fetchers next to them.\n\t\t\t\t\taction = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Why no history step: it comes from no `navigate` call, and the fetch hook reloads it.\n\t\t\t// Why the first call only: the router runs the middleware of a navigation before the\n\t\t\t// fetchers that it revalidates, and they have the same initiator.\n\t\t\tif (\n\t\t\t\tinitiator !== \"navigation\" ||\n\t\t\t\tnavigationType == null ||\n\t\t\t\tnavigationType === \"POP\" ||\n\t\t\t\tcurrent == null ||\n\t\t\t\tcurrent.claimed\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tcurrent.claimed = true;\n\t\t\tcurrent.page = pageOf(request.url);\n\t\t\tif (\n\t\t\t\trequest.signal.aborted ||\n\t\t\t\twatch()?.isStale() !== true ||\n\t\t\t\tpageOf(request.url) === pageOf(location.href)\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\treturn load(request, request.url + current.hash, { navigationType });\n\t\t},\n\t};\n}\n\n/**\n * Moves an open TanStack Router tab to a new build at a navigation, so the\n * old client code never renders data from the new server, and the page that\n * the visitor reads never reloads. Call it with the router on the client.\n *\n * - A navigation runs from `onBeforeNavigate` to `onResolved`. The router\n * moves history and runs its blockers before it.\n * - When a GET response from a new build comes back while a navigation\n * runs, such as from a server function in a loader, the browser loads the\n * page as a document.\n * - When the tab already knows of a new build, a navigation to a new path or\n * query clears the router cache and loads the page as a document.\n * - A request outside a navigation gets its response, and only marks the tab.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n * It returns a function that stops it and gives back `fetch`. If the app\n * wrapped `fetch` after it, the wrapper stays, and each request passes on.\n *\n * @example\n * // src/router.tsx\n * export function getRouter() {\n * \tconst router = createRouter({ routeTree });\n * \tif (!router.isServer) {\n * \t\tstaleBuildTanStack(router);\n * \t}\n * \treturn router;\n * }\n */\nexport function staleBuildTanStack(\n\trouter: NavigationEvents,\n\toptions: StaleBuildOptions = {},\n): () => void {\n\tconst watch = watchBuild(options);\n\tif (watch == null) {\n\t\treturn () => {};\n\t}\n\t/** The navigation that runs now. `leaving` is true when it already loads its page as a document. */\n\tlet navigation: { leaving: boolean } | undefined;\n\tconst reload = async (current: { leaving: boolean }, response?: Response) => {\n\t\tif (current.leaving) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<Response>(() => {});\n\t\t}\n\t\tcurrent.leaving = true;\n\t\t// Why flush: the router's history moves the browser's URL in a microtask, after\n\t\t// `onBeforeNavigate`. A reload before that loads the page that the visitor leaves.\n\t\trouter.history.flush();\n\t\treturn loadDocument(location.href, { response });\n\t};\n\tconst unsubscribe = [\n\t\trouter.subscribe(\"onBeforeNavigate\", ({ fromLocation, toLocation }) => {\n\t\t\t// Why clear first: a change to the fragment replaces a navigation that has not ended.\n\t\t\tnavigation = undefined;\n\t\t\tif (fromLocation == null || eventPage(fromLocation) === eventPage(toLocation)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tnavigation = { leaving: false };\n\t\t\tif (watch.isStale()) {\n\t\t\t\t// Why clear: the router matches the target after this event, and a preload can hold the\n\t\t\t\t// new build's data. With no cache, each loader fetches again, and `fetch` holds it.\n\t\t\t\trouter.clearCache();\n\t\t\t\tvoid reload(navigation);\n\t\t\t}\n\t\t}),\n\t\trouter.subscribe(\"onResolved\", () => {\n\t\t\tnavigation = undefined;\n\t\t}),\n\t];\n\tconst send = globalThis.fetch;\n\tlet isStopped = false;\n\tconst patched: typeof fetch = async (input, init) => {\n\t\tif (isStopped) {\n\t\t\treturn send.call(globalThis, input, init);\n\t\t}\n\t\tconst isGet = methodOf(input, init) === \"GET\";\n\t\tif (isGet && navigation != null && watch.isStale()) {\n\t\t\treturn reload(navigation);\n\t\t}\n\t\tconst response = await send.call(globalThis, input, init);\n\t\t// Why the navigation at the response: a navigation can take the pending loader of a preload,\n\t\t// or of the navigation that it replaced.\n\t\tif (!watch.isNew(response, urlOf(input)) || !isGet || navigation == null) {\n\t\t\treturn response;\n\t\t}\n\t\treturn reload(navigation, response);\n\t};\n\tglobalThis.fetch = patched;\n\treturn () => {\n\t\tfor (const stop of unsubscribe) {\n\t\t\tstop();\n\t\t}\n\t\twatch.stop();\n\t\tisStopped = true;\n\t\tnavigation = undefined;\n\t\t// Why check: a wrapper that the app adds later still calls this one, and must stay.\n\t\tif (globalThis.fetch === patched) {\n\t\t\tglobalThis.fetch = send;\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAgB,gBAAoC;CAEnD,OAAO,SAAS,cAA2B,SAAS,CAAC,EAAE;AACxD;;;;ACwCA,SAAS,MAAM,KAAsB;CACpC,OAAO,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,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,CAAC,CACF;CACA,MAAM,OAAO,WAAW;CACxB,IAAI,YAAY;CAChB,MAAM,UAAwB,OAAO,OAAO,SAAS;EACpD,IAAI,WACH,OAAO,KAAK,KAAK,YAAY,OAAO,IAAI;EAEzC,MAAM,QAAQ,SAAS,OAAO,IAAI,MAAM;EACxC,IAAI,SAAS,cAAc,QAAQ,MAAM,QAAQ,GAChD,OAAO,OAAO,UAAU;EAEzB,MAAM,WAAW,MAAM,KAAK,KAAK,YAAY,OAAO,IAAI;EAGxD,IAAI,CAAC,MAAM,MAAM,UAAU,MAAM,KAAK,CAAC,KAAK,CAAC,SAAS,cAAc,MACnE,OAAO;EAER,OAAO,OAAO,YAAY,QAAQ;CACnC;CACA,WAAW,QAAQ;CACnB,aAAa;EACZ,KAAK,MAAM,QAAQ,aAClB,KAAK;EAEN,MAAM,KAAK;EACX,YAAY;EACZ,aAAa;EAEb,IAAI,WAAW,UAAU,SACxB,WAAW,QAAQ;CAErB;AACD"}
1
+ {"version":3,"file":"stale-build-navigation-rg5xxmTr.js","names":[],"sources":["../src/client/document-nonce.ts","../src/client/stale-build-navigation.ts"],"sourcesContent":["/**\n * The CSP nonce of the document's first element with a nonce, or `undefined`\n * when it has none. The browser build of `@ngrok/app-server/client` exports it\n * as `cspNonce()`, so the browser bundle holds no server code.\n *\n * @example\n * documentNonce(); // => \"d2hhdCBhIG5vbmNl\"\n */\nexport function documentNonce(): string | undefined {\n\t// Why the property: a browser hides the value of the `nonce` attribute when the page's CSP applies.\n\treturn document.querySelector<HTMLElement>(\"[nonce]\")?.nonce;\n}\n","import {\n\tBUILD_ID_HEADER,\n\tBUILD_ID_METRIC,\n\tisBuildMetric,\n\tserverTimingMetrics,\n} from \"../core/plugins/build-id.js\";\n\n/** Options for {@link staleBuildReactRouter} and {@link staleBuildTanStack}. */\nexport type StaleBuildOptions = {\n\t/**\n\t * The header that `buildId()` sets on data responses.\n\t * @default \"X-Build-Id\"\n\t */\n\theader?: string;\n\t/**\n\t * The build that this document runs. Set it only when the server does not\n\t * send it.\n\t * @default the `build` metric of the document's `Server-Timing`, which `buildId()` sends\n\t */\n\tbuild?: string;\n\t/**\n\t * Runs once, when the tab first sees a response from another build. Use\n\t * it to count stale tabs in the app's RUM tool.\n\t */\n\tonNewBuild?: (served: string) => void;\n};\n\n/** The context that React Router gives `unstable_fetch` with each request. */\nexport type RouterFetchContext = {\n\t/** `\"navigation\"` for the data request of a navigation that the router started. */\n\ttype: string;\n\t/** `\"PUSH\"`, `\"REPLACE\"`, or `\"POP\"` for a navigation. */\n\tnavigationType?: string | null;\n\t/** The fetcher that sends the request, also in a navigation that revalidates it. */\n\tfetcherKey?: string | null;\n};\n\n/** The location in a TanStack Router event. */\ntype EventLocation = { pathname: string; searchStr: string };\n\n/** The part of a TanStack Router that {@link staleBuildTanStack} reads. */\nexport type NavigationEvents = {\n\thistory: { flush: () => void };\n\tclearCache: () => void;\n\tsubscribe: (\n\t\ttype: \"onBeforeNavigate\" | \"onResolved\",\n\t\tlistener: (event: { fromLocation?: EventLocation; toLocation: EventLocation }) => void,\n\t) => () => void;\n};\n\n/** Whether `url` is on the origin of this page. */\nfunction isOwn(url: string): boolean {\n\treturn new URL(url, location.href).origin === location.origin;\n}\n\n/** The build in the `Server-Timing` of the first of `entries` that has one, from this origin only. */\nfunction timingBuild(entries: PerformanceEntryList): string | undefined {\n\treturn (\n\t\tentries\n\t\t\t.filter(\n\t\t\t\t(entry): entry is PerformanceResourceTiming => \"serverTiming\" in entry && isOwn(entry.name),\n\t\t\t)\n\t\t\t// Why: a redirected resource keeps its first URL as its name, and the redirect can end on\n\t\t\t// another origin. A document entry has its final URL.\n\t\t\t.filter((entry) => entry.entryType !== \"resource\" || entry.redirectStart === 0)\n\t\t\t.flatMap((entry) => entry.serverTiming)\n\t\t\t.find((metric) => metric.name === BUILD_ID_METRIC)?.description\n\t);\n}\n\n/** The build in a `Server-Timing` header, as `buildId()` writes it. */\nfunction headerBuild(header: string | null): string | undefined {\n\tconst { quoted, token } =\n\t\tserverTimingMetrics(header)\n\t\t\t.find((metric) => isBuildMetric(metric))\n\t\t\t?.match(/;\\s*desc\\s*=\\s*(?:\"(?<quoted>(?:[^\"\\\\]|\\\\.)*)\"|(?<token>[^;\\s]*))/iu)?.groups ?? {};\n\treturn quoted?.replaceAll(/\\\\(?<char>.)/gu, \"$<char>\") ?? token;\n}\n\n/** The page of `url`: the router renders a new route for a new path or query, not for a new fragment. */\nfunction pageOf(url: string): string {\n\tconst { origin, pathname, search } = new URL(url, location.href);\n\treturn `${origin}${pathname}${search}`;\n}\n\n/** The page of a TanStack Router location, as {@link pageOf} reads a URL. */\nfunction eventPage({ pathname, searchStr }: EventLocation): string {\n\treturn `${pathname}${searchStr}`;\n}\n\n/** The URL of a `fetch` call. */\nfunction urlOf(input: RequestInfo | URL): string {\n\treturn input instanceof Request ? input.url : String(input);\n}\n\n/** The method of a `fetch` call. */\nfunction methodOf(input: RequestInfo | URL, init: RequestInit | undefined): string {\n\treturn (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n}\n\n/** The page that a React Router data request loads: `/a.data` loads `/a`, and `/a/_.data` loads `/a/`. */\nfunction targetOf(request: Request): string {\n\tconst url = new URL(request.url);\n\turl.pathname = url.pathname.replace(/\\/_\\.data$/u, \"/\").replace(/\\.data$/u, \"\");\n\turl.searchParams.delete(\"_routes\");\n\treturn url.href;\n}\n\n/**\n * Reloads a document that the back/forward cache shows again. Why: Back can\n * show the document that {@link loadDocument} left, with its router still in a\n * navigation that never ends. Why one function: the browser adds it once.\n */\nfunction reloadIfRestored(event: PageTransitionEvent): void {\n\tif (event.persisted) {\n\t\tlocation.reload();\n\t}\n}\n\n/**\n * Loads `target` as a document, so the old code never gets the new build's\n * data. It returns a promise that never settles, because the page unloads.\n */\nasync function loadDocument(\n\ttarget: string,\n\t{\n\t\tresponse,\n\t\tnavigationType,\n\t}: { response?: Response | undefined; navigationType?: string | null | undefined } = {},\n): Promise<never> {\n\t// Why no wait: the cancel of a cloned body waits for the other branch.\n\tresponse?.body?.cancel().catch(() => undefined);\n\t// Why reload on this page: the router can move history first, and `assign` to the same page\n\t// with a fragment scrolls with no document load. A history step already moved history. Why\n\t// not to remove a fragment: `assign` to a URL with no fragment loads the document.\n\tconst isSamePage = pageOf(target) === pageOf(location.href);\n\tconst removesFragment = new URL(target, location.href).hash === \"\" && location.hash !== \"\";\n\taddEventListener(\"pageshow\", reloadIfRestored, { once: true });\n\tif (navigationType === \"POP\" || (isSamePage && !removesFragment)) {\n\t\tlocation.reload();\n\t} else if (navigationType === \"REPLACE\") {\n\t\tlocation.replace(target);\n\t} else {\n\t\tlocation.assign(target);\n\t}\n\treturn new Promise<never>(() => {});\n}\n\n/**\n * Runs `clear` when `signal` aborts. Why: the router aborts a navigation when a\n * newer one starts, such as after the visitor stays on the page at a leave prompt.\n */\nfunction onAbort(signal: AbortSignal, clear: () => void): void {\n\tsignal.addEventListener(\"abort\", clear, { once: true });\n}\n\n/** Reads the build of each response, and tells when the server runs a new build. */\nfunction watchBuild({ header = BUILD_ID_HEADER, build, onNewBuild }: StaleBuildOptions) {\n\t// Why: on the server, such as in a router factory that runs for each request, there is no tab to move.\n\tif (typeof document === \"undefined\") {\n\t\treturn null;\n\t}\n\tconst current = build ?? timingBuild(performance.getEntriesByType(\"navigation\"));\n\tif (current == null) {\n\t\treturn null;\n\t}\n\tlet stale = false;\n\tconst see = (served: string | null | undefined) => {\n\t\tif (served == null || served === current || stale) {\n\t\t\treturn;\n\t\t}\n\t\tstale = true;\n\t\t// Why a catch: an error in the app's callback must not fail the request that found the build.\n\t\ttry {\n\t\t\tonNewBuild?.(served);\n\t\t} catch (error) {\n\t\t\treportError(error);\n\t\t}\n\t};\n\t// Why resource timing: it shows the build of a response that no script fetched, such as a\n\t// prefetch on hover, so the tab can find a new build before the click. Why buffered: a prefetch\n\t// can finish before this module runs.\n\tconst observer =\n\t\ttypeof PerformanceObserver === \"function\"\n\t\t\t? new PerformanceObserver((list) => {\n\t\t\t\t\t// Why each entry: one delivery can hold the old build first and the new build after it.\n\t\t\t\t\tfor (const entry of list.getEntries()) {\n\t\t\t\t\t\tsee(timingBuild([entry]));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: undefined;\n\tobserver?.observe({ type: \"resource\", buffered: true });\n\treturn {\n\t\tisStale: () => stale,\n\t\t/** Whether `response` comes from a new build of this origin. `url` is the URL of the request. */\n\t\tisNew: (response: Response, url: string) => {\n\t\t\t// Why the final URL: a redirect can end on another origin. Why `Server-Timing`: a proxy\n\t\t\t// route of `buildId({ paths })` sends no build header.\n\t\t\tconst served = isOwn(response.url === \"\" ? url : response.url)\n\t\t\t\t? (response.headers.get(header) ?? headerBuild(response.headers.get(\"Server-Timing\")))\n\t\t\t\t: null;\n\t\t\tsee(served);\n\t\t\treturn served != null && served !== current;\n\t\t},\n\t\tstop: () => observer?.disconnect(),\n\t};\n}\n\n/** The `navigate` call of a React Router instrumentation. */\ntype NavigateInfo = { to: string | number; formMethod?: string };\n\n/** The router instrumentations that {@link staleBuildReactRouter} adds. */\ntype RouterInstrumentations = {\n\tnavigate: (handler: () => Promise<unknown>, info: NavigateInfo) => Promise<void>;\n};\n\n/**\n * The arguments of a client middleware call. Why the `unstable_` fields: React\n * Router gives the middleware the arguments of its data strategy, which tell a\n * navigation from a fetcher and give its history action.\n */\ntype MiddlewareArgs = {\n\trequest: Request;\n\tunstable_initiator?: string;\n\tunstable_navigationType?: string | null;\n};\n\n/** The hooks that {@link staleBuildReactRouter} gives to React Router. */\nexport type StaleBuildReactRouter = {\n\t/** Give it to `HydratedRouter` as `unstable_fetch`. */\n\tfetch: (request: Request, context: RouterFetchContext) => Promise<Response>;\n\t/** Give it to `HydratedRouter` in `instrumentations`. */\n\tinstrumentation: {\n\t\trouter: (router: { instrument: (instrumentations: RouterInstrumentations) => void }) => void;\n\t};\n\t/** Export it from `app/root.tsx` in `clientMiddleware`. */\n\tmiddleware: <Result>(args: { request: Request }, next: () => Promise<Result>) => Promise<Result>;\n};\n\n/** The fragment of a `navigate` target, such as `#usage`, or `\"\"`. */\nfunction hashOf(to: string | number): string {\n\treturn typeof to === \"string\" && to.includes(\"#\") ? to.slice(to.indexOf(\"#\")) : \"\";\n}\n\n/**\n * Moves an open React Router tab to a new build at a navigation, so the old\n * client code never renders data from the new server, and the page that the\n * visitor reads never reloads. Create it in a module that the client entry\n * and `app/root.tsx` both import. It reads no browser state until React\n * Router calls it, so the server can import it.\n *\n * - When the data request of a navigation gets a response from a new build,\n * the browser loads the target URL as a document.\n * - When the tab already knows of a new build, a `navigate` call, such as a\n * link click, loads its target as a document before the router renders it\n * or sends a data request. The root middleware does this also for a route\n * with no loader.\n * - A revalidation, a fetcher, an action, and the loaders after an action\n * get their response. They only mark the tab, so the page that the visitor\n * reads never reloads.\n * - The router's blockers run first, and a canceled navigation never loads\n * its target.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n *\n * @example\n * // app/stale-build.ts\n * export const staleBuild = staleBuildReactRouter();\n *\n * // app/root.tsx\n * export const clientMiddleware = [staleBuild.middleware];\n *\n * // app/entry.client.tsx\n * startTransition(() => {\n * \thydrateRoot(\n * \t\tdocument,\n * \t\t<HydratedRouter\n * \t\t\tunstable_fetch={staleBuild.fetch}\n * \t\t\tinstrumentations={[staleBuild.instrumentation]}\n * \t\t/>,\n * \t);\n * });\n */\nexport function staleBuildReactRouter(options: StaleBuildOptions = {}): StaleBuildReactRouter {\n\t// Why lazy: `app/root.tsx` also runs on the server, which has no tab to watch.\n\tlet watched: { watch: ReturnType<typeof watchBuild> } | undefined;\n\tconst watch = () => {\n\t\twatched ??= { watch: watchBuild(options) };\n\t\treturn watched.watch;\n\t};\n\t/**\n\t * The path of the last action of a navigation, until its loaders run. The\n\t * router revalidates the page with one or more loader requests after it.\n\t * `loading` is true while they run.\n\t */\n\tlet action: { path: string; loading: boolean } | undefined;\n\t/** The target that the tab loads as a document now. */\n\tlet leaving: string | undefined;\n\t/**\n\t * The last `navigate` call. `claimed` is true when its first middleware call\n\t * already ran, or when it is not a page load. `page` is the target page of\n\t * that first call.\n\t */\n\tlet navigating: { hash: string; claimed: boolean; page?: string } | undefined;\n\tconst load = async (\n\t\trequest: Request,\n\t\ttarget: string,\n\t\t{ response, navigationType }: { response?: Response; navigationType?: string | null } = {},\n\t) => {\n\t\tif (leaving === target) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<never>(() => {});\n\t\t}\n\t\tleaving = target;\n\t\tonAbort(request.signal, () => {\n\t\t\tif (leaving === target) {\n\t\t\t\tleaving = undefined;\n\t\t\t}\n\t\t});\n\t\treturn loadDocument(target, { response, navigationType });\n\t};\n\treturn {\n\t\tfetch: async (request, context) => {\n\t\t\tconst navigationType =\n\t\t\t\tcontext.type === \"navigation\" && context.fetcherKey == null\n\t\t\t\t\t? context.navigationType\n\t\t\t\t\t: undefined;\n\t\t\t// Why the global at each call: an app can wrap `fetch` after this module, such as for RUM.\n\t\t\tconst send = async () => {\n\t\t\t\tconst response = await globalThis.fetch(request);\n\t\t\t\treturn { response, isNew: watch()?.isNew(response, request.url) === true };\n\t\t\t};\n\t\t\tif (watch() == null || navigationType == null) {\n\t\t\t\treturn (await send()).response;\n\t\t\t}\n\t\t\t// Why the hash of the `navigate` call: the router removes it from the data request. Why\n\t\t\t// its page only: a redirect goes to another page with no `navigate` call.\n\t\t\tconst page = targetOf(request);\n\t\t\tconst hash =\n\t\t\t\tnavigationType !== \"POP\" && navigating?.page === pageOf(page) ? navigating.hash : \"\";\n\t\t\tconst target = page + hash;\n\t\t\tconst path = new URL(target).pathname;\n\t\t\tconst isAfterAction = request.method === \"GET\" && action?.path === path;\n\t\t\t// Why check the signal: a canceled navigation must never load its target.\n\t\t\tconst isNavigation = () =>\n\t\t\t\trequest.method === \"GET\" && !isAfterAction && !request.signal.aborted;\n\t\t\tif (isNavigation() && watch()?.isStale() === true) {\n\t\t\t\treturn load(request, target, { navigationType });\n\t\t\t}\n\t\t\tconst { response, isNew } = await send();\n\t\t\tif (!isNew || !isNavigation()) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\treturn load(request, target, { response, navigationType });\n\t\t},\n\t\tinstrumentation: {\n\t\t\trouter: ({ instrument }) => {\n\t\t\t\twatch();\n\t\t\t\tinstrument({\n\t\t\t\t\tnavigate: async (handler, { to, formMethod }) => {\n\t\t\t\t\t\t// Why claimed: a history step and a form submission are not a page load to take over.\n\t\t\t\t\t\tconst current = {\n\t\t\t\t\t\t\thash: hashOf(to),\n\t\t\t\t\t\t\tclaimed: typeof to === \"number\" || (formMethod ?? \"GET\").toUpperCase() !== \"GET\",\n\t\t\t\t\t\t};\n\t\t\t\t\t\tnavigating = current;\n\t\t\t\t\t\tawait handler();\n\t\t\t\t\t\t// Why keep an unclaimed call: a blocker stops it, and `blocker.proceed()` starts it\n\t\t\t\t\t\t// again with no `navigate` call.\n\t\t\t\t\t\tif (navigating === current && current.claimed) {\n\t\t\t\t\t\t\tnavigating = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tmiddleware: async (args, next) => {\n\t\t\tconst {\n\t\t\t\trequest,\n\t\t\t\tunstable_initiator: initiator,\n\t\t\t\tunstable_navigationType: navigationType,\n\t\t\t} = args as MiddlewareArgs;\n\t\t\tconst current = navigating;\n\t\t\tif (initiator === \"navigation\") {\n\t\t\t\t// Why here: a `clientAction` sends no request, and the router runs the middleware once\n\t\t\t\t// for an action and once for all the loaders after it.\n\t\t\t\tconst path = new URL(request.url).pathname;\n\t\t\t\tconst mark = action;\n\t\t\t\tif (navigationType === \"POP\") {\n\t\t\t\t\taction = undefined;\n\t\t\t\t} else if (request.method !== \"GET\") {\n\t\t\t\t\tconst started = { path, loading: false };\n\t\t\t\t\taction = started;\n\t\t\t\t\tonAbort(request.signal, () => {\n\t\t\t\t\t\tif (action === started) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn next();\n\t\t\t\t} else if (mark?.path === path) {\n\t\t\t\t\tmark.loading = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await next();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (action === mark) {\n\t\t\t\t\t\t\taction = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (mark?.loading === false) {\n\t\t\t\t\t// Why: a redirect after the action goes to another page, and its loaders never run.\n\t\t\t\t\t// Why not while they run: the router revalidates the fetchers next to them.\n\t\t\t\t\taction = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Why no history step: it comes from no `navigate` call, and the fetch hook reloads it.\n\t\t\t// Why the first call only: the router runs the middleware of a navigation before the\n\t\t\t// fetchers that it revalidates, and they have the same initiator.\n\t\t\tif (\n\t\t\t\tinitiator !== \"navigation\" ||\n\t\t\t\tnavigationType == null ||\n\t\t\t\tnavigationType === \"POP\" ||\n\t\t\t\tcurrent == null ||\n\t\t\t\tcurrent.claimed\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tcurrent.claimed = true;\n\t\t\tcurrent.page = pageOf(request.url);\n\t\t\tif (\n\t\t\t\trequest.signal.aborted ||\n\t\t\t\twatch()?.isStale() !== true ||\n\t\t\t\tpageOf(request.url) === pageOf(location.href)\n\t\t\t) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\treturn load(request, request.url + current.hash, { navigationType });\n\t\t},\n\t};\n}\n\n/**\n * Moves an open TanStack Router tab to a new build at a navigation, so the\n * old client code never renders data from the new server, and the page that\n * the visitor reads never reloads. Call it with the router on the client.\n *\n * - A navigation runs from `onBeforeNavigate` to `onResolved`. The router\n * moves history and runs its blockers before it.\n * - When a GET response from a new build comes back while a navigation\n * runs, such as from a server function in a loader, the browser loads the\n * page as a document.\n * - When the tab already knows of a new build, a navigation to a new path or\n * query clears the router cache and loads the page as a document.\n * - A request outside a navigation gets its response, and only marks the tab.\n *\n * It sends no request of its own and adds no wait. It needs `buildId()` in\n * the server's pipeline, and it does nothing on a document with no build.\n * It returns a function that stops it and gives back `fetch`. If the app\n * wrapped `fetch` after it, the wrapper stays, and each request passes on.\n *\n * @example\n * // src/router.tsx\n * export function getRouter() {\n * \tconst router = createRouter({ routeTree });\n * \tif (!router.isServer) {\n * \t\tstaleBuildTanStack(router);\n * \t}\n * \treturn router;\n * }\n */\nexport function staleBuildTanStack(\n\trouter: NavigationEvents,\n\toptions: StaleBuildOptions = {},\n): () => void {\n\tconst watch = watchBuild(options);\n\tif (watch == null) {\n\t\treturn () => {};\n\t}\n\t/** The navigation that runs now. `leaving` is true when it already loads its page as a document. */\n\tlet navigation: { leaving: boolean } | undefined;\n\tconst reload = async (current: { leaving: boolean }, response?: Response) => {\n\t\tif (current.leaving) {\n\t\t\tvoid response?.body?.cancel().catch(() => undefined);\n\t\t\treturn new Promise<Response>(() => {});\n\t\t}\n\t\tcurrent.leaving = true;\n\t\t// Why flush: the router's history moves the browser's URL in a microtask, after\n\t\t// `onBeforeNavigate`. A reload before that loads the page that the visitor leaves.\n\t\trouter.history.flush();\n\t\treturn loadDocument(location.href, { response });\n\t};\n\tconst unsubscribe = [\n\t\trouter.subscribe(\"onBeforeNavigate\", ({ fromLocation, toLocation }) => {\n\t\t\t// Why clear first: a change to the fragment replaces a navigation that has not ended.\n\t\t\tnavigation = undefined;\n\t\t\tif (fromLocation == null || eventPage(fromLocation) === eventPage(toLocation)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tnavigation = { leaving: false };\n\t\t\tif (watch.isStale()) {\n\t\t\t\t// Why clear: the router matches the target after this event, and a preload can hold the\n\t\t\t\t// new build's data. With no cache, each loader fetches again, and `fetch` holds it.\n\t\t\t\trouter.clearCache();\n\t\t\t\tvoid reload(navigation);\n\t\t\t}\n\t\t}),\n\t\trouter.subscribe(\"onResolved\", () => {\n\t\t\tnavigation = undefined;\n\t\t}),\n\t];\n\tconst send = globalThis.fetch;\n\tlet isStopped = false;\n\tconst patched: typeof fetch = async (input, init) => {\n\t\tif (isStopped) {\n\t\t\treturn send.call(globalThis, input, init);\n\t\t}\n\t\tconst isGet = methodOf(input, init) === \"GET\";\n\t\tif (isGet && navigation != null && watch.isStale()) {\n\t\t\treturn reload(navigation);\n\t\t}\n\t\tconst response = await send.call(globalThis, input, init);\n\t\t// Why the navigation at the response: a navigation can take the pending loader of a preload,\n\t\t// or of the navigation that it replaced.\n\t\tif (!watch.isNew(response, urlOf(input)) || !isGet || navigation == null) {\n\t\t\treturn response;\n\t\t}\n\t\treturn reload(navigation, response);\n\t};\n\tglobalThis.fetch = patched;\n\treturn () => {\n\t\tfor (const stop of unsubscribe) {\n\t\t\tstop();\n\t\t}\n\t\twatch.stop();\n\t\tisStopped = true;\n\t\tnavigation = undefined;\n\t\t// Why check: a wrapper that the app adds later still calls this one, and must stay.\n\t\tif (globalThis.fetch === patched) {\n\t\t\tglobalThis.fetch = send;\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAgB,gBAAoC;CAEnD,OAAO,SAAS,cAA2B,SAAS,CAAC,EAAE;AACxD;;;;ACwCA,SAAS,MAAM,KAAsB;CACpC,OAAO,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,WAAW,SAAS;AACxD;;AAGA,SAAS,YAAY,SAAmD;CACvE,OACC,QACE,QACC,UAA8C,kBAAkB,SAAS,MAAM,MAAM,IAAI,CAC3F,CAAC,CAGA,QAAQ,UAAU,MAAM,cAAc,cAAc,MAAM,kBAAkB,CAAC,CAAC,CAC9E,SAAS,UAAU,MAAM,YAAY,CAAC,CACtC,MAAM,WAAW,OAAO,SAAS,eAAe,CAAC,EAAE;AAEvD;;AAGA,SAAS,YAAY,QAA2C;CAC/D,MAAM,EAAE,QAAQ,UACf,oBAAoB,MAAM,CAAC,CACzB,MAAM,WAAW,cAAc,MAAM,CAAC,CAAC,EACtC,MAAM,qEAAqE,CAAC,EAAE,UAAU,CAA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C;CACA,WAAW,QAAQ;CACnB,aAAa;EACZ,KAAK,MAAM,QAAQ,aAClB,KAAK;EAEN,MAAM,KAAK;EACX,YAAY;EACZ,aAAa;EAEb,IAAI,WAAW,UAAU,SACxB,WAAW,QAAQ;CAErB;AACD"}
@@ -2,8 +2,8 @@ import { t as parsePort } from "./tcp-Dd1Mt6sN.js";
2
2
  import { r as jsonSink, t as errorAttributes } from "./log-BP6xXXZl.js";
3
3
  import { i as exitAfterFlush, n as devServerStage } from "./node-C1qudLs_.js";
4
4
  import { t as requestListener } from "./response-writer-B7FoJjEE.js";
5
- import { t as SERVER_ENTRY_ID } from "./vite-tTxVimP6.js";
6
- import { t as loadEntry } from "./load-entry-Bodyd2Ok.js";
5
+ import { t as SERVER_ENTRY_ID } from "./vite-BDREIgiH.js";
6
+ import { t as loadEntry } from "./load-entry-D7r0mjEp.js";
7
7
  import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
8
8
  import { createServer } from "node:http";
9
9
  import { createServer as createServer$1 } from "node:net";
@@ -132,7 +132,8 @@ function isAddressInUse(error) {
132
132
  * Runs the app in development: the same pipeline as production, with Vite in
133
133
  * middleware mode inside it. Each request loads the server entry through
134
134
  * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies
135
- * at once. HMR shares the port.
135
+ * at once. HMR shares the port. Vite's plugins get the CLI's HTTP server as
136
+ * `server.httpServer`.
136
137
  *
137
138
  * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the
138
139
  * server tries each next port, unless Vite's `server.strictPort` is true. The
@@ -146,7 +147,8 @@ async function start() {
146
147
  middlewareMode: true,
147
148
  ws: { server: httpServer }
148
149
  },
149
- appType: "custom"
150
+ appType: "custom",
151
+ plugins: [shareHttpServer(httpServer)]
150
152
  });
151
153
  const ssrRunner = () => {
152
154
  const { ssr } = viteServer.environments;
@@ -215,6 +217,32 @@ async function start() {
215
217
  ]).finally(exitAfterFlush);
216
218
  });
217
219
  }
220
+ /**
221
+ * A Vite plugin that sets `server.httpServer` to the CLI's HTTP server before
222
+ * the `configureServer` hooks of the app's plugins run. Why: in middleware
223
+ * mode, Vite sets it to `null`. Then a plugin that waits for `listening` or
224
+ * `close` on it does nothing, with no error.
225
+ *
226
+ * @example
227
+ * vite.createServer({ plugins: [shareHttpServer(httpServer)] });
228
+ */
229
+ function shareHttpServer(httpServer) {
230
+ const plugin = {
231
+ name: "@ngrok/app-server:http-server",
232
+ configResolved: (config) => {
233
+ const plugins = config.plugins;
234
+ plugins.splice(plugins.indexOf(plugin), 1);
235
+ plugins.unshift(plugin);
236
+ },
237
+ configureServer: {
238
+ order: "pre",
239
+ handler: (server) => {
240
+ server.httpServer = httpServer;
241
+ }
242
+ }
243
+ };
244
+ return plugin;
245
+ }
218
246
  /** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */
219
247
  function viteHostname(host) {
220
248
  if (host === true) return;
@@ -222,4 +250,4 @@ function viteHostname(host) {
222
250
  }
223
251
 
224
252
  export { start };
225
- //# sourceMappingURL=start-DREqYrZh.js.map
253
+ //# sourceMappingURL=start-CifYPRq1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start-CifYPRq1.js","names":["createServer","createHttpServer"],"sources":["../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import type { AppServerEntry } from \"../core/entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/** What {@link servedApps} returns. */\ntype ServedApps = {\n\t/** Runs `handle` for a request that `entry` serves. */\n\tserve: <Result>(\n\t\tentry: AppServerEntry,\n\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t) => Promise<Result>;\n\t/**\n\t * At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each\n\t * app still held. Resolves when the hooks finish or pass the deadline.\n\t */\n\tstopAll: () => Promise<void>;\n};\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps(): ServedApps {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\t// Why keep the app until its hooks settle: `stopAll` must wait for hooks that already run.\n\t// `stopPlugins` runs the hooks once, so a second call only waits.\n\tconst retire = async (app: ServedApp) => {\n\t\ttry {\n\t\t\tawait app.entry.stopPlugins();\n\t\t} finally {\n\t\t\tserved.delete(app);\n\t\t}\n\t};\n\treturn {\n\t\tserve: async (entry, handle) => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tvoid retire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tvoid retire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tstopAll: async () => {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(served, async (app) => {\n\t\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\t\tawait retire(app);\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string | undefined;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nasync function bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tfunction onError(error: Error) {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t}\n\t\tfunction onListening() {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t}\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import { createServer as createHttpServer } from \"node:http\";\nimport type { Server } from \"node:http\";\nimport type { Plugin } from \"vite\";\nimport { errorAttributes, jsonSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { loadEntry } from \"./load-entry.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { listenFromPort } from \"./start-port.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port. Vite's plugins get the CLI's HTTP server as\n * `server.httpServer`.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\t// Why `true`, not `{ server }`: Vite then adds a proxy `upgrade` listener to the server, and a\n\t\t// restart does not remove it.\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t\tplugins: [shareHttpServer(httpServer)],\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst { ssr } = viteServer.environments;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tif (!viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")) {\n\t\tawait viteServer.close();\n\t\tthrow new Error(\n\t\t\t\"`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.\",\n\t\t);\n\t}\n\tconst devServer = devServerStage(viteServer.middlewares, {\n\t\tpublicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n\t});\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = requestListener(async (request, bindings) => {\n\t\ttry {\n\t\t\treturn await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) => entry.fetchDev(request, bindings, devServer),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst hostname = process.env.HOST || viteHostname(viteServer.config.server.host);\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tconst pluginsStopped = apps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\tconst httpClosed = new Promise<void>((resolve) => {\n\t\t\t\thttpServer.close(() => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst viteClosed = viteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t\tvoid Promise.all([pluginsStopped, httpClosed, viteClosed]).finally(exitAfterFlush);\n\t\t});\n\t}\n}\n\n/**\n * A Vite plugin that sets `server.httpServer` to the CLI's HTTP server before\n * the `configureServer` hooks of the app's plugins run. Why: in middleware\n * mode, Vite sets it to `null`. Then a plugin that waits for `listening` or\n * `close` on it does nothing, with no error.\n *\n * @example\n * vite.createServer({ plugins: [shareHttpServer(httpServer)] });\n */\nfunction shareHttpServer(httpServer: Server): Plugin {\n\tconst plugin: Plugin = {\n\t\tname: \"@ngrok/app-server:http-server\",\n\t\t// Why first: Vite puts an inline plugin after the config file's plugins, so an app plugin with\n\t\t// `enforce: \"pre\"` and `order: \"pre\"` runs its `configureServer` before this one.\n\t\tconfigResolved: (config) => {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Vite sorts each hook from this array later.\n\t\t\tconst plugins = config.plugins as Plugin[];\n\t\t\tplugins.splice(plugins.indexOf(plugin), 1);\n\t\t\tplugins.unshift(plugin);\n\t\t},\n\t\tconfigureServer: {\n\t\t\torder: \"pre\",\n\t\t\thandler: (server) => {\n\t\t\t\tserver.httpServer = httpServer;\n\t\t\t},\n\t\t},\n\t};\n\treturn plugin;\n}\n\n/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */\nfunction viteHostname(host: string | boolean | undefined): string | undefined {\n\tif (host === true) {\n\t\treturn undefined;\n\t}\n\treturn typeof host === \"string\" && host !== \"\" ? host : \"localhost\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAgB,aAAyB;CACxC,IAAI;CACJ,MAAM,yBAAS,IAAI,IAAe;CAGlC,MAAM,SAAS,OAAO,QAAmB;EACxC,IAAI;GACH,MAAM,IAAI,MAAM,YAAY;EAC7B,UAAU;GACT,OAAO,OAAO,GAAG;EAClB;CACD;CACA,OAAO;EACN,OAAO,OAAO,OAAO,WAAW;GAC/B,IAAI,SAAS,MAAM,QAAQ,MAAM,KAChC,QAAQ,QAAQ;QACV;IACN,IAAI,WAAW,MAAM;KACpB,QAAQ,WAAW;KACnB,IAAI,QAAQ,YAAY,GACvB,AAAK,OAAO,OAAO;IAErB;IACA,UAAU;KAAE;KAAO,SAAS;KAAG,UAAU;IAAM;IAC/C,OAAO,IAAI,OAAO;GACnB;GACA,MAAM,MAAM;GACZ,IAAI,WAAW;GACf,IAAI;IACH,OAAO,MAAM,OAAO,KAAK;GAC1B,UAAU;IACT,IAAI,WAAW;IACf,IAAI,IAAI,YAAY,IAAI,YAAY,GACnC,AAAK,OAAO,GAAG;GAEjB;EACD;EACA,SAAS,YAAY;GACpB,MAAM,QAAQ,IACb,MAAM,KAAK,QAAQ,OAAO,QAAQ;IACjC,IAAI,MAAM,oBAAoB;IAC9B,MAAM,OAAO,GAAG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U,CAAC,CAAC,CAAC,QAAQ,cAAc;CAClF,CAAC;AAEH;;;;;;;;;;AAWA,SAAS,gBAAgB,YAA4B;CACpD,MAAM,SAAiB;EACtB,MAAM;EAGN,iBAAiB,WAAW;GAE3B,MAAM,UAAU,OAAO;GACvB,QAAQ,OAAO,QAAQ,QAAQ,MAAM,GAAG,CAAC;GACzC,QAAQ,QAAQ,MAAM;EACvB;EACA,iBAAiB;GAChB,OAAO;GACP,UAAU,WAAW;IACpB,OAAO,aAAa;GACrB;EACD;CACD;CACA,OAAO;AACR;;AAGA,SAAS,aAAa,MAAwD;CAC7E,IAAI,SAAS,MACZ;CAED,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AACzD"}
@@ -1,4 +1,4 @@
1
- import { n as FrameworkBuild } from "./index-Bo5G9LuQ.js";
1
+ import { n as FrameworkBuild } from "./index-Db7dspq6.js";
2
2
  /**
3
3
  * The build side of the TanStack Start adapter. `appServer` uses it when the
4
4
  * Vite config has the TanStack Start plugin, so pass it only to override that.
@@ -1,5 +1,5 @@
1
- import { a as FrameworkRuntime, h as Mode } from "./types-CEvzAmcn.js";
2
- import { t as TrailingSlash } from "./trailing-slash-BrymAEGv.js";
1
+ import { a as FrameworkRuntime, h as Mode } from "./types-j29vspx_.js";
2
+ import { t as TrailingSlash } from "./trailing-slash-CFSv_Gzx.js";
3
3
  import { AnyRouter, RegisteredRouter } from "@tanstack/react-router";
4
4
  /**
5
5
  * The `trailingSlash` mode of a TanStack router: the app's registered router
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as RequestContext, a as FrameworkRuntime } from "./types-CEvzAmcn.js";
2
- import { t as AppServer } from "./create-server-kzZWd_Lo.js";
1
+ import { _ as RequestContext, a as FrameworkRuntime } from "./types-j29vspx_.js";
2
+ import { t as AppServer } from "./create-server-D4-nVOVJ.js";
3
3
  /** Options for {@link createTestServer}. */
4
4
  export type TestServerOptions = {
5
5
  /**
package/dist/testing.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { r as withRequestContext$1 } from "./request-context-BtQ87VYb.js";
2
2
  import { i as requestLogger } from "./log-BP6xXXZl.js";
3
- import { t as BUILD_MANIFEST_FILE } from "./build-manifest-UDNk81Ce.js";
4
- import { t as createEntry } from "./entry-UDsxuqBC.js";
3
+ import { t as BUILD_MANIFEST_FILE } from "./build-manifest-DBMWe3Lx.js";
4
+ import { t as createEntry } from "./entry-D9H4LA9c.js";
5
5
  import { t as host } from "./node-C1qudLs_.js";
6
6
  import { n as scriptHashesOf } from "./script-hashes-C6hQ5XnP.js";
7
7
  import { Context } from "hono";
@@ -1,4 +1,4 @@
1
- import { g as Plugin } from "./types-CEvzAmcn.js";
1
+ import { g as Plugin } from "./types-j29vspx_.js";
2
2
  /**
3
3
  * How a page URL ends:
4
4
  *
@@ -33,4 +33,4 @@ type TrailingSlashOptions = {
33
33
  */
34
34
  declare function trailingSlash({ mode }: TrailingSlashOptions): Plugin;
35
35
  export { TrailingSlashOptions as n, trailingSlash as r, TrailingSlash as t };
36
- //# sourceMappingURL=trailing-slash-BrymAEGv.d.ts.map
36
+ //# sourceMappingURL=trailing-slash-CFSv_Gzx.d.ts.map
@@ -217,6 +217,12 @@ type ListenerBindings = {
217
217
  /** The Hono bindings of an app server: the listener's values and the framework. */
218
218
  type ServerBindings = ListenerBindings & {
219
219
  framework: FrameworkRuntime;
220
+ /**
221
+ * Gets the URL path of the client build's file that `prerendered()` sends,
222
+ * such as `/about/index.html`. Only the build's check of the CDN pages
223
+ * gives it. Why a binding: each other request then pays one property read.
224
+ */
225
+ onServedFile?: (path: string) => void;
220
226
  };
221
227
  /** The Hono environment of an app server. */
222
228
  type AppServerEnv = {
@@ -238,6 +244,12 @@ type AppServerEnv = {
238
244
  * dev server stage sets it, for a 304 too.
239
245
  */
240
246
  documentScriptHashes?: readonly string[];
247
+ /**
248
+ * The route pattern that the framework matched, such as
249
+ * `/domains/:domainId`. The framework adapter sets it, and the access log
250
+ * writes it as `http.route`.
251
+ */
252
+ routePattern?: string;
241
253
  /** The client's IP address. See `trustedProxyHops` on `createServer`. */
242
254
  clientAddress?: string | undefined;
243
255
  /** Attributes that each log line of the request carries, such as the trace IDs from the `requestId` plugin. */
@@ -313,6 +325,8 @@ type SetupInfo = {
313
325
  mode: "production";
314
326
  /** The URL paths that the build prerendered. */
315
327
  prerenderedPaths: readonly string[];
328
+ /** The URL path of the hashed files of the client build, such as `/assets/`. */
329
+ assetsPath: string;
316
330
  } | {
317
331
  mode: "development";
318
332
  /** The dev server as a pipeline stage. It serves source modules, HMR, and CSS. */
@@ -389,4 +403,4 @@ type ListenerStartOptions = {
389
403
  trustForwardedProto?: boolean;
390
404
  };
391
405
  export { SetupInfo as C, ResponseEdge as E, ServerBindings as S, StaticFiles as T, RequestContext as _, FrameworkRuntime as a, ResponseHeaders as b, HostRuntime as c, ListenerBindings as d, ListenerStartOptions as f, Plugin as g, Mode as h, FileInfo as i, Lifecycle as l, LogSink as m, ByteRange as n, FrameworkRuntimeFactory as o, LogLevel as p, FetchHandler as r, HeaderHook as s, AppServerEnv as t, Listener as u, RequestLogger as v, StartedListener as w, SentResponse as x, RequestStore as y };
392
- //# sourceMappingURL=types-CEvzAmcn.d.ts.map
406
+ //# sourceMappingURL=types-j29vspx_.d.ts.map
@@ -0,0 +1,32 @@
1
+ /** A prerendered path that the CDN serves, as `vercel()` writes it. */
2
+ export type CdnPageReport = {
3
+ path: string;
4
+ /**
5
+ * The URL path of the page's body under the static directory, such as
6
+ * `/0/index.html`. Why not the page's file: two paths can have one file,
7
+ * such as with `prerendered({ rewrite })`, and different bodies.
8
+ */
9
+ file: string;
10
+ answers: {
11
+ present: readonly string[];
12
+ headers: Readonly<Record<string, string>>;
13
+ }[];
14
+ twin?: string;
15
+ };
16
+ /** What the step found: the paths that the CDN serves, and why the function serves each other path. */
17
+ export type PagesReport = {
18
+ cdn: CdnPageReport[];
19
+ server: {
20
+ path: string;
21
+ reason: string;
22
+ }[];
23
+ };
24
+ /**
25
+ * Writes the body of each page that the CDN can serve to `staticDirectory`,
26
+ * at the path of its file, and the {@link PagesReport} to `reportFile`.
27
+ *
28
+ * @example
29
+ * await writePages("build/server/app-server.js", ".vercel/output/static/_app-server/pages", "pages.json");
30
+ */
31
+ export declare function writePages(entryFile: string, staticDirectory: string, reportFile: string): Promise<void>;
32
+ //# sourceMappingURL=vercel-pages.d.ts.map
@@ -0,0 +1,54 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+
5
+ // src/vercel/pages.ts
6
+ function isEntry(value) {
7
+ return typeof value === "object" && value != null && "staticPages" in value && typeof value.staticPages === "function" && "stopPlugins" in value && typeof value.stopPlugins === "function";
8
+ }
9
+ /**
10
+ * Writes the body of each page that the CDN can serve to `staticDirectory`,
11
+ * at the path of its file, and the {@link PagesReport} to `reportFile`.
12
+ *
13
+ * @example
14
+ * await writePages("build/server/app-server.js", ".vercel/output/static/_app-server/pages", "pages.json");
15
+ */
16
+ async function writePages(entryFile, staticDirectory, reportFile) {
17
+ const module = await import(pathToFileURL(entryFile).href);
18
+ const entry = typeof module === "object" && module != null && "appServer" in module ? module.appServer : void 0;
19
+ if (!isEntry(entry)) throw new Error(`${entryFile} exports no appServer of this version of @ngrok/app-server.`);
20
+ const report = {
21
+ cdn: [],
22
+ server: []
23
+ };
24
+ try {
25
+ for await (const page of entry.staticPages()) if ("cdn" in page) {
26
+ const { body, answers, twin } = page.cdn;
27
+ const file = `/${report.cdn.length}/${basename(page.cdn.file)}`;
28
+ const target = join(staticDirectory, file);
29
+ mkdirSync(dirname(target), { recursive: true });
30
+ writeFileSync(target, body);
31
+ report.cdn.push({
32
+ path: page.path,
33
+ file,
34
+ answers,
35
+ ...twin == null ? {} : { twin }
36
+ });
37
+ } else report.server.push({
38
+ path: page.path,
39
+ reason: page.reason
40
+ });
41
+ } finally {
42
+ await entry.stopPlugins();
43
+ }
44
+ mkdirSync(dirname(reportFile), { recursive: true });
45
+ writeFileSync(reportFile, JSON.stringify(report));
46
+ }
47
+ if (import.meta.main) {
48
+ const [entryFile = "", staticDirectory = "", reportFile = ""] = process.argv.slice(2);
49
+ await writePages(entryFile, staticDirectory, reportFile);
50
+ process.exit(0);
51
+ }
52
+
53
+ export { writePages };
54
+ //# sourceMappingURL=vercel-pages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercel-pages.js","names":[],"sources":["../src/vercel/pages.ts"],"sourcesContent":["// The step of `vercel()` that finds the prerendered pages that Vercel's content delivery network\n// (CDN) can serve with no function. `vercel()` runs it in a child process after the build:\n//\n// node vercel-pages.js <server entry> <static directory> <report file>\n//\n// Why a child process: the step starts the built server, and the build output must stay sync. A\n// plugin's `setup` can also leave a socket or a timer, so the process exits when the step ends.\n// Why no relative import: the build runs this file from `src` in the tests of this package.\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/** A prerendered path that the CDN serves, as `vercel()` writes it. */\nexport type CdnPageReport = {\n\tpath: string;\n\t/**\n\t * The URL path of the page's body under the static directory, such as\n\t * `/0/index.html`. Why not the page's file: two paths can have one file,\n\t * such as with `prerendered({ rewrite })`, and different bodies.\n\t */\n\tfile: string;\n\tanswers: { present: readonly string[]; headers: Readonly<Record<string, string>> }[];\n\ttwin?: string;\n};\n\n/** What the step found: the paths that the CDN serves, and why the function serves each other path. */\nexport type PagesReport = {\n\tcdn: CdnPageReport[];\n\tserver: { path: string; reason: string }[];\n};\n\n/** The part of the server entry that this step calls. */\ntype Entry = {\n\tstaticPages: () => AsyncIterable<\n\t\t{ path: string } & (\n\t\t\t| {\n\t\t\t\t\tcdn: { file: string; body: Uint8Array; answers: CdnPageReport[\"answers\"]; twin?: string };\n\t\t\t }\n\t\t\t| { reason: string }\n\t\t)\n\t>;\n\tstopPlugins: () => Promise<void>;\n};\n\nfunction isEntry(value: unknown): value is Entry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"staticPages\" in value &&\n\t\ttypeof value.staticPages === \"function\" &&\n\t\t\"stopPlugins\" in value &&\n\t\ttypeof value.stopPlugins === \"function\"\n\t);\n}\n\n/**\n * Writes the body of each page that the CDN can serve to `staticDirectory`,\n * at the path of its file, and the {@link PagesReport} to `reportFile`.\n *\n * @example\n * await writePages(\"build/server/app-server.js\", \".vercel/output/static/_app-server/pages\", \"pages.json\");\n */\nexport async function writePages(\n\tentryFile: string,\n\tstaticDirectory: string,\n\treportFile: string,\n): Promise<void> {\n\tconst module: unknown = await import(pathToFileURL(entryFile).href);\n\tconst entry =\n\t\ttypeof module === \"object\" && module != null && \"appServer\" in module\n\t\t\t? module.appServer\n\t\t\t: undefined;\n\tif (!isEntry(entry)) {\n\t\tthrow new Error(`${entryFile} exports no appServer of this version of @ngrok/app-server.`);\n\t}\n\tconst report: PagesReport = { cdn: [], server: [] };\n\ttry {\n\t\tfor await (const page of entry.staticPages()) {\n\t\t\tif (\"cdn\" in page) {\n\t\t\t\tconst { body, answers, twin } = page.cdn;\n\t\t\t\tconst file = `/${report.cdn.length}/${basename(page.cdn.file)}`;\n\t\t\t\tconst target = join(staticDirectory, file);\n\t\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\t\twriteFileSync(target, body);\n\t\t\t\treport.cdn.push({ path: page.path, file, answers, ...(twin == null ? {} : { twin }) });\n\t\t\t} else {\n\t\t\t\treport.server.push({ path: page.path, reason: page.reason });\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tawait entry.stopPlugins();\n\t}\n\tmkdirSync(dirname(reportFile), { recursive: true });\n\twriteFileSync(reportFile, JSON.stringify(report));\n}\n\nif (import.meta.main) {\n\tconst [entryFile = \"\", staticDirectory = \"\", reportFile = \"\"] = process.argv.slice(2);\n\tawait writePages(entryFile, staticDirectory, reportFile);\n\t// oxlint-disable-next-line unicorn/no-process-exit -- a plugin's `setup` can leave a socket or a timer that keeps the process alive.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Q,KAAK,MAAM,CAAC;CACpF,MAAM,WAAW,WAAW,iBAAiB,UAAU;CAEvD,QAAQ,KAAK,CAAC;AACf"}
@@ -1,29 +1,50 @@
1
- import { r as HostBuild } from "./index-Bo5G9LuQ.js";
1
+ import { r as HostBuild } from "./index-Db7dspq6.js";
2
2
  /** Options for {@link vercel}. */
3
3
  export type VercelOptions = {
4
4
  /**
5
5
  * More URL path prefixes of the client build that Vercel's CDN serves,
6
- * such as `["/blog-assets/"]`. Each starts and ends with `/`. `/assets/`
7
- * is always one. Their files skip the pipeline, and the function does not
8
- * carry them.
6
+ * such as `["/blog-assets/"]`. Each starts and ends with `/`. The URL path
7
+ * of Vite's `build.assetsDir`, `/assets/` by default, is always one. Their
8
+ * files skip the pipeline, and the function does not carry them.
9
9
  */
10
10
  cdnPaths?: readonly string[];
11
- /** Headers for each file that the CDN serves, such as CORS headers. */
11
+ /** Headers for each file under `cdnPaths` and Vite's `build.assetsDir`, such as CORS headers. */
12
12
  cdnHeaders?: Readonly<Record<string, string>>;
13
+ /**
14
+ * Which prerendered pages the CDN serves, with no function. With `true`,
15
+ * `vercel()` starts the server build once after the build and sends each
16
+ * prerendered path through the pipeline as an anonymous client. The CDN
17
+ * serves a page when its answer is a public 200 from its file, and the
18
+ * same for a second client with another host, address, query, cookie,
19
+ * `Authorization`, language, and country. The CDN then sends the
20
+ * pipeline's body and headers. The function serves each other page, and
21
+ * the CDN never keeps its answer. A function keeps each path that it
22
+ * refuses in either trailing-slash form in the function, such as a page
23
+ * whose answer depends on one query key. Why off by default: the build
24
+ * runs each plugin's `setup`, and a check that the build cannot see can
25
+ * then reach the CDN.
26
+ * @default false
27
+ */
28
+ cdnPages?: boolean | ((path: string) => boolean);
13
29
  /** The Vercel regions of the function, such as `["iad1"]`. @default the project's */
14
30
  regions?: readonly string[];
15
31
  /** The memory of the function, in MB. @default the project's */
16
32
  memory?: number;
17
- /** The longest time that a request runs, in seconds. @default the project's */
33
+ /**
34
+ * The longest time that a request runs, in seconds. It applies to each
35
+ * request, because one function serves each route. A route module's
36
+ * `config` export does nothing. @default the project's
37
+ */
18
38
  maxDuration?: number;
19
39
  };
20
40
  /**
21
41
  * The build side of the vercel host. After the build, it writes
22
42
  * `.vercel/output` in the Vite root, for `vercel deploy --prebuilt`:
23
43
  *
24
- * - `static/`: the files under `/assets/` and the other `cdnPaths`. The CDN
25
- * serves them, and each file under `/assets/` gets a one-year immutable
26
- * cache.
44
+ * - `static/`: the files of Vite's `build.assetsDir` (`/assets/` by default)
45
+ * and the other `cdnPaths`. The CDN serves them, and each file of
46
+ * `build.assetsDir` gets a one-year immutable cache. It also holds the
47
+ * prerendered pages that the CDN serves, with `cdnPages`.
27
48
  * - `functions/index.func/`: one Node.js function that runs the pipeline for
28
49
  * each other request, with the whole server build and the rest of the
29
50
  * client build.