@opentf/afw 0.38.0 → 0.40.0

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.
@@ -16,16 +16,22 @@
16
16
  // (passed to the fetcher as `{ signal }`), so an out-of-order resolution can never
17
17
  // overwrite newer data — even for fetchers that ignore the signal.
18
18
  //
19
+ // Caching: a server function fetcher (`resource(() => ({ id }), getTodo)`) or a `key`
20
+ // option puts the result in the query cache (query-cache.js). Every user of the key
21
+ // shares one request and shows the same data; a remount shows the cached data at once
22
+ // and revalidates it (or skips the request while it is younger than `staleTime`).
23
+ //
19
24
  // Server (SSG/SSR): no effect is created and nothing is fetched — `loading` stays
20
- // `true`, so the prerendered HTML shows the loading branch. That is exactly what
21
- // the client's first paint renders before its own fetch resolves, keeping
22
- // hydration adoption aligned.
25
+ // `true` (or `false` for a source that starts paused), so the prerendered HTML shows
26
+ // the branch the client's first paint renders, keeping hydration adoption aligned.
23
27
 
24
28
  import { getCurrentInstance } from "../core/context.js";
25
29
  import { reportError } from "../core/errors.js";
26
30
  import { batch, effect, signal, untracked } from "../core/signals.js";
27
31
  import { endpointOf, registerResource, unregisterResource, withTracking } from "./invalidate.js";
28
32
  import { buildingPending, closestPending } from "./pending-scope.js";
33
+ import { DEFAULT_GC_TIME, callKey, customKey, fetchShared, isFresh, peek, subscribe, viewOf } from "./query-cache.js";
34
+ import { revalidateEvents, watch } from "./revalidate.js";
29
35
 
30
36
  // Test override: the DOM suites run in esdev's `--dom` realm (a `document`
31
37
  // always exists), so server behavior is opted into explicitly.
@@ -38,6 +44,8 @@ export function __setResourceServer(v) {
38
44
 
39
45
  const isServer = () => serverOverride ?? typeof document === "undefined";
40
46
 
47
+ const paused = (value) => value == null || value === false;
48
+
41
49
  /**
42
50
  * Create a resource. Two call shapes:
43
51
  *
@@ -45,17 +53,31 @@ const isServer = () => serverOverride ?? typeof document === "undefined";
45
53
  * resource(source, fetcher, options?) — re-fetch when the reactive `source`
46
54
  * changes; `null`/`false` pauses
47
55
  *
56
+ * A server function as the fetcher (`resource(() => ({ id }), getTodo)`, or
57
+ * `resource(listTodos)` for one without input) is cached by its endpoint and input; a
58
+ * `key` option caches any other fetcher. A cached resource shows the entry's data at
59
+ * once, shares requests with every other user of the key, and follows their updates.
60
+ *
48
61
  * @param {Function} source reactive source read inside the tracking effect; its
49
62
  * value is passed to the fetcher.
50
63
  * @param {Function} fetcher `(sourceValue, { signal }) => data | Promise<data>`.
51
- * @param {{ initial?: unknown, invalidatedBy?: Function[], errors?: "inline" }} [options]
64
+ * @param {{ initial?: unknown, invalidatedBy?: Function[], errors?: "inline",
65
+ * key?: unknown, staleTime?: number, gcTime?: number, timeout?: number,
66
+ * revalidateOn?: "focus" | "online" | Array<"focus" | "online"> }} [options]
52
67
  * `initial` seeds `data` before the first resolution. `invalidatedBy` names
53
68
  * server functions whose `invalidate()` refetches this resource, beyond those
54
69
  * its fetcher calls as it starts (which are recorded automatically).
55
70
  * `errors: "inline"` keeps failures on `error` only, even under `<Pending>`.
71
+ * `key` (a value, or a function of the source value) caches the fetcher's result.
72
+ * `staleTime` (ms, default 0): how long cached data answers without a request.
73
+ * `gcTime` (ms, default 5 minutes): how long an unused cache entry is kept.
74
+ * `timeout` (ms): abort a run that takes longer, with a TimeoutError.
75
+ * `revalidateOn` ("focus" | "online" | both): refetch when the tab becomes
76
+ * visible again or the browser reconnects, once the data is older than staleTime.
56
77
  * @returns {{ data: unknown, loading: boolean, error: unknown,
57
78
  * refetch: () => Promise<unknown> | undefined }} reactive getters —
58
- * read them inside bindings/effects to subscribe.
79
+ * read them inside bindings/effects to subscribe. `refetch()` resolves with the
80
+ * new data and rejects when the fetch fails.
59
81
  */
60
82
  export function resource(source, fetcher, options = {}) {
61
83
  if (typeof fetcher !== "function") {
@@ -66,55 +88,156 @@ export function resource(source, fetcher, options = {}) {
66
88
  const src = typeof source === "function" ? source : () => true;
67
89
  const data = signal(options.initial);
68
90
  const error = signal(undefined);
69
- const loading = signal(true); // a fetch is intended; the server leaves it true
91
+ // A fetch is intended. The server settles it as the browser's first paint will: still
92
+ // loading, unless the source starts paused (hydration adopts the same branch).
93
+ const loading = signal(isServer() ? !startsPaused(src) : true);
70
94
  // Has a run succeeded at least once? A `<Pending>` shows its fallback while a
71
95
  // resource it waits on is loading and has never loaded, so retrying a failed first
72
96
  // load shows the fallback again.
73
97
  const settled = signal(false);
74
98
  let token = 0;
75
99
  let controller = null;
76
- // This resource in the `invalidate()` registry (runtime/invalidate.js).
77
- const entry = { refetch: () => refetch() };
100
+ // This resource in the `invalidate()` registry (runtime/invalidate.js). `fromCache`:
101
+ // a call its fetcher made changed in the cache (`setQueryData`, an optimistic overlay,
102
+ // an action's refresh), so it re-runs against the cache. A resource that shows the
103
+ // entry itself heard the write already.
104
+ const entry = {
105
+ refetch: () => reload(),
106
+ fromCache: (key) => {
107
+ if (key === followed || disposed) return;
108
+ const value = untracked(src);
109
+ if (!paused(value)) run(value, { fromCache: true });
110
+ },
111
+ };
78
112
  const named = (options.invalidatedBy ?? []).map(endpointOf).filter(Boolean);
79
113
 
80
- function run(value) {
114
+ // --- The query cache (query-cache.js) ---------------------------------------
115
+ const staleTime = Math.max(0, Number(options.staleTime) || 0);
116
+ const timeout = Number(options.timeout) > 0 ? Number(options.timeout) : 0;
117
+ let loadedAt = 0; // when the shown data was fetched, for `revalidateOn`
118
+ const gcTime = options.gcTime ?? DEFAULT_GC_TIME;
119
+ const stub = typeof fetcher.endpoint === "string" ? fetcher.endpoint : null;
120
+ const custom = "key" in options;
121
+ // `resource(listTodos)`: a server function without a source takes no input.
122
+ const input = (value) => (stub && !source ? undefined : value);
123
+ const keyOf = (value) => {
124
+ if (custom) return customKey(typeof options.key === "function" ? options.key(value) : options.key);
125
+ return stub ? callKey(stub, input(value)) : null;
126
+ };
127
+ let followed = null; // the key this resource shows
128
+ let unfollow = null;
129
+ function follow(key) {
130
+ if (key === followed) return;
131
+ unfollow?.();
132
+ followed = key;
133
+ unfollow = key ? subscribe(key, onWrite, { gcTime }) : null;
134
+ }
135
+ // Another user of the key stored new data.
136
+ function onWrite(value) {
137
+ batch(() => {
138
+ data.value = value;
139
+ error.value = undefined;
140
+ settled.value = true;
141
+ });
142
+ }
143
+ // A cached resource's dependencies for `invalidate()`: its own call, or what the
144
+ // fetcher behind its custom key called.
145
+ function register(key, endpoints = new Set(), keys = new Set()) {
146
+ if (key && stub && !custom) {
147
+ endpoints.add(stub);
148
+ keys.add(key);
149
+ }
150
+ const deps = key && custom ? peek(key)?.deps : null;
151
+ if (deps) {
152
+ for (const endpoint of deps.endpoints) endpoints.add(endpoint);
153
+ for (const k of deps.keys) keys.add(k);
154
+ }
155
+ registerResource(entry, endpoints, keys, named);
156
+ }
157
+
158
+ // One run of the fetcher. Resolves with its outcome, never rejects:
159
+ // `{ ok: true, value }`, `{ ok: false, error }`, or `{ superseded: true }`.
160
+ function run(value, { force = false, fromCache = false } = {}) {
81
161
  controller?.abort();
82
162
  // Captured per-run: by the time a superseded run's promise settles, the
83
163
  // module-level `controller` already belongs to a newer run.
84
164
  const c = (controller = typeof AbortController !== "undefined" ? new AbortController() : null);
165
+ // `timeout` ms: the run aborts with a TimeoutError (the resource's error).
166
+ const runSignal = timeout && c ? AbortSignal.any([c.signal, AbortSignal.timeout(timeout)]) : c?.signal;
85
167
  const t = ++token;
86
- batch(() => {
87
- loading.value = true;
88
- error.value = undefined;
89
- });
168
+ // `refetch()` and `invalidate()` always ask the server. A re-run from the cache runs
169
+ // the fetcher again, its server function calls answering from cached data.
170
+ const age = force || fromCache ? 0 : staleTime;
171
+ const inner = fromCache ? Infinity : age;
172
+ let key = null;
173
+ let keyError = null;
174
+ try {
175
+ key = keyOf(value);
176
+ } catch (e) {
177
+ keyError = e; // a key or input the codec refuses
178
+ }
179
+ follow(key);
180
+ const cached = key ? peek(key) : undefined;
181
+ if (cached?.hasData) {
182
+ // Show the cached data at once; a stale entry revalidates behind it.
183
+ const shown = viewOf(cached);
184
+ batch(() => {
185
+ data.value = shown;
186
+ error.value = undefined;
187
+ settled.value = true;
188
+ if (isFresh(cached, age)) loading.value = false;
189
+ });
190
+ if (isFresh(cached, age)) {
191
+ loadedAt = cached.updatedAt;
192
+ register(key);
193
+ return Promise.resolve({ ok: true, value: shown });
194
+ }
195
+ }
196
+ // A re-run from the cache settles within microtasks: no loading state to show.
197
+ if (!fromCache) {
198
+ batch(() => {
199
+ loading.value = true;
200
+ error.value = undefined;
201
+ });
202
+ }
90
203
  // The async IIFE starts the fetcher *synchronously* (no wasted microtask)
91
204
  // while converting a synchronous throw into a rejection.
205
+ const start = (s) => (async () => fetcher(input(value), { signal: s }))();
92
206
  // Started under tracking: the server functions the fetcher calls register it.
93
- const { result, endpoints } = withTracking(() => (async () => fetcher(value, { signal: c?.signal }))());
94
- for (const endpoint of named) endpoints.add(endpoint);
95
- registerResource(entry, endpoints);
96
- return result
97
- .then(
98
- (v) => {
99
- if (t !== token) return; // superseded — a newer run owns the signals
100
- batch(() => {
101
- data.value = v;
102
- loading.value = false;
103
- settled.value = true;
104
- });
105
- return v;
106
- },
107
- (e) => {
108
- if (t !== token) return;
109
- // Keep the last good `data` (stale-while-error); only `error` flips.
110
- const first = !settled.value;
111
- batch(() => {
112
- error.value = e;
113
- loading.value = false;
114
- });
115
- failed(e, first);
116
- },
117
- );
207
+ let tracked = null;
208
+ const { result, endpoints, keys } = withTracking(() => {
209
+ if (keyError) return Promise.reject(keyError);
210
+ if (!custom) return start(runSignal);
211
+ return fetchShared(key, start, { signal: runSignal, staleTime: age, deps: () => tracked });
212
+ }, { staleTime: inner });
213
+ tracked = { endpoints, keys };
214
+ register(key, endpoints, keys);
215
+ return result.then(
216
+ (v) => {
217
+ if (t !== token) return { superseded: true };
218
+ loadedAt = Date.now();
219
+ batch(() => {
220
+ data.value = v;
221
+ error.value = undefined;
222
+ loading.value = false;
223
+ settled.value = true;
224
+ });
225
+ // A custom key joined a request someone else started: register what it called.
226
+ if (custom && endpoints.size === 0) register(key, endpoints, keys);
227
+ return { ok: true, value: v };
228
+ },
229
+ (e) => {
230
+ if (t !== token) return { superseded: true };
231
+ // Keep the last good `data` (stale-while-error); only `error` flips.
232
+ const first = !settled.value;
233
+ batch(() => {
234
+ error.value = e;
235
+ loading.value = false;
236
+ });
237
+ failed(e, first);
238
+ return { ok: false, error: e };
239
+ },
240
+ );
118
241
  }
119
242
 
120
243
  // --- `<Pending>` boundaries (pending.js) ------------------------------------
@@ -125,7 +248,7 @@ export function resource(source, fetcher, options = {}) {
125
248
  const handle = {
126
249
  loading: () => loading.value,
127
250
  settled: () => settled.value,
128
- refetch: () => (disposed ? undefined : refetch()),
251
+ refetch: () => (disposed ? undefined : reload()),
129
252
  };
130
253
  function track(boundary) {
131
254
  if (!boundary || boundaries.has(boundary)) return;
@@ -148,14 +271,19 @@ export function resource(source, fetcher, options = {}) {
148
271
  const host = getCurrentInstance();
149
272
  if (host) track(closestPending(host));
150
273
  // Runs its cleanup only when the owning scope is disposed (no tracked reads).
274
+ // `revalidateOn`: refetch on focus / reconnect once the data is older than staleTime.
275
+ const unwatch = watch(revalidateEvents(options.revalidateOn), () => {
276
+ if (!disposed && Date.now() - loadedAt >= staleTime) reload();
277
+ });
151
278
  const disposeTracking = effect(() => () => {
152
279
  disposed = true;
280
+ unwatch();
153
281
  for (const boundary of boundaries) boundary.__untrack(handle);
154
282
  boundaries.clear();
155
283
  });
156
284
  const disposeFetching = effect(() => {
157
285
  const value = src(); // the effect's ONLY tracked read
158
- if (value == null || value === false) {
286
+ if (paused(value)) {
159
287
  // Paused: cancel anything in flight and settle as "not loading".
160
288
  untracked(() => {
161
289
  token++;
@@ -164,6 +292,7 @@ export function resource(source, fetcher, options = {}) {
164
292
  loading.value = false;
165
293
  });
166
294
  unregisterResource(entry);
295
+ follow(null);
167
296
  return;
168
297
  }
169
298
  untracked(() => run(value));
@@ -173,6 +302,7 @@ export function resource(source, fetcher, options = {}) {
173
302
  token++;
174
303
  controller?.abort();
175
304
  unregisterResource(entry);
305
+ follow(null);
176
306
  };
177
307
  });
178
308
  // A component body runs outside any scope; its host tears down `_cleanups` on
@@ -181,10 +311,27 @@ export function resource(source, fetcher, options = {}) {
181
311
  if (host && Array.isArray(host._cleanups)) host._cleanups.push(disposeTracking, disposeFetching);
182
312
  }
183
313
 
184
- function refetch() {
314
+ // Re-run with the current source value, bypassing `staleTime`. Paused: undefined.
315
+ function rerun() {
185
316
  const value = untracked(src);
186
- if (value == null || value === false) return undefined;
187
- return run(value);
317
+ return paused(value) ? undefined : run(value, { force: true });
318
+ }
319
+ // For `invalidate()`, `<Pending>` and error-boundary retries: never rejects, since
320
+ // the failure already shows on `error` (or goes to a boundary).
321
+ function reload() {
322
+ return rerun()?.then(() => undefined);
323
+ }
324
+ // Public: resolves with the new data (undefined if a newer run superseded it) and
325
+ // rejects when the fetch fails. The failure also shows on `error`, so a caller that
326
+ // ignores the promise (`onclick={() => r.refetch()}`) is not an unhandled rejection;
327
+ // one that awaits it still sees the rejection.
328
+ function refetch() {
329
+ const result = rerun()?.then((outcome) => {
330
+ if (outcome.ok === false) throw outcome.error;
331
+ return outcome.value;
332
+ });
333
+ result?.catch(() => {});
334
+ return result;
188
335
  }
189
336
 
190
337
  // A read while a boundary's children are being built makes that boundary wait on
@@ -207,7 +354,19 @@ export function resource(source, fetcher, options = {}) {
207
354
  reading();
208
355
  return error.value;
209
356
  },
210
- /** Re-run the fetcher with the current source value (no-op while paused). */
357
+ /**
358
+ * Re-run the fetcher with the current source value (no-op while paused). Resolves
359
+ * with the new data; rejects when the fetch fails.
360
+ */
211
361
  refetch,
212
362
  };
213
363
  }
364
+
365
+ /** Is the source paused on the server? A source that throws there counts as running. */
366
+ function startsPaused(src) {
367
+ try {
368
+ return paused(untracked(src));
369
+ } catch {
370
+ return false;
371
+ }
372
+ }
@@ -0,0 +1,39 @@
1
+ // Revalidation triggers for `resource(…, { revalidateOn })` (docs/DATA.md §3): when the
2
+ // tab becomes visible again ("focus") or the browser comes back online ("online"), a
3
+ // resource whose data is older than its `staleTime` refetches. One listener per event
4
+ // serves every resource; nothing is installed until a resource asks.
5
+
6
+ const watchers = { focus: new Set(), online: new Set() };
7
+ let installed = false;
8
+
9
+ function fire(event) {
10
+ for (const fn of [...watchers[event]]) fn();
11
+ }
12
+
13
+ function install() {
14
+ if (installed || typeof document === "undefined") return;
15
+ installed = true;
16
+ document.addEventListener("visibilitychange", () => {
17
+ if (document.visibilityState === "visible") fire("focus");
18
+ });
19
+ globalThis.addEventListener?.("online", () => fire("online"));
20
+ }
21
+
22
+ /** Normalize `revalidateOn` to a list of events, refusing unknown ones. */
23
+ export function revalidateEvents(value) {
24
+ const events = value == null ? [] : Array.isArray(value) ? value : [value];
25
+ for (const event of events) {
26
+ if (!(event in watchers)) throw new TypeError(`revalidateOn: expected "focus" or "online", got ${JSON.stringify(event)}`);
27
+ }
28
+ return events;
29
+ }
30
+
31
+ /** Call `fn` on each of `events`; returns the unwatch function. */
32
+ export function watch(events, fn) {
33
+ if (events.length === 0) return () => {};
34
+ install();
35
+ for (const event of events) watchers[event].add(fn);
36
+ return () => {
37
+ for (const event of events) watchers[event].delete(fn);
38
+ };
39
+ }
@@ -2,9 +2,9 @@
2
2
  * `"/todos"` → `/todos/__data.json`, preserving the query string. */
3
3
  export function dataUrlFor(pathname: any, search?: string): string;
4
4
  /**
5
- * Fetch a route's loader data. 200 → the parsed JSON; 404 → `undefined` (no
6
- * loader / `notFound()`); anything else throws (the router reports it and
7
- * commits the navigation with no data).
5
+ * Fetch a route's loader data. 200 → the parsed JSON; 404 → a `RouteNotFound`
6
+ * (`notFound()`, or a path with no page); a redirect → a `RouteRedirect`; anything
7
+ * else throws (the router reports it and commits the navigation with no data).
8
8
  */
9
9
  export function fetchRouteData(pathname: any, search?: string): Promise<any>;
10
10
  /** The loader data inlined by the server for the current document, or `undefined`. */
@@ -22,3 +22,9 @@ export class RouteRedirect {
22
22
  /** A full page load is needed (the server redirected the data request itself). */
23
23
  reload: boolean;
24
24
  }
25
+ /** Returned by `fetchRouteData` when the route has no data: the loader called `notFound()`. */
26
+ export class RouteNotFound {}
27
+ /** The inline-data payload marking a server-rendered 404 page (a loader's `notFound()`). */
28
+ export const NOT_FOUND_PAYLOAD: string;
29
+ /** Does the inline data mark a server-rendered 404 page? */
30
+ export function isNotFoundPayload(data: unknown): boolean;
@@ -8,9 +8,10 @@
8
8
  // servers answer dynamically);
9
9
  // • dev/CSR first load — the same fetch, since there is no server markup.
10
10
  //
11
- // The endpoint returns the raw loader JSON (no envelope): 404 means "no data for
12
- // this route" (no loader, or the loader called `notFound()`) and maps to
13
- // `undefined` so the page renders its empty state.
11
+ // The endpoint returns the raw loader JSON (no envelope). A loader that returns
12
+ // nothing answers 200 `null` (and a prerendered page's file holds `null`), so a 404
13
+ // means the loader called `notFound()` or the path has no page: the router shows
14
+ // the 404 page, as a full page load of that URL does.
14
15
 
15
16
  /** The reserved per-route data filename/URL suffix (`/todos` → `/todos/__data.json`). */
16
17
  export const DATA_FILE = "__data.json";
@@ -41,9 +42,15 @@ export class RouteRedirect {
41
42
  }
42
43
 
43
44
  /**
44
- * Fetch a route's loader data. 200 → the parsed JSON; 404 → `undefined` (no
45
- * loader / `notFound()`); a redirect → a {@link RouteRedirect}; anything else throws
46
- * (the router reports it and commits the navigation with no data).
45
+ * What `fetchRouteData` returns when the endpoint answers 404: the loader called
46
+ * `notFound()`, or (on a static host) the path was never prerendered.
47
+ */
48
+ export class RouteNotFound {}
49
+
50
+ /**
51
+ * Fetch a route's loader data. 200 → the parsed JSON; 404 → a {@link RouteNotFound};
52
+ * a redirect → a {@link RouteRedirect}; anything else throws (the router reports it
53
+ * and commits the navigation with no data).
47
54
  */
48
55
  export async function fetchRouteData(pathname, search = "") {
49
56
  // "manual": a redirect is not data. Following it would fetch an HTML page.
@@ -55,7 +62,7 @@ export async function fetchRouteData(pathname, search = "") {
55
62
  if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
56
63
  return new RouteRedirect(pathname + search, { reload: true });
57
64
  }
58
- if (res.status === 404) return undefined;
65
+ if (res.status === 404) return new RouteNotFound();
59
66
  if (!res.ok) {
60
67
  const error = Object.assign(new Error(`route data request for ${pathname} failed (${res.status})`), { status: res.status });
61
68
  // The endpoint names the layout whose loader failed (see the server's loader registry).
@@ -89,6 +96,20 @@ export function routeErrorPayload(error) {
89
96
  return JSON.stringify(marker).replace(/</g, "\\u003c");
90
97
  }
91
98
 
99
+ const NOT_FOUND = "__afwNotFound";
100
+
101
+ /**
102
+ * The inline-data payload marking a page the server answered with the 404 page (a
103
+ * loader called `notFound()`): the URL matches a route, but the markup is the 404
104
+ * page's, so first paint must adopt that instead of the route's layouts.
105
+ */
106
+ export const NOT_FOUND_PAYLOAD = JSON.stringify({ [NOT_FOUND]: true });
107
+
108
+ /** Does the inline data mark a server-rendered 404 page? */
109
+ export function isNotFoundPayload(data) {
110
+ return !!data && typeof data === "object" && data[NOT_FOUND] === true;
111
+ }
112
+
92
113
  /** The error a {@link routeErrorPayload} carries, as an `Error` with `status`, or null. */
93
114
  export function routeErrorFrom(data) {
94
115
  const marker = data && typeof data === "object" ? data[ROUTE_ERROR] : null;
@@ -125,17 +125,24 @@ const segmentKind = (seg) => {
125
125
  /**
126
126
  * Sort comparator: more specific routes first, by URL (groups dropped). Compares
127
127
  * segment kinds left to right (static < `[param]` < `[[param]]` < `[...rest]` <
128
- * `[[...rest]]`); with equal kinds the route with more segments is more specific; the
129
- * final tie-break is lexical, for a deterministic order.
128
+ * `[[...rest]]`). With equal kinds, the route with more segments is more specific —
129
+ * unless every extra segment is optional: then both match the shorter URL, and the
130
+ * route that names it exactly wins (`/shop` before `/shop/[[...filters]]`). The final
131
+ * tie-break is lexical, for a deterministic order.
130
132
  */
131
133
  export function compareRoutes(a, b) {
132
134
  const sa = urlOf(a).split("/").filter(Boolean);
133
135
  const sb = urlOf(b).split("/").filter(Boolean);
134
- for (let i = 0; i < Math.min(sa.length, sb.length); i++) {
136
+ const shared = Math.min(sa.length, sb.length);
137
+ for (let i = 0; i < shared; i++) {
135
138
  const d = segmentKind(sa[i]) - segmentKind(sb[i]);
136
139
  if (d !== 0) return d;
137
140
  }
138
- if (sa.length !== sb.length) return sb.length - sa.length;
141
+ if (sa.length !== sb.length) {
142
+ const extra = (sa.length > sb.length ? sa : sb).slice(shared);
143
+ const longerFirst = sb.length - sa.length;
144
+ return extra.every((seg) => OPTIONAL.test(seg)) ? -longerFirst : longerFirst;
145
+ }
139
146
  return a < b ? -1 : a > b ? 1 : 0;
140
147
  }
141
148
 
@@ -164,3 +171,21 @@ export function decodeParams(route, groups, { strict = false } = {}) {
164
171
  }
165
172
  return params;
166
173
  }
174
+
175
+ /**
176
+ * Mark a route-table entry (page, layout, loading or error file) as rendered in the
177
+ * browser — its folder's `_config.js` says `render: "client"`. The generated route tables
178
+ * wrap these entries: the client's keeps the lazy import, the server's has none (the module
179
+ * never enters the server bundle). A server render stops at the first such entry and
180
+ * leaves its region empty; the client builds it there.
181
+ */
182
+ export function clientRoute(load) {
183
+ const entry = load ?? (() => {
184
+ throw new Error("This route renders in the browser: its module is not part of the server bundle.");
185
+ });
186
+ entry.__afwClient = true;
187
+ return entry;
188
+ }
189
+
190
+ /** Whether a route-table entry renders in the browser (see {@link clientRoute}). */
191
+ export const isClientRoute = (entry) => entry?.__afwClient === true;
@@ -183,3 +183,12 @@ export namespace router {
183
183
  function push(path: any): Promise<void>;
184
184
  function replace(path: any): Promise<void>;
185
185
  }
186
+
187
+ /**
188
+ * Mark a route-table entry as rendered in the browser (its folder's `_config.js` says
189
+ * `render: "client"`). Used by the generated route tables; `load` is the client's lazy
190
+ * import, omitted on the server, whose bundle never includes the module.
191
+ */
192
+ export function clientRoute<T extends (() => unknown) | undefined>(load?: T): T extends () => unknown ? T : () => never;
193
+ /** Whether a route-table entry renders in the browser (see `clientRoute`). */
194
+ export function isClientRoute(entry: unknown): boolean;