@rangojs/router 0.36.0 → 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 (74) 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-UECTPF6K.js → runtime-discovery-T7ZLA6E3.js} +2 -2
  5. package/dist/bin/{temp-rsc-server-QLNMTFEE.js → temp-rsc-server-FGGXPKVQ.js} +2 -2
  6. package/dist/types/browser/event-controller.d.ts +61 -0
  7. package/dist/types/browser/fetched-loader-handles.d.ts +76 -0
  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 +14 -0
  17. package/dist/types/handles/pushed-by.d.ts +36 -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/flight.entry.d.ts +1 -1
  23. package/dist/types/testing/render-route.d.ts +76 -14
  24. package/dist/types/testing/serve-shell-request.d.ts +31 -0
  25. package/dist/vite/index.js +23 -20
  26. package/package.json +1 -1
  27. package/skills/breadcrumbs/SKILL.md +68 -6
  28. package/skills/caching/SKILL.md +4 -2
  29. package/skills/catalog.json +3 -3
  30. package/skills/client-urls/SKILL.md +13 -1
  31. package/skills/document-cache/SKILL.md +31 -1
  32. package/skills/hooks/SKILL.md +8 -4
  33. package/skills/hooks/data.md +10 -1
  34. package/skills/hooks/handle-and-actions.md +402 -26
  35. package/skills/hooks/navigation.md +4 -0
  36. package/skills/hooks/urls.md +3 -0
  37. package/skills/links/SKILL.md +5 -3
  38. package/skills/loader/SKILL.md +40 -1
  39. package/skills/migrate-nextjs/SKILL.md +5 -0
  40. package/skills/migrate-react-router/component-migration.md +4 -1
  41. package/skills/parallel/SKILL.md +8 -0
  42. package/skills/ppr/SKILL.md +1 -0
  43. package/skills/rango/SKILL.md +6 -3
  44. package/skills/testing/client-components.md +35 -32
  45. package/skills/testing/handles.md +58 -6
  46. package/skills/testing/serve-shell-request.md +33 -14
  47. package/skills/ux-architecture/SKILL.md +4 -0
  48. package/src/browser/event-controller.ts +311 -2
  49. package/src/browser/fetched-loader-handles.ts +269 -0
  50. package/src/browser/navigation-store.ts +261 -2
  51. package/src/browser/partial-update.ts +3 -2
  52. package/src/browser/react/use-handle.ts +74 -27
  53. package/src/browser/react/use-push-handle.ts +113 -0
  54. package/src/browser/rsc-router.tsx +11 -14
  55. package/src/browser/types.ts +48 -0
  56. package/src/cache/document-cache-policy.ts +6 -5
  57. package/src/client.rsc.tsx +1 -0
  58. package/src/client.tsx +31 -1
  59. package/src/handle.ts +13 -5
  60. package/src/handles/client-pushes.ts +120 -0
  61. package/src/handles/deferred-resolution.ts +41 -2
  62. package/src/handles/pushed-by.ts +130 -1
  63. package/src/loader-store.ts +26 -0
  64. package/src/rsc/loader-fetch.ts +64 -5
  65. package/src/rsc/prefetch-render-error.ts +2 -1
  66. package/src/rsc/request-stages.ts +7 -6
  67. package/src/rsc/rsc-rendering.ts +32 -14
  68. package/src/server/handle-store.ts +23 -0
  69. package/src/ssr/ssr-root.tsx +6 -0
  70. package/src/testing/dom.entry.ts +2 -0
  71. package/src/testing/flight.entry.ts +1 -0
  72. package/src/testing/render-route.tsx +319 -72
  73. package/src/testing/serve-shell-request.ts +62 -1
  74. package/src/use-loader.tsx +44 -4
@@ -615,6 +615,32 @@ export type UpdateSubscriber = (update: NavigationUpdate) => void;
615
615
  */
616
616
  export type StateListener = () => void;
617
617
 
