@ngrok/app-server 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { t as loadEntry } from "./load-entry-AfYS_zS9.js";
1
+ import { t as loadEntry } from "./load-entry-CmkdlmDX.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-CDNgThjk.js.map
29
+ //# sourceMappingURL=serve-Cc-ADdhZ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve-CDNgThjk.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-Cc-ADdhZ.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"}
@@ -0,0 +1,339 @@
1
+ import { a as serverTimingMetrics, i as isBuildMetric, n as BUILD_ID_METRIC, t as BUILD_ID_HEADER } from "./build-id-C6sYO9Yp.js";
2
+
3
+ // src/client/document-nonce.ts
4
+ /**
5
+ * The CSP nonce of the document's first element with a nonce, or `undefined`
6
+ * when it has none. The browser build of `@ngrok/app-server/client` exports it
7
+ * as `cspNonce()`, so the browser bundle holds no server code.
8
+ *
9
+ * @example
10
+ * documentNonce(); // => "d2hhdCBhIG5vbmNl"
11
+ */
12
+ function documentNonce() {
13
+ return document.querySelector("[nonce]")?.nonce;
14
+ }
15
+
16
+ // src/client/stale-build-navigation.ts
17
+ /** Whether `url` is on the origin of this page. */
18
+ function isOwn(url) {
19
+ return new URL(url, location.href).origin === location.origin;
20
+ }
21
+ /** The build in the `Server-Timing` of the first of `entries` that has one, from this origin only. */
22
+ function timingBuild(entries) {
23
+ return entries.filter((entry) => "serverTiming" in entry && isOwn(entry.name)).filter((entry) => entry.entryType !== "resource" || entry.redirectStart === 0).flatMap((entry) => entry.serverTiming).find((metric) => metric.name === BUILD_ID_METRIC)?.description;
24
+ }
25
+ /** The build in a `Server-Timing` header, as `buildId()` writes it. */
26
+ function headerBuild(header) {
27
+ const { quoted, token } = serverTimingMetrics(header).find((metric) => isBuildMetric(metric))?.match(/;\s*desc\s*=\s*(?:"(?<quoted>(?:[^"\\]|\\.)*)"|(?<token>[^;\s]*))/iu)?.groups ?? {};
28
+ return quoted?.replaceAll(/\\(?<char>.)/gu, "$<char>") ?? token;
29
+ }
30
+ /** The page of `url`: the router renders a new route for a new path or query, not for a new fragment. */
31
+ function pageOf(url) {
32
+ const { origin, pathname, search } = new URL(url, location.href);
33
+ return `${origin}${pathname}${search}`;
34
+ }
35
+ /** The page of a TanStack Router location, as {@link pageOf} reads a URL. */
36
+ function eventPage({ pathname, searchStr }) {
37
+ return `${pathname}${searchStr}`;
38
+ }
39
+ /** The URL of a `fetch` call. */
40
+ function urlOf(input) {
41
+ return input instanceof Request ? input.url : String(input);
42
+ }
43
+ /** The method of a `fetch` call. */
44
+ function methodOf(input, init) {
45
+ return (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
46
+ }
47
+ /** The page that a React Router data request loads: `/a.data` loads `/a`, and `/a/_.data` loads `/a/`. */
48
+ function targetOf(request) {
49
+ const url = new URL(request.url);
50
+ url.pathname = url.pathname.replace(/\/_\.data$/u, "/").replace(/\.data$/u, "");
51
+ url.searchParams.delete("_routes");
52
+ return url.href;
53
+ }
54
+ /**
55
+ * Reloads a document that the back/forward cache shows again. Why: Back can
56
+ * show the document that {@link loadDocument} left, with its router still in a
57
+ * navigation that never ends. Why one function: the browser adds it once.
58
+ */
59
+ function reloadIfRestored(event) {
60
+ if (event.persisted) location.reload();
61
+ }
62
+ /**
63
+ * Loads `target` as a document, so the old code never gets the new build's
64
+ * data. It returns a promise that never settles, because the page unloads.
65
+ */
66
+ async function loadDocument(target, { response, navigationType } = {}) {
67
+ response?.body?.cancel().catch(() => void 0);
68
+ const isSamePage = pageOf(target) === pageOf(location.href);
69
+ const removesFragment = new URL(target, location.href).hash === "" && location.hash !== "";
70
+ addEventListener("pageshow", reloadIfRestored, { once: true });
71
+ if (navigationType === "POP" || isSamePage && !removesFragment) location.reload();
72
+ else if (navigationType === "REPLACE") location.replace(target);
73
+ else location.assign(target);
74
+ return new Promise(() => {});
75
+ }
76
+ /**
77
+ * Runs `clear` when `signal` aborts. Why: the router aborts a navigation when a
78
+ * newer one starts, such as after the visitor stays on the page at a leave prompt.
79
+ */
80
+ function onAbort(signal, clear) {
81
+ signal.addEventListener("abort", clear, { once: true });
82
+ }
83
+ /** Reads the build of each response, and tells when the server runs a new build. */
84
+ function watchBuild({ header = BUILD_ID_HEADER, build, onNewBuild }) {
85
+ if (typeof document === "undefined") return null;
86
+ const current = build ?? timingBuild(performance.getEntriesByType("navigation"));
87
+ if (current == null) return null;
88
+ let stale = false;
89
+ const see = (served) => {
90
+ if (served == null || served === current || stale) return;
91
+ stale = true;
92
+ try {
93
+ onNewBuild?.(served);
94
+ } catch (error) {
95
+ reportError(error);
96
+ }
97
+ };
98
+ const observer = typeof PerformanceObserver === "function" ? new PerformanceObserver((list) => {
99
+ for (const entry of list.getEntries()) see(timingBuild([entry]));
100
+ }) : void 0;
101
+ observer?.observe({
102
+ type: "resource",
103
+ buffered: true
104
+ });
105
+ return {
106
+ isStale: () => stale,
107
+ /** Whether `response` comes from a new build of this origin. `url` is the URL of the request. */
108
+ isNew: (response, url) => {
109
+ const served = isOwn(response.url === "" ? url : response.url) ? response.headers.get(header) ?? headerBuild(response.headers.get("Server-Timing")) : null;
110
+ see(served);
111
+ return served != null && served !== current;
112
+ },
113
+ stop: () => observer?.disconnect()
114
+ };
115
+ }
116
+ /** The fragment of a `navigate` target, such as `#usage`, or `""`. */
117
+ function hashOf(to) {
118
+ return typeof to === "string" && to.includes("#") ? to.slice(to.indexOf("#")) : "";
119
+ }
120
+ /**
121
+ * Moves an open React Router tab to a new build at a navigation, so the old
122
+ * client code never renders data from the new server, and the page that the
123
+ * visitor reads never reloads. Create it in a module that the client entry
124
+ * and `app/root.tsx` both import. It reads no browser state until React
125
+ * Router calls it, so the server can import it.
126
+ *
127
+ * - When the data request of a navigation gets a response from a new build,
128
+ * the browser loads the target URL as a document.
129
+ * - When the tab already knows of a new build, a `navigate` call, such as a
130
+ * link click, loads its target as a document before the router renders it
131
+ * or sends a data request. The root middleware does this also for a route
132
+ * with no loader.
133
+ * - A revalidation, a fetcher, an action, and the loaders after an action
134
+ * get their response. They only mark the tab, so the page that the visitor
135
+ * reads never reloads.
136
+ * - The router's blockers run first, and a canceled navigation never loads
137
+ * its target.
138
+ *
139
+ * It sends no request of its own and adds no wait. It needs `buildId()` in
140
+ * the server's pipeline, and it does nothing on a document with no build.
141
+ *
142
+ * @example
143
+ * // app/stale-build.ts
144
+ * export const staleBuild = staleBuildReactRouter();
145
+ *
146
+ * // app/root.tsx
147
+ * export const clientMiddleware = [staleBuild.middleware];
148
+ *
149
+ * // app/entry.client.tsx
150
+ * startTransition(() => {
151
+ * hydrateRoot(
152
+ * document,
153
+ * <HydratedRouter
154
+ * unstable_fetch={staleBuild.fetch}
155
+ * instrumentations={[staleBuild.instrumentation]}
156
+ * />,
157
+ * );
158
+ * });
159
+ */
160
+ function staleBuildReactRouter(options = {}) {
161
+ let watched;
162
+ const watch = () => {
163
+ watched ??= { watch: watchBuild(options) };
164
+ return watched.watch;
165
+ };
166
+ /**
167
+ * The path of the last action of a navigation, until its loaders run. The
168
+ * router revalidates the page with one or more loader requests after it.
169
+ * `loading` is true while they run.
170
+ */
171
+ let action;
172
+ /** The target that the tab loads as a document now. */
173
+ let leaving;
174
+ /**
175
+ * The last `navigate` call. `claimed` is true when its first middleware call
176
+ * already ran, or when it is not a page load. `page` is the target page of
177
+ * that first call.
178
+ */
179
+ let navigating;
180
+ const load = async (request, target, { response, navigationType } = {}) => {
181
+ if (leaving === target) {
182
+ response?.body?.cancel().catch(() => void 0);
183
+ return new Promise(() => {});
184
+ }
185
+ leaving = target;
186
+ onAbort(request.signal, () => {
187
+ if (leaving === target) leaving = void 0;
188
+ });
189
+ return loadDocument(target, {
190
+ response,
191
+ navigationType
192
+ });
193
+ };
194
+ return {
195
+ fetch: async (request, context) => {
196
+ const navigationType = context.type === "navigation" && context.fetcherKey == null ? context.navigationType : void 0;
197
+ const send = async () => {
198
+ const response = await globalThis.fetch(request);
199
+ return {
200
+ response,
201
+ isNew: watch()?.isNew(response, request.url) === true
202
+ };
203
+ };
204
+ if (watch() == null || navigationType == null) return (await send()).response;
205
+ const page = targetOf(request);
206
+ const target = page + (navigationType !== "POP" && navigating?.page === pageOf(page) ? navigating.hash : "");
207
+ const path = new URL(target).pathname;
208
+ const isAfterAction = request.method === "GET" && action?.path === path;
209
+ const isNavigation = () => request.method === "GET" && !isAfterAction && !request.signal.aborted;
210
+ if (isNavigation() && watch()?.isStale() === true) return load(request, target, { navigationType });
211
+ const { response, isNew } = await send();
212
+ if (!isNew || !isNavigation()) return response;
213
+ return load(request, target, {
214
+ response,
215
+ navigationType
216
+ });
217
+ },
218
+ instrumentation: { router: ({ instrument }) => {
219
+ watch();
220
+ instrument({ navigate: async (handler, { to, formMethod }) => {
221
+ const current = {
222
+ hash: hashOf(to),
223
+ claimed: typeof to === "number" || (formMethod ?? "GET").toUpperCase() !== "GET"
224
+ };
225
+ navigating = current;
226
+ await handler();
227
+ if (navigating === current && current.claimed) navigating = void 0;
228
+ } });
229
+ } },
230
+ middleware: async (args, next) => {
231
+ const { request, unstable_initiator: initiator, unstable_navigationType: navigationType } = args;
232
+ const current = navigating;
233
+ if (initiator === "navigation") {
234
+ const path = new URL(request.url).pathname;
235
+ const mark = action;
236
+ if (navigationType === "POP") action = void 0;
237
+ else if (request.method !== "GET") {
238
+ const started = {
239
+ path,
240
+ loading: false
241
+ };
242
+ action = started;
243
+ onAbort(request.signal, () => {
244
+ if (action === started) action = void 0;
245
+ });
246
+ return next();
247
+ } else if (mark?.path === path) {
248
+ mark.loading = true;
249
+ try {
250
+ return await next();
251
+ } finally {
252
+ if (action === mark) action = void 0;
253
+ }
254
+ } else if (mark?.loading === false) action = void 0;
255
+ }
256
+ if (initiator !== "navigation" || navigationType == null || navigationType === "POP" || current == null || current.claimed) return next();
257
+ current.claimed = true;
258
+ current.page = pageOf(request.url);
259
+ if (request.signal.aborted || watch()?.isStale() !== true || pageOf(request.url) === pageOf(location.href)) return next();
260
+ return load(request, request.url + current.hash, { navigationType });
261
+ }
262
+ };
263
+ }
264
+ /**
265
+ * Moves an open TanStack Router tab to a new build at a navigation, so the
266
+ * old client code never renders data from the new server, and the page that
267
+ * the visitor reads never reloads. Call it with the router on the client.
268
+ *
269
+ * - A navigation runs from `onBeforeNavigate` to `onResolved`. The router
270
+ * moves history and runs its blockers before it.
271
+ * - When a GET response from a new build comes back while a navigation
272
+ * runs, such as from a server function in a loader, the browser loads the
273
+ * page as a document.
274
+ * - When the tab already knows of a new build, a navigation to a new path or
275
+ * query clears the router cache and loads the page as a document.
276
+ * - A request outside a navigation gets its response, and only marks the tab.
277
+ *
278
+ * It sends no request of its own and adds no wait. It needs `buildId()` in
279
+ * the server's pipeline, and it does nothing on a document with no build.
280
+ * It returns a function that stops it and gives back `fetch`. If the app
281
+ * wrapped `fetch` after it, the wrapper stays, and each request passes on.
282
+ *
283
+ * @example
284
+ * // src/router.tsx
285
+ * export function getRouter() {
286
+ * const router = createRouter({ routeTree });
287
+ * if (!router.isServer) {
288
+ * staleBuildTanStack(router);
289
+ * }
290
+ * return router;
291
+ * }
292
+ */
293
+ function staleBuildTanStack(router, options = {}) {
294
+ const watch = watchBuild(options);
295
+ if (watch == null) return () => {};
296
+ /** The navigation that runs now. `leaving` is true when it already loads its page as a document. */
297
+ let navigation;
298
+ const reload = async (current, response) => {
299
+ if (current.leaving) {
300
+ response?.body?.cancel().catch(() => void 0);
301
+ return new Promise(() => {});
302
+ }
303
+ current.leaving = true;
304
+ router.history.flush();
305
+ return loadDocument(location.href, { response });
306
+ };
307
+ const unsubscribe = [router.subscribe("onBeforeNavigate", ({ fromLocation, toLocation }) => {
308
+ navigation = void 0;
309
+ if (fromLocation == null || eventPage(fromLocation) === eventPage(toLocation)) return;
310
+ navigation = { leaving: false };
311
+ if (watch.isStale()) {
312
+ router.clearCache();
313
+ reload(navigation);
314
+ }
315
+ }), router.subscribe("onResolved", () => {
316
+ navigation = void 0;
317
+ })];
318
+ const send = globalThis.fetch;
319
+ let isStopped = false;
320
+ const patched = async (input, init) => {
321
+ if (isStopped) return send.call(globalThis, input, init);
322
+ const isGet = methodOf(input, init) === "GET";
323
+ if (isGet && navigation != null && watch.isStale()) return reload(navigation);
324
+ const response = await send.call(globalThis, input, init);
325
+ if (!watch.isNew(response, urlOf(input)) || !isGet || navigation == null) return response;
326
+ return reload(navigation, response);
327
+ };
328
+ globalThis.fetch = patched;
329
+ return () => {
330
+ for (const stop of unsubscribe) stop();
331
+ watch.stop();
332
+ isStopped = true;
333
+ navigation = void 0;
334
+ if (globalThis.fetch === patched) globalThis.fetch = send;
335
+ };
336
+ }
337
+
338
+ export { staleBuildTanStack as n, documentNonce as r, staleBuildReactRouter as t };
339
+ //# sourceMappingURL=stale-build-navigation-PnMLtTF8.js.map
@@ -0,0 +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,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,CAAC;CAC7F,OAAO,QAAQ,WAAW,kBAAkB,SAAS,KAAK;AAC3D;;AAGA,SAAS,OAAO,KAAqB;CACpC,MAAM,EAAE,QAAQ,UAAU,WAAW,IAAI,IAAI,KAAK,SAAS,IAAI;CAC/D,OAAO,GAAG,SAAS,WAAW;AAC/B;;AAGA,SAAS,UAAU,EAAE,UAAU,aAAoC;CAClE,OAAO,GAAG,WAAW;AACtB;;AAGA,SAAS,MAAM,OAAkC;CAChD,OAAO,iBAAiB,UAAU,MAAM,MAAM,OAAO,KAAK;AAC3D;;AAGA,SAAS,SAAS,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,IAAI,cAAwB,CAAC,CAAC;EACtC;EACA,QAAQ,UAAU;EAGlB,OAAO,QAAQ,MAAM;EACrB,OAAO,aAAa,SAAS,MAAM,EAAE,SAAS,CAAC;CAChD;CACA,MAAM,cAAc,CACnB,OAAO,UAAU,qBAAqB,EAAE,cAAc,iBAAiB;EAEtE,aAAa;EACb,IAAI,gBAAgB,QAAQ,UAAU,YAAY,MAAM,UAAU,UAAU,GAC3E;EAED,aAAa,EAAE,SAAS,MAAM;EAC9B,IAAI,MAAM,QAAQ,GAAG;GAGpB,OAAO,WAAW;GAClB,AAAK,OAAO,UAAU;EACvB;CACD,CAAC,GACD,OAAO,UAAU,oBAAoB;EACpC,aAAa;CACd,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"}
@@ -0,0 +1,141 @@
1
+ /** Options for {@link staleBuildReactRouter} and {@link staleBuildTanStack}. */
2
+ type StaleBuildOptions = {
3
+ /**
4
+ * The header that `buildId()` sets on data responses.
5
+ * @default "X-Build-Id"
6
+ */
7
+ header?: string;
8
+ /**
9
+ * The build that this document runs. Set it only when the server does not
10
+ * send it.
11
+ * @default the `build` metric of the document's `Server-Timing`, which `buildId()` sends
12
+ */
13
+ build?: string;
14
+ /**
15
+ * Runs once, when the tab first sees a response from another build. Use
16
+ * it to count stale tabs in the app's RUM tool.
17
+ */
18
+ onNewBuild?: (served: string) => void;
19
+ };
20
+ /** The context that React Router gives `unstable_fetch` with each request. */
21
+ type RouterFetchContext = {
22
+ /** `"navigation"` for the data request of a navigation that the router started. */
23
+ type: string;
24
+ /** `"PUSH"`, `"REPLACE"`, or `"POP"` for a navigation. */
25
+ navigationType?: string | null;
26
+ /** The fetcher that sends the request, also in a navigation that revalidates it. */
27
+ fetcherKey?: string | null;
28
+ };
29
+ /** The location in a TanStack Router event. */
30
+ type EventLocation = {
31
+ pathname: string;
32
+ searchStr: string;
33
+ };
34
+ /** The part of a TanStack Router that {@link staleBuildTanStack} reads. */
35
+ type NavigationEvents = {
36
+ history: {
37
+ flush: () => void;
38
+ };
39
+ clearCache: () => void;
40
+ subscribe: (type: "onBeforeNavigate" | "onResolved", listener: (event: {
41
+ fromLocation?: EventLocation;
42
+ toLocation: EventLocation;
43
+ }) => void) => () => void;
44
+ };
45
+ /** The `navigate` call of a React Router instrumentation. */
46
+ type NavigateInfo = {
47
+ to: string | number;
48
+ formMethod?: string;
49
+ };
50
+ /** The router instrumentations that {@link staleBuildReactRouter} adds. */
51
+ type RouterInstrumentations = {
52
+ navigate: (handler: () => Promise<unknown>, info: NavigateInfo) => Promise<void>;
53
+ };
54
+ /** The hooks that {@link staleBuildReactRouter} gives to React Router. */
55
+ type StaleBuildReactRouter = {
56
+ /** Give it to `HydratedRouter` as `unstable_fetch`. */
57
+ fetch: (request: Request, context: RouterFetchContext) => Promise<Response>;
58
+ /** Give it to `HydratedRouter` in `instrumentations`. */
59
+ instrumentation: {
60
+ router: (router: {
61
+ instrument: (instrumentations: RouterInstrumentations) => void;
62
+ }) => void;
63
+ };
64
+ /** Export it from `app/root.tsx` in `clientMiddleware`. */
65
+ middleware: <Result>(args: {
66
+ request: Request;
67
+ }, next: () => Promise<Result>) => Promise<Result>;
68
+ };
69
+ /**
70
+ * Moves an open React Router tab to a new build at a navigation, so the old
71
+ * client code never renders data from the new server, and the page that the
72
+ * visitor reads never reloads. Create it in a module that the client entry
73
+ * and `app/root.tsx` both import. It reads no browser state until React
74
+ * Router calls it, so the server can import it.
75
+ *
76
+ * - When the data request of a navigation gets a response from a new build,
77
+ * the browser loads the target URL as a document.
78
+ * - When the tab already knows of a new build, a `navigate` call, such as a
79
+ * link click, loads its target as a document before the router renders it
80
+ * or sends a data request. The root middleware does this also for a route
81
+ * with no loader.
82
+ * - A revalidation, a fetcher, an action, and the loaders after an action
83
+ * get their response. They only mark the tab, so the page that the visitor
84
+ * reads never reloads.
85
+ * - The router's blockers run first, and a canceled navigation never loads
86
+ * its target.
87
+ *
88
+ * It sends no request of its own and adds no wait. It needs `buildId()` in
89
+ * the server's pipeline, and it does nothing on a document with no build.
90
+ *
91
+ * @example
92
+ * // app/stale-build.ts
93
+ * export const staleBuild = staleBuildReactRouter();
94
+ *
95
+ * // app/root.tsx
96
+ * export const clientMiddleware = [staleBuild.middleware];
97
+ *
98
+ * // app/entry.client.tsx
99
+ * startTransition(() => {
100
+ * hydrateRoot(
101
+ * document,
102
+ * <HydratedRouter
103
+ * unstable_fetch={staleBuild.fetch}
104
+ * instrumentations={[staleBuild.instrumentation]}
105
+ * />,
106
+ * );
107
+ * });
108
+ */
109
+ declare function staleBuildReactRouter(options?: StaleBuildOptions): StaleBuildReactRouter;
110
+ /**
111
+ * Moves an open TanStack Router tab to a new build at a navigation, so the
112
+ * old client code never renders data from the new server, and the page that
113
+ * the visitor reads never reloads. Call it with the router on the client.
114
+ *
115
+ * - A navigation runs from `onBeforeNavigate` to `onResolved`. The router
116
+ * moves history and runs its blockers before it.
117
+ * - When a GET response from a new build comes back while a navigation
118
+ * runs, such as from a server function in a loader, the browser loads the
119
+ * page as a document.
120
+ * - When the tab already knows of a new build, a navigation to a new path or
121
+ * query clears the router cache and loads the page as a document.
122
+ * - A request outside a navigation gets its response, and only marks the tab.
123
+ *
124
+ * It sends no request of its own and adds no wait. It needs `buildId()` in
125
+ * the server's pipeline, and it does nothing on a document with no build.
126
+ * It returns a function that stops it and gives back `fetch`. If the app
127
+ * wrapped `fetch` after it, the wrapper stays, and each request passes on.
128
+ *
129
+ * @example
130
+ * // src/router.tsx
131
+ * export function getRouter() {
132
+ * const router = createRouter({ routeTree });
133
+ * if (!router.isServer) {
134
+ * staleBuildTanStack(router);
135
+ * }
136
+ * return router;
137
+ * }
138
+ */
139
+ declare function staleBuildTanStack(router: NavigationEvents, options?: StaleBuildOptions): () => void;
140
+ export { staleBuildReactRouter as a, StaleBuildReactRouter as i, RouterFetchContext as n, staleBuildTanStack as o, StaleBuildOptions as r, NavigationEvents as t };
141
+ //# sourceMappingURL=stale-build-navigation-ypV7Ow4o.d.ts.map
@@ -3,7 +3,7 @@ import { r as jsonSink, t as errorAttributes } from "./log-BP6xXXZl.js";
3
3
  import { i as exitAfterFlush, n as devServerStage } from "./node-BFH82eeL.js";
4
4
  import { t as requestListener } from "./response-writer-B7FoJjEE.js";
5
5
  import { t as SERVER_ENTRY_ID } from "./vite-iioAoxSt.js";
6
- import { t as loadEntry } from "./load-entry-AfYS_zS9.js";
6
+ import { t as loadEntry } from "./load-entry-CmkdlmDX.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";
@@ -222,4 +222,4 @@ function viteHostname(host) {
222
222
  }
223
223
 
224
224
  export { start };
225
- //# sourceMappingURL=start-TLIprD74.js.map
225
+ //# sourceMappingURL=start-Cb3kknlF.js.map