@rangojs/router 0.22.1 → 0.23.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 (179) hide show
  1. package/dist/bin/rango.js +8 -3
  2. package/dist/testing/vitest.js +31 -1
  3. package/dist/types/browser/defer.d.ts +48 -0
  4. package/dist/types/browser/document-revealed.d.ts +17 -0
  5. package/dist/types/browser/event-controller.d.ts +7 -1
  6. package/dist/types/browser/navigation-transaction.d.ts +21 -7
  7. package/dist/types/browser/partial-update.d.ts +34 -5
  8. package/dist/types/browser/react/NavigationProvider.d.ts +13 -3
  9. package/dist/types/browser/react/filter-segment-order.d.ts +7 -0
  10. package/dist/types/browser/response-adapter.d.ts +7 -0
  11. package/dist/types/browser/types.d.ts +19 -9
  12. package/dist/types/browser/validate-redirect-origin.d.ts +11 -0
  13. package/dist/types/build/generate-route-types.d.ts +1 -1
  14. package/dist/types/build/route-types/router-processing.d.ts +1 -1
  15. package/dist/types/build/route-types/scan-filter.d.ts +16 -2
  16. package/dist/types/cache/cf/cf-cache-store.d.ts +16 -1
  17. package/dist/types/cache/cf/cf-cache-types.d.ts +23 -2
  18. package/dist/types/client-urls/client-urls.d.ts +1 -1
  19. package/dist/types/client-urls/hoisted-revalidate.d.ts +13 -0
  20. package/dist/types/client-urls/navigation.d.ts +0 -37
  21. package/dist/types/client-urls/revalidate-registry.d.ts +4 -0
  22. package/dist/types/client-urls/server-projection.d.ts +29 -1
  23. package/dist/types/client-urls/types.d.ts +34 -69
  24. package/dist/types/client.d.ts +0 -1
  25. package/dist/types/errors.d.ts +5 -0
  26. package/dist/types/handles/deferred-resolution.d.ts +2 -1
  27. package/dist/types/handles/pushed-by.d.ts +23 -0
  28. package/dist/types/loader-store.d.ts +8 -0
  29. package/dist/types/prefetch-markers.d.ts +11 -0
  30. package/dist/types/route-definition/helpers-types.d.ts +27 -0
  31. package/dist/types/router/is-action.d.ts +2 -1
  32. package/dist/types/router/segment-resolution/loader-mask.d.ts +3 -2
  33. package/dist/types/router/segment-resolution/prefetch-deferral.d.ts +241 -0
  34. package/dist/types/server/context.d.ts +21 -1
  35. package/dist/types/server/handle-store.d.ts +9 -1
  36. package/dist/types/server/request-context.d.ts +14 -1
  37. package/dist/types/server.d.ts +1 -0
  38. package/dist/types/testing/flight.entry.d.ts +1 -1
  39. package/dist/types/testing/index.d.ts +3 -3
  40. package/dist/types/testing/internal/action-id.d.ts +10 -1
  41. package/dist/types/testing/internal/client-urls-projection.d.ts +16 -0
  42. package/dist/types/testing/internal/test-action.d.ts +8 -0
  43. package/dist/types/testing/run-loader.d.ts +2 -1
  44. package/dist/types/testing/run-revalidate.d.ts +74 -0
  45. package/dist/types/testing/run-transition-when.d.ts +2 -3
  46. package/dist/types/testing/serve-shell-request.d.ts +38 -0
  47. package/dist/types/testing/vitest.d.ts +11 -0
  48. package/dist/types/types/boundaries.d.ts +9 -0
  49. package/dist/types/types/handler-context.d.ts +14 -0
  50. package/dist/types/types/loader-types.d.ts +30 -0
  51. package/dist/types/types/segments.d.ts +21 -4
  52. package/dist/types/urls/path-helper-types.d.ts +25 -4
  53. package/dist/types/urls/type-extraction.d.ts +6 -2
  54. package/dist/types/vite/discovery/discover-routers.d.ts +9 -0
  55. package/dist/types/vite/discovery/state.d.ts +11 -4
  56. package/dist/types/vite/plugins/client-urls-revalidate-hoist.d.ts +54 -0
  57. package/dist/types/vite/plugins/hoist/literal.d.ts +83 -0
  58. package/dist/types/vite/plugins/hoist/scope.d.ts +40 -0
  59. package/dist/types/vite/plugins/hoist/source.d.ts +41 -0
  60. package/dist/types/vite/plugins/transition-when-hoist.d.ts +8 -11
  61. package/dist/types/vite/router-discovery.d.ts +10 -0
  62. package/dist/vite/index.js +842 -308
  63. package/package.json +1 -1
  64. package/skills/caching/SKILL.md +42 -5
  65. package/skills/catalog.json +2 -2
  66. package/skills/client-urls/SKILL.md +113 -24
  67. package/skills/cloudflare/SKILL.md +14 -9
  68. package/skills/hooks/SKILL.md +11 -3
  69. package/skills/links/SKILL.md +24 -0
  70. package/skills/loader/SKILL.md +192 -1
  71. package/skills/migrate-nextjs/SKILL.md +2 -2
  72. package/skills/migrate-react-router/SKILL.md +10 -7
  73. package/skills/migrate-react-router/data-and-actions.md +1 -1
  74. package/skills/ppr/SKILL.md +13 -0
  75. package/skills/prerender/SKILL.md +22 -8
  76. package/skills/rango/SKILL.md +12 -6
  77. package/skills/route/SKILL.md +139 -0
  78. package/skills/testing/SKILL.md +3 -2
  79. package/skills/testing/client-components.md +1 -1
  80. package/skills/testing/predicates.md +67 -32
  81. package/skills/testing/serve-shell-request.md +88 -18
  82. package/skills/testing/setup.md +2 -2
  83. package/skills/typesafety/route-types.md +2 -2
  84. package/skills/view-transitions/SKILL.md +26 -0
  85. package/src/browser/defer.ts +82 -0
  86. package/src/browser/document-revealed.ts +52 -0
  87. package/src/browser/event-controller.ts +43 -32
  88. package/src/browser/navigation-bridge.ts +64 -14
  89. package/src/browser/navigation-client.ts +48 -36
  90. package/src/browser/navigation-store.ts +13 -0
  91. package/src/browser/navigation-transaction.ts +25 -8
  92. package/src/browser/partial-update.ts +528 -135
  93. package/src/browser/prefetch/fetch.ts +2 -1
  94. package/src/browser/react/NavigationProvider.tsx +47 -28
  95. package/src/browser/react/filter-segment-order.ts +13 -2
  96. package/src/browser/response-adapter.ts +20 -0
  97. package/src/browser/rsc-router.tsx +17 -45
  98. package/src/browser/server-action-bridge.ts +19 -63
  99. package/src/browser/types.ts +19 -9
  100. package/src/browser/validate-redirect-origin.ts +16 -0
  101. package/src/build/generate-route-types.ts +1 -0
  102. package/src/build/route-types/router-processing.ts +3 -6
  103. package/src/build/route-types/scan-filter.ts +37 -10
  104. package/src/cache/cf/cf-cache-store.ts +59 -21
  105. package/src/cache/cf/cf-cache-types.ts +24 -2
  106. package/src/cache/document-cache.ts +22 -1
  107. package/src/client-urls/client-urls.ts +22 -6
  108. package/src/client-urls/hoisted-revalidate.ts +25 -0
  109. package/src/client-urls/navigation.ts +0 -96
  110. package/src/client-urls/revalidate-registry.ts +30 -0
  111. package/src/client-urls/server-projection.ts +151 -65
  112. package/src/client-urls/types.ts +39 -71
  113. package/src/client.tsx +9 -5
  114. package/src/errors.ts +15 -0
  115. package/src/handles/deferred-resolution.ts +28 -5
  116. package/src/handles/pushed-by.ts +122 -0
  117. package/src/loader-store.ts +18 -7
  118. package/src/prefetch-markers.ts +13 -0
  119. package/src/route-content-wrapper.tsx +18 -4
  120. package/src/route-definition/dsl-helpers.ts +27 -4
  121. package/src/route-definition/helpers-types.ts +27 -1
  122. package/src/router/intercept-resolution.ts +6 -4
  123. package/src/router/is-action.ts +2 -1
  124. package/src/router/loader-resolution.ts +83 -4
  125. package/src/router/match-api.ts +36 -1
  126. package/src/router/match-middleware/background-revalidation.ts +11 -1
  127. package/src/router/match-middleware/cache-lookup.ts +29 -6
  128. package/src/router/match-middleware/cache-store.ts +17 -1
  129. package/src/router/match-result.ts +14 -2
  130. package/src/router/navigation-snapshot.ts +2 -1
  131. package/src/router/segment-resolution/fresh.ts +22 -18
  132. package/src/router/segment-resolution/loader-cache.ts +2 -1
  133. package/src/router/segment-resolution/loader-mask.ts +5 -3
  134. package/src/router/segment-resolution/prefetch-deferral.ts +543 -0
  135. package/src/router/segment-resolution/revalidation.ts +169 -60
  136. package/src/rsc/rsc-rendering.ts +50 -7
  137. package/src/rsc/shell-capture.ts +2 -1
  138. package/src/segment-loader-promise.ts +23 -20
  139. package/src/segment-system.tsx +60 -26
  140. package/src/server/context.ts +39 -5
  141. package/src/server/handle-store.ts +104 -8
  142. package/src/server/request-context.ts +21 -1
  143. package/src/server.ts +4 -0
  144. package/src/testing/action-form.ts +2 -11
  145. package/src/testing/e2e/page-helpers.ts +3 -1
  146. package/src/testing/flight.entry.ts +1 -0
  147. package/src/testing/index.ts +6 -3
  148. package/src/testing/internal/action-id.ts +16 -1
  149. package/src/testing/internal/client-urls-projection.ts +70 -0
  150. package/src/testing/internal/test-action.ts +25 -0
  151. package/src/testing/run-loader.ts +2 -1
  152. package/src/testing/run-revalidate.ts +142 -0
  153. package/src/testing/run-transition-when.ts +7 -8
  154. package/src/testing/serve-shell-request.ts +116 -6
  155. package/src/testing/vitest.ts +67 -1
  156. package/src/types/boundaries.ts +12 -0
  157. package/src/types/handler-context.ts +14 -0
  158. package/src/types/loader-types.ts +30 -0
  159. package/src/types/segments.ts +26 -4
  160. package/src/urls/path-helper-types.ts +27 -5
  161. package/src/urls/type-extraction.ts +30 -10
  162. package/src/use-loader.tsx +18 -13
  163. package/src/vite/discovery/client-urls-projection.ts +20 -21
  164. package/src/vite/discovery/discover-routers.ts +94 -26
  165. package/src/vite/discovery/state.ts +20 -4
  166. package/src/vite/discovery/virtual-module-codegen.ts +22 -17
  167. package/src/vite/plugins/client-urls-revalidate-hoist.ts +564 -0
  168. package/src/vite/plugins/hoist/literal.ts +417 -0
  169. package/src/vite/plugins/hoist/scope.ts +370 -0
  170. package/src/vite/plugins/hoist/source.ts +84 -0
  171. package/src/vite/plugins/transition-when-hoist.ts +113 -779
  172. package/src/vite/rango.ts +2 -0
  173. package/src/vite/router-discovery.ts +93 -32
  174. package/dist/types/client-urls/revalidate-chain.d.ts +0 -33
  175. package/dist/types/client-urls/revalidation-protocol.d.ts +0 -25
  176. package/dist/types/testing/run-client-revalidate.d.ts +0 -43
  177. package/src/client-urls/revalidate-chain.ts +0 -83
  178. package/src/client-urls/revalidation-protocol.ts +0 -56
  179. package/src/testing/run-client-revalidate.ts +0 -92