618
+ /**
619
+ * A page read in flight (NavigationStore.beginPageRead): the page it was
620
+ * sent from and the loader data that page held for the loader then. The
621
+ * page's entries are those of the key it was sent from, those a shallow
622
+ * navigation shares its segments with, and those a later commit wrote in
623
+ * their place.
624
+ */
625
+ export interface PageRead {
626
+ /**
627
+ * The keys of the page's entries the read is for: those holding the data
628
+ * it was requested for, and once it landed, those holding its result.
629
+ */
630
+ historyKeys(): string[];
631
+ /** An entry of the page still holds the data the read was requested for. */
632
+ current(): boolean;
633
+ /**
634
+ * Write `result` into every entry of the page that holds the data the read
635
+ * was requested for: each of their loader segments for the loader becomes
636
+ * a copy carrying it, in place, and the page's read record names it.
637
+ * False, and nothing written, when none does.
638
+ */
639
+ land(result: unknown): boolean;
640
+ /** The read landed and an entry of the page still holds its result. */
641
+ holds(): boolean;
642
+ }
643
+
618
644
  /**
619
645
  * Navigation store interface
620
646
  *
@@ -652,6 +678,28 @@ export interface NavigationStore {
652
678
  getHistoryEntryMemory(entryKey?: string): HistoryEntryMemory | undefined;
653
679
  /** Monotonic token of the most recently committed navigation. */
654
680
  getNavInstance(): number;
