@rangojs/router 0.36.1 → 0.37.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.
Files changed (69) hide show
  1. package/dist/bin/{chunk-THW7E5A2.js → chunk-A64EG6MI.js} +22 -19
  2. package/dist/bin/{client-urls-projection-DHUUOJZM.js → client-urls-projection-RLDSA3BL.js} +1 -1
  3. package/dist/bin/rango.js +1 -1
  4. package/dist/bin/{runtime-discovery-OPRGB3DF.js → runtime-discovery-T7ZLA6E3.js} +2 -2
  5. package/dist/bin/{temp-rsc-server-FV4ERMAS.js → temp-rsc-server-FGGXPKVQ.js} +2 -2
  6. package/dist/types/browser/event-controller.d.ts +53 -2
  7. package/dist/types/browser/fetched-loader-handles.d.ts +57 -14
  8. package/dist/types/browser/navigation-store.d.ts +3 -2
  9. package/dist/types/browser/react/use-handle.d.ts +18 -5
  10. package/dist/types/browser/react/use-push-handle.d.ts +44 -0
  11. package/dist/types/browser/types.d.ts +44 -0
  12. package/dist/types/client.d.ts +1 -0
  13. package/dist/types/client.rsc.d.ts +1 -0
  14. package/dist/types/handle.d.ts +13 -5
  15. package/dist/types/handles/client-pushes.d.ts +51 -0
  16. package/dist/types/handles/deferred-resolution.d.ts +7 -0
  17. package/dist/types/handles/pushed-by.d.ts +11 -0
  18. package/dist/types/loader-store.d.ts +13 -0
  19. package/dist/types/rsc/prefetch-render-error.d.ts +2 -1
  20. package/dist/types/server/handle-store.d.ts +8 -0
  21. package/dist/types/testing/dom.entry.d.ts +1 -1
  22. package/dist/types/testing/render-route.d.ts +74 -14
  23. package/dist/vite/index.js +23 -20
  24. package/package.json +1 -1
  25. package/skills/breadcrumbs/SKILL.md +68 -6
  26. package/skills/caching/SKILL.md +4 -2
  27. package/skills/catalog.json +3 -3
  28. package/skills/client-urls/SKILL.md +13 -1
  29. package/skills/document-cache/SKILL.md +31 -1
  30. package/skills/hooks/SKILL.md +8 -4
  31. package/skills/hooks/data.md +10 -1
  32. package/skills/hooks/handle-and-actions.md +402 -26
  33. package/skills/hooks/navigation.md +4 -0
  34. package/skills/hooks/urls.md +3 -0
  35. package/skills/links/SKILL.md +5 -3
  36. package/skills/loader/SKILL.md +28 -9
  37. package/skills/migrate-nextjs/SKILL.md +5 -0
  38. package/skills/migrate-react-router/component-migration.md +4 -1
  39. package/skills/parallel/SKILL.md +8 -0
  40. package/skills/ppr/SKILL.md +1 -0
  41. package/skills/rango/SKILL.md +6 -3
  42. package/skills/testing/client-components.md +35 -32
  43. package/skills/testing/handles.md +58 -6
  44. package/skills/ux-architecture/SKILL.md +4 -0
  45. package/src/browser/event-controller.ts +265 -4
  46. package/src/browser/fetched-loader-handles.ts +227 -54
  47. package/src/browser/navigation-store.ts +261 -2
  48. package/src/browser/partial-update.ts +3 -2
  49. package/src/browser/react/use-handle.ts +74 -27
  50. package/src/browser/react/use-push-handle.ts +113 -0
  51. package/src/browser/rsc-router.tsx +11 -14
  52. package/src/browser/types.ts +48 -0
  53. package/src/cache/document-cache-policy.ts +6 -5
  54. package/src/client.rsc.tsx +1 -0
  55. package/src/client.tsx +31 -1
  56. package/src/handle.ts +13 -5
  57. package/src/handles/client-pushes.ts +120 -0
  58. package/src/handles/deferred-resolution.ts +12 -0
  59. package/src/handles/pushed-by.ts +55 -1
  60. package/src/loader-store.ts +26 -0
  61. package/src/rsc/loader-fetch.ts +17 -0
  62. package/src/rsc/prefetch-render-error.ts +2 -1
  63. package/src/rsc/request-stages.ts +7 -6
  64. package/src/rsc/rsc-rendering.ts +32 -14
  65. package/src/server/handle-store.ts +23 -0
  66. package/src/ssr/ssr-root.tsx +5 -0
  67. package/src/testing/dom.entry.ts +2 -0
  68. package/src/testing/render-route.tsx +317 -72
  69. package/src/use-loader.tsx +16 -5
@@ -97,8 +97,11 @@ import { renderSegments } from "../segment-system.js";
97
97
  import {
98
98
  createNavigationStore,
99
99
  generateHistoryKey,
100
+ liveHandleDataForCache,
100
101
  } from "../browser/navigation-store.js";
101
102
  import { createEventController } from "../browser/event-controller.js";