@@ -0,0 +1,543 @@
1
+ /**
2
+ * `prefetch: false`: what a prefetch request defers and what its fill request
3
+ * runs (docs/design/prefetch-false.md).
4
+ *
5
+ * Two layers. The SCOPE is static per matched chain: which loader
6
+ * registrations are deferrable and which entries can be a handler unit. The
7
+ * PLAN is per match and rides the handler context
8
+ * (InternalHandlerContext._prefetchDeferral): the request's mode and where the
9
+ * chain's stored handler output starts. A request context cannot carry it: a
10
+ * shell capture derives its context from the request that scheduled it and
11
+ * would inherit a prefetch's mode.
12
+ *
13
+ * The decisions themselves are made in revalidation.ts, by asking this module.
14
+ *
15
+ * One rule runs through every decision: the flag applies only to a segment
16
+ * the client does not have yet. A segment the client holds is never deferred,
17
+ * whether or not it re-renders, and nothing is deferred because of it. A
18
+ * placeholder over content that is on screen would replace it with a fallback,
19
+ * or make the click wait where a plain navigation would not.
20
+ *
21
+ * "Holds" is what the request listed in `_rsc_segments` (PrefetchDeferral.held),
22
+ * the set buildMatchResult (match-result.ts) filters the response with. Not
23
+ * the set resolution works on: the match deletes a route's id from that one to
24
+ * force a same-route render from an intercept source (match-api.ts), and a
25
+ * unit deferred on that ground would be dropped from the response as held.
26
+ */
27
+
28
+ import {
29
+ getParallelEntries,
30
+ getParallelSlotEntries,
31
+ isPprEntry,
32
+ type EntryData,
33
+ type LoaderEntry,
34
+ } from "../../server/context.js";
35
+ import { requestHeaders } from "../../server/request-headers.js";
36
+ import type { HandlerContext, InternalHandlerContext } from "../../types.js";
37
+ import type { CacheScope } from "../../cache/cache-scope.js";
38
+ import { FILL_PARAM, PREFETCH_HEADER } from "../../prefetch-markers.js";
39
+
40
+ /**
41
+ * What a request says it is, read once when its context is created
42
+ * (RequestContext._requestKind). A fill is marked on the raw URL and wins
43
+ * over the prefetch header. Whether a prefetch defers anything is decided per
44
+ * match, by partialDeferralMode: a shell capture inherits the context of the
45
+ * request that scheduled it and is never a prefetch.
46
+ */
47
+ export function requestKind(
48
+ request: Request,
49
+ rawUrl: URL,
50
+ ): "prefetch" | "fill" | undefined {
51
+ if (rawUrl.searchParams.has(FILL_PARAM)) return "fill";
52
+ return requestHeaders(request).has(PREFETCH_HEADER) ? "prefetch" : undefined;
53
+ }
54
+
55
+ /** Static, per matched chain. */
56
+ interface DeferralScope {
57
+ /**
58
+ * Loader registrations a prefetch can defer, each with what makes it so:
59
+ * `true` for its own flag, else the segment ids of the flagged entries whose
60
+ * fallback covers it. A covered loader is deferred only while one of those
61
+ * segments is new to the client.
62
+ */
63
+ readonly loaders: ReadonlyMap<LoaderEntry, true | readonly string[]>;
64
+ /** `$$id`s of `loaders`: the loaders that cannot call ctx.rendered(). */
65
+ readonly loaderIds: ReadonlySet<string>;
66
+ /**
67
+ * Entries whose handler a prefetch can skip (a flagged loading() with a
68
+ * fallback to show). `index` is the chain index that owns the entry: its
69
+ * own for a chain entry, its parent's for a parallel entry. `ids` are its
70
+ * segment ids: the entry's for a chain entry, one per slot for a parallel
71
+ * entry.
72
+ */
73
+ readonly units: ReadonlyMap<EntryData, DeferralUnit>;
74
+ }
75
+
76
+ interface DeferralUnit {
77
+ readonly index: number;
78
+ readonly ids: readonly string[];
79
+ }
80
+
81
+ /** Per match: InternalHandlerContext._prefetchDeferral. */
82
+ export interface PrefetchDeferral {
83
+ readonly scope: DeferralScope;
84
+ /**
85
+ * "prefetch": deferral replaces execution. "fill": the request that follows
86
+ * an adopted prefetch; a held segment is skipped outright. Unset on every
87
+ * other request, where the plan only feeds the ctx.rendered() guards.
88
+ */
89
+ readonly mode?: "prefetch" | "fill";
90
+ /**
91
+ * First chain index whose handler output is stored or about to be (a
92
+ * cache() boundary, a ppr or Prerender route): no unit at or below it.
93
+ */
94
+ readonly storedFrom: number;
95
+ /** The segment ids the request listed as held (`_rsc_segments`). */
96
+ readonly held: ReadonlySet<string>;
97
+ /**
98
+ * Segment ids of the handler units this prefetch skips: every unit that is
99
+ * not stored and not held. Empty outside a prefetch.
100
+ */
101
+ readonly skipped: ReadonlySet<string>;
102
+ /**
103
+ * One of `skipped` is a chain entry: nothing below it runs, so the response
104
+ * has no content for it, a route cache() record included.
105
+ */
106
+ readonly skipsChain: boolean;
107
+ /** Segment id of the handler unit this prefetch skipped. */
108
+ deferredUnit?: string;
109
+ /**
110
+ * The walk is below a chain unit it skipped (resolution is in chain order,
111
+ * a route's orphan layouts and slots after its handler): every handler it
112
+ * reaches from here on is skipped too, and sends a placeholder with what
113
+ * the entry declares. The browser builds the page's tree once, from those
114
+ * (browser/partial-update.ts armHoles), so they have to list every segment
115
+ * a navigation to the page lists.
116
+ */
117
+ below?: true;
118
+ /**
119
+ * The loaders this prefetch deferred, by `$$id` (registerDeferredLoader).
120
+ * A deferred loader runs only if something reads it: a handler's or another
121
+ * loader's ctx.use() starts it through its registration
122
+ * (startDeferredLoader), and revalidation.ts deliverStartedLoaders delivers
123
+ * what was started by the end of resolution.
124
+ */
125
+ deferredLoaders?: Map<string, DeferredLoader>;
126
+ }
127
+
128
+ /** A loader this prefetch deferred: PrefetchDeferral.deferredLoaders. */
129
+ export interface DeferredLoader {
130
+ /**
131
+ * The segment that registers it. Its run files its handle pushes there,
132
+ * where a navigation's run of it files them, not under the reader
133
+ * (loaderOwner).
134
+ */
135
+ readonly owner: string;
136
+ /**
137
+ * Starts it as resolution would have: resolveLoaderData with its cache()
138
+ * binding, so the reader and the delivered segment share one value.
139
+ */
140
+ readonly start: () => Promise<unknown>;
141
+ /** A reader started it. */
142
+ started?: true;
143
+ }
144
+
145
+ const EMPTY_SCOPE: DeferralScope = {
146
+ loaders: new Map(),
147
+ loaderIds: new Set(),
148
+ units: new Map(),
149
+ };
150
+
151
+ const scopes = new WeakMap<EntryData, DeferralScope>();
152
+ const warnedBakeLoaders = new Set<string>();
153
+
154
+ /**
155
+ * The deferral scope of a matched chain, memoized on its leaf entry (entries
156
+ * are per-isSSR manifest objects, replaced on HMR). EMPTY_SCOPE when nothing
157
+ * in the tree declares `prefetch: false`.
158
+ */
159
+ export function resolveDeferralScope(
160
+ entries: readonly EntryData[],
161
+ ): DeferralScope {
162
+ const leaf = entries[entries.length - 1];
163
+ if (!leaf) return EMPTY_SCOPE;
164
+ const cached = scopes.get(leaf);
165
+ if (cached) return cached;
166
+
167
+ const loaders = new Map<LoaderEntry, true | readonly string[]>();
168
+ const loaderIds = new Set<string>();
169
+ const units = new Map<EntryData, DeferralUnit>();
170
+ const chain = new Set(entries);
171
+ // ssr: false on a ppr route is the bake lane (loader-cache.ts
172
+ // resolveLoaderData): shell material, served from the record.
173
+ const pprRoute = isPprEntry(leaf);
174
+ // A clientUrls() group route renders loading() itself and its handler is
175
+ // ClientUrlsRoot (segment-system.tsx keys it by group): a unit would hand
176
+ // React a promise in place of the optimistic destination on screen. So
177
+ // in its chain only a loader's own flag counts, the group's and a server
178
+ // layout's above it; a flagged loading() defers nothing.
179
+ const clientGroupChain = leaf.clientGroup !== undefined;
180
+ const flagsLoading = (entry: EntryData): boolean =>
181
+ !clientGroupChain && entry.loadingPrefetch === false;
182
+
183
+ // `behind`: the segment ids of the flagged entries whose fallback covers
184
+ // `entry`'s loaders.
185
+ const collect = (
186
+ entry: EntryData,
187
+ behind: readonly string[],
188
+ index: number,
189
+ ): void => {
190
+ for (const loaderEntry of entry.loader ?? []) {
191
+ const own = loaderEntry.prefetch === false;
192
+ if (!own && behind.length === 0) continue;
193
+ if (pprRoute && loaderEntry.bake) {
194
+ if (
195
+ process.env.NODE_ENV !== "production" &&
196
+ loaderEntry.prefetch === false &&
197
+ !warnedBakeLoaders.has(loaderEntry.loader.$$id)
198
+ ) {
199
+ warnedBakeLoaders.add(loaderEntry.loader.$$id);
200
+ console.warn(
201
+ `[rango] loader "${loaderEntry.loader.$$id}" is registered with ssr: false and prefetch: false on a ppr route ("${leaf.id}"). ` +
202
+ `Under ppr an ssr: false loader is baked into the shell and served from it, so prefetch: false is ignored there. Drop one of the two options.`,
203
+ );
204
+ }
205
+ continue;
206
+ }
207
+ loaders.set(loaderEntry, own ? true : behind);
208
+ loaderIds.add(loaderEntry.loader.$$id);
209
+ }
210
+ for (const parallelEntry of getParallelEntries(entry.parallel)) {
211
+ // A slot's segment id, as resolveParallelSegmentsWithRevalidation
212
+ // (revalidation.ts) forms it.
213
+ const slotIds = flagsLoading(parallelEntry)
214
+ ? getParallelSlotEntries(entry.parallel)
215
+ .filter((slot) => slot.entry === parallelEntry)
216
+ .map((slot) => `${entry.shortCode}.${slot.slot}`)
217
+ : [];
218
+ if (slotIds.length > 0) units.set(parallelEntry, { index, ids: slotIds });
219
+ collect(parallelEntry, [...behind, ...slotIds], index);
220
+ }
221
+ for (const orphan of entry.layout) {
222
+ if (chain.has(orphan)) continue;
223
+ // An orphan layout's handler is awaited after its owner's ran
224
+ // (revalidation.ts resolveOrphanLayoutWithRevalidation): never a unit,
225
+ // its loaders are still behind its fallback.
226
+ collect(
227
+ orphan,
228
+ flagsLoading(orphan) ? [...behind, orphan.shortCode] : behind,
229
+ index,
230
+ );
231
+ }
232
+ };
233
+
234
+ let behind: readonly string[] = [];
235
+ entries.forEach((entry, index) => {
236
+ const flagged = flagsLoading(entry);
237
+ if (flagged) units.set(entry, { index, ids: [entry.shortCode] });
238
+ const own = flagged ? [...behind, entry.shortCode] : behind;
239
+ collect(entry, own, index);
240
+ // A layout's fallback covers its outlet: every deeper chain entry.
241
+ if (flagged && entry.type !== "route") behind = own;
242
+ });
243
+
244
+ const scope: DeferralScope =
245
+ loaders.size === 0 && units.size === 0
246
+ ? EMPTY_SCOPE
247
+ : { loaders, loaderIds, units };
248
+ scopes.set(leaf, scope);
249
+ return scope;
250
+ }
251
+
252
+ /**
253
+ * Which half of the feature a partial request is, if either (`fill` and
254
+ * `prefetch` are requestKind's answer). Both halves are GETs: a request of
255
+ * another method that carries either marker is a normal request. A prefetch
256
+ * defers only on a plain GET navigation: an action re-renders what it
257
+ * changed, an intercept resolves its loaders outside the shared funnel, and a
258
+ * shell capture is never a prefetch whatever the request that scheduled it
259
+ * sent. The four conditions overlap today (an action is a POST, a capture
260
+ * runs the full match): each one states its own reason.
261
+ */
262
+ export function partialDeferralMode(request: {
263
+ fill: boolean;
264
+ prefetch: boolean;
265
+ method: string;
266
+ isAction: boolean;
267
+ isIntercept: boolean;
268
+ isShellCapture: boolean;
269
+ }): PrefetchDeferral["mode"] {
270
+ if (request.method !== "GET") return undefined;
271
+ if (request.fill) return "fill";
272
+ return request.prefetch &&
273
+ !request.isAction &&
274
+ !request.isIntercept &&
275
+ !request.isShellCapture
276
+ ? "prefetch"
277
+ : undefined;
278
+ }
279
+
280
+ const NOTHING_HELD: ReadonlySet<string> = new Set();
281
+
282
+ /**
283
+ * The plan for one match, or undefined when the tree declares no flag and the
284
+ * request is not a fill (the common case: nothing to carry). `held` is the
285
+ * client's segment ids as the request listed them.
286
+ */
287
+ export function planPrefetchDeferral(
288
+ entries: readonly EntryData[],
289
+ mode: PrefetchDeferral["mode"],
290
+ matched: { pr?: boolean; od?: boolean },
291
+ cacheScope: CacheScope | null | undefined,
292
+ held: ReadonlySet<string> = NOTHING_HELD,
293
+ ): PrefetchDeferral | undefined {
294
+ const scope = resolveDeferralScope(entries);
295
+ if (scope === EMPTY_SCOPE && mode !== "fill") return undefined;
296
+
297
+ const leaf = entries[entries.length - 1];
298
+ let storedFrom = Infinity;
299
+ if (
300
+ matched.pr ||
301
+ matched.od ||
302
+ (leaf &&
303
+ (isPprEntry(leaf) ||
304
+ // A Prerender route is stored whether or not this request found the
305
+ // artifact (dev renders it live): the rule is the declaration's.
306
+ (leaf.type === "route" && leaf.isPrerender)))
307
+ ) {
308
+ storedFrom = 0;
309
+ } else if (cacheScope?.enabled) {
310
+ // The same index withCacheLookup resolves its live entries above.
311
+ storedFrom =
312
+ cacheScope.boundary === undefined
313
+ ? 0
314
+ : Math.max(
315
+ 0,
316
+ entries.findIndex((e) => e.shortCode === cacheScope.boundary),
317
+ );
318
+ }
319
+
320
+ const skipped = new Set<string>();
321
+ let skipsChain = false;
322
+ if (mode === "prefetch") {
323
+ for (const [entry, unit] of scope.units) {
324
+ if (!unitEligible(storedFrom, entry, unit)) continue;
325
+ for (const id of unit.ids) {
326
+ if (held.has(id)) continue;
327
+ skipped.add(id);
328
+ if (entry.type !== "parallel") skipsChain = true;
329
+ }
330
+ }
331
+ }
332
+ return { scope, mode, storedFrom, held, skipped, skipsChain };
333
+ }
334
+
335
+ export function getPrefetchDeferral(
336
+ ctx: HandlerContext<any, any> | undefined,
337
+ ): PrefetchDeferral | undefined {
338
+ return (ctx as InternalHandlerContext<any, any> | undefined)
339
+ ?._prefetchDeferral;
340
+ }
341
+
342
+ /** The request is a fill: a held segment is skipped without consulting anything. */
343
+ export function isFillRequest(ctx: HandlerContext<any, any>): boolean {
344
+ return getPrefetchDeferral(ctx)?.mode === "fill";
345
+ }
346
+
347
+ /**
348
+ * Register a loader this prefetch deferred, with the segment that registers
349
+ * it and how to start it there (PrefetchDeferral.deferredLoaders). The first
350
+ * registration wins, as the loader's one run per request does.
351
+ */
352
+ export function registerDeferredLoader(
353
+ ctx: HandlerContext<any, any>,
354
+ loaderId: string,
355
+ owner: string,
356
+ start: () => Promise<unknown>,
357
+ ): void {
358
+ const plan = getPrefetchDeferral(ctx);
359
+ if (plan && !plan.deferredLoaders?.has(loaderId)) {
360
+ (plan.deferredLoaders ??= new Map()).set(loaderId, { owner, start });
361
+ }
362
+ }
363
+
364
+ /**
365
+ * A reader asks for a loader this prefetch deferred and nothing has started:
366
+ * start it through its registration and return the run, or undefined when
367
+ * the read takes the ordinary path. Without this the reader ran the loader
368
+ * bare, without its cache() binding, and the segment delivered afterwards
369
+ * read the binding: two values on one page and an extra run on a HIT.
370
+ *
371
+ * A started cache() binding of the loader (`_loaderCacheOverrides`) is never
372
+ * redirected here: the read is that binding's own MISS execution, and
373
+ * starting the registration would hand the binding its own pending value.
374
+ */
375
+ export function startDeferredLoader(
376
+ ctx: HandlerContext<any, any>,
377
+ loaderId: string,
378
+ ): Promise<unknown> | undefined {
379
+ const internal = ctx as InternalHandlerContext<any, any>;
380
+ const deferred = internal._prefetchDeferral?.deferredLoaders?.get(loaderId);
381
+ if (
382
+ !deferred ||
383
+ deferred.started ||
384
+ internal._loaderCacheOverrides?.has(loaderId)
385
+ ) {
386
+ return undefined;
387
+ }
388
+ deferred.started = true;
389
+ return deferred.start();
390
+ }
391
+
392
+ /**
393
+ * The segment a run of `loaderId` files its handle pushes under: the one
394
+ * that registers it when this prefetch deferred it, else the segment being
395
+ * resolved.
396
+ */
397
+ export function loaderOwner(
398
+ ctx: HandlerContext<any, any>,
399
+ loaderId: string,
400
+ ): string | undefined {
401
+ const internal = ctx as InternalHandlerContext<any, any>;
402
+ return (
403
+ internal._prefetchDeferral?.deferredLoaders?.get(loaderId)?.owner ??
404
+ internal._currentSegmentId
405
+ );
406
+ }
407
+
408
+ /**
409
+ * This prefetch defers `loaderEntry`, whose segment is `segmentId`: the client
410
+ * does not hold that segment, and the loader is flagged itself or sits behind
411
+ * the fallback of a flagged entry the client does not hold either. Under a
412
+ * flagged layout the client holds, a new route's loaders run.
413
+ */
414
+ export function defersLoader(
415
+ ctx: HandlerContext<any, any>,
416
+ loaderEntry: LoaderEntry,
417
+ segmentId: string,
418
+ ): boolean {
419
+ const plan = getPrefetchDeferral(ctx);
420
+ if (plan?.mode !== "prefetch" || plan.held.has(segmentId)) return false;
421
+ const by = plan.scope.loaders.get(loaderEntry);
422
+ return (
423
+ by === true || (by !== undefined && by.some((id) => !plan.held.has(id)))
424
+ );
425
+ }
426
+
427
+ /** A unit whose handler output is not stored: a prefetch can skip it. */
428
+ function unitEligible(
429
+ storedFrom: number,
430
+ entry: EntryData,
431
+ unit: DeferralUnit,
432
+ ): boolean {
433
+ return (
434
+ unit.index < storedFrom &&
435
+ !("isStaticPrerender" in entry && entry.isStaticPrerender)
436
+ );
437
+ }
438
+
439
+ /**
440
+ * This prefetch skips the handler of the entry whose segment is `segmentId`:
441
+ * a unit the client does not hold, or anything the client does not hold
442
+ * below one (belowDeferredUnit). A held segment that re-renders is rendered
443
+ * by the prefetch, as by a navigation.
444
+ */
445
+ export function defersUnit(
446
+ ctx: HandlerContext<any, any>,
447
+ segmentId: string,
448
+ ): boolean {
449
+ return (
450
+ getPrefetchDeferral(ctx)?.skipped.has(segmentId) === true ||
451
+ belowDeferredUnit(ctx, segmentId)
452
+ );
453
+ }
454
+
455
+ /**
456
+ * `segmentId` is new to the client and the walk is below a chain unit this
457
+ * prefetch skipped (PrefetchDeferral.below). Nothing of such a segment runs
458
+ * in the prefetch, a slot's revalidate() predicates included: on a new
459
+ * segment they cannot change the outcome, and what they would read from
460
+ * context was set by handlers that did not run.
461
+ */
462
+ export function belowDeferredUnit(
463
+ ctx: HandlerContext<any, any>,
464
+ segmentId: string,
465
+ ): boolean {
466
+ const plan = getPrefetchDeferral(ctx);
467
+ return plan?.below === true && !plan.held.has(segmentId);
468
+ }
469
+
470
+ /**
471
+ * A unit candidate that is not stored: a prefetch of this tree can skip a
472
+ * handler. Returns its entry (the first in chain order), for the
473
+ * ctx.rendered() guards (loader-resolution.ts).
474
+ */
475
+ export function firstUnitCandidate(
476
+ plan: PrefetchDeferral,
477
+ ): EntryData | undefined {
478
+ for (const [entry, unit] of plan.scope.units) {
479
+ if (unitEligible(plan.storedFrom, entry, unit)) return entry;
480
+ }
481
+ return undefined;
482
+ }
483
+
484
+ /**
485
+ * This prefetch skips a layout above the route cache's boundary, and with it
486
+ * everything the record below holds: withCacheLookup and withCacheStore leave
487
+ * the record alone for it. Decided per request, from what the client holds:
488
+ * a prefetch of the same tree that holds the layout reads and writes the
489
+ * record like any other request.
490
+ */
491
+ export function defersAboveRecord(ctx: HandlerContext<any, any>): boolean {
492
+ return getPrefetchDeferral(ctx)?.skipsChain === true;
493
+ }
494
+
495
+ /**
496
+ * Record the handler unit this prefetch skipped. A `chain` entry takes what
497
+ * the walk reaches after it (PrefetchDeferral.below); a slot is skipped
498
+ * alone.
499
+ */
500
+ export function markUnitDeferred(
501
+ ctx: HandlerContext<any, any>,
502
+ segmentId: string,
503
+ chain?: boolean,
504
+ ): void {
505
+ const plan = getPrefetchDeferral(ctx);
506
+ if (!plan) return;
507
+ plan.deferredUnit ??= segmentId;
508
+ if (chain) plan.below = true;
509
+ }
510
+
511
+ /** What the segment of a unit a prefetch skipped carries. */
512
+ const DEFERRED = { deferred: true } as const;
513
+
514
+ /**
515
+ * Whether this prefetch skips the handler of the unit whose segment is
516
+ * `segmentId`, recorded: the flag the segment carries
517
+ * (ResolvedSegment.deferred), or undefined when the handler runs.
518
+ * - `chain`: a chain entry, its own unit or below one (defersUnit). The walk
519
+ * takes what it reaches after it (markUnitDeferred).
520
+ * - `slot`: a slot that is its own unit, skipped alone.
521
+ * - `below`: what the walk reaches below a chain unit it skipped
522
+ * (belowDeferredUnit): a slot, before its predicates run, and an orphan
523
+ * layout, which is never a unit of its own (resolveDeferralScope). The unit
524
+ * above is recorded already.
525
+ */
526
+ export function deferUnit(
527
+ ctx: HandlerContext<any, any>,
528
+ segmentId: string,
529
+ kind: "chain" | "slot" | "below",
530
+ ): { readonly deferred: true } | undefined {
531
+ if (kind === "below") {
532
+ return belowDeferredUnit(ctx, segmentId) ? DEFERRED : undefined;
533
+ }
534
+ if (
535
+ kind === "chain"
536
+ ? !defersUnit(ctx, segmentId)
537
+ : getPrefetchDeferral(ctx)?.skipped.has(segmentId) !== true
538
+ ) {
539
+ return undefined;
540
+ }
541
+ markUnitDeferred(ctx, segmentId, kind === "chain");
542
+ return DEFERRED;
543
+ }