@rangojs/router 0.0.0-experimental.110 → 0.0.0-experimental.112

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/bin/rango.js +41 -37
  2. package/dist/vite/index.js +144 -191
  3. package/package.json +17 -14
  4. package/skills/handler-use/SKILL.md +1 -1
  5. package/skills/rango/SKILL.md +20 -0
  6. package/src/browser/action-coordinator.ts +53 -36
  7. package/src/browser/event-controller.ts +42 -66
  8. package/src/browser/navigation-bridge.ts +4 -0
  9. package/src/browser/navigation-client.ts +12 -15
  10. package/src/browser/navigation-store.ts +7 -8
  11. package/src/browser/navigation-transaction.ts +7 -21
  12. package/src/browser/partial-update.ts +8 -16
  13. package/src/browser/react/NavigationProvider.tsx +29 -40
  14. package/src/browser/react/use-params.ts +3 -4
  15. package/src/browser/response-adapter.ts +25 -0
  16. package/src/browser/rsc-router.tsx +16 -2
  17. package/src/browser/server-action-bridge.ts +23 -30
  18. package/src/browser/types.ts +2 -0
  19. package/src/build/generate-manifest.ts +29 -31
  20. package/src/build/generate-route-types.ts +2 -0
  21. package/src/build/route-types/router-processing.ts +37 -9
  22. package/src/build/runtime-discovery.ts +9 -20
  23. package/src/decode-loader-results.ts +36 -0
  24. package/src/errors.ts +29 -0
  25. package/src/index.rsc.ts +1 -0
  26. package/src/index.ts +1 -0
  27. package/src/response-utils.ts +9 -0
  28. package/src/route-content-wrapper.tsx +6 -28
  29. package/src/route-definition/dsl-helpers.ts +231 -259
  30. package/src/route-definition/helper-factories.ts +29 -139
  31. package/src/route-definition/use-item-types.ts +32 -0
  32. package/src/route-types.ts +19 -41
  33. package/src/router/content-negotiation.ts +15 -2
  34. package/src/router/intercept-resolution.ts +4 -18
  35. package/src/router/match-result.ts +32 -30
  36. package/src/router/middleware.ts +46 -78
  37. package/src/router/preview-match.ts +3 -1
  38. package/src/router/request-classification.ts +4 -28
  39. package/src/rsc/handler.ts +20 -65
  40. package/src/rsc/helpers.ts +3 -2
  41. package/src/rsc/origin-guard.ts +28 -10
  42. package/src/rsc/response-route-handler.ts +32 -52
  43. package/src/rsc/rsc-rendering.ts +27 -53
  44. package/src/rsc/runtime-warnings.ts +9 -10
  45. package/src/rsc/server-action.ts +13 -37
  46. package/src/rsc/ssr-setup.ts +16 -0
  47. package/src/segment-system.tsx +5 -39
  48. package/src/server/context.ts +76 -35
  49. package/src/urls/include-helper.ts +10 -53
  50. package/src/urls/index.ts +0 -3
  51. package/src/urls/path-helper.ts +17 -52
  52. package/src/urls/pattern-types.ts +2 -19
  53. package/src/urls/response-types.ts +20 -19
  54. package/src/urls/type-extraction.ts +20 -115
  55. package/src/urls/urls-function.ts +1 -5
  56. package/src/vite/discovery/discover-routers.ts +10 -22
  57. package/src/vite/discovery/route-types-writer.ts +38 -82
  58. package/src/vite/plugins/cjs-to-esm.ts +3 -7
  59. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  60. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  61. package/src/vite/plugins/expose-internal-ids.ts +34 -62
  62. package/src/vite/plugins/version-injector.ts +2 -12
  63. package/src/vite/router-discovery.ts +71 -26
  64. package/src/vite/utils/shared-utils.ts +13 -1
  65. package/src/browser/action-response-classifier.ts +0 -99
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rangojs/router",
3
- "version": "0.0.0-experimental.110",
3
+ "version": "0.0.0-experimental.112",
4
4
  "description": "Django-inspired RSC router with composable URL patterns",
5
5
  "keywords": [
6
6
  "react",
@@ -132,6 +132,16 @@
132
132
  "access": "public",
133
133
  "tag": "experimental"
134
134
  },