103
+ import { applyLateHandles } from "../browser/fetched-loader-handles.js";
104
+ import { pushedByKey } from "../handles/pushed-by.js";
102
105
  import { resolveDeferredHandleValues } from "../handles/deferred-resolution.js";
103
106
  import {
104
107
  commitInTransition,
@@ -173,6 +176,19 @@ let pendingPrefetchReset: object | undefined;
173
176
  */
174
177
  export type HandleDataSeed = Record<string, Record<string, unknown[]>>;
175
178
 
179
+ /**
180
+ * Where a handle seed lands: the index of a spec in `routes` (its layout or
181
+ * route segment), or `[index, "@slot"]` for a slot that spec declares
182
+ * (`RenderRouteSpec.slots`). Omitted: the leaf route.
183
+ */
184
+ export type HandleSegment = number | readonly [number, `@${string}`];
185
+
186
+ /**
187
+ * `[handle, values, segment?]`: the values the server pushed for `handle` in
188
+ * one segment (the leaf route when `segment` is omitted).
189
+ */
190
+ export type HandleSeed = readonly [Handle<any, any>, unknown[], HandleSegment?];
191
+
176
192
  const syntheticIds = new WeakMap<object, string>();
177
193
  let syntheticIdCounter = 0;
178
194
 
@@ -229,6 +245,20 @@ export interface RenderRouteSpec {
229
245
  * `router.navigate(url, { loaders })` pins `useLoader().isLoading`.
230
246
  */
231
247
  transition?: TransitionConfig;
248
+ /**
249
+ * Parallel slots this node declares (`parallel({ "@side": Side })`), each
250
+ * rendered where the node's component places `<ParallelOutlet name>`. A
251
+ * slot given as `{ Component, intercept: true }` is an intercept's: it
252
+ * renders through the same slot outlet, as an intercepting navigation's
253
+ * does. Each is a segment of its own (`L0.@side`), so a handle seed or a
254
+ * client push can land in it.
255
+ */
256
+ slots?: Readonly<
257
+ Record<
258
+ `@${string}`,
259
+ ComponentType | { Component: ComponentType; intercept: true }
260
+ >
261
+ >;
232
262
  }
233
263
 
234
264
  /**
@@ -328,14 +358,15 @@ export interface RenderRouteOptions {
328
358
  /**
329
359
  * Handles to seed by REFERENCE, for components that read handle output via
330
360
  * `useHandle(SomeHandle)` (e.g. a client `Breadcrumbs` trail). Each entry is
331
- * `[handle, pushedValues[]]` — the values a route's handlers would have pushed;
332
- * renderRoute attaches them to the leaf route segment under the handle's id.
361
+ * `[handle, pushedValues[], segment?]` — the values a segment's handlers would
362
+ * have pushed, attached to the segment `segment` names (a spec's index in
363
+ * `routes`, or `[index, "@slot"]`), the leaf route when omitted.
333
364
  * Built-in handles (Breadcrumbs/Meta) have stable ids and work directly.
334
365
  *
335
- * Handle data is accumulated GLOBALLY on the event controller, not scoped per
336
- * segment like loaders — so ANY component in the chain reads the seeded values,
337
- * a LAYOUT (e.g. a DetailLayout/ActionToolbar reading a handle) just as much as
338
- * the leaf route. Most handle usage is server-side (`ctx.use(...)`) and is
366
+ * A handle's values are collected over every segment, in segment order — so
367
+ * ANY component in the chain reads the seeded values, a LAYOUT (e.g. a
368
+ * DetailLayout/ActionToolbar reading a handle) just as much as the leaf
369
+ * route. Most handle usage is server-side (`ctx.use(...)`) and is
339
370
  * better covered by `renderToFlightString`/e2e; this seeds the client read path
340
371
  * only.
341
372
  *
@@ -344,7 +375,7 @@ export interface RenderRouteOptions {
344
375
  * handles: [[Breadcrumbs, [{ label: "Home", href: "/" }, { label: "P", href: "/p" }]]],
345
376
  * });
346
377
  */
347
- handles?: ReadonlyArray<readonly [Handle<any, any>, unknown[]]>;
378
+ handles?: ReadonlyArray<HandleSeed>;
348
379
  /**
349
380
  * Advanced: raw handle data in wire format
350
381
  * `{ [handleId]: { [segmentId]: pushedValues[] } }`. Prefer `handles` (which
@@ -368,7 +399,7 @@ export interface RenderRouteOptions {
368
399
  * lateHandles: [[Notes, ["from-handler", "from-loader"]]],
369
400
  * });
370
401
  */
371
- lateHandles?: ReadonlyArray<readonly [Handle<any, any>, unknown[]]>;
402
+ lateHandles?: ReadonlyArray<HandleSeed>;
372
403
  /**
373
404
  * Route name -> pattern map. Informational for parity with the server test
374
405
  * context; client useReverse takes its map directly as an argument, so this
@@ -504,8 +535,7 @@ export interface TestRouterHandle {
504
535
  * `navigate(url, { replace: false })` are the same call.
505
536
  *
506
537
  * `options.handles` are the destination's handle pushes (`[handle,
507
- * values]`, attached to its leaf route as in `renderRoute`'s own
508
- * `handles`). They arrive on the response's handle stream, so `useHandle`
538
+ * values, segment?]`, as in `renderRoute`'s own `handles`). They arrive on the response's handle stream, so `useHandle`
509
539
  * readers take them with the page's commit: while React holds the page,
510
540
  * readers keep the values of the page being left.
511
541
  *
@@ -547,9 +577,12 @@ export interface TestRouterHandle {
547
577
  * Re-render the current location, as router.refresh() does: a spec's
548
578
  * transition({ when }) decides it with kind "revalidate" (`to` is `from`).
549
579
  * `options.loaders` is the loader data the response carries, merged over
550
- * the render-time seeds as in navigate().
580
+ * the render-time seeds as in navigate(). `options.handles` are the handle
581
+ * values the response carries, on its handle stream, as in navigate().
551
582
  */
552
- refresh(options?: Pick<RenderRouteOptions, "loaders">): Promise<void>;
583
+ refresh(
584
+ options?: Pick<RenderRouteOptions, "loaders" | "handles">,
585
+ ): Promise<void>;
553
586
  /**
554
587
  * Prefetch `url`, as a `<Link>` hover or viewport trigger does: the page is
555
588
  * kept with the loader data its response would carry now (the render-time
@@ -587,21 +620,60 @@ export interface TestRouterHandle {
587
620
  * redirect are e2e territory.
588
621
  */
589
622
  action(
590
- options?: Pick<RenderRouteOptions, "loaders"> & {
623
+ options?: Pick<RenderRouteOptions, "loaders" | "handles"> & {
591
624
  keepClientCache?: boolean;
592
625
  },
593
626
  ): Promise<void>;
627
+ /**
628
+ * A server push that arrives after the page committed (a settled
629
+ * `push(promise)` or `.defer()`, a streamed loader's push, a `ppr`
630
+ * live-lane push): each `[handle, values, segment?]` replaces that handle's
631
+ * server values in that segment, through production's late handle channel
632
+ * (`applyLateHandles`: the controller's late write, then the page's history
633
+ * entry). The other segments' server values stay. `pushedBy`: the loader
634
+ * whose run pushed the values (a streamed loader body's push, tagged as the
635
+ * server tags it), so a seed replaces only that run's values in the
636
+ * segment; omitted, the segment's handler pushed them. A loader whose data
637
+ * a `load()` refreshed since keeps the page's values: the read is newer.
638
+ *
639
+ * @example
640
+ * await router.pushLateHandles([[Meta, [{ title: "Late" }], 0]]);
641
+ * await router.pushLateHandles([[Meta, [{ title: "Item" }]]], {
642
+ * pushedBy: ItemLoader,
643
+ * });
644
+ */
645
+ pushLateHandles(
646
+ handles: ReadonlyArray<HandleSeed>,
647
+ options?: { pushedBy?: LoaderDefinition<any> },
648
+ ): Promise<void>;
649
+ /**
650
+ * What `useHandle(handle)` collects over, per segment id: the server's
651
+ * values followed by the client's pushes (`usePushHandle`), as readers
652
+ * merge them. Only segments with values are listed.
653
+ */
654
+ handleData(handle: Handle<any, any>): Record<string, unknown[]>;
655
+ /** The segment id a `HandleSegment` names on the page on screen. */
656
+ segmentId(segment?: HandleSegment): string;
594
657
  /**
595
658
  * Set what the loader endpoint answers from now on: a later
596
659
  * `useLoader().load()` or refreshGroup refresh of each loader resolves to
597
660
  * its value (a pending Promise holds the answer, a rejection is the
598
661
  * loader's error). Renders nothing; the page on screen keeps its data.
599
662
  *
663
+ * `handles`: what the body of each loader in `loaders` pushes on such a
664
+ * read (`[handle, values]`). The reply carries them as rsc/loader-fetch.ts
665
+ * does, and the browser applies them to the loader's segment as it does a
666
+ * real read's (browser/fetched-loader-handles.ts).
667
+ *
600
668
  * @example
601
669
  * router.respondToLoads({ loaders: [[CartLoader, { count: 3 }]] });
602
670
  * fireEvent.click(getByText("Refresh")); // load(): count 3
603
671
  */
604
- respondToLoads(options: Pick<RenderRouteOptions, "loaders">): void;
672
+ respondToLoads(
673
+ options: Pick<RenderRouteOptions, "loaders"> & {
674
+ handles?: ReadonlyArray<readonly [Handle<any, any>, unknown[]]>;
675
+ },
676
+ ): void;
605
677
  /**
606
678
  * The background revalidations a click on a stale prefetch started, in
607
679
  * order: the page's pathname and search, and the segment ids the request
@@ -796,6 +868,41 @@ function staticPrefix(pattern: string): string {
796
868
  return "/" + out.join("/");
797
869
  }
798
870
 
871
+ /**
872
+ * The id of the segment `at` names among `segments` (a HandleSegment), the
873
+ * leaf route when omitted.
874
+ */
875
+ function segmentIdIn(segments: ResolvedSegment[], at?: HandleSegment): string {
876
+ if (at === undefined) {
877
+ const leafId =
878
+ [...segments].reverse().find((s) => s.type === "route")?.id ??
879
+ segments[segments.length - 1]?.id;
880
+ if (leafId === undefined) throw new Error("renderRoute: no segments");
881
+ return leafId;
882
+ }
883
+ const [index, slot] = typeof at === "number" ? [at, undefined] : at;
884
+ const owner = segments.filter(
885
+ (s) => s.type === "layout" || s.type === "route",
886
+ )[index]?.id;
887
+ if (owner === undefined) {
888
+ throw new Error(`renderRoute: no route spec at index ${index}`);
889
+ }
890
+ return slot === undefined ? owner : `${owner}.${slot}`;
891
+ }
892
+
893
+ /** Writes each `[handle, values, segment?]` into `seed`. */
894
+ function seedHandles(
895
+ seed: HandleDataSeed,
896
+ handles: ReadonlyArray<HandleSeed> | undefined,
897
+ segments: ResolvedSegment[],
898
+ ): HandleDataSeed {
899
+ for (const [handle, values, at] of handles ?? []) {
900
+ const id = (handle as unknown as { $$id: string }).$$id;
901
+ (seed[id] ??= {})[segmentIdIn(segments, at)] = values;
902
+ }
903
+ return seed;
904
+ }
905
+
799
906
  function buildSegments(
800
907
  routes: RenderRouteSpec[],
801
908
  params: Record<string, string>,
@@ -836,6 +943,23 @@ function buildSegments(
836
943
  }
837
944
  segments.push(node);
838
945
 
946
+ for (const [slot, def] of Object.entries(spec.slots ?? {}) as [
947
+ `@${string}`,
948
+ NonNullable<RenderRouteSpec["slots"]>[`@${string}`],
949
+ ][]) {
950
+ const intercept = "intercept" in def;
951
+ const SlotComponent = intercept ? def.Component : def;
952
+ segments.push({
953
+ id: `${segmentId}.${slot}`,
954
+ namespace: intercept ? `intercept:${spec.name ?? spec.path}` : "",
955
+ type: "parallel",
956
+ index: i,
957
+ slot,
958
+ component: <SlotComponent />,
959
+ params,
960
+ });
961
+ }
962
+
839
963
  const ownedIds = spec.loaderIds
840
964
  ? spec.loaderIds.filter((id) => id in loaderData)
841
965
  : isLeaf
@@ -903,6 +1027,8 @@ export async function renderRoute(
903
1027
  // What the loader endpoint answers (LoaderEndpoint): the render seeds, then
904
1028
  // what respondToLoads() gave each loader.
905
1029
  const loadAnswers: Record<string, unknown> = { ...loaderData };
1030
+ // The handle values each loader's body pushes on a read (respondToLoads).
1031
+ const loadPushes: Record<string, Record<string, unknown[]>> = {};
906
1032
  // The payload has rsc/loader-fetch.ts's shape; the value is taken when the
907
1033
  // request is made, as a server reads its data then.
908
1034
  const answerLoad = async (
@@ -927,7 +1053,17 @@ export async function renderRoute(
927
1053
  );
928
1054
  } else {
929
1055
  try {
930
- payload = { loaderResult: await loadAnswers[loaderId] };
1056
+ const handles = loadPushes[loaderId] ?? {};
1057
+ payload = {
1058
+ loaderResult: await loadAnswers[loaderId],
1059
+ handles,
1060
+ pushedBy: Object.fromEntries(
1061
+ Object.entries(handles).map(([id, values]) => [
1062
+ id,
1063
+ values.map(() => null),
1064
+ ]),
1065
+ ),
1066
+ } as Answer;
931
1067
  } catch (error) {
932
1068
  payload = failure(
933
1069
  error instanceof Error ? error.name : "Error",
@@ -1009,15 +1145,11 @@ export async function renderRoute(
1009
1145
  initialSegments,
1010
1146
  crossTabSync: false,
1011
1147
  });
1012
- const leafRouteSegmentId =
1013
- [...initialSegments].reverse().find((s) => s.type === "route")?.id ??
1014
- initialSegments[initialSegments.length - 1]?.id;
1015
- const handleSeed: HandleDataSeed = cloneHandleSeed(options.handle);
1016
- for (const [handle, values] of options.handles ?? []) {
1017
- if (leafRouteSegmentId === undefined) continue;
1018
- const id = (handle as unknown as { $$id: string }).$$id;
1019
- (handleSeed[id] ??= {})[leafRouteSegmentId] = values;
1020
- }
1148
+ const handleSeed = seedHandles(
1149
+ cloneHandleSeed(options.handle),
1150
+ options.handles,
1151
+ initialSegments,
1152
+ );
1021
1153
 
1022
1154
  const eventController = createEventController({ initialLocation: url });
1023
1155
  eventController.setParams(initialMatch.params);
@@ -1029,6 +1161,8 @@ export async function renderRoute(
1029
1161
  const resolvedSeed = await resolveDeferredHandleValues(handleSeed);
1030
1162
  const initialSegmentIds = initialSegments.map((s) => s.id);
1031
1163
  eventController.setHandleData(resolvedSeed, initialSegmentIds);
1164
+ // As initBrowserApp: the document's entry keeps its handle data.
1165
+ store.updateCacheHandleData(historyKey, resolvedSeed);
1032
1166
  // As initBrowserApp before hydrateRoot: until the provider's barrier commit,
1033
1167
  // handle reads return this state and later writes wait.
1034
1168
  if (options.hydrate) eventController.lockHydration();
@@ -1040,18 +1174,25 @@ export async function renderRoute(
1040
1174
  : undefined;
1041
1175
  // A late update carries the full state: the seed with these handles' values
1042
1176
  // replaced, resolved as the browser resolves a late yield before applying.
1043
- let applyLateHandles: (() => void) | undefined;
1044
- if (options.lateHandles && leafRouteSegmentId !== undefined) {
1045
- const lateSeed = cloneHandleSeed(resolvedSeed);
1046
- for (const [handle, values] of options.lateHandles) {
1047
- const id = (handle as unknown as { $$id: string }).$$id;
1048
- (lateSeed[id] ??= {})[leafRouteSegmentId] = values;
1049
- }
1050
- const lateState = await resolveDeferredHandleValues(lateSeed);
1177
+ let applyDocumentLate: (() => void) | undefined;
1178
+ if (options.lateHandles) {
1179
+ const lateState = await resolveDeferredHandleValues(
1180
+ seedHandles(
1181
+ cloneHandleSeed(resolvedSeed),
1182
+ options.lateHandles,
1183
+ initialSegments,
1184
+ ),
1185
+ );
1051
1186
  // Flushed, not left to the notify timer: renderRoute's act() has
1052
1187
  // returned by then.
1053
- applyLateHandles = () => {
1054
- eventController.setHandleData(lateState, initialSegmentIds);
1188
+ applyDocumentLate = () => {
1189
+ // Production's late channel (browser/rsc-router.tsx).
1190
+ applyLateHandles(
1191
+ { store, eventController },
1192
+ lateState,
1193
+ initialSegmentIds,
1194
+ historyKey,
1195
+ );
1055
1196
  eventController.flushRouteState();
1056
1197
  };
1057
1198
  }
@@ -1070,17 +1211,18 @@ export async function renderRoute(
1070
1211
  };
1071
1212
 
1072
1213
  // The page each history entry shows, by the entry's `idx` stamp (the
1073
- // seeded entry has none: 0), so a back/forward can restore it as
1074
- // production restores a history-cache entry. `state` is the entry's
1075
- // history state as the router last wrote it: an entry the test wrote over
1076
- // it (no `idx` reads as 0) is not that page. `handleData` is the page's
1077
- // pushes, taken when it is left.
1214
+ // seeded entry has none: 0), so a back/forward can restore it. `state` is
1215
+ // the entry's history state as the router last wrote it: an entry the test
1216
+ // wrote over it (no `idx` reads as 0) is not that page. What a restore
1217
+ // renders, its segments and handle data, comes from the store's history
1218
+ // cache under the entry's URL key, as production restores it
1219
+ // (navigation-bridge.ts handlePopstate); `segments` stands in when the
1220
+ // cache no longer holds the key.
1078
1221
  interface EntryPage {
1079
1222
  url: URL;
1080
1223
  segments: ResolvedSegment[];
1081
1224
  params: Record<string, string>;
1082
1225
  state: unknown;
1083
- handleData?: HandleData;
1084
1226
  }
1085
1227
  const entries = new Map<number, EntryPage>();
1086
1228
  const entryIndex = (): number => {
@@ -1106,10 +1248,9 @@ export async function renderRoute(
1106
1248
  /**
1107
1249
  * The history-cache reads production's stale-prefetch guards make
1108
1250
  * (navigation-bridge.ts scheduleStalePrefetchRevalidation), over this
1109
- * harness's history: the store's own history key never moves here, so the
1110
- * key on screen is its location's, and the one cached page is the entry on
1111
- * screen. Marking it stale writes nothing: a stale entry's revalidation on
1112
- * Back is not modeled.
1251
+ * harness's history: the key on screen is its location's, and the one
1252
+ * cached page is the entry on screen. Marking it stale writes nothing: a
1253
+ * stale entry's revalidation on Back is not modeled.
1113
1254
  */
1114
1255
  const historyView: Pick<
1115
1256
  NavigationStore,
@@ -1122,15 +1263,45 @@ export async function renderRoute(
1122
1263
  return {
1123
1264
  segments: page.segments,
1124
1265
  stale: false,
1125
- handleData: page.handleData,
1266
+ handleData: store.getCachedSegments(key)?.handleData,
1126
1267
  };
1127
1268
  },
1128
1269
  updateCacheHandleData: () => {},
1129
1270
  };
1130
- /** The page being left keeps its pushes for a back/forward onto it. */
1271
+ /**
1272
+ * The page being left keeps its pushes for a back/forward onto it, written
1273
+ * to its history-cache entry as production's navigate does before it
1274
+ * leaves (navigation-bridge.ts).
1275
+ */
1131
1276
  const leaveEntry = (): void => {
1132
- const left = entries.get(entryOnScreen);
1133
- if (left) left.handleData = eventController.getHandleState().data;
1277
+ const key = store.getHistoryKey();
1278
+ if (!store.getCachedSegments(key)) return;
1279
+ store.updateCacheHandleData(
1280
+ key,
1281
+ liveHandleDataForCache(eventController, store, key),
1282
+ );
1283
+ };
1284
+ /**
1285
+ * A commit of `segments` at `pageUrl`: the store moves to its entry and
1286
+ * caches it with the handle data on screen, as production's commit does
1287
+ * (navigation-transaction.ts; a commit onto the page on screen, an action's
1288
+ * or a revalidation's, as its storeOnly re-cache) before the response's
1289
+ * handle stream writes the entry's own.
1290
+ */
1291
+ const cacheCommit = (
1292
+ pageUrl: URL,
1293
+ segments: ResolvedSegment[],
1294
+ samePage: boolean,
1295
+ ): void => {
1296
+ const key = generateHistoryKey(pageUrl.href);
1297
+ store.setHistoryKey(key);
1298
+ store.cacheSegmentsForHistory(
1299
+ key,
1300
+ segments,
1301
+ samePage
1302
+ ? liveHandleDataForCache(eventController, store, key)
1303
+ : eventController.getHandleState().data,
1304
+ );
1134
1305
  };
1135
1306
  let popGeneration = 0;
1136
1307
  // The navigation's lifecycle, as navigation-transaction.ts drives it:
@@ -1243,20 +1414,10 @@ export async function renderRoute(
1243
1414
  const metadata = makeMetadata(nextUrl.pathname, segments, match.params);
1244
1415
  // The destination's handle pushes arrive on the response's handle
1245
1416
  // stream, as production's do, behind the page's commit.
1246
- const navHandles = navOptions?.handles;
1247
- if (navHandles) {
1248
- const leafId =
1249
- [...segments].reverse().find((s) => s.type === "route")?.id ??
1250
- segments[segments.length - 1]?.id;
1251
- const pushed: HandleDataSeed = {};
1252
- for (const [h, values] of navHandles) {
1253
- if (leafId === undefined) continue;
1254
- const id = (h as unknown as { $$id: string }).$$id;
1255
- (pushed[id] ??= {})[leafId] = values;
1256
- }
1257
- metadata.handles = (async function* () {
1258
- yield pushed;
1259
- })();
1417
+ if (navOptions?.handles) {
1418
+ metadata.handles = handleStream(
1419
+ seedHandles({}, navOptions.handles, segments),
1420
+ );
1260
1421
  }
1261
1422
  // Production's browser-run transition({ when }) decision
1262
1423
  // (browser/partial-update.ts): the committed location is the source.
@@ -1322,6 +1483,7 @@ export async function renderRoute(
1322
1483
  params: match.params,
1323
1484
  state: window.history.state,
1324
1485
  });
1486
+ cacheCommit(nextUrl, segments, navOptions?.sameEntry === true);
1325
1487
  const emit: UpdateSubscriber = (update) => store.emitUpdate(update);
1326
1488
  await act(async () => {
1327
1489
  // As production's emitters name their cause (suspense-audit.ts I6).
@@ -1345,12 +1507,13 @@ export async function renderRoute(
1345
1507
  };
1346
1508
 
1347
1509
  const refresh = (
1348
- refreshOptions?: Pick<RenderRouteOptions, "loaders">,
1510
+ refreshOptions?: Pick<RenderRouteOptions, "loaders" | "handles">,
1349
1511
  ): Promise<void> => {
1350
1512
  const current = new URL(eventController.getLocation().href);
1351
1513
  return navigate(current.pathname + current.search, {
1352
1514
  kind: "revalidate",
1353
1515
  loaders: refreshOptions?.loaders,
1516
+ handles: refreshOptions?.handles,
1354
1517
  sameEntry: true,
1355
1518
  });
1356
1519
  };
@@ -1386,10 +1549,13 @@ export async function renderRoute(
1386
1549
  url: URL,
1387
1550
  kind: "action" | "revalidate",
1388
1551
  renderOptions: { forceAwait?: boolean; isAction?: boolean },
1552
+ handles?: ReadonlyArray<HandleSeed>,
1389
1553
  ): Promise<{ commit(): Promise<void> }> => {
1390
1554
  const match = resolve(url.pathname);
1391
1555
  const segments = buildSegments(routes, match.params, loaderData, mount);
1392
1556
  const metadata = makeMetadata(url.pathname, segments, match.params);
1557
+ if (handles)
1558
+ metadata.handles = handleStream(seedHandles({}, handles, segments));
1393
1559
  const gatedOff = decideTransitionGatedOff(segments, () => ({
1394
1560
  kind,
1395
1561
  from: {
@@ -1415,6 +1581,7 @@ export async function renderRoute(
1415
1581
  store.setSegmentIds(segments.map((s) => s.id));
1416
1582
  const shown = entries.get(entryOnScreen);
1417
1583
  if (shown) shown.segments = segments;
1584
+ cacheCommit(url, segments, true);
1418
1585
  const emit: UpdateSubscriber = (update) => store.emitUpdate(update);
1419
1586
  await act(async () => {
1420
1587
  auditTreeCause(kind === "action" ? "action" : "stale-revalidation");
@@ -1475,7 +1642,7 @@ export async function renderRoute(
1475
1642
 
1476
1643
  // action(): the response of a server action, landing on the page on screen.
1477
1644
  const action = async (
1478
- actionOptions?: Pick<RenderRouteOptions, "loaders"> & {
1645
+ actionOptions?: Pick<RenderRouteOptions, "loaders" | "handles"> & {
1479
1646
  keepClientCache?: boolean;
1480
1647
  },
1481
1648
  ): Promise<void> => {
@@ -1484,6 +1651,7 @@ export async function renderRoute(
1484
1651
  new URL(eventController.getLocation().href),
1485
1652
  "action",
1486
1653
  { isAction: true },
1654
+ actionOptions?.handles,
1487
1655
  );
1488
1656
  // The action bridge's landing (server-action-bridge.ts finalizeAction).
1489
1657
  if (!actionOptions?.keepClientCache) store.markCacheAsStaleAndBroadcast();
@@ -1498,9 +1666,12 @@ export async function renderRoute(
1498
1666
  const generation = ++popGeneration;
1499
1667
  eventController.abortNavigation();
1500
1668
  const historyState = window.history.state;
1669
+ const historyKey = generateHistoryKey(page.url.href);
1670
+ const cached = store.getCachedSegments(historyKey);
1671
+ const segments = cached?.segments ?? page.segments;
1501
1672
  // transition({ when }) decides the restore (kind "pop") against the
1502
1673
  // entry being left.
1503
- const gatedOff = decideTransitionGatedOff(page.segments, () => ({
1674
+ const gatedOff = decideTransitionGatedOff(segments, () => ({
1504
1675
  kind: "pop",
1505
1676
  from: {
1506
1677
  url: eventController.getLocation().href,
@@ -1515,7 +1686,7 @@ export async function renderRoute(
1515
1686
  state: historyState,
1516
1687
  },
1517
1688
  }));
1518
- const root = await renderSegments(page.segments, {
1689
+ const root = await renderSegments(segments, {
1519
1690
  forceAwait: true,
1520
1691
  outletPending: options.outletPending,
1521
1692
  transitionGatedOff: gatedOff,
@@ -1524,14 +1695,15 @@ export async function renderRoute(
1524
1695
  if (generation !== popGeneration) return;
1525
1696
  leaveEntry();
1526
1697
  entryOnScreen = index;
1698
+ store.setHistoryKey(historyKey);
1527
1699
  store.setCurrentUrl(page.url.href);
1528
- store.setSegmentIds(page.segments.map((s) => s.id));
1700
+ store.setSegmentIds(segments.map((s) => s.id));
1529
1701
  const update: NavigationUpdate = {
1530
1702
  root,
1531
1703
  metadata: {
1532
- ...makeMetadata(page.url.pathname, page.segments, page.params),
1704
+ ...makeMetadata(page.url.pathname, segments, page.params),
1533
1705
  isPartial: true,
1534
- cachedHandleData: page.handleData,
1706
+ cachedHandleData: store.getCachedSegments(historyKey)?.handleData,
1535
1707
  },
1536
1708
  };
1537
1709
  await act(async () => {
@@ -1541,7 +1713,7 @@ export async function renderRoute(
1541
1713
  eventController.setParams(page.params);
1542
1714
  eventController.commitLocationState(historyState);
1543
1715
  auditTreeCause("popstate");
1544
- if (!shouldStartViewTransition(page.segments, gatedOff)) {
1716
+ if (!shouldStartViewTransition(segments, gatedOff)) {
1545
1717
  store.emitUpdate(update);
1546
1718
  } else {
1547
1719
  startTransition(() => {
@@ -1632,7 +1804,7 @@ export async function renderRoute(
1632
1804
  <LinkInterceptionRegistration bridge={bridge} />
1633
1805
  <LoaderEndpoint answer={answerLoad} />
1634
1806
  {options.hydrate && <HydratedMarker />}
1635
- {applyLateHandles && <AfterTree run={applyLateHandles} />}
1807
+ {applyDocumentLate && <AfterTree run={applyDocumentLate} />}
1636
1808
  {resolveDocumentRevealed && <AfterTree run={resolveDocumentRevealed} />}
1637
1809
  </>
1638
1810
  );
@@ -1695,6 +1867,8 @@ export async function renderRoute(
1695
1867
  });
1696
1868
  });
1697
1869
 
1870
+ const shownSegments = (): ResolvedSegment[] =>
1871
+ entries.get(entryOnScreen)?.segments ?? initialSegments;
1698
1872
  const router: TestRouterHandle = {
1699
1873
  navigate: (target, navOptions) =>
1700
1874
  navigate(target, {
@@ -1711,9 +1885,73 @@ export async function renderRoute(
1711
1885
  prefetch,
1712
1886
  action,
1713
1887
  respondToLoads: (respondOptions) => {
1714
- Object.assign(loadAnswers, seedLoaders({}, respondOptions.loaders));
1888
+ const answers = seedLoaders({}, respondOptions.loaders);
1889
+ Object.assign(loadAnswers, answers);
1890
+ for (const loaderId of Object.keys(answers)) {
1891
+ loadPushes[loaderId] = Object.fromEntries(
1892
+ (respondOptions.handles ?? []).map(([h, values]) => [
1893
+ (h as unknown as { $$id: string }).$$id,
1894
+ values,
1895
+ ]),
1896
+ );
1897
+ }
1715
1898
  },
1716
1899
  revalidations: () => [...revalidations],
1900
+ pushLateHandles: async (late, lateOptions) => {
1901
+ const segments = shownSegments();
1902
+ // The yield: the page's state with each seed's run replaced, its
1903
+ // pushedBy record kept aligned (handles/pushed-by.ts), as the server's
1904
+ // handle store tags every yield.
1905
+ const run =
1906
+ lateOptions?.pushedBy === undefined
1907
+ ? null
1908
+ : ensureSyntheticId(lateOptions.pushedBy);
1909
+ const next = cloneHandleSeed(eventController.getHandleState().data);
1910
+ for (const [handle, values, at] of late) {
1911
+ const id = (handle as unknown as { $$id: string }).$$id;
1912
+ const segmentId = segmentIdIn(segments, at);
1913
+ const byName = pushedByKey(id);
1914
+ const oldValues = next[id]?.[segmentId] ?? [];
1915
+ const oldBy = next[byName]?.[segmentId] ?? [];
1916
+ // A seed replaces its run's values in the segment: every value for
1917
+ // the handler's (untagged) run, as a seed always did; only the
1918
+ // loader's own for a tagged one.
1919
+ const kept = run === null ? [] : oldValues.map((_, i) => i);
1920
+ const keep = kept.filter((i) => (oldBy[i] ?? null) !== run);
1921
+ const by = [
1922
+ ...keep.map((i) => oldBy[i] ?? null),
1923
+ ...values.map(() => run),
1924
+ ];
1925
+ (next[id] ??= {})[segmentId] = [
1926
+ ...keep.map((i) => oldValues[i]),
1927
+ ...values,
1928
+ ];
1929
+ if (by.some((r) => r !== null)) (next[byName] ??= {})[segmentId] = by;
1930
+ else if (next[byName]) delete next[byName][segmentId];
1931
+ }
1932
+ await act(async () => {
1933
+ // Production's late channel (browser/rsc-router.tsx): merged with
1934
+ // the reads that landed on the page, then its entry written.
1935
+ applyLateHandles(
1936
+ { store, eventController },
1937
+ next,
1938
+ segments.map((s) => s.id),
1939
+ store.getHistoryKey(),
1940
+ );
1941
+ eventController.flushRouteState();
1942
+ });
1943
+ },
1944
+ handleData: (h) => {
1945
+ const merged =
1946
+ eventController.withClientHandles(
1947
+ eventController.getHandleState().data,
1948
+ h.$$id,
1949
+ )[h.$$id] ?? {};
1950
+ return Object.fromEntries(
1951
+ Object.entries(merged).filter(([, values]) => values.length > 0),
1952
+ );
1953
+ },
1954
+ segmentId: (at) => segmentIdIn(shownSegments(), at),
1717
1955
  pathname: () => new URL(eventController.getLocation().href).pathname,
1718
1956
  params: () => eventController.getParams(),
1719
1957
  store,
@@ -1767,6 +2005,13 @@ function withoutBrowserGlobals<T>(fn: () => T): T {
1767
2005
  }
1768
2006
  }
1769
2007
 
2008
+ /** A response's handle stream that yields `pushed` once. */
2009
+ async function* handleStream(
2010
+ pushed: HandleDataSeed,
2011
+ ): AsyncGenerator<HandleData> {
2012
+ yield pushed;
2013
+ }
2014
+
1770
2015
  function makeMetadata(
1771
2016
  pathname: string,
1772
2017
  segments: ResolvedSegment[],