@rangojs/router 0.0.0-experimental.111 → 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 (49) hide show
  1. package/dist/bin/rango.js +41 -37
  2. package/dist/vite/index.js +144 -191
  3. package/package.json +3 -1
  4. package/src/browser/action-coordinator.ts +53 -36
  5. package/src/browser/event-controller.ts +42 -66
  6. package/src/browser/navigation-bridge.ts +4 -0
  7. package/src/browser/navigation-client.ts +12 -15
  8. package/src/browser/navigation-store.ts +7 -8
  9. package/src/browser/navigation-transaction.ts +7 -21
  10. package/src/browser/partial-update.ts +8 -16
  11. package/src/browser/react/NavigationProvider.tsx +29 -40
  12. package/src/browser/react/use-params.ts +3 -4
  13. package/src/browser/response-adapter.ts +25 -0
  14. package/src/browser/rsc-router.tsx +16 -2
  15. package/src/browser/server-action-bridge.ts +23 -30
  16. package/src/browser/types.ts +2 -0
  17. package/src/build/generate-manifest.ts +29 -31
  18. package/src/build/generate-route-types.ts +2 -0
  19. package/src/build/route-types/router-processing.ts +37 -9
  20. package/src/build/runtime-discovery.ts +9 -20
  21. package/src/decode-loader-results.ts +36 -0
  22. package/src/errors.ts +11 -0
  23. package/src/response-utils.ts +9 -0
  24. package/src/route-content-wrapper.tsx +6 -28
  25. package/src/router/content-negotiation.ts +15 -2
  26. package/src/router/intercept-resolution.ts +4 -18
  27. package/src/router/match-result.ts +32 -30
  28. package/src/router/middleware.ts +46 -78
  29. package/src/router/preview-match.ts +3 -1
  30. package/src/router/request-classification.ts +4 -28
  31. package/src/rsc/handler.ts +20 -65
  32. package/src/rsc/helpers.ts +3 -2
  33. package/src/rsc/origin-guard.ts +28 -10
  34. package/src/rsc/response-route-handler.ts +32 -52
  35. package/src/rsc/rsc-rendering.ts +27 -53
  36. package/src/rsc/runtime-warnings.ts +9 -10
  37. package/src/rsc/server-action.ts +13 -37
  38. package/src/rsc/ssr-setup.ts +16 -0
  39. package/src/segment-system.tsx +5 -39
  40. package/src/vite/discovery/discover-routers.ts +10 -22
  41. package/src/vite/discovery/route-types-writer.ts +38 -82
  42. package/src/vite/plugins/cjs-to-esm.ts +3 -7
  43. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  44. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  45. package/src/vite/plugins/expose-internal-ids.ts +34 -62
  46. package/src/vite/plugins/version-injector.ts +2 -12
  47. package/src/vite/router-discovery.ts +71 -26
  48. package/src/vite/utils/shared-utils.ts +13 -1
  49. package/src/browser/action-response-classifier.ts +0 -99
@@ -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
  });
@@ -4,6 +4,8 @@ import { useContext, useState, useEffect, useRef } from "react";
4
4
  import { NavigationStoreContext } from "./context.js";
5
5
  import { shallowEqual } from "./shallow-equal.js";
6
6
 
7
+ const EMPTY_PARAMS: Record<string, string> = Object.freeze({});
8
+
7
9
  /**
8
10
  * Hook to access the current route params.
9
11
  *
@@ -43,10 +45,7 @@ export function useParams<T>(
43
45
  const ctx = useContext(NavigationStoreContext);
44
46
 
45
47
  const [value, setValue] = useState<T | Record<string, string>>(() => {
46
- if (!ctx) {
47
- return selector ? selector({}) : {};
48
- }
49
- const params = ctx.eventController.getParams();
48
+ const params = ctx ? ctx.eventController.getParams() : EMPTY_PARAMS;
50
49
  return selector ? selector(params) : params;
51
50
  });
52
51
 
@@ -24,6 +24,31 @@ export function emptyResponse(): Response {
24
24
  return new Response(null, { status: 200 });
25
25
  }
26
26
 
27
+ /**
28
+ * Handle the X-RSC-Reload control header (server requests a full page reload on
29
+ * a version mismatch). Returns a short-circuit response when the header is
30
+ * present -- emptyResponse() if the URL was blocked by origin validation, or a
31
+ * never-resolving promise while the page reloads -- and null when absent, so
32
+ * the caller continues processing (e.g. the X-RSC-Redirect check). Scoped to
33
+ * X-RSC-Reload only; redirect handling differs between callers.
34
+ */
35
+ export function handleReloadHeader(
36
+ response: Response,
37
+ opts: { onBlocked: () => void; onReload: (url: string) => void },
38
+ ): Response | Promise<Response> | null {
39
+ const reload = extractRscHeaderUrl(response, "X-RSC-Reload");
40
+ if (reload === "blocked") {
41
+ opts.onBlocked();
42
+ return emptyResponse();
43
+ }
44
+ if (reload) {
45
+ opts.onReload(reload.url);
46
+ window.location.href = reload.url;
47
+ return new Promise<Response>(() => {});
48
+ }
49
+ return null;
50
+ }
51
+
27
52
  /**
28
53
  * Tee a response body for RSC parsing and stream completion tracking.
29
54
  * Returns a new Response with one branch; the other is consumed to detect
@@ -364,11 +364,18 @@ export async function initBrowserApp(
364
364
  // Update version BEFORE rebuilding state so that
365
365
  // clearHistoryCache() runs first, then the fresh segment
366
366
  // cache entry we create below survives.
367
+ //
368
+ // Compare against the bridge's live version, not the init-time
369
+ // `version` const: after the first HMR bump the const is stale, so a
370
+ // later update with an unchanged version would otherwise re-clear the
371
+ // cache and re-broadcast across tabs/apps. The live read fires only
372
+ // on a genuine version change.
367
373
  const newVersion = payload.metadata.version;
368
- if (newVersion && newVersion !== version) {
374
+ const currentVersion = navigationBridge.getVersion();
375
+ if (newVersion && newVersion !== currentVersion) {
369
376
  console.log(
370
377
  "[Rango] HMR: version changed",
371
- version,
378
+ currentVersion,
372
379
  "→",
373
380
  newVersion,
374
381
  "clearing caches",
@@ -376,6 +383,13 @@ export async function initBrowserApp(
376
383
  navigationBridge.updateVersion(newVersion);
377
384
  }
378
385
 
386
+ // Apply only partial segment updates. A non-partial payload during
387
+ // HMR is transient: the worker route table is still rebuilding after
388
+ // the edit, so the URL momentarily resolves to not-found/catch-all.
389
+ // Skip it -- the debounced follow-up refetch returns the settled
390
+ // route's partial payload and renders it below. We never reload here:
391
+ // a paramless document GET would run the SSR path and surface the
392
+ // not-found page during that same transient.
379
393
  if (payload.metadata?.isPartial) {
380
394
  const segments = payload.metadata.segments || [];
381
395
  const matched = payload.metadata.matched || [];