681
+ /**
682
+ * Begin a page read of `loaderId` (`load()`, a group refresh) from the
683
+ * entry on screen: it captures, by identity, the loader data that entry
684
+ * holds in every loader segment of the loader
685
+ * (browser/fetched-loader-handles.ts).
686
+ */
687
+ beginPageRead(loaderId: string): PageRead;
688
+ /**
689
+ * The loaders whose data a landed page read replaced on the page of
690
+ * `historyKey`'s entry, since the server last sent them: the run of each
691
+ * is newer on the page than the document's (a late handle push keeps it).
692
+ */
693
+ getPageReadLoaders(historyKey: string): ReadonlySet<string>;
694
+ /**
695
+ * Rewrite an entry's segments array in place (a `prefetch: false` fill):
696
+ * the array keeps its identity, and the page's read record is carried over
697
+ * as cacheSegmentsForHistory carries it.
698
+ */
699
+ replaceEntrySegments(
700
+ segments: ResolvedSegment[],
701
+ next: readonly ResolvedSegment[],
702
+ ): void;
655
703
  cacheSegmentsForHistory(
656
704
  historyKey: string,
657
705
  segments: ResolvedSegment[],
@@ -112,17 +112,18 @@ export function shouldCacheResponse(
112
112
 
113
113
  // prefetch: false. The payload carries deferred units: it answers one
114
114
  // page's prefetch and nothing else. parseCacheControl refuses the
115
- // Cache-Control it is sent with (rsc-rendering.ts NOT_REUSED), but a
116
- // middleware can replace that after next(), and a navigation answered
117
- // with this body would show a fallback no fill ever replaces.
115
+ // Cache-Control it is sent with (rsc-rendering.ts NOT_REUSED, or the
116
+ // route's own no-store), but a middleware can replace that after next(),
117
+ // and a navigation answered with this body would show a fallback no fill
118
+ // ever replaces.
118
119
  if (requestCtx?._payloadDeferred) {
119
120
  return null;
120
121
  }
121
122
 
122
123
  // A partial scoped to its source page: this cache keys it by
123
124
  // URL and the ids the client holds, so it would answer another page with
124
- // the same ids. rsc-rendering.ts sends it NOT_REUSED; a middleware can
125
- // replace that after next().
125
+ // the same ids. rsc-rendering.ts sends it NOT_REUSED (or keeps the route's
126
+ // no-store); a middleware can replace that after next().
126
127
  if (requestCtx?._payloadSourceScoped) {
127
128
  return null;
128
129
  }
@@ -124,5 +124,6 @@ export { useHref } from "./browser/react/use-href.js";
124
124
  export { useReverse } from "./browser/react/use-reverse.js";
125
125
 
126
126
  export { useHandle } from "./browser/react/use-handle.js";
127
+ export { usePushHandle } from "./browser/react/use-push-handle.js";
127
128
 
128
129
  export { useLocationState } from "./browser/react/location-state.js";
package/src/client.tsx CHANGED
@@ -93,7 +93,7 @@ function renderSlotContent(segment: ResolvedSegment | null): ReactNode {
93
93
  // Common for intercept routes that use useLoader without a custom layout.
94
94
  result = loaderWrapped;
95
95
  } else {
96
- result = content;
96
+ result = <SlotSegment segment={segment}>{content}</SlotSegment>;
97
97
  }
98
98
 
99
99
  if (process.env.NODE_ENV !== "production" && INTERNAL_RANGO_SUSPENSE_AUDIT) {
@@ -111,6 +111,29 @@ function renderSlotContent(segment: ResolvedSegment | null): ReactNode {
111
111
  return result;
112
112
  }
113
113
 
114
+ /**
115
+ * The slot's own segment for what its content reads from OutletContext
116
+ * (usePushHandle files its values under it). A slot with neither a layout nor
117
+ * loaders has no OutletProvider of its own and would read its parent's; the
118
+ * rest of the parent's context (loaders, parallel, content) stays.
119
+ */
120
+ function SlotSegment({
121
+ segment,
122
+ children,
123
+ }: {
124
+ segment: ResolvedSegment;
125
+ children: ReactNode;
126
+ }): ReactNode {
127
+ const context = useContext(OutletContext);
128
+ const value = useMemo(
129
+ () => (context ? { ...context, segment } : null),
130
+ [context, segment],
131
+ );
132
+ return (
133
+ <OutletContext.Provider value={value}>{children}</OutletContext.Provider>
134
+ );
135
+ }
136
+
114
137
  // Dev only (suspense-audit.ts): the boundaries renderSlotContent built, as
115
138
  // their audited components with the same props. After the fact, not a choice
116
139
  // per JSX element: a build must fold to the product elements alone (see
@@ -136,6 +159,12 @@ function auditedSlot(node: ReactNode): ReactNode {
136
159
  props as ComponentProps<typeof RouteContentWrapper>,
137
160
  );
138
161
  }
162
+ if (node.type === SlotSegment) {
163
+ return createElement(SlotSegment, {
164
+ segment: props.segment,
165
+ children: auditedSlot(props.children),
166
+ });
167
+ }
139
168
  return node;
140
169
  }
141
170
 
@@ -491,6 +520,7 @@ export {
491
520
 
492
521
  export { type Handle } from "./handle.js";
493
522
  export { useHandle } from "./browser/react/use-handle.js";
523
+ export { usePushHandle } from "./browser/react/use-push-handle.js";
494
524
 
495
525
  export { Meta } from "./handles/meta.js";
496
526
  export type { MetaDescriptor, MetaDescriptorBase } from "./router/types.js";
package/src/handle.ts CHANGED
@@ -4,9 +4,14 @@ import { isUnderTestRunner } from "./runtime-env.js";
4
4
  /**
5
5
  * Handle definition for accumulating data across route segments.
6
6
  *
7
- * Handles allow server-side route handlers to pass accumulated data to client
8
- * components. Unlike loaders (which fetch data for specific routes), handles
9
- * accumulate data across all matched route segments.
7
+ * A handle accumulates values across the matched route segments: each
8
+ * segment's values, in tree order, are collected into what `useHandle`
9
+ * returns. Values are pushed by the server, from a handler or a loader
10
+ * (`ctx.use(handle)`), and by client components, for data they learn or
11
+ * change after the server rendered (`usePushHandle(handle)`). In each
12
+ * segment the client's values follow the server's. Unlike loaders (which
13
+ * fetch data for specific routes), handles accumulate data across all
14
+ * matched route segments.
10
15
  *
11
16
  * @example
12
17
  * ```ts
@@ -16,11 +21,14 @@ import { isUnderTestRunner } from "./runtime-env.js";
16
21
  * (segments) => segments.flat(), // opt into a single flat list
17
22
  * );
18
23
  *
19
- * // Use in handler
24
+ * // Push from a handler or a loader
20
25
  * const push = ctx.use(Breadcrumbs);
21
26
  * push({ label: "Home", href: "/" });
22
27
  *
23
- * // Consume on client
28
+ * // Push from a client component, during render
29
+ * usePushHandle(Breadcrumbs)({ label: draft.name, href: "/draft" });
30
+ *
31
+ * // Read in a client component
24
32
  * const crumbs = useHandle(Breadcrumbs);
25
33
  * ```
26
34
  */
@@ -0,0 +1,120 @@
1
+ import type { HandleData } from "../server/handle-store.js";
2
+
3
+ /**
4
+ * A usePushHandle component's owner object, as setClientHandle sees it:
5
+ * `resync` renders it again; `generation` counts the renders resync asked
6
+ * for, as of the render that published. Both are set by the hook before it
7
+ * publishes; a bare owner has neither and is never asked to resync.
8
+ */
9
+ export interface ClientPushOwner {
10
+ resync?: () => void;
11
+ generation?: number;
12
+ }
13
+
14
+ /**
15
+ * The client handle layer (usePushHandle): handle id -> segment id -> pusher
16
+ * -> the values that pusher's last committed render pushed, its promises
17
+ * resolved. Pushers are kept in tree order (Map insertion order, which
18
+ * EventController.setClientHandle rebuilds when a pusher joins).
19
+ */
20
+ export type ClientPushes = Map<
21
+ string,
22
+ Map<string, Map<ClientPushOwner, unknown[]>>
23
+ >;
24
+
25
+ /** Object pairs a samePushValue walk compares before it remembers equal ones. */
26
+ const UNREMEMBERED_PAIRS = 64;
27
+
28
+ /**
29
+ * Structural equality for pushed values: arrays and plain objects by their
30
+ * entries, React elements by type, key and props, dates by time, anything
31
+ * else (a promise, a function, a Map, a Set, a class instance, a
32
+ * null-prototype object) by Object.is. A component that pushes a fresh
33
+ * literal on each render (nested objects included) and reads the same handle
34
+ * would otherwise re-render itself without end: each render's push would
35
+ * look new. useCommitAnchoredState (browser/react/use-handle.ts) compares
36
+ * what useHandle and useSegments return with it too, so a re-delivery of
37
+ * equal content keeps the reader's reference. The walk goes no deeper than
38
+ * 32 levels: what it cannot compare within them, a cyclic value included,
39
+ * counts as different.
40
+ *
41
+ * Each pair of objects is walked once. A shared sub-object (Flight keeps a
42
+ * shared reference shared) is reached once per path to it, so a walk that
43
+ * remembers nothing is exponential in the sharing: an equal binary DAG 20
44
+ * levels deep took 164 ms, 22 levels 685 ms. Pairs found equal are remembered once the walk has
45
+ * visited UNREMEMBERED_PAIRS of them, so a small value such as a breadcrumb
46
+ * trail allocates no map. A pair found different needs no entry: `every`
47
+ * stops there and the whole walk is false. A pair still being walked is not
48
+ * remembered yet, so a cycle still runs into the depth bound; a pair already
49
+ * found equal stays equal wherever the walk meets it again, past the bound
50
+ * too.
51
+ */
52
+ export function samePushValue(a: unknown, b: unknown): boolean {
53
+ let visits = 0;
54
+ let equal: Map<object, Set<object>> | undefined;
55
+ const same = (a: unknown, b: unknown, depth: number): boolean => {
56
+ if (Object.is(a, b)) return true;
57
+ if (a instanceof Date)
58
+ return b instanceof Date && a.getTime() === b.getTime();
59
+ const proto = a && typeof a === "object" && Object.getPrototypeOf(a);
60
+ if (
61
+ depth > 32 ||
62
+ !proto ||
63
+ !b ||
64
+ typeof b !== "object" ||
65
+ proto !== Object.getPrototypeOf(b) ||
66
+ (proto !== Object.prototype && proto !== Array.prototype)
67
+ ) {
68
+ return false;
69
+ }
70
+ if (++visits > UNREMEMBERED_PAIRS) equal ??= new Map();
71
+ const partners = equal?.get(a);
72
+ if (partners?.has(b)) return true;
73
+ // A React element's dev-only `_owner` is a fiber: compare what renders.
74
+ const element = "$$typeof" in a;
75
+ const keys = element
76
+ ? ["$$typeof", "type", "key", "props"]
77
+ : Object.keys(a);
78
+ const result =
79
+ (element || keys.length === Object.keys(b).length) &&
80
+ keys.every(
81
+ (key) =>
82
+ key in b &&
83
+ same(
84
+ (a as Record<string, unknown>)[key],
85
+ (b as Record<string, unknown>)[key],
86
+ depth + 1,
87
+ ),
88
+ );
89
+ if (result && equal) {
90
+ if (partners) partners.add(b);
91
+ else equal.set(a, new Set([b]));
92
+ }
93
+ return result;
94
+ };
95
+ return same(a, b, 0);
96
+ }
97
+
98
+ /**
99
+ * `data` (the server's handle data) with `handleId`'s client pushes after the
100
+ * server's values in each segment: `[...server, ...pusher1, ...pusher2]`. A
101
+ * fixed position, so what arrives first never decides what shows. A segment
102
+ * only the client pushes into is collected in segment order like any other;
103
+ * one outside the order is skipped by collectHandleData.
104
+ */
105
+ export function withClientPushes(
106
+ data: HandleData,
107
+ handleId: string,
108
+ pushes: ClientPushes,
109
+ ): HandleData {
110
+ const bySegment = pushes.get(handleId);
111
+ if (!bySegment) return data;
112
+ const merged: Record<string, unknown[]> = { ...data[handleId] };
113
+ for (const [segmentId, owners] of bySegment) {
114
+ merged[segmentId] = [
115
+ ...(merged[segmentId] ?? []),
116
+ ...[...owners.values()].flat(),
117
+ ];
118
+ }
119
+ return { ...data, [handleId]: merged };
120
+ }
@@ -1,6 +1,10 @@
1
1
  import type { HandleData, HandleStore } from "../server/handle-store.js";
2
2
  import { isThenable } from "./is-thenable.js";
3
- import { isPushedByKey, pushedByKey } from "./pushed-by.js";
3
+ import {
4
+ isPushedByKey,
5
+ pushedByKey,
6
+ type LoaderReadPushes,
7
+ } from "./pushed-by.js";
4
8
 
5
9
  /**
6
10
  * Runtime-neutral resolution of deferred (Promise) handle values. Shared by the
@@ -68,6 +72,29 @@ export async function resolveDeferredHandleValues(
68
72
  return out;
69
73
  }
70
74
 
75
+ /**
76
+ * A fetched loader read's pushes, as its reply carries them, with deferred
77
+ * values awaited as resolveDeferredHandleValues awaits them; `pushedBy` loses
78
+ * the entries of the dropped values.
79
+ */
80
+ export async function resolveDeferredPushes(
81
+ pushes: Readonly<Record<string, readonly unknown[]>>,
82
+ pushedBy: Readonly<Record<string, readonly (string | null)[]>> = {},
83
+ ): Promise<LoaderReadPushes> {
84
+ const out: LoaderReadPushes = { values: {}, pushedBy: {} };
85
+ await Promise.all(
86
+ Object.entries(pushes).map(async ([handleName, values]) => {
87
+ const resolved = await resolveValues(values);
88
+ out.values[handleName] = keptValues(resolved);
89
+ const by = pushedBy[handleName];
90
+ if (by) {
91
+ out.pushedBy[handleName] = by.filter((_, i) => resolved[i].keep);
92
+ }
93
+ }),
94
+ );
95
+ return out;
96
+ }
97
+
71
98
  interface ResolvedValue {
72
99
  keep: boolean;
73
100
  value: unknown;
@@ -78,7 +105,7 @@ interface ResolvedValue {
78
105
  // A thenable is awaited and dropped when it rejects OR resolves to null/undefined
79
106
  // (the `.defer({ else })` skip semantics: a forgotten resolver times out to
80
107
  // `else ?? undefined`), so a nullish deferred slot never reaches a collector.
81
- function resolveValues(values: unknown[]): Promise<ResolvedValue[]> {
108
+ function resolveValues(values: readonly unknown[]): Promise<ResolvedValue[]> {
82
109
  return Promise.all(
83
110
  values.map(async (v) => {
84
111
  if (!isThenable(v)) return { keep: true, value: v };
@@ -96,6 +123,18 @@ function keptValues(resolved: ResolvedValue[]): unknown[] {
96
123
  return resolved.filter((r) => r.keep).map((r) => r.value);
97
124
  }
98
125
 
126
+ /**
127
+ * One list of pushed values with its deferred entries awaited, as
128
+ * resolveDeferredHandleValues awaits a segment's: shallow, in order, a
129
+ * rejected or nullish deferred dropped. A client component's pushes
130
+ * (usePushHandle) resolve through it, so they follow the server's rules.
131
+ */
132
+ export async function resolveDeferredList(
133
+ values: readonly unknown[],
134
+ ): Promise<unknown[]> {
135
+ return keptValues(await resolveValues(values));
136
+ }
137
+
99
138
  /**
100
139
  * Full-render handle stream: a one-shot async generator that yields the FINAL
101
140
  * handle snapshot with every top-level deferred value resolved. Drop-in for
@@ -1,4 +1,7 @@
1
- import { LOADER_SEGMENT_ID } from "../browser/react/filter-segment-order.js";
1
+ import {
2
+ LOADER_SEGMENT_ID,
3
+ filterSegmentOrder,
4
+ } from "../browser/react/filter-segment-order.js";
2
5
  import type { HandleData } from "../server/handle-store.js";
3
6
 
4
7
  /**
@@ -75,6 +78,81 @@ export function withSegmentHandles(
75
78
  return out;
76
79
  }
77
80
 
81
+ /**
82
+ * What a fetched loader read pushed, settled: the values by handle $$id, and
83
+ * the loader whose run pushed each (index-aligned; null, or no entry for the
84
+ * handle, for the read loader's own body).
85
+ */
86
+ export interface LoaderReadPushes {
87
+ values: Record<string, unknown[]>;
88
+ pushedBy: Record<string, (string | null)[]>;
89
+ }
90
+
91
+ /**
92
+ * The handle data after a fetched read of loader `loaderId` (the `_rsc_loader`
93
+ * lane: `load()`, a `refreshGroup` refresh) pushed `pushes`. The read renders
94
+ * no segment, so its pushes go where the page's run of the loader put its
95
+ * own: the first segment of `segmentOrder` holding a value the loader pushed,
96
+ * else the first segment of `matched` (the raw list `current` was built from)
97
+ * that registers it, where a render files them (loader-resolution.ts
98
+ * loaderOwner). The loader's earlier values give way to these in their
99
+ * position, in every segment that registers it, and every other run keeps its
100
+ * own (mergePartialHandleData, with the loader as the run that ran). A value
101
+ * pushed by another loader the page registers, one the body read with
102
+ * ctx.use, belongs to that loader's run, which the read did not refresh: the
103
+ * page keeps that run's values, as it keeps its data. Undefined when no
104
+ * segment registers the loader: its pushes have no segment to belong to.
105
+ */
106
+ export function mergeLoaderReadHandleData(
107
+ current: HandleData,
108
+ segmentOrder: readonly string[],
109
+ matched: readonly string[],
110
+ loaderId: string,
111
+ pushes: LoaderReadPushes,
112
+ ): HandleData | undefined {
113
+ const registrations: string[] = [];
114
+ const registers = new Set<string>();
115
+ const otherLoaders = new Set<string | null>();
116
+ for (const id of matched) {
117
+ const marker = LOADER_SEGMENT_ID.exec(id);
118
+ if (!marker) continue;
119
+ const loader = id.slice(marker.index + marker[0].length);
120
+ if (loader !== loaderId) {
121
+ otherLoaders.add(loader);
122
+ continue;
123
+ }
124
+ registrations.push(id);
125
+ registers.add(id.slice(0, marker.index));
126
+ }
127
+ if (registrations.length === 0) return undefined;
128
+ const pushedHere = (segmentId: string): boolean =>
129
+ Object.keys(current).some(
130
+ (name) =>
131
+ isPushedByKey(name) &&
132
+ current[name][segmentId]?.includes(loaderId) === true,
133
+ );
134
+ const owner =
135
+ segmentOrder.find((id) => registers.has(id) && pushedHere(id)) ??
136
+ [...registers][0]!;
137
+ const incoming: HandleData = {};
138
+ for (const name in pushes.values) {
139
+ const by = pushes.pushedBy[name];
140
+ const own = pushes.values[name].filter(
141
+ (_, i) => !otherLoaders.has(by?.[i] ?? null),
142
+ );
143
+ if (own.length === 0) continue;
144
+ incoming[name] = { [owner]: own };
145
+ incoming[pushedByKey(name)] = { [owner]: own.map(() => loaderId) };
146
+ }
147
+ return mergePartialHandleData(
148
+ current,
149
+ incoming,
150
+ segmentOrder,
151
+ matched,
152
+ registrations,
153
+ );
154
+ }
155
+
78
156
  /**
79
157
  * The handle data after a partial response's snapshot `incoming` (each stream
80
158
  * yield holds everything the response pushed so far). A segment outside
@@ -171,3 +249,54 @@ export function mergePartialHandleData(
171
249
  }
172
250
  return out;
173
251
  }
252
+
253
+ /**
254
+ * The handle data after a late handle yield of the document (`late`: the
255
+ * document render's full state so far, `matched` its segment ids) lands on
256
+ * `current`, the page's data. Swapped in whole, except the runs of the
257
+ * loaders in `refreshed`: a fetched read landed for each since the document
258
+ * rendered (NavigationStore.getPageReadLoaders), so the page's values of that
259
+ * run are newer than the yield's and stay. The yield's values of those runs
260
+ * are dropped and the rest goes in as a partial response in which every
261
+ * other run ran (mergePartialHandleData). `late` itself when no read landed.
262
+ */
263
+ export function mergeLateHandleData(
264
+ current: HandleData,
265
+ late: HandleData,
266
+ matched: readonly string[],
267
+ refreshed: ReadonlySet<string>,
268
+ ): HandleData {
269
+ if (refreshed.size === 0) return late;
270
+ const incoming: HandleData = {};
271
+ for (const name in late) {
272
+ if (isPushedByKey(name)) continue;
273
+ const byName = pushedByKey(name);
274
+ for (const [segmentId, values] of Object.entries(late[name])) {
275
+ const by = late[byName]?.[segmentId] as PushedBy;
276
+ const keptValues: unknown[] = [];
277
+ const keptBy: (string | null)[] = [];
278
+ values.forEach((value, i) => {
279
+ const run = by?.[i] ?? null;
280
+ if (run !== null && refreshed.has(run)) return;
281
+ keptValues.push(value);
282
+ keptBy.push(run);
283
+ });
284
+ if (keptValues.length === 0) continue;
285
+ (incoming[name] ??= {})[segmentId] = keptValues;
286
+ if (keptBy.some((run) => run !== null)) {
287
+ (incoming[byName] ??= {})[segmentId] = keptBy;
288
+ }
289
+ }
290
+ }
291
+ const ran = matched.filter((id) => {
292
+ const marker = LOADER_SEGMENT_ID.exec(id);
293
+ return !marker || !refreshed.has(id.slice(marker.index + marker[0].length));
294
+ });
295
+ return mergePartialHandleData(
296
+ current,
297
+ incoming,
298
+ filterSegmentOrder([...matched]),
299
+ matched,
300
+ ran,
301
+ );
302
+ }
@@ -494,6 +494,32 @@ export class LoaderStore {
494
494
  this.dropIfSettled(bucketKey, e);
495
495
  }
496
496
 
497
+ /**
498
+ * True while a reader with route context subscribes to the bucket: a value
499
+ * committed to it shows on the page (browser/fetched-loader-handles.ts
500
+ * treats a read into it as the page's own).
501
+ */
502
+ hasRouteReaders(bucketKey: string): boolean {
503
+ return (this.entries.get(bucketKey)?.routeDataSources.size ?? 0) > 0;
504
+ }
505
+
506
+ /**
507
+ * True while `requestId`'s result is what the bucket holds: finishData
508
+ * committed it and no newer request or clear() (a route-data change) has
509
+ * moved the bucket on since. A fetched read's handle values and history
510
+ * write land exactly when this holds (browser/fetched-loader-handles.ts).
511
+ */
512
+ holdsRequest(bucketKey: string, requestId: number): boolean {
513
+ const e = this.entries.get(bucketKey);
514
+ return (
515
+ e !== undefined &&
516
+ e.latestRequestId === requestId &&
517
+ e.snapshot.requestId === requestId &&
518
+ e.snapshot.hasValue &&
519
+ e.snapshot.error === null
520
+ );
521
+ }
522
+
497
523
  /**
498
524
  * Commit an error. Preserves the last good `value` so consumers can keep
499
525
  * showing previous data while displaying the error if they choose. No-op
@@ -38,6 +38,20 @@ import {
38
38
  } from "./helpers.js";
39
39
  import type { HandlerContext } from "./handler-context.js";
40
40
  import { WIRE } from "../wire-params.js";
41
+ import { isHandle } from "../handle.js";
42
+ import { runInsideLoaderBodyScope } from "../server/context.js";
43
+
44
+ /**
45
+ * A successful read's reply: the loader's value, the values its body pushed
46
+ * to each handle (by handle $$id, in push order), and which loader's run
47
+ * pushed each (index-aligned, null for the body's own; a handle with no entry
48
+ * holds only the body's own).
49
+ */
50
+ interface LoaderFetchPayload {
51
+ loaderResult: unknown;
52
+ handles: Record<string, unknown[]>;
53
+ pushedBy: Record<string, (string | null)[]>;
54
+ }
41
55
 
42
56
  export interface LoaderErrorMeta<TEnv> {
43
57
  request: Request;
@@ -255,6 +269,17 @@ export async function handleLoaderFetch<TEnv>(
255
269
  variables,
256
270
  async () => {
257
271
  const reqCtx = getRequestContext();
272
+ // ctx.use(Handle) pushes file under the request context's segment
273
+ // (request-context.ts createUseFunction), which throws without one,
274
+ // and this lane renders no segment: the loader's id stands in. The
275
+ // body's pushes, and those of the loaders it reads with ctx.use,
276
+ // file under the loader's id and ride the reply; the browser files
277
+ // them under the segments that register the loader
278
+ // (browser/fetched-loader-handles.ts). Set before the copy below:
279
+ // a "use cache" function handed the loader's ctx replays a HIT's
280
+ // pushes into its segment (cache-runtime.ts callerSegmentId).
281
+ (reqCtx as { _currentSegmentId?: string })._currentSegmentId =
282
+ loaderId;
258
283
  // Merge route params (from previewMatch) with explicit loader params.
259
284
  // Explicit params take precedence over route-matched params.
260
285
  const resolvedRouteParams = routeParams ?? {};
@@ -290,6 +315,17 @@ export async function handleLoaderFetch<TEnv>(
290
315
  : undefined,
291
316
  ),
292
317
  ...(loaderFormData ? { formData: loaderFormData } : {}),
318
+ // A loader the body reads runs as its own run, as a render runs
319
+ // it (loader-resolution.ts): its pushes name it
320
+ // (getHandlePushOwner), so the reply's pushedBy tells the browser
321
+ // they are that loader's, not this one's.
322
+ use: ((item: any) =>
323
+ isHandle(item)
324
+ ? reqCtx.use(item)
325
+ : runInsideLoaderBodyScope(
326
+ () => reqCtx.use(item),
327
+ item.$$id,
328
+ )) as typeof reqCtx.use,
293
329
  };
294
330
 
295
331
  // Meter the fetchable-loader execution via observePhase, the sole
@@ -299,13 +335,36 @@ export async function handleLoaderFetch<TEnv>(
299
335
  fn(loaderCtx),
300
336
  );
301
337
 
302
- interface LoaderPayload {
303
- loaderResult: unknown;
304
- }
305
- const loaderPayload: LoaderPayload = { loaderResult: result };
338
+ const loaderPayload: LoaderFetchPayload = {
339
+ loaderResult: result,
340
+ // The pushes the body made, a pending one as its promise: the
341
+ // browser applies them once they settle, after the data.
342
+ handles: reqCtx._handleStore.getDataForSegment(loaderId),
343
+ // A loader the body read with ctx.use pushed as its own run: the
344
+ // browser leaves the page's run of it alone when the page
345
+ // registers it (handles/pushed-by.ts mergeLoaderReadHandleData).
346
+ pushedBy: reqCtx._handleStore.getPushedBy(loaderId) ?? {},
347
+ };
348
+ // The reply holds what the body pushed by the time it returned. A
349
+ // push it makes later (a timer, a promise it did not await) cannot
350
+ // reach the browser: warned in development, once per read.
351
+ let warnedLate = false;
352
+ reqCtx._handleStore.closeSegment(loaderId, (handleName) => {
353
+ if (process.env.NODE_ENV === "production" || warnedLate) return;
354
+ warnedLate = true;
355
+ console.warn(
356
+ `[rango] Loader "${loaderId}" pushed handle "${handleName}" ` +
357
+ `after its body returned, on a fetched read (load(), ` +
358
+ `useRefreshLoaders()). The reply carries only the values ` +
359
+ `pushed before the body returned, so this push came too late ` +
360
+ `and is not applied. Push before returning: await the work, ` +
361
+ `or push a promise (or reserve the slot with ` +
362
+ `ctx.use(Handle).defer()) and settle it later.`,
363
+ );
364
+ });
306
365
  // Read once here: onError can fire outside the ALS frame.
307
366
  const requestContext = _getRequestContext();
308
- const rscStream = ctx.renderToReadableStream<LoaderPayload>(
367
+ const rscStream = ctx.renderToReadableStream<LoaderFetchPayload>(
309
368
  loaderPayload,
310
369
  {
311
370
  onError: (error: unknown) => {
@@ -17,7 +17,8 @@
17
17
  * a prefetch with nothing live in it carries `private, max-age`
18
18
  * (request-stages.ts applyStoredPrefetchCacheControl); a prefetch
19
19
  * scoped to its source page or carrying deferred units is sent
20
- * `private, no-cache` (rsc-rendering.ts NOT_REUSED).
20
+ * `private, no-cache` (rsc-rendering.ts NOT_REUSED), or the route's own
21
+ * `no-store`.
21
22
  *
22
23
  * The errors are the render's `_renderErrors`: a Flight error row, a streamed
23
24
  * handler recovered into its boundary, a loader that threw (redirect() and