135
+ "scripts": {
136
+ "build": "pnpm dlx esbuild src/vite/index.ts --bundle --format=esm --outfile=dist/vite/index.js --platform=node --packages=external && mkdir -p dist/vite/plugins && cp src/vite/plugins/cloudflare-protocol-loader-hook.mjs dist/vite/plugins/cloudflare-protocol-loader-hook.mjs && pnpm dlx esbuild src/bin/rango.ts --bundle --format=esm --outfile=dist/bin/rango.js --platform=node --packages=external --banner:js='#!/usr/bin/env node' && chmod +x dist/bin/rango.js",
137
+ "prepublishOnly": "pnpm build",
138
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.strict-check.json --noEmit && tsc -p tsconfig.augment-check.json --noEmit",
139
+ "test": "playwright test",
140
+ "test:ui": "playwright test --ui",
141
+ "test:hmr-local": "playwright test --project=dev-warmup --project=hmr-routes --project=hmr-basename --project=hmr-prerender --no-deps --workers=1",
142
+ "test:unit": "vitest run",
143
+ "test:unit:watch": "vitest"
144
+ },
135
145
  "dependencies": {
136
146
  "@types/debug": "^4.1.12",
137
147
  "@vitejs/plugin-rsc": "^0.5.26",
@@ -142,13 +152,14 @@
142
152
  },
143
153
  "devDependencies": {
144
154
  "@playwright/test": "^1.49.1",
155
+ "@shared/e2e": "workspace:*",
145
156
  "@types/node": "^24.10.1",
146
- "@types/react": "^19.2.7",
147
- "@types/react-dom": "^19.2.3",
157
+ "@types/react": "catalog:",
158
+ "@types/react-dom": "catalog:",
148
159
  "esbuild": "^0.27.0",
149
160
  "jiti": "^2.6.1",
150
- "react": "^19.2.6",
151
- "react-dom": "^19.2.6",
161
+ "react": "catalog:",
162
+ "react-dom": "catalog:",
152
163
  "tinyexec": "^0.3.2",
153
164
  "typescript": "^5.3.0",
154
165
  "vitest": "^4.0.0"
@@ -167,13 +178,5 @@
167
178
  "vite": {
168
179
  "optional": true
169
180
  }
170
- },
171
- "scripts": {
172
- "build": "pnpm dlx esbuild src/vite/index.ts --bundle --format=esm --outfile=dist/vite/index.js --platform=node --packages=external && mkdir -p dist/vite/plugins && cp src/vite/plugins/cloudflare-protocol-loader-hook.mjs dist/vite/plugins/cloudflare-protocol-loader-hook.mjs && pnpm dlx esbuild src/bin/rango.ts --bundle --format=esm --outfile=dist/bin/rango.js --platform=node --packages=external --banner:js='#!/usr/bin/env node' && chmod +x dist/bin/rango.js",
173
- "typecheck": "tsc --noEmit && tsc -p tsconfig.strict-check.json --noEmit && tsc -p tsconfig.augment-check.json --noEmit",
174
- "test": "playwright test",
175
- "test:ui": "playwright test --ui",
176
- "test:unit": "vitest run",
177
- "test:unit:watch": "vitest"
178
181
  }
179
- }
182
+ }
@@ -297,7 +297,7 @@ QuickViewModal.use = () => [
297
297
 
298
298
  ## `loading()` is a single-assignment item — scope it correctly
299
299
 
300
- Most `use` items accumulate when merged: `handler.use` `middleware()` runs _and_ explicit `middleware()` runs; both `loader()` registrations apply. `loading()` is different — it mutates `entry.loading` directly, last call wins ([dsl-helpers.ts `loadingFn`](../../src/route-definition/dsl-helpers.ts)).
300
+ Most `use` items accumulate when merged: `handler.use` `middleware()` runs _and_ explicit `middleware()` runs; both `loader()` registrations apply. `loading()` is different — it mutates `entry.loading` directly, last call wins ([dsl-helpers.ts `loading`](../../src/route-definition/dsl-helpers.ts)).
301
301
 
302
302
  For pages, layouts, and intercepts that's straightforward: explicit `loading()` at the mount site replaces any `loading()` from `handler.use`. The merge order is `handler.use → explicit`, so the explicit one is the last writer and wins.
303
303
 
@@ -142,6 +142,18 @@ by reference with `ctx.isAction(Action)` (rename-safe, where `CartActions` is an
142
142
  `import * as CartActions from "./actions/cart"`); see `/typesafety` → "Stable
143
143
  identity".
144
144
 
145
+ The predicate arg carries the action's full context, not just its identity. Match
146
+ _which_ action with `ctx.isAction(addToCart)` (rename-safe); branch on _what it
147
+ returned_ with `ctx.actionResult` — the value your `"use server"` function
148
+ returned, for outcome-conditional revalidation. The arg also exposes `actionId`
149
+ (raw `path#export`), `actionUrl`, `formData`, `method`, and `stale` (cross-tab
150
+ `_rsc_stale` signal). All are `undefined` on plain navigation (no action).
151
+
152
+ ```ts
153
+ // re-render only when checkout actually succeeded; defer otherwise
154
+ revalidate((ctx) => (ctx.isAction(checkout) && ctx.actionResult?.ok) || undefined),
155
+ ```
156
+
145
157
  **The source is the source of truth.** Structure, types, and update policy are
146
158
  visible and local in the tree — read top-down, no hidden global model to hold in
147
159
  your head. A snippet earns its place only if, from the code alone, you can answer:
@@ -150,6 +162,14 @@ without leaving the call site?_ (type-safety), _what re-renders after this
150
162
  action?_ (partial rendering). If any answer needs another file, it isn't legible
151
163
  yet.
152
164
 
165
+ **Reading Rango's own source.** Rango is consumed as raw TypeScript — the
166
+ `exports` map resolves `@rangojs/router` and its subpaths to `./src/*.ts` for
167
+ both types and runtime, so a consuming app bundles Rango straight from source.
168
+ Only the `./vite` plugin entry and the CLI `bin` load from `dist/`. To confirm
169
+ any runtime or type detail against an installed copy, read the resolved source
170
+ under `node_modules/@rangojs/router/src/`, not `dist/` — the runtime does not
171
+ resolve `dist/` outside `./vite`, and it may lag `src/`.
172
+
153
173
  ## Skills
154
174
 
155
175
  Grouped by concern — read when you need to…
@@ -1,9 +1,21 @@
1
- import {
2
- classifyActionResponse,
3
- type ActionScenario,
4
- } from "./action-response-classifier.js";
5
1
  import type { ActionEntry } from "./event-controller.js";
6
2
 
3
+ /**
4
+ * Post-reconciliation action outcome (discriminated union). Error and
5
+ * full-update-unsupported cases are handled inline in the bridge before
6
+ * reconciliation; this only covers successfully-reconciled partial responses.
7
+ */
8
+ export type ActionScenario =
9
+ | {
10
+ type: "navigated-away";
11
+ historyKeyChanged: boolean;
12
+ onInterceptRoute: boolean;
13
+ }
14
+ | { type: "hmr-missing" }
15
+ | { type: "consolidation-needed"; segmentIds: string[] }
16
+ | { type: "concurrent-skip"; otherFetchingCount: number }
17
+ | { type: "normal" };
18
+
7
19
  /**
8
20
  * Plain data inputs for classifying a post-reconciliation action outcome.
9
21
  * No browser objects or controller references — all values are snapshots.
@@ -33,20 +45,15 @@ export interface ActionOutcomeInput {
33
45
  currentInterceptSource: string | null;
34
46
  }
35
47
 
36
- /**
37
- * Compute consolidation segments from concurrent action state.
38
- *
39
- * Returns segment IDs that need re-fetching when concurrent actions
40
- * have each revalidated different parts of the tree, or null if
41
- * consolidation is not needed.
42
- */
48
+ // Segment IDs to re-fetch when concurrent actions each revalidated different
49
+ // parts of the tree; null when consolidation does not apply. Returns null while
50
+ // any action is still fetching — consolidation must wait for all to land.
43
51
  function computeConsolidationSegments(
44
52
  input: ActionOutcomeInput,
45
53
  ): string[] | null {
46
54
  if (!input.hadAnyConcurrentActions) return null;
47
55
  if (input.revalidatedSegments.size === 0) return null;
48
56
 
49
- // Can't consolidate while any action is still waiting for a server response
50
57
  const stillFetchingCount = [...input.inflightActions.values()].filter(
51
58
  (a) => a.phase === "fetching",
52
59
  ).length;
@@ -55,9 +62,6 @@ function computeConsolidationSegments(
55
62
  return Array.from(input.revalidatedSegments);
56
63
  }
57
64
 
58
- /**
59
- * Count other actions still in "fetching" phase (excluding this handle).
60
- */
61
65
  function countOtherFetchingActions(input: ActionOutcomeInput): number {
62
66
  let count = 0;
63
67
  for (const [, a] of input.inflightActions) {
@@ -69,29 +73,42 @@ function countOtherFetchingActions(input: ActionOutcomeInput): number {
69
73
  }
70
74
 
71
75
  /**
72
- * Classify a post-reconciliation action outcome into one of 5 scenarios.
73
- *
74
- * This is the single entry point for post-action decision logic.
75
- * It gathers consolidation and concurrency data from the plain inputs,
76
- * then delegates to the pure classifyActionResponse function.
77
- *
78
- * The server-action-bridge calls this after reconciliation to decide
79
- * whether to render, skip, consolidate, or refetch.
76
+ * Classify a post-reconciliation action outcome. Ordered priority chain: each
77
+ * case assumes the earlier ones are false (e.g. concurrent-skip only applies on
78
+ * the still-current route, consolidation only once no action is still fetching).
79
+ * The bridge calls this to decide whether to render, skip, consolidate, or refetch.
80
80
  */
81
81
  export function classifyActionOutcome(
82
82
  input: ActionOutcomeInput,
83
83
  ): ActionScenario {
84
- return classifyActionResponse({
85
- actionStartPathname: input.actionStartPathname,
86
- currentPathname: input.currentPathname,
87
- actionStartLocationKey: input.actionStartLocationKey,
88
- currentLocationKey: input.currentLocationKey,
89
- reconciledSegmentCount: input.reconciledSegmentCount,
90
- matchedCount: input.matchedCount,
91
- currentInterceptSource: input.currentInterceptSource,
92
- consolidationSegments: computeConsolidationSegments(input),
93
- otherFetchingActionCount: countOtherFetchingActions(input),
94
- });
95
- }
84
+ if (
85
+ input.currentPathname !== input.actionStartPathname ||
86
+ input.currentLocationKey !== input.actionStartLocationKey
87
+ ) {
88
+ return {
89
+ type: "navigated-away",
90
+ historyKeyChanged:
91
+ input.currentLocationKey !== input.actionStartLocationKey,
92
+ onInterceptRoute: input.currentInterceptSource !== null,
93
+ };
94
+ }
95
+
96
+ if (input.reconciledSegmentCount < input.matchedCount) {
97
+ return { type: "hmr-missing" };
98
+ }
99
+
100
+ const consolidationSegments = computeConsolidationSegments(input);
101
+ if (consolidationSegments && consolidationSegments.length > 0) {
102
+ return { type: "consolidation-needed", segmentIds: consolidationSegments };
103
+ }
104
+
105
+ const otherFetchingActionCount = countOtherFetchingActions(input);
106
+ if (otherFetchingActionCount > 0) {
107
+ return {
108
+ type: "concurrent-skip",
109
+ otherFetchingCount: otherFetchingActionCount,
110
+ };
111
+ }
96
112
 
97
- export type { ActionScenario };
113
+ return { type: "normal" };
114
+ }
@@ -268,6 +268,20 @@ function matchesActionId(
268
268
  return entryActionId.endsWith(`#${subscriptionId}`);
269
269
  }
270
270
 
271
+ // Coalesce rapid notifications into one microtask-deferred fan-out; the
272
+ // setTimeout(0) batching prevents render storms. Each notifier owns its timer
273
+ // so listener kinds coalesce independently.
274
+ function makeDebouncedNotifier(listeners: Set<() => void>): () => void {
275
+ let timeout: ReturnType<typeof setTimeout> | null = null;
276
+ return () => {
277
+ if (timeout !== null) clearTimeout(timeout);
278
+ timeout = setTimeout(() => {
279
+ timeout = null;
280
+ listeners.forEach((listener) => listener());
281
+ }, 0);
282
+ };
283
+ }
284
+
271
285
  // ============================================================================
272
286
  // Implementation
273
287
  // ============================================================================
@@ -334,18 +348,7 @@ export function createEventController(
334
348
  const actionListeners = new Map<string, Set<ActionStateListener>>();
335
349
  const handleListeners = new Set<HandleListener>();
336
350
 
337
- // Debounce state notifications to batch rapid updates
338
- let notifyTimeout: ReturnType<typeof setTimeout> | null = null;
339
-
340
- function notify() {
341
- if (notifyTimeout !== null) {
342
- clearTimeout(notifyTimeout);
343
- }
344
- notifyTimeout = setTimeout(() => {
345
- notifyTimeout = null;
346
- stateListeners.forEach((listener) => listener());
347
- }, 0);
348
- }
351
+ const notify = makeDebouncedNotifier(stateListeners);
349
352
 
350
353
  // Debounce per-action notifications
351
354
  const actionNotifyTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
@@ -371,18 +374,7 @@ export function createEventController(
371
374
  );
372
375
  }
373
376
 
374
- // Debounce handle notifications
375
- let handleNotifyTimeout: ReturnType<typeof setTimeout> | null = null;
376
-
377
- function notifyHandles() {
378
- if (handleNotifyTimeout !== null) {
379
- clearTimeout(handleNotifyTimeout);
380
- }
381
- handleNotifyTimeout = setTimeout(() => {
382
- handleNotifyTimeout = null;
383
- handleListeners.forEach((listener) => listener());
384
- }, 0);
385
- }
377
+ const notifyHandles = makeDebouncedNotifier(handleListeners);
386
378
 
387
379
  // ========================================================================
388
380
  // Derived State
@@ -429,22 +421,17 @@ export function createEventController(
429
421
  }
430
422
 
431
423
  function getActionState(actionId: string): TrackedActionState {
432
- // Find the most recent action with this ID that's not settling
433
- // Uses suffix matching when actionId is just a name (no #)
434
- const activeEntry = [...inflightActions.values()]
435
- .filter(
436
- (a) => matchesActionId(actionId, a.actionId) && a.phase !== "settling",
437
- )
438
- .sort((a, b) => b.startedAt - a.startedAt)[0];
439
-
440
- // Also check for settling entries to get result/error
441
- const settlingEntry = [...inflightActions.values()]
442
- .filter(
443
- (a) => matchesActionId(actionId, a.actionId) && a.phase === "settling",
444
- )
445
- .sort((a, b) => b.startedAt - a.startedAt)[0];
446
-
447
- const entry = activeEntry || settlingEntry;
424
+ // Prefer the most-recent non-settling entry; fall back to most-recent
425
+ // settling so a just-settled action's result/error stays readable.
426
+ const entry = [...inflightActions.values()]
427
+ .filter((a) => matchesActionId(actionId, a.actionId))
428
+ .reduce<ActionEntry | undefined>((best, a) => {
429
+ if (!best) return a;
430
+ const aActive = a.phase !== "settling";
431
+ const bActive = best.phase !== "settling";
432
+ if (aActive !== bActive) return aActive ? a : best;
433
+ return a.startedAt > best.startedAt ? a : best;
434
+ }, undefined);
448
435
 
449
436
  if (!entry) {
450
437
  return { ...DEFAULT_ACTION_STATE };
@@ -632,6 +619,19 @@ export function createEventController(
632
619
  doSettle();
633
620
  }
634
621
 
622
+ // streamingEnded is forced here for the "streaming never started" case so
623
+ // tryFinalize can run; otherwise the streaming token's end() finalizes.
624
+ function settleWith(result: NonNullable<typeof pendingResult>) {
625
+ if (!inflightActions.has(id) || settled) return;
626
+ actionCompleted = true;
627
+ entry.completed = true;
628
+ pendingResult = result;
629
+ if (entry.phase === "fetching" || streamingEnded) {
630
+ streamingEnded = true;
631
+ tryFinalize();
632
+ }
633
+ }
634
+
635
635
  return {
636
636
  id,
637
637
  abort,
@@ -668,35 +668,11 @@ export function createEventController(
668
668
  },
669
669
 
670
670
  complete(result?: unknown) {
671
- if (!inflightActions.has(id) || settled) return;
672
-
673
- actionCompleted = true;
674
- entry.completed = true;
675
- pendingResult = { type: "success", value: result };
676
-
677
- // If streaming never started or already ended, finalize immediately
678
- // Otherwise wait for streaming to end
679
- if (entry.phase === "fetching" || streamingEnded) {
680
- streamingEnded = true; // Mark as ended if never started
681
- tryFinalize();
682
- }
683
- // If streaming is in progress, tryFinalize() will be called when streaming ends
671
+ settleWith({ type: "success", value: result });
684
672
  },
685
673
 
686
674
  fail(error: unknown) {
687
- if (!inflightActions.has(id) || settled) return;
688
-
689
- actionCompleted = true;
690
- entry.completed = true;
691
- pendingResult = { type: "error", value: error };
692
-
693
- // If streaming never started or already ended, finalize immediately
694
- // Otherwise wait for streaming to end
695
- if (entry.phase === "fetching" || streamingEnded) {
696
- streamingEnded = true; // Mark as ended if never started
697
- tryFinalize();
698
- }
699
- // If streaming is in progress, tryFinalize() will be called when streaming ends
675
+ settleWith({ type: "error", value: error });
700
676
  },
701
677
 
702
678
  getRevalidatedSegments(): Set<string> {
@@ -707,6 +707,10 @@ export function createNavigationBridge(
707
707
  };
708
708
  },
709
709
 
710
+ getVersion(): string | undefined {
711
+ return version;
712
+ },
713
+
710
714
  updateVersion(newVersion: string): void {
711
715
  version = newVersion;
712
716
  setAppVersion(newVersion);
@@ -15,6 +15,7 @@ import { getRangoState } from "./rango-state.js";
15
15
  import {
16
16
  extractRscHeaderUrl,
17
17
  emptyResponse,
18
+ handleReloadHeader,
18
19
  teeWithCompletion,
19
20
  } from "./response-adapter.js";
20
21
  import {
@@ -148,21 +149,17 @@ export function createNavigationClient(
148
149
  source: string,
149
150
  ): Response | Promise<Response> => {
150
151
  // Version mismatch — server wants a full page reload
151
- const reload = extractRscHeaderUrl(response, "X-RSC-Reload");
152
- if (reload === "blocked") {
153
- resolveStreamComplete();
154
- return emptyResponse();
155
- }
156
- if (reload) {
157
- if (tx) {
158
- browserDebugLog(tx, `version mismatch, reloading (${source})`, {
159
- reloadUrl: reload.url,
160
- });
161
- }
162
- window.location.href = reload.url;
163
- // Block further processing — page is reloading
164
- return new Promise<Response>(() => {});
165
- }
152
+ const reloadResult = handleReloadHeader(response, {
153
+ onBlocked: resolveStreamComplete,
154
+ onReload: (url) => {
155
+ if (tx) {
156
+ browserDebugLog(tx, `version mismatch, reloading (${source})`, {
157
+ reloadUrl: url,
158
+ });
159
+ }
160
+ },
161
+ });
162
+ if (reloadResult) return reloadResult;
166
163
 
167
164
  // Server-side redirect without state: the server returned 204 with
168
165
  // X-RSC-Redirect instead of a 3xx (which fetch would auto-follow
@@ -283,18 +283,17 @@ export function createNavigationStore(
283
283
  /**
284
284
  * Create a debounced function that batches rapid calls
285
285
  */
286
+ // A non-keyed notifier is the keyed one restricted to a single constant key;
287
+ // its own keyed instance means the "" key never collides with action keys.
286
288
  function createDebouncedNotifier<T extends (...args: any[]) => void>(
287
289
  fn: T,
288
290
  ms: number = 20,
289
291
  ): T {
290
- let timeout: ReturnType<typeof setTimeout> | null = null;
291
- return ((...args: Parameters<T>) => {
292
- if (timeout !== null) clearTimeout(timeout);
293
- timeout = setTimeout(() => {
294
- timeout = null;
295
- fn(...args);
296
- }, ms);
297
- }) as T;
292
+ const keyed = createKeyedDebouncedNotifier(
293
+ (_key: string, ...args: any[]) => fn(...args),
294
+ ms,
295
+ );
296
+ return ((...args: Parameters<T>) => keyed("", ...args)) as T;
298
297
  }
299
298
 
300
299
  /**
@@ -236,30 +236,16 @@ export function createNavigationTransaction(
236
236
  segments: ResolvedSegment[],
237
237
  overrides?: BoundCommitOverrides,
238
238
  ) => {
239
- // Allow overrides to disable scroll (e.g., for intercepts)
240
- const finalScroll =
241
- overrides?.scroll !== undefined ? overrides.scroll : opts.scroll;
242
- // Allow overrides to force replace (e.g., for intercepts)
243
- const finalReplace =
244
- overrides?.replace !== undefined ? overrides.replace : opts.replace;
245
- // Intercept info: overrides take precedence, fallback to opts
246
- const intercept =
247
- overrides?.intercept !== undefined
248
- ? overrides.intercept
249
- : opts.intercept;
239
+ const finalScroll = overrides?.scroll ?? opts.scroll;
240
+ const finalReplace = overrides?.replace ?? opts.replace;
241
+ const intercept = overrides?.intercept ?? opts.intercept;
250
242
  const interceptSourceUrl =
251
- overrides?.interceptSourceUrl !== undefined
252
- ? overrides.interceptSourceUrl
253
- : opts.interceptSourceUrl;
254
- // Cache-only mode: overrides take precedence, fallback to opts
255
- const cacheOnly =
256
- overrides?.cacheOnly !== undefined
257
- ? overrides.cacheOnly
258
- : opts.cacheOnly;
259
- // User state: overrides take precedence, fallback to opts
243
+ overrides?.interceptSourceUrl ?? opts.interceptSourceUrl;
244
+ const cacheOnly = overrides?.cacheOnly ?? opts.cacheOnly;
245
+ // state is `unknown` (null is meaningful) so `??` would wrongly drop a
246
+ // null override; serverState always comes from overrides, never opts.
260
247
  const state =
261
248
  overrides?.state !== undefined ? overrides.state : opts.state;
262
- // Server-set location state: only from overrides (set by partial-update)
263
249
  const serverState = overrides?.serverState;
264
250
  return commit({
265
251
  ...opts,
@@ -103,7 +103,7 @@ export type UpdateMode =
103
103
  /** Source URL for intercept restore (popstate cache miss) */
104
104
  interceptSourceUrl?: string;
105
105
  }
106
- | { type: "leave-intercept" }
106
+ | { type: "leave-intercept"; interceptSourceUrl?: string }
107
107
  | { type: "stale-revalidation"; interceptSourceUrl?: string }
108
108
  | { type: "action"; interceptSourceUrl?: string };
109
109
 
@@ -169,13 +169,7 @@ export function createPartialUpdater(
169
169
  // Capture history key at start for stale revalidation consistency check
170
170
  const historyKeyAtStart = store.getHistoryKey();
171
171
 
172
- // Derive interceptSourceUrl from modes that carry it
173
- const interceptSourceUrl =
174
- mode.type === "stale-revalidation" ||
175
- mode.type === "action" ||
176
- mode.type === "navigate"
177
- ? mode.interceptSourceUrl
178
- : undefined;
172
+ const interceptSourceUrl = mode.interceptSourceUrl;
179
173
 
180
174
  // When leaving intercept, filter out intercept-specific segments
181
175
  let segments: string[];
@@ -218,13 +212,11 @@ export function createPartialUpdater(
218
212
  // When navigating with targetCacheSegments, use those for consistency.
219
213
  // Otherwise fall back to current page's segments (for same-route revalidation).
220
214
  const targetCache =
221
- mode.type === "navigate" ? mode.targetCacheSegments : undefined;
222
- const cachedSegs =
223
- targetCache && targetCache.length > 0
224
- ? targetCache
225
- : getCurrentCachedSegments();
226
- const cachedSegsSource =
227
- targetCache && targetCache.length > 0 ? "history-cache" : "current-page";
215
+ mode.type === "navigate" && mode.targetCacheSegments?.length
216
+ ? mode.targetCacheSegments
217
+ : undefined;
218
+ const cachedSegs = targetCache ?? getCurrentCachedSegments();
219
+ const cachedSegsSource = targetCache ? "history-cache" : "current-page";
228
220
  debugLog(
229
221
  `[Browser] cachedSegs source: ${cachedSegsSource} (${cachedSegs.length} segments: ${cachedSegs.map((s) => s.id).join(", ")})`,
230
222
  );
@@ -318,7 +310,7 @@ export function createPartialUpdater(
318
310
  .filter(Boolean) as ResolvedSegment[];
319
311
 
320
312
  // When navigating with cached segments to a different route, render them.
321
- if (mode.type === "navigate" && targetCache && targetCache.length > 0) {
313
+ if (mode.type === "navigate" && targetCache) {
322
314
  debugLog(
323
315
  "[Browser] No diff but navigating with cached segments - rendering target route",
324
316
  );
@@ -28,7 +28,7 @@ import { NonceContext } from "./nonce-context.js";
28
28
  import type { ResolvedThemeConfig, Theme } from "../../theme/types.js";
29
29
  import { cancelAllPrefetches } from "../prefetch/queue.js";
30
30
  import { handleNavigationEnd } from "../scroll-restoration.js";
31
- import type { AppShellRef } from "../app-shell.js";
31
+ import { createAppShellRef, type AppShellRef } from "../app-shell.js";
32
32
 
33
33
  /**
34
34
  * Process handles from an async generator, updating the event controller
@@ -217,38 +217,33 @@ export function NavigationProvider({
217
217
  await bridge.refresh();
218
218
  }, []);
219
219
 
220
- // Context value is stable (store, eventController, navigate, refresh never
221
- // change). When an appShellRef is supplied, `basename` and `version` are
222
- // installed as live getters so app-switch transitions (which update the ref)
223
- // propagate to consumers without forcing a tree-wide rerender.
220
+ // basename/version are always read through a shell ref so the context value
221
+ // has a single shape: a supplied appShellRef stays live (app-switch updates
222
+ // it), the standalone fallback is a frozen ref over the mount-time props.
223
+ const fallbackShellRef = useRef<AppShellRef | null>(null);
224
+ if (!fallbackShellRef.current) {
225
+ fallbackShellRef.current = createAppShellRef({ basename, version });
226
+ }
227
+ const shellRef = appShellRef ?? fallbackShellRef.current;
228
+
224
229
  const contextValue = useMemo<NavigationStoreContextValue>(() => {
225
- if (appShellRef) {
226
- const value = {
227
- store,
228
- eventController,
229
- navigate,
230
- refresh,
231
- } as NavigationStoreContextValue;
232
- Object.defineProperty(value, "basename", {
233
- configurable: true,
234
- enumerable: true,
235
- get: () => appShellRef.get().basename,
236
- });
237
- Object.defineProperty(value, "version", {
238
- configurable: true,
239
- enumerable: true,
240
- get: () => appShellRef.get().version,
241
- });
242
- return value;
243
- }
244
- return {
230
+ const value = {
245
231
  store,
246
232
  eventController,
247
233
  navigate,
248
234
  refresh,
249
- version,
250
- basename,
251
- };
235
+ } as NavigationStoreContextValue;
236
+ Object.defineProperty(value, "basename", {
237
+ configurable: true,
238
+ enumerable: true,
239
+ get: () => shellRef.get().basename,
240
+ });
241
+ Object.defineProperty(value, "version", {
242
+ configurable: true,
243
+ enumerable: true,
244
+ get: () => shellRef.get().version,
245
+ });
246
+ return value;
252
247
  }, []);
253
248
 
254
249
  // Connection warmup: keep TLS alive after idle periods.
@@ -410,21 +405,15 @@ export function NavigationProvider({
410
405
  }).catch((err) =>
411
406
  console.error("[NavigationProvider] Error consuming handles:", err),
412
407
  );
413
- } else if (update.metadata.cachedHandleData) {
414
- // For back/forward navigation from cache, restore the cached handleData
415
- // This restores breadcrumbs to the exact state they were when the page was cached
416
- eventController.setHandleData(
417
- update.metadata.cachedHandleData,
418
- update.metadata.matched,
419
- false, // full replace - restore entire cached state
420
- );
421
408
  } else if (update.metadata.matched) {
422
- // For cached navigations without handleData, update segmentOrder to clean up stale data
409
+ // cachedHandleData present -> full restore (back/forward); absent ->
410
+ // partial cleanup of segments no longer matched.
411
+ const cached = update.metadata.cachedHandleData;
423
412
  eventController.setHandleData(
424
- {}, // Empty data - all existing data not in matched will be cleaned up
413
+ cached ?? {},
425
414
  update.metadata.matched,
426
- true, // partial update - will clean up segments not in matched
427
- update.metadata.resolvedIds,
415
+ cached === undefined,
416
+ cached === undefined ? update.metadata.resolvedIds : undefined,
428
417
  );
429
418
  }
430
419
  });