@rangojs/router 0.0.0-experimental.8 → 0.0.0-experimental.80

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 (312) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +942 -4
  3. package/dist/bin/rango.js +1689 -0
  4. package/dist/vite/index.js +4960 -935
  5. package/package.json +70 -60
  6. package/skills/breadcrumbs/SKILL.md +250 -0
  7. package/skills/cache-guide/SKILL.md +294 -0
  8. package/skills/caching/SKILL.md +93 -23
  9. package/skills/composability/SKILL.md +172 -0
  10. package/skills/debug-manifest/SKILL.md +12 -8
  11. package/skills/document-cache/SKILL.md +18 -16
  12. package/skills/fonts/SKILL.md +167 -0
  13. package/skills/handler-use/SKILL.md +362 -0
  14. package/skills/hooks/SKILL.md +334 -72
  15. package/skills/host-router/SKILL.md +218 -0
  16. package/skills/intercept/SKILL.md +151 -8
  17. package/skills/layout/SKILL.md +122 -3
  18. package/skills/links/SKILL.md +92 -31
  19. package/skills/loader/SKILL.md +404 -44
  20. package/skills/middleware/SKILL.md +205 -37
  21. package/skills/migrate-nextjs/SKILL.md +560 -0
  22. package/skills/migrate-react-router/SKILL.md +764 -0
  23. package/skills/mime-routes/SKILL.md +128 -0
  24. package/skills/parallel/SKILL.md +263 -1
  25. package/skills/prerender/SKILL.md +685 -0
  26. package/skills/rango/SKILL.md +87 -16
  27. package/skills/response-routes/SKILL.md +411 -0
  28. package/skills/route/SKILL.md +281 -14
  29. package/skills/router-setup/SKILL.md +210 -32
  30. package/skills/tailwind/SKILL.md +129 -0
  31. package/skills/theme/SKILL.md +9 -8
  32. package/skills/typesafety/SKILL.md +328 -89
  33. package/skills/use-cache/SKILL.md +324 -0
  34. package/src/__internal.ts +102 -4
  35. package/src/bin/rango.ts +321 -0
  36. package/src/browser/action-coordinator.ts +97 -0
  37. package/src/browser/action-response-classifier.ts +99 -0
  38. package/src/browser/app-version.ts +14 -0
  39. package/src/browser/event-controller.ts +92 -64
  40. package/src/browser/history-state.ts +80 -0
  41. package/src/browser/intercept-utils.ts +52 -0
  42. package/src/browser/link-interceptor.ts +24 -4
  43. package/src/browser/logging.ts +55 -0
  44. package/src/browser/merge-segment-loaders.ts +20 -12
  45. package/src/browser/navigation-bridge.ts +317 -560
  46. package/src/browser/navigation-client.ts +206 -68
  47. package/src/browser/navigation-store.ts +73 -55
  48. package/src/browser/navigation-transaction.ts +297 -0
  49. package/src/browser/network-error-handler.ts +61 -0
  50. package/src/browser/partial-update.ts +343 -316
  51. package/src/browser/prefetch/cache.ts +216 -0
  52. package/src/browser/prefetch/fetch.ts +206 -0
  53. package/src/browser/prefetch/observer.ts +65 -0
  54. package/src/browser/prefetch/policy.ts +48 -0
  55. package/src/browser/prefetch/queue.ts +160 -0
  56. package/src/browser/prefetch/resource-ready.ts +77 -0
  57. package/src/browser/rango-state.ts +112 -0
  58. package/src/browser/react/Link.tsx +253 -74
  59. package/src/browser/react/NavigationProvider.tsx +87 -11
  60. package/src/browser/react/context.ts +11 -0
  61. package/src/browser/react/filter-segment-order.ts +11 -0
  62. package/src/browser/react/index.ts +12 -12
  63. package/src/browser/react/location-state-shared.ts +95 -53
  64. package/src/browser/react/location-state.ts +60 -15
  65. package/src/browser/react/mount-context.ts +6 -1
  66. package/src/browser/react/nonce-context.ts +23 -0
  67. package/src/browser/react/shallow-equal.ts +27 -0
  68. package/src/browser/react/use-action.ts +29 -51
  69. package/src/browser/react/use-client-cache.ts +5 -3
  70. package/src/browser/react/use-handle.ts +30 -126
  71. package/src/browser/react/use-href.tsx +2 -2
  72. package/src/browser/react/use-link-status.ts +6 -5
  73. package/src/browser/react/use-navigation.ts +44 -65
  74. package/src/browser/react/use-params.ts +65 -0
  75. package/src/browser/react/use-pathname.ts +47 -0
  76. package/src/browser/react/use-router.ts +76 -0
  77. package/src/browser/react/use-search-params.ts +56 -0
  78. package/src/browser/react/use-segments.ts +80 -97
  79. package/src/browser/response-adapter.ts +73 -0
  80. package/src/browser/rsc-router.tsx +214 -58
  81. package/src/browser/scroll-restoration.ts +127 -52
  82. package/src/browser/segment-reconciler.ts +243 -0
  83. package/src/browser/segment-structure-assert.ts +16 -0
  84. package/src/browser/server-action-bridge.ts +510 -603
  85. package/src/browser/shallow.ts +6 -1
  86. package/src/browser/types.ts +141 -48
  87. package/src/browser/validate-redirect-origin.ts +29 -0
  88. package/src/build/generate-manifest.ts +235 -24
  89. package/src/build/generate-route-types.ts +39 -0
  90. package/src/build/index.ts +13 -0
  91. package/src/build/route-trie.ts +291 -0
  92. package/src/build/route-types/ast-helpers.ts +25 -0
  93. package/src/build/route-types/ast-route-extraction.ts +98 -0
  94. package/src/build/route-types/codegen.ts +102 -0
  95. package/src/build/route-types/include-resolution.ts +418 -0
  96. package/src/build/route-types/param-extraction.ts +48 -0
  97. package/src/build/route-types/per-module-writer.ts +128 -0
  98. package/src/build/route-types/router-processing.ts +618 -0
  99. package/src/build/route-types/scan-filter.ts +85 -0
  100. package/src/build/runtime-discovery.ts +231 -0
  101. package/src/cache/background-task.ts +34 -0
  102. package/src/cache/cache-key-utils.ts +44 -0
  103. package/src/cache/cache-policy.ts +125 -0
  104. package/src/cache/cache-runtime.ts +342 -0
  105. package/src/cache/cache-scope.ts +167 -309
  106. package/src/cache/cf/cf-cache-store.ts +571 -17
  107. package/src/cache/cf/index.ts +13 -3
  108. package/src/cache/document-cache.ts +116 -77
  109. package/src/cache/handle-capture.ts +81 -0
  110. package/src/cache/handle-snapshot.ts +41 -0
  111. package/src/cache/index.ts +1 -15
  112. package/src/cache/memory-segment-store.ts +191 -13
  113. package/src/cache/profile-registry.ts +73 -0
  114. package/src/cache/read-through-swr.ts +134 -0
  115. package/src/cache/segment-codec.ts +256 -0
  116. package/src/cache/taint.ts +153 -0
  117. package/src/cache/types.ts +72 -122
  118. package/src/client.rsc.tsx +3 -1
  119. package/src/client.tsx +135 -301
  120. package/src/component-utils.ts +4 -4
  121. package/src/components/DefaultDocument.tsx +5 -1
  122. package/src/context-var.ts +156 -0
  123. package/src/debug.ts +19 -9
  124. package/src/errors.ts +108 -2
  125. package/src/handle.ts +55 -29
  126. package/src/handles/MetaTags.tsx +73 -20
  127. package/src/handles/breadcrumbs.ts +66 -0
  128. package/src/handles/index.ts +1 -0
  129. package/src/handles/meta.ts +30 -13
  130. package/src/host/cookie-handler.ts +21 -15
  131. package/src/host/errors.ts +8 -8
  132. package/src/host/index.ts +4 -7
  133. package/src/host/pattern-matcher.ts +27 -27
  134. package/src/host/router.ts +61 -39
  135. package/src/host/testing.ts +8 -8
  136. package/src/host/types.ts +15 -7
  137. package/src/host/utils.ts +1 -1
  138. package/src/href-client.ts +119 -29
  139. package/src/index.rsc.ts +155 -19
  140. package/src/index.ts +251 -30
  141. package/src/internal-debug.ts +11 -0
  142. package/src/loader.rsc.ts +26 -157
  143. package/src/loader.ts +27 -10
  144. package/src/network-error-thrower.tsx +3 -1
  145. package/src/outlet-provider.tsx +45 -0
  146. package/src/prerender/param-hash.ts +37 -0
  147. package/src/prerender/store.ts +186 -0
  148. package/src/prerender.ts +524 -0
  149. package/src/reverse.ts +354 -0
  150. package/src/root-error-boundary.tsx +41 -29
  151. package/src/route-content-wrapper.tsx +7 -4
  152. package/src/route-definition/dsl-helpers.ts +1121 -0
  153. package/src/route-definition/helper-factories.ts +200 -0
  154. package/src/route-definition/helpers-types.ts +478 -0
  155. package/src/route-definition/index.ts +55 -0
  156. package/src/route-definition/redirect.ts +101 -0
  157. package/src/route-definition/resolve-handler-use.ts +149 -0
  158. package/src/route-definition.ts +1 -1428
  159. package/src/route-map-builder.ts +217 -123
  160. package/src/route-name.ts +53 -0
  161. package/src/route-types.ts +77 -8
  162. package/src/router/content-negotiation.ts +215 -0
  163. package/src/router/debug-manifest.ts +72 -0
  164. package/src/router/error-handling.ts +9 -9
  165. package/src/router/find-match.ts +160 -0
  166. package/src/router/handler-context.ts +438 -86
  167. package/src/router/intercept-resolution.ts +402 -0
  168. package/src/router/lazy-includes.ts +237 -0
  169. package/src/router/loader-resolution.ts +356 -128
  170. package/src/router/logging.ts +251 -0
  171. package/src/router/manifest.ts +163 -35
  172. package/src/router/match-api.ts +555 -0
  173. package/src/router/match-context.ts +5 -3
  174. package/src/router/match-handlers.ts +440 -0
  175. package/src/router/match-middleware/background-revalidation.ts +108 -93
  176. package/src/router/match-middleware/cache-lookup.ts +460 -10
  177. package/src/router/match-middleware/cache-store.ts +98 -26
  178. package/src/router/match-middleware/intercept-resolution.ts +57 -17
  179. package/src/router/match-middleware/segment-resolution.ts +80 -6
  180. package/src/router/match-pipelines.ts +10 -45
  181. package/src/router/match-result.ts +135 -35
  182. package/src/router/metrics.ts +240 -15
  183. package/src/router/middleware-cookies.ts +55 -0
  184. package/src/router/middleware-types.ts +220 -0
  185. package/src/router/middleware.ts +324 -369
  186. package/src/router/navigation-snapshot.ts +182 -0
  187. package/src/router/pattern-matching.ts +211 -43
  188. package/src/router/prerender-match.ts +502 -0
  189. package/src/router/preview-match.ts +98 -0
  190. package/src/router/request-classification.ts +310 -0
  191. package/src/router/revalidation.ts +137 -38
  192. package/src/router/route-snapshot.ts +245 -0
  193. package/src/router/router-context.ts +41 -21
  194. package/src/router/router-interfaces.ts +484 -0
  195. package/src/router/router-options.ts +618 -0
  196. package/src/router/router-registry.ts +24 -0
  197. package/src/router/segment-resolution/fresh.ts +748 -0
  198. package/src/router/segment-resolution/helpers.ts +268 -0
  199. package/src/router/segment-resolution/loader-cache.ts +199 -0
  200. package/src/router/segment-resolution/revalidation.ts +1379 -0
  201. package/src/router/segment-resolution/static-store.ts +67 -0
  202. package/src/router/segment-resolution.ts +21 -0
  203. package/src/router/segment-wrappers.ts +291 -0
  204. package/src/router/telemetry-otel.ts +299 -0
  205. package/src/router/telemetry.ts +300 -0
  206. package/src/router/timeout.ts +148 -0
  207. package/src/router/trie-matching.ts +239 -0
  208. package/src/router/types.ts +78 -3
  209. package/src/router.ts +740 -4252
  210. package/src/rsc/handler-context.ts +45 -0
  211. package/src/rsc/handler.ts +907 -797
  212. package/src/rsc/helpers.ts +140 -6
  213. package/src/rsc/index.ts +0 -20
  214. package/src/rsc/loader-fetch.ts +229 -0
  215. package/src/rsc/manifest-init.ts +90 -0
  216. package/src/rsc/nonce.ts +14 -0
  217. package/src/rsc/origin-guard.ts +141 -0
  218. package/src/rsc/progressive-enhancement.ts +391 -0
  219. package/src/rsc/response-error.ts +37 -0
  220. package/src/rsc/response-route-handler.ts +347 -0
  221. package/src/rsc/rsc-rendering.ts +246 -0
  222. package/src/rsc/runtime-warnings.ts +42 -0
  223. package/src/rsc/server-action.ts +356 -0
  224. package/src/rsc/ssr-setup.ts +128 -0
  225. package/src/rsc/types.ts +46 -11
  226. package/src/search-params.ts +230 -0
  227. package/src/segment-content-promise.ts +67 -0
  228. package/src/segment-loader-promise.ts +122 -0
  229. package/src/segment-system.tsx +134 -36
  230. package/src/server/context.ts +341 -61
  231. package/src/server/cookie-store.ts +190 -0
  232. package/src/server/fetchable-loader-store.ts +37 -0
  233. package/src/server/handle-store.ts +113 -15
  234. package/src/server/loader-registry.ts +24 -64
  235. package/src/server/request-context.ts +607 -81
  236. package/src/server.ts +35 -130
  237. package/src/ssr/index.tsx +103 -30
  238. package/src/static-handler.ts +126 -0
  239. package/src/theme/ThemeProvider.tsx +21 -15
  240. package/src/theme/ThemeScript.tsx +5 -5
  241. package/src/theme/constants.ts +5 -2
  242. package/src/theme/index.ts +4 -14
  243. package/src/theme/theme-context.ts +4 -30
  244. package/src/theme/theme-script.ts +21 -18
  245. package/src/types/boundaries.ts +158 -0
  246. package/src/types/cache-types.ts +198 -0
  247. package/src/types/error-types.ts +192 -0
  248. package/src/types/global-namespace.ts +100 -0
  249. package/src/types/handler-context.ts +791 -0
  250. package/src/types/index.ts +88 -0
  251. package/src/types/loader-types.ts +210 -0
  252. package/src/types/route-config.ts +170 -0
  253. package/src/types/route-entry.ts +120 -0
  254. package/src/types/segments.ts +150 -0
  255. package/src/types.ts +1 -1623
  256. package/src/urls/include-helper.ts +207 -0
  257. package/src/urls/index.ts +53 -0
  258. package/src/urls/path-helper-types.ts +372 -0
  259. package/src/urls/path-helper.ts +364 -0
  260. package/src/urls/pattern-types.ts +107 -0
  261. package/src/urls/response-types.ts +116 -0
  262. package/src/urls/type-extraction.ts +372 -0
  263. package/src/urls/urls-function.ts +98 -0
  264. package/src/urls.ts +1 -802
  265. package/src/use-loader.tsx +161 -81
  266. package/src/vite/discovery/bundle-postprocess.ts +181 -0
  267. package/src/vite/discovery/discover-routers.ts +348 -0
  268. package/src/vite/discovery/prerender-collection.ts +439 -0
  269. package/src/vite/discovery/route-types-writer.ts +258 -0
  270. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  271. package/src/vite/discovery/state.ts +117 -0
  272. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  273. package/src/vite/index.ts +15 -1133
  274. package/src/vite/plugin-types.ts +103 -0
  275. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  276. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  277. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  278. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -53
  279. package/src/vite/plugins/expose-id-utils.ts +299 -0
  280. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  281. package/src/vite/plugins/expose-ids/handler-transform.ts +209 -0
  282. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  283. package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
  284. package/src/vite/plugins/expose-ids/types.ts +45 -0
  285. package/src/vite/plugins/expose-internal-ids.ts +786 -0
  286. package/src/vite/plugins/performance-tracks.ts +88 -0
  287. package/src/vite/plugins/refresh-cmd.ts +127 -0
  288. package/src/vite/plugins/use-cache-transform.ts +323 -0
  289. package/src/vite/plugins/version-injector.ts +83 -0
  290. package/src/vite/plugins/version-plugin.ts +266 -0
  291. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  292. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  293. package/src/vite/rango.ts +462 -0
  294. package/src/vite/router-discovery.ts +918 -0
  295. package/src/vite/utils/ast-handler-extract.ts +517 -0
  296. package/src/vite/utils/banner.ts +36 -0
  297. package/src/vite/utils/bundle-analysis.ts +137 -0
  298. package/src/vite/utils/manifest-utils.ts +70 -0
  299. package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
  300. package/src/vite/utils/prerender-utils.ts +221 -0
  301. package/src/vite/utils/shared-utils.ts +170 -0
  302. package/CLAUDE.md +0 -43
  303. package/src/browser/lru-cache.ts +0 -69
  304. package/src/browser/request-controller.ts +0 -164
  305. package/src/cache/memory-store.ts +0 -253
  306. package/src/href-context.ts +0 -33
  307. package/src/href.ts +0 -255
  308. package/src/server/route-manifest-cache.ts +0 -173
  309. package/src/vite/expose-handle-id.ts +0 -209
  310. package/src/vite/expose-loader-id.ts +0 -426
  311. package/src/vite/expose-location-state-id.ts +0 -177
  312. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
@@ -0,0 +1,1379 @@
1
+ /**
2
+ * Revalidation Path Segment Resolution
3
+ *
4
+ * Functions for resolving segments during partial (revalidation) requests.
5
+ * Mirrors the fresh path but adds revalidation awareness: only re-resolves
6
+ * segments whose revalidate() predicate returns true.
7
+ */
8
+
9
+ import type { ReactNode } from "react";
10
+ import { invariant } from "../../errors";
11
+ import { revalidate } from "../loader-resolution.js";
12
+ import { evaluateRevalidation } from "../revalidation.js";
13
+ import {
14
+ getParallelEntries,
15
+ getParallelSlotEntries,
16
+ type EntryData,
17
+ } from "../../server/context";
18
+ import type {
19
+ HandlerContext,
20
+ InternalHandlerContext,
21
+ ResolvedSegment,
22
+ ShouldRevalidateFn,
23
+ } from "../../types";
24
+ import type {
25
+ SegmentResolutionDeps,
26
+ SegmentRevalidationResult,
27
+ ActionContext,
28
+ } from "../types.js";
29
+ import {
30
+ debugLog,
31
+ pushRevalidationTraceEntry,
32
+ isTraceActive,
33
+ } from "../logging.js";
34
+ import { resolveLoaderData } from "./loader-cache.js";
35
+ import {
36
+ handleHandlerResult,
37
+ tryStaticHandler,
38
+ tryStaticSlot,
39
+ resolveLayoutComponent,
40
+ resolveWithErrorBoundary,
41
+ } from "./helpers.js";
42
+ import { getRouterContext } from "../router-context.js";
43
+ import { resolveSink, safeEmit } from "../telemetry.js";
44
+ import {
45
+ track,
46
+ RSCRouterContext,
47
+ runInsideLoaderScope,
48
+ } from "../../server/context.js";
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // Telemetry helpers
52
+ // ---------------------------------------------------------------------------
53
+
54
+ /**
55
+ * Attach a fire-and-forget rejection observer to a streamed handler promise.
56
+ * Silently no-ops when called outside RouterContext (e.g. in unit tests).
57
+ */
58
+ function observeStreamedHandler(
59
+ promise: Promise<ReactNode>,
60
+ segmentId: string,
61
+ segmentType: string,
62
+ pathname?: string,
63
+ routeKey?: string,
64
+ params?: Record<string, string>,
65
+ ): void {
66
+ let routerCtx;
67
+ try {
68
+ routerCtx = getRouterContext();
69
+ } catch {
70
+ return;
71
+ }
72
+ if (!routerCtx?.telemetry) return;
73
+ const sink = resolveSink(routerCtx.telemetry);
74
+ const reqId = routerCtx.requestId;
75
+ promise.catch((err: unknown) => {
76
+ const errorObj = err instanceof Error ? err : new Error(String(err));
77
+ safeEmit(sink, {
78
+ type: "handler.error",
79
+ timestamp: performance.now(),
80
+ requestId: reqId,
81
+ segmentId,
82
+ segmentType,
83
+ error: errorObj,
84
+ handledByBoundary: true,
85
+ pathname,
86
+ routeKey,
87
+ params,
88
+ });
89
+ });
90
+ }
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // Revalidation telemetry helper
94
+ // ---------------------------------------------------------------------------
95
+
96
+ /**
97
+ * Emit revalidation.decision telemetry for a segment if a sink is configured.
98
+ * Called after evaluateRevalidation returns to capture the decision.
99
+ * Silently no-ops when called outside RouterContext (e.g. in unit tests).
100
+ */
101
+ function emitRevalidationDecision(
102
+ segmentId: string,
103
+ pathname: string,
104
+ routeKey: string,
105
+ shouldRevalidate: boolean,
106
+ ): void {
107
+ let routerCtx;
108
+ try {
109
+ routerCtx = getRouterContext();
110
+ } catch {
111
+ return;
112
+ }
113
+ if (routerCtx?.telemetry) {
114
+ safeEmit(resolveSink(routerCtx.telemetry), {
115
+ type: "revalidation.decision",
116
+ timestamp: performance.now(),
117
+ requestId: routerCtx.requestId,
118
+ segmentId,
119
+ pathname,
120
+ routeKey,
121
+ shouldRevalidate,
122
+ });
123
+ }
124
+ }
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // Revalidation path (partial match)
128
+ // ---------------------------------------------------------------------------
129
+
130
+ /**
131
+ * Resolve loaders with revalidation awareness (for partial rendering).
132
+ * Returns both segments to render AND all matched segment IDs.
133
+ */
134
+ export async function resolveLoadersWithRevalidation<TEnv>(
135
+ entry: EntryData,
136
+ ctx: HandlerContext<any, TEnv>,
137
+ belongsToRoute: boolean,
138
+ clientSegmentIds: Set<string>,
139
+ prevParams: Record<string, string>,
140
+ request: Request,
141
+ prevUrl: URL,
142
+ nextUrl: URL,
143
+ routeKey: string,
144
+ deps: SegmentResolutionDeps<TEnv>,
145
+ actionContext?: ActionContext,
146
+ shortCodeOverride?: string,
147
+ stale?: boolean,
148
+ ): Promise<{ segments: ResolvedSegment[]; matchedIds: string[] }> {
149
+ const loaderEntries = entry.loader ?? [];
150
+ if (loaderEntries.length === 0) return { segments: [], matchedIds: [] };
151
+
152
+ const shortCode = shortCodeOverride ?? entry.shortCode;
153
+
154
+ const loaderMeta = loaderEntries.map((loaderEntry, i) => ({
155
+ loaderEntry,
156
+ loader: loaderEntry.loader,
157
+ loaderRevalidateFns: loaderEntry.revalidate,
158
+ segmentId: `${shortCode}D${i}.${loaderEntry.loader.$$id}`,
159
+ index: i,
160
+ }));
161
+
162
+ const matchedIds = loaderMeta.map((m) => m.segmentId);
163
+
164
+ const revalidationChecks = await Promise.all(
165
+ loaderMeta.map(
166
+ async ({
167
+ loaderEntry,
168
+ loader,
169
+ loaderRevalidateFns,
170
+ segmentId,
171
+ index,
172
+ }) => {
173
+ const shouldRun = await revalidate(
174
+ async () => {
175
+ if (!clientSegmentIds.has(segmentId)) {
176
+ if (isTraceActive()) {
177
+ pushRevalidationTraceEntry({
178
+ segmentId,
179
+ segmentType: "loader",
180
+ belongsToRoute,
181
+ source: "loader",
182
+ defaultShouldRevalidate: true,
183
+ finalShouldRevalidate: true,
184
+ reason: "new-segment",
185
+ });
186
+ }
187
+ return true;
188
+ }
189
+
190
+ const dummySegment: ResolvedSegment = {
191
+ id: segmentId,
192
+ namespace: entry.id,
193
+ type: "loader",
194
+ index,
195
+ component: null,
196
+ params: ctx.params,
197
+ loaderId: loader.$$id,
198
+ belongsToRoute,
199
+ };
200
+
201
+ return await evaluateRevalidation({
202
+ segment: dummySegment,
203
+ prevParams,
204
+ getPrevSegment: null,
205
+ request,
206
+ prevUrl,
207
+ nextUrl,
208
+ revalidations: loaderRevalidateFns.map((fn, j) => ({
209
+ name: `loader-revalidate${j}`,
210
+ fn,
211
+ })),
212
+ routeKey,
213
+ context: ctx,
214
+ actionContext,
215
+ stale,
216
+ traceSource: "loader",
217
+ });
218
+ },
219
+ async () => true,
220
+ () => false,
221
+ );
222
+ emitRevalidationDecision(segmentId, ctx.pathname, routeKey, shouldRun);
223
+ return { shouldRun, loaderEntry, loader, segmentId, index };
224
+ },
225
+ ),
226
+ );
227
+
228
+ const loadersToRun = revalidationChecks.filter((c) => c.shouldRun);
229
+ const segments: ResolvedSegment[] = loadersToRun.map(
230
+ ({ loaderEntry, loader, segmentId, index }) => ({
231
+ id: segmentId,
232
+ namespace: entry.id,
233
+ type: "loader" as const,
234
+ index,
235
+ component: null,
236
+ params: ctx.params,
237
+ loaderId: loader.$$id,
238
+ loaderData: deps.wrapLoaderPromise(
239
+ runInsideLoaderScope(() =>
240
+ resolveLoaderData(loaderEntry, ctx, ctx.pathname),
241
+ ),
242
+ entry,
243
+ segmentId,
244
+ ctx.pathname,
245
+ ),
246
+ belongsToRoute,
247
+ }),
248
+ );
249
+
250
+ return { segments, matchedIds };
251
+ }
252
+
253
+ /**
254
+ * Resolve only loader segments for all entries with revalidation logic.
255
+ */
256
+ export async function resolveLoadersOnlyWithRevalidation<TEnv>(
257
+ entries: EntryData[],
258
+ context: HandlerContext<any, TEnv>,
259
+ clientSegmentIds: Set<string>,
260
+ prevParams: Record<string, string>,
261
+ request: Request,
262
+ prevUrl: URL,
263
+ nextUrl: URL,
264
+ routeKey: string,
265
+ deps: SegmentResolutionDeps<TEnv>,
266
+ actionContext?: ActionContext,
267
+ stale?: boolean,
268
+ ): Promise<{ segments: ResolvedSegment[]; matchedIds: string[] }> {
269
+ const allLoaderSegments: ResolvedSegment[] = [];
270
+ const allMatchedIds: string[] = [];
271
+ const seenIds = new Set<string>();
272
+
273
+ async function collectEntryLoaders(
274
+ entry: EntryData,
275
+ belongsToRoute: boolean,
276
+ shortCodeOverride?: string,
277
+ ): Promise<void> {
278
+ // Skip if all loaders from this entry have already been resolved
279
+ // via a parent (e.g., cache boundary wrapping a layout with shared loaders).
280
+ const loaderEntries = entry.loader ?? [];
281
+ const sc = shortCodeOverride ?? entry.shortCode;
282
+ const allAlreadySeen =
283
+ loaderEntries.length > 0 &&
284
+ loaderEntries.every((le, i) =>
285
+ seenIds.has(`${sc}D${i}.${le.loader.$$id}`),
286
+ );
287
+ if (!allAlreadySeen) {
288
+ const { segments, matchedIds } = await resolveLoadersWithRevalidation(
289
+ entry,
290
+ context,
291
+ belongsToRoute,
292
+ clientSegmentIds,
293
+ prevParams,
294
+ request,
295
+ prevUrl,
296
+ nextUrl,
297
+ routeKey,
298
+ deps,
299
+ actionContext,
300
+ shortCodeOverride,
301
+ stale,
302
+ );
303
+ for (const seg of segments) {
304
+ if (!seenIds.has(seg.id)) {
305
+ seenIds.add(seg.id);
306
+ allLoaderSegments.push(seg);
307
+ }
308
+ }
309
+ allMatchedIds.push(...matchedIds);
310
+ }
311
+
312
+ const seenParallelEntryIds = new Set<string>();
313
+ for (const parallelEntry of getParallelEntries(entry.parallel)) {
314
+ if (seenParallelEntryIds.has(parallelEntry.id)) continue;
315
+ seenParallelEntryIds.add(parallelEntry.id);
316
+ await collectEntryLoaders(parallelEntry, belongsToRoute, entry.shortCode);
317
+ }
318
+
319
+ const childBelongsToRoute = belongsToRoute || entry.type === "route";
320
+ for (const layoutEntry of entry.layout) {
321
+ await collectEntryLoaders(layoutEntry, childBelongsToRoute);
322
+ // Inherit route loaders for orphan layouts with parallels.
323
+ // Resolve directly — do NOT re-enter collectEntryLoaders with the
324
+ // route entry, as that would re-iterate route.layout and loop.
325
+ if (
326
+ entry.type === "route" &&
327
+ entry.loader &&
328
+ entry.loader.length > 0 &&
329
+ Object.keys(layoutEntry.parallel).length > 0
330
+ ) {
331
+ const inherited = await resolveLoadersWithRevalidation(
332
+ entry,
333
+ context,
334
+ childBelongsToRoute,
335
+ clientSegmentIds,
336
+ prevParams,
337
+ request,
338
+ prevUrl,
339
+ nextUrl,
340
+ routeKey,
341
+ deps,
342
+ actionContext,
343
+ layoutEntry.shortCode,
344
+ stale,
345
+ );
346
+ for (const seg of inherited.segments) {
347
+ if (!seenIds.has(seg.id)) {
348
+ seenIds.add(seg.id);
349
+ seg._inherited = true;
350
+ allLoaderSegments.push(seg);
351
+ }
352
+ }
353
+ allMatchedIds.push(...inherited.matchedIds);
354
+ }
355
+ }
356
+ }
357
+
358
+ for (const entry of entries) {
359
+ await collectEntryLoaders(entry, entry.type === "route");
360
+ }
361
+
362
+ return { segments: allLoaderSegments, matchedIds: allMatchedIds };
363
+ }
364
+
365
+ /**
366
+ * Build a map of segment shortCode -> entry with revalidate functions.
367
+ */
368
+ export function buildEntryRevalidateMap(
369
+ entries: EntryData[],
370
+ ): Map<
371
+ string,
372
+ { entry: EntryData; revalidate: ShouldRevalidateFn<any, any>[] }
373
+ > {
374
+ const map = new Map<
375
+ string,
376
+ { entry: EntryData; revalidate: ShouldRevalidateFn<any, any>[] }
377
+ >();
378
+
379
+ function processEntry(entry: EntryData, parentShortCode?: string) {
380
+ map.set(entry.shortCode, { entry, revalidate: entry.revalidate });
381
+
382
+ if (entry.type !== "parallel") {
383
+ for (const { slot, entry: parallelEntry } of getParallelSlotEntries(
384
+ entry.parallel,
385
+ )) {
386
+ const parallelParentShortCode = parentShortCode ?? entry.shortCode;
387
+ const parallelId = `${parallelParentShortCode}.${slot}`;
388
+ map.set(parallelId, {
389
+ entry: parallelEntry,
390
+ revalidate: parallelEntry.revalidate,
391
+ });
392
+ }
393
+ }
394
+
395
+ for (const layoutEntry of entry.layout) {
396
+ processEntry(layoutEntry, entry.shortCode);
397
+ }
398
+ }
399
+
400
+ for (const entry of entries) {
401
+ processEntry(entry);
402
+ }
403
+
404
+ return map;
405
+ }
406
+
407
+ /**
408
+ * Resolve parallel segments with revalidation.
409
+ */
410
+ export async function resolveParallelSegmentsWithRevalidation<TEnv>(
411
+ entry: EntryData,
412
+ params: Record<string, string>,
413
+ context: HandlerContext<any, TEnv>,
414
+ belongsToRoute: boolean,
415
+ clientSegmentIds: Set<string>,
416
+ prevParams: Record<string, string>,
417
+ request: Request,
418
+ prevUrl: URL,
419
+ nextUrl: URL,
420
+ routeKey: string,
421
+ deps: SegmentResolutionDeps<TEnv>,
422
+ actionContext?: ActionContext,
423
+ stale?: boolean,
424
+ ): Promise<SegmentRevalidationResult> {
425
+ const segments: ResolvedSegment[] = [];
426
+ const matchedIds: string[] = [];
427
+
428
+ const resolvedParallelEntries = new Set<string>();
429
+ for (const { slot, entry: parallelEntry } of getParallelSlotEntries(
430
+ entry.parallel,
431
+ )) {
432
+ invariant(
433
+ parallelEntry.type === "parallel",
434
+ `Expected parallel entry, got: ${parallelEntry.type}`,
435
+ );
436
+
437
+ const slots = parallelEntry.handler as Record<
438
+ `@${string}`,
439
+ | ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>)
440
+ | ReactNode
441
+ >;
442
+ // In production, static handler bodies are evicted and the slot value
443
+ // may be undefined. The static store holds the pre-rendered component.
444
+ // We defer the handler check until after tryStaticSlot.
445
+ const handler = slots[slot];
446
+
447
+ const parallelId = `${entry.shortCode}.${slot}`;
448
+
449
+ const isFullRefetch = clientSegmentIds.size === 0;
450
+ const isNewParent = !clientSegmentIds.has(entry.shortCode);
451
+ if (
452
+ isFullRefetch ||
453
+ clientSegmentIds.has(parallelId) ||
454
+ belongsToRoute ||
455
+ isNewParent
456
+ ) {
457
+ matchedIds.push(parallelId);
458
+ }
459
+
460
+ const shouldResolve = await (async () => {
461
+ if (isFullRefetch) {
462
+ if (isTraceActive()) {
463
+ pushRevalidationTraceEntry({
464
+ segmentId: parallelId,
465
+ segmentType: "parallel",
466
+ belongsToRoute,
467
+ source: "parallel",
468
+ defaultShouldRevalidate: true,
469
+ finalShouldRevalidate: true,
470
+ reason: "full-refetch",
471
+ });
472
+ }
473
+ return true;
474
+ }
475
+ if (!clientSegmentIds.has(parallelId)) {
476
+ const result = belongsToRoute || isNewParent;
477
+ if (isTraceActive()) {
478
+ pushRevalidationTraceEntry({
479
+ segmentId: parallelId,
480
+ segmentType: "parallel",
481
+ belongsToRoute,
482
+ source: "parallel",
483
+ defaultShouldRevalidate: result,
484
+ finalShouldRevalidate: result,
485
+ reason: result ? "new-segment" : "skip-parent-chain",
486
+ });
487
+ }
488
+ return result;
489
+ }
490
+
491
+ const dummySegment: ResolvedSegment = {
492
+ id: parallelId,
493
+ namespace: parallelEntry.id,
494
+ type: "parallel",
495
+ index: 0,
496
+ component: null as any,
497
+ params,
498
+ slot,
499
+ belongsToRoute,
500
+ parallelName: `${parallelEntry.id}.${slot}`,
501
+ ...(parallelEntry.mountPath
502
+ ? { mountPath: parallelEntry.mountPath }
503
+ : {}),
504
+ };
505
+
506
+ return await evaluateRevalidation({
507
+ segment: dummySegment,
508
+ prevParams,
509
+ getPrevSegment: null,
510
+ request,
511
+ prevUrl,
512
+ nextUrl,
513
+ revalidations: parallelEntry.revalidate.map((fn, i) => ({
514
+ name: `revalidate${i}`,
515
+ fn,
516
+ })),
517
+ routeKey,
518
+ context,
519
+ actionContext,
520
+ stale,
521
+ traceSource: "parallel",
522
+ });
523
+ })();
524
+ emitRevalidationDecision(
525
+ parallelId,
526
+ context.pathname,
527
+ routeKey,
528
+ shouldResolve,
529
+ );
530
+
531
+ let component: ReactNode | undefined;
532
+ if (shouldResolve) {
533
+ component = await tryStaticSlot(parallelEntry, slot, parallelId);
534
+ }
535
+ if (component === undefined) {
536
+ const hasLoadingFallback =
537
+ parallelEntry.loading !== undefined && parallelEntry.loading !== false;
538
+ if (!shouldResolve) {
539
+ component = null;
540
+ } else if (handler === undefined) {
541
+ // Handler evicted (production static slot) but static lookup missed.
542
+ // Nothing to render — use null so the client keeps its cached version.
543
+ component = null;
544
+ } else if (hasLoadingFallback) {
545
+ const result =
546
+ typeof handler === "function" ? handler(context) : handler;
547
+ if (result instanceof Promise) {
548
+ const tracked = deps.trackHandler(result, {
549
+ segmentId: parallelId,
550
+ segmentType: "parallel",
551
+ });
552
+ observeStreamedHandler(
553
+ tracked,
554
+ parallelId,
555
+ "parallel",
556
+ context.pathname,
557
+ routeKey,
558
+ params,
559
+ );
560
+ component = tracked as ReactNode;
561
+ } else {
562
+ component = result as ReactNode;
563
+ }
564
+ } else {
565
+ component =
566
+ typeof handler === "function" ? await handler(context) : handler;
567
+ }
568
+ }
569
+
570
+ segments.push({
571
+ id: parallelId,
572
+ namespace: parallelEntry.id,
573
+ type: "parallel",
574
+ index: 0,
575
+ component,
576
+ loading: parallelEntry.loading === false ? null : parallelEntry.loading,
577
+ transition: parallelEntry.transition,
578
+ params,
579
+ slot,
580
+ belongsToRoute,
581
+ parallelName: `${parallelEntry.id}.${slot}`,
582
+ ...(parallelEntry.mountPath
583
+ ? { mountPath: parallelEntry.mountPath }
584
+ : {}),
585
+ });
586
+
587
+ if (resolvedParallelEntries.has(parallelEntry.id)) {
588
+ continue;
589
+ }
590
+
591
+ const loaderResult = await resolveLoadersWithRevalidation(
592
+ parallelEntry,
593
+ context,
594
+ belongsToRoute,
595
+ clientSegmentIds,
596
+ prevParams,
597
+ request,
598
+ prevUrl,
599
+ nextUrl,
600
+ routeKey,
601
+ deps,
602
+ actionContext,
603
+ entry.shortCode,
604
+ stale,
605
+ );
606
+ segments.push(...loaderResult.segments);
607
+ matchedIds.push(...loaderResult.matchedIds);
608
+ resolvedParallelEntries.add(parallelEntry.id);
609
+ }
610
+
611
+ return { segments, matchedIds };
612
+ }
613
+
614
+ /**
615
+ * Resolve entry handler (layout, cache, or route) with revalidation.
616
+ */
617
+ export async function resolveEntryHandlerWithRevalidation<TEnv>(
618
+ entry: Exclude<EntryData, { type: "parallel" }>,
619
+ params: Record<string, string>,
620
+ context: HandlerContext<any, TEnv>,
621
+ belongsToRoute: boolean,
622
+ clientSegmentIds: Set<string>,
623
+ prevParams: Record<string, string>,
624
+ request: Request,
625
+ prevUrl: URL,
626
+ nextUrl: URL,
627
+ routeKey: string,
628
+ deps: SegmentResolutionDeps<TEnv>,
629
+ actionContext?: ActionContext,
630
+ stale?: boolean,
631
+ ): Promise<{ segment: ResolvedSegment; matchedId: string }> {
632
+ const matchedId = entry.shortCode;
633
+
634
+ const component = await revalidate(
635
+ async () => {
636
+ const hasSegment = clientSegmentIds.has(entry.shortCode);
637
+ debugLog("segment.revalidate", "entry presence check", {
638
+ segmentId: entry.shortCode,
639
+ entryType: entry.type,
640
+ clientHasSegment: hasSegment,
641
+ belongsToRoute,
642
+ });
643
+ if (!hasSegment) {
644
+ if (isTraceActive()) {
645
+ const segType =
646
+ entry.type === "cache"
647
+ ? "layout"
648
+ : (entry.type as "layout" | "route");
649
+ pushRevalidationTraceEntry({
650
+ segmentId: entry.shortCode,
651
+ segmentType: segType,
652
+ belongsToRoute,
653
+ source: "segment-resolution",
654
+ defaultShouldRevalidate: true,
655
+ finalShouldRevalidate: true,
656
+ reason: "new-segment",
657
+ });
658
+ }
659
+ return true;
660
+ }
661
+
662
+ const dummySegment: ResolvedSegment = {
663
+ id: entry.shortCode,
664
+ namespace: entry.id,
665
+ type:
666
+ entry.type === "cache"
667
+ ? "layout"
668
+ : (entry.type as "layout" | "route"),
669
+ index: 0,
670
+ component: null as any,
671
+ params,
672
+ belongsToRoute,
673
+ ...(entry.type === "layout" || entry.type === "cache"
674
+ ? { layoutName: entry.id }
675
+ : {}),
676
+ ...(entry.mountPath ? { mountPath: entry.mountPath } : {}),
677
+ };
678
+
679
+ const shouldRevalidate = await evaluateRevalidation({
680
+ segment: dummySegment,
681
+ prevParams,
682
+ getPrevSegment: null,
683
+ request,
684
+ prevUrl,
685
+ nextUrl,
686
+ revalidations: entry.revalidate.map((fn, i) => ({
687
+ name: `revalidate${i}`,
688
+ fn,
689
+ })),
690
+ routeKey,
691
+ context,
692
+ actionContext,
693
+ stale,
694
+ traceSource:
695
+ entry.type === "route" ? "route-handler" : "layout-handler",
696
+ });
697
+ emitRevalidationDecision(
698
+ entry.shortCode,
699
+ context.pathname,
700
+ routeKey,
701
+ shouldRevalidate,
702
+ );
703
+ debugLog("segment.revalidate", "entry revalidation decision", {
704
+ segmentId: entry.shortCode,
705
+ shouldRevalidate,
706
+ });
707
+ return shouldRevalidate;
708
+ },
709
+ async () => {
710
+ const doneHandler = track(`handler:${entry.id}`, 2);
711
+ (context as InternalHandlerContext<any, TEnv>)._currentSegmentId =
712
+ entry.shortCode;
713
+ if (entry.type === "layout" || entry.type === "cache") {
714
+ const layoutComponent = await resolveLayoutComponent(entry, context);
715
+ doneHandler();
716
+ return layoutComponent;
717
+ }
718
+ const staticComponent = await tryStaticHandler(entry, entry.shortCode);
719
+ if (staticComponent !== undefined) {
720
+ doneHandler();
721
+ return staticComponent;
722
+ }
723
+ const routeEntry = entry as Extract<EntryData, { type: "route" }>;
724
+ // For Passthrough routes at runtime, use the live handler instead of
725
+ // the build handler. At build time (context.build === true), always
726
+ // use the build handler from routeEntry.handler.
727
+ const handler =
728
+ !context.build && routeEntry.liveHandler
729
+ ? routeEntry.liveHandler
730
+ : routeEntry.handler;
731
+ if (!routeEntry.loading) {
732
+ const result = handleHandlerResult(await handler(context));
733
+ doneHandler();
734
+ return result;
735
+ }
736
+ if (!actionContext) {
737
+ const result = handleHandlerResult(handler(context));
738
+ if (result instanceof Promise) {
739
+ result.finally(doneHandler).catch(() => {});
740
+ const tracked = deps.trackHandler(result, {
741
+ segmentId: entry.shortCode,
742
+ segmentType: entry.type,
743
+ });
744
+ observeStreamedHandler(
745
+ tracked,
746
+ entry.shortCode,
747
+ entry.type,
748
+ context.pathname,
749
+ routeKey,
750
+ params,
751
+ );
752
+ return { content: tracked };
753
+ }
754
+ doneHandler();
755
+ return { content: result };
756
+ }
757
+ debugLog("segment.action", "resolving action route with awaited value", {
758
+ entryId: entry.id,
759
+ });
760
+ const actionResult = handleHandlerResult(await handler(context));
761
+ doneHandler();
762
+ return {
763
+ content: Promise.resolve(actionResult),
764
+ };
765
+ },
766
+ () => null,
767
+ );
768
+
769
+ // Normalize void handlers (undefined) to null so the reconciler's
770
+ // component === null checks work consistently for both void and explicit null.
771
+ const resolvedComponent =
772
+ component && typeof component === "object" && "content" in component
773
+ ? ((component as { content: ReactNode }).content ?? null)
774
+ : (component ?? null);
775
+
776
+ const segment: ResolvedSegment = {
777
+ id: entry.shortCode,
778
+ namespace: entry.id,
779
+ type:
780
+ entry.type === "cache" ? "layout" : (entry.type as "layout" | "route"),
781
+ index: 0,
782
+ component: resolvedComponent,
783
+ loading: entry.loading === false ? null : entry.loading,
784
+ transition: entry.transition,
785
+ params,
786
+ belongsToRoute,
787
+ ...(entry.type === "layout" || entry.type === "cache"
788
+ ? { layoutName: entry.id }
789
+ : {}),
790
+ ...(entry.mountPath ? { mountPath: entry.mountPath } : {}),
791
+ };
792
+
793
+ return { segment, matchedId };
794
+ }
795
+
796
+ /**
797
+ * Resolve segments with revalidation awareness (for partial rendering).
798
+ */
799
+ export async function resolveSegmentWithRevalidation<TEnv>(
800
+ entry: Exclude<EntryData, { type: "parallel" }>,
801
+ routeKey: string,
802
+ params: Record<string, string>,
803
+ context: HandlerContext<any, TEnv>,
804
+ clientSegmentIds: Set<string>,
805
+ prevParams: Record<string, string>,
806
+ request: Request,
807
+ prevUrl: URL,
808
+ nextUrl: URL,
809
+ loaderPromises: Map<string, Promise<any>>,
810
+ deps: SegmentResolutionDeps<TEnv>,
811
+ actionContext?: ActionContext,
812
+ stale?: boolean,
813
+ ): Promise<SegmentRevalidationResult> {
814
+ const segments: ResolvedSegment[] = [];
815
+ const matchedIds: string[] = [];
816
+
817
+ const belongsToRoute = entry.type === "route";
818
+
819
+ const loaderResult = await resolveLoadersWithRevalidation(
820
+ entry,
821
+ context,
822
+ belongsToRoute,
823
+ clientSegmentIds,
824
+ prevParams,
825
+ request,
826
+ prevUrl,
827
+ nextUrl,
828
+ routeKey,
829
+ deps,
830
+ actionContext,
831
+ undefined,
832
+ stale,
833
+ );
834
+ segments.push(...loaderResult.segments);
835
+ matchedIds.push(...loaderResult.matchedIds);
836
+
837
+ // For route entries, execute the handler BEFORE orphan layouts and parallels
838
+ // so ctx.set() data is available to them via ctx.get(). The handler's
839
+ // segment is pushed after children to preserve tree composition order.
840
+ let routeHandlerResult:
841
+ | { segment: ResolvedSegment; matchedId: string }
842
+ | undefined;
843
+ if (entry.type === "route") {
844
+ routeHandlerResult = await resolveEntryHandlerWithRevalidation(
845
+ entry,
846
+ params,
847
+ context,
848
+ belongsToRoute,
849
+ clientSegmentIds,
850
+ prevParams,
851
+ request,
852
+ prevUrl,
853
+ nextUrl,
854
+ routeKey,
855
+ deps,
856
+ actionContext,
857
+ stale,
858
+ );
859
+
860
+ for (const orphan of entry.layout) {
861
+ const orphanResult = await resolveOrphanLayoutWithRevalidation(
862
+ orphan,
863
+ params,
864
+ context,
865
+ clientSegmentIds,
866
+ prevParams,
867
+ request,
868
+ prevUrl,
869
+ nextUrl,
870
+ routeKey,
871
+ loaderPromises,
872
+ true,
873
+ deps,
874
+ actionContext,
875
+ stale,
876
+ entry,
877
+ );
878
+ segments.push(...orphanResult.segments);
879
+ matchedIds.push(...orphanResult.matchedIds);
880
+ }
881
+ }
882
+
883
+ if (routeHandlerResult) {
884
+ // Route entry: handler already executed above; resolve parallels
885
+ // (handler data visible) then push handler segment last for tree order.
886
+ const parallelResult = await resolveParallelSegmentsWithRevalidation(
887
+ entry,
888
+ params,
889
+ context,
890
+ belongsToRoute,
891
+ clientSegmentIds,
892
+ prevParams,
893
+ request,
894
+ prevUrl,
895
+ nextUrl,
896
+ routeKey,
897
+ deps,
898
+ actionContext,
899
+ stale,
900
+ );
901
+ segments.push(...parallelResult.segments);
902
+ matchedIds.push(...parallelResult.matchedIds);
903
+
904
+ segments.push(routeHandlerResult.segment);
905
+ matchedIds.push(routeHandlerResult.matchedId);
906
+ } else {
907
+ // Layout/cache entry: handler-first — resolve handler before parallels
908
+ // so ctx.set() values are visible to parallel children.
909
+ const handlerResult = await resolveEntryHandlerWithRevalidation(
910
+ entry,
911
+ params,
912
+ context,
913
+ belongsToRoute,
914
+ clientSegmentIds,
915
+ prevParams,
916
+ request,
917
+ prevUrl,
918
+ nextUrl,
919
+ routeKey,
920
+ deps,
921
+ actionContext,
922
+ stale,
923
+ );
924
+ segments.push(handlerResult.segment);
925
+ matchedIds.push(handlerResult.matchedId);
926
+
927
+ const parallelResult = await resolveParallelSegmentsWithRevalidation(
928
+ entry,
929
+ params,
930
+ context,
931
+ belongsToRoute,
932
+ clientSegmentIds,
933
+ prevParams,
934
+ request,
935
+ prevUrl,
936
+ nextUrl,
937
+ routeKey,
938
+ deps,
939
+ actionContext,
940
+ stale,
941
+ );
942
+ segments.push(...parallelResult.segments);
943
+ matchedIds.push(...parallelResult.matchedIds);
944
+
945
+ for (const orphan of entry.layout) {
946
+ const orphanResult = await resolveOrphanLayoutWithRevalidation(
947
+ orphan,
948
+ params,
949
+ context,
950
+ clientSegmentIds,
951
+ prevParams,
952
+ request,
953
+ prevUrl,
954
+ nextUrl,
955
+ routeKey,
956
+ loaderPromises,
957
+ false,
958
+ deps,
959
+ actionContext,
960
+ stale,
961
+ );
962
+ segments.push(...orphanResult.segments);
963
+ matchedIds.push(...orphanResult.matchedIds);
964
+ }
965
+ }
966
+
967
+ return { segments, matchedIds };
968
+ }
969
+
970
+ /**
971
+ * Resolve orphan layout with revalidation.
972
+ */
973
+ export async function resolveOrphanLayoutWithRevalidation<TEnv>(
974
+ orphan: EntryData,
975
+ params: Record<string, string>,
976
+ context: HandlerContext<any, TEnv>,
977
+ clientSegmentIds: Set<string>,
978
+ prevParams: Record<string, string>,
979
+ request: Request,
980
+ prevUrl: URL,
981
+ nextUrl: URL,
982
+ routeKey: string,
983
+ loaderPromises: Map<string, Promise<any>>,
984
+ belongsToRoute: boolean,
985
+ deps: SegmentResolutionDeps<TEnv>,
986
+ actionContext?: ActionContext,
987
+ stale?: boolean,
988
+ /** Parent route entry — its loaders are inherited so parallel slots can access them. */
989
+ parentRouteEntry?: EntryData,
990
+ ): Promise<SegmentRevalidationResult> {
991
+ invariant(
992
+ orphan.type === "layout" || orphan.type === "cache",
993
+ `Expected orphan to be a layout or cache, got: ${orphan.type}`,
994
+ );
995
+
996
+ const segments: ResolvedSegment[] = [];
997
+ const matchedIds: string[] = [];
998
+
999
+ const loaderResult = await resolveLoadersWithRevalidation(
1000
+ orphan,
1001
+ context,
1002
+ belongsToRoute,
1003
+ clientSegmentIds,
1004
+ prevParams,
1005
+ request,
1006
+ prevUrl,
1007
+ nextUrl,
1008
+ routeKey,
1009
+ deps,
1010
+ actionContext,
1011
+ undefined,
1012
+ stale,
1013
+ );
1014
+ segments.push(...loaderResult.segments);
1015
+ matchedIds.push(...loaderResult.matchedIds);
1016
+
1017
+ // Inherit parent route's loaders so parallel slots inside this layout
1018
+ // can access them via useLoader(). See resolveOrphanLayout in fresh.ts.
1019
+ if (
1020
+ parentRouteEntry &&
1021
+ parentRouteEntry.loader &&
1022
+ parentRouteEntry.loader.length > 0 &&
1023
+ Object.keys(orphan.parallel).length > 0
1024
+ ) {
1025
+ const inheritedResult = await resolveLoadersWithRevalidation(
1026
+ parentRouteEntry,
1027
+ context,
1028
+ belongsToRoute,
1029
+ clientSegmentIds,
1030
+ prevParams,
1031
+ request,
1032
+ prevUrl,
1033
+ nextUrl,
1034
+ routeKey,
1035
+ deps,
1036
+ actionContext,
1037
+ orphan.shortCode,
1038
+ stale,
1039
+ );
1040
+ // Tag as inherited so buildMatchResult can deduplicate when safe
1041
+ for (const s of inheritedResult.segments) {
1042
+ s._inherited = true;
1043
+ }
1044
+ segments.push(...inheritedResult.segments);
1045
+ matchedIds.push(...inheritedResult.matchedIds);
1046
+ }
1047
+
1048
+ // Handler-first: resolve orphan layout handler before its parallels
1049
+ // so ctx.set() values are visible to parallel children.
1050
+ matchedIds.push(orphan.shortCode);
1051
+
1052
+ const component = await revalidate(
1053
+ async () => {
1054
+ if (!clientSegmentIds.has(orphan.shortCode)) {
1055
+ if (isTraceActive()) {
1056
+ pushRevalidationTraceEntry({
1057
+ segmentId: orphan.shortCode,
1058
+ segmentType: "layout",
1059
+ belongsToRoute,
1060
+ source: "orphan-layout",
1061
+ defaultShouldRevalidate: true,
1062
+ finalShouldRevalidate: true,
1063
+ reason: "new-segment",
1064
+ });
1065
+ }
1066
+ return true;
1067
+ }
1068
+
1069
+ const dummySegment: ResolvedSegment = {
1070
+ id: orphan.shortCode,
1071
+ namespace: orphan.id,
1072
+ type: "layout",
1073
+ index: 0,
1074
+ component: null as any,
1075
+ params,
1076
+ belongsToRoute,
1077
+ layoutName: orphan.id,
1078
+ ...(orphan.mountPath ? { mountPath: orphan.mountPath } : {}),
1079
+ };
1080
+
1081
+ const shouldRevalidate = await evaluateRevalidation({
1082
+ segment: dummySegment,
1083
+ prevParams,
1084
+ getPrevSegment: null,
1085
+ request,
1086
+ prevUrl,
1087
+ nextUrl,
1088
+ revalidations: orphan.revalidate.map((fn, i) => ({
1089
+ name: `revalidate${i}`,
1090
+ fn,
1091
+ })),
1092
+ routeKey,
1093
+ context,
1094
+ actionContext,
1095
+ stale,
1096
+ traceSource: "orphan-layout",
1097
+ });
1098
+ emitRevalidationDecision(
1099
+ orphan.shortCode,
1100
+ context.pathname,
1101
+ routeKey,
1102
+ shouldRevalidate,
1103
+ );
1104
+ return shouldRevalidate;
1105
+ },
1106
+ async () => resolveLayoutComponent(orphan, context),
1107
+ () => null,
1108
+ );
1109
+
1110
+ segments.push({
1111
+ id: orphan.shortCode,
1112
+ namespace: orphan.id,
1113
+ type: "layout",
1114
+ index: 0,
1115
+ component,
1116
+ params,
1117
+ belongsToRoute,
1118
+ layoutName: orphan.id,
1119
+ loading: orphan.loading === false ? null : orphan.loading,
1120
+ transition: orphan.transition,
1121
+ ...(orphan.mountPath ? { mountPath: orphan.mountPath } : {}),
1122
+ });
1123
+
1124
+ const resolvedParallelEntries = new Set<string>();
1125
+ for (const { slot, entry: parallelEntry } of getParallelSlotEntries(
1126
+ orphan.parallel,
1127
+ )) {
1128
+ invariant(
1129
+ parallelEntry.type === "parallel",
1130
+ `Expected parallel entry, got: ${parallelEntry.type}`,
1131
+ );
1132
+
1133
+ if (!resolvedParallelEntries.has(parallelEntry.id)) {
1134
+ // shortCodeOverride must match the parent layout, not the parallel entry.
1135
+ const loaderResult = await resolveLoadersWithRevalidation(
1136
+ parallelEntry,
1137
+ context,
1138
+ belongsToRoute,
1139
+ clientSegmentIds,
1140
+ prevParams,
1141
+ request,
1142
+ prevUrl,
1143
+ nextUrl,
1144
+ routeKey,
1145
+ deps,
1146
+ actionContext,
1147
+ orphan.shortCode,
1148
+ stale,
1149
+ );
1150
+ segments.push(...loaderResult.segments);
1151
+ matchedIds.push(...loaderResult.matchedIds);
1152
+ resolvedParallelEntries.add(parallelEntry.id);
1153
+ }
1154
+
1155
+ const slots = parallelEntry.handler as Record<
1156
+ `@${string}`,
1157
+ | ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>)
1158
+ | ReactNode
1159
+ >;
1160
+ // Handler may be undefined in production after static handler eviction.
1161
+ const handler = slots[slot];
1162
+
1163
+ // Use orphan.shortCode (the parent layout) to match the SSR path
1164
+ // (resolveParallelEntry receives parentShortCode = orphan.shortCode).
1165
+ // Using parallelEntry.shortCode would generate IDs the client doesn't know about.
1166
+ const parallelId = `${orphan.shortCode}.${slot}`;
1167
+ matchedIds.push(parallelId);
1168
+
1169
+ const shouldResolve = await (async () => {
1170
+ if (!clientSegmentIds.has(parallelId)) {
1171
+ if (isTraceActive()) {
1172
+ pushRevalidationTraceEntry({
1173
+ segmentId: parallelId,
1174
+ segmentType: "parallel",
1175
+ belongsToRoute,
1176
+ source: "parallel",
1177
+ defaultShouldRevalidate: true,
1178
+ finalShouldRevalidate: true,
1179
+ reason: "new-segment",
1180
+ });
1181
+ }
1182
+ return true;
1183
+ }
1184
+
1185
+ const dummySegment: ResolvedSegment = {
1186
+ id: parallelId,
1187
+ namespace: parallelEntry.id,
1188
+ type: "parallel",
1189
+ index: 0,
1190
+ component: null as any,
1191
+ params,
1192
+ slot,
1193
+ belongsToRoute,
1194
+ parallelName: `${parallelEntry.id}.${slot}`,
1195
+ ...(parallelEntry.mountPath
1196
+ ? { mountPath: parallelEntry.mountPath }
1197
+ : {}),
1198
+ };
1199
+
1200
+ return await evaluateRevalidation({
1201
+ segment: dummySegment,
1202
+ prevParams,
1203
+ getPrevSegment: null,
1204
+ request,
1205
+ prevUrl,
1206
+ nextUrl,
1207
+ revalidations: parallelEntry.revalidate.map((fn, i) => ({
1208
+ name: `revalidate${i}`,
1209
+ fn,
1210
+ })),
1211
+ routeKey,
1212
+ context,
1213
+ actionContext,
1214
+ stale,
1215
+ traceSource: "parallel",
1216
+ });
1217
+ })();
1218
+ emitRevalidationDecision(
1219
+ parallelId,
1220
+ context.pathname,
1221
+ routeKey,
1222
+ shouldResolve,
1223
+ );
1224
+
1225
+ let component: ReactNode | undefined;
1226
+ if (shouldResolve) {
1227
+ component = await tryStaticSlot(parallelEntry, slot, parallelId);
1228
+ }
1229
+ if (component === undefined) {
1230
+ const hasLoadingFallback =
1231
+ parallelEntry.loading !== undefined && parallelEntry.loading !== false;
1232
+ if (!shouldResolve) {
1233
+ component = null;
1234
+ } else if (handler === undefined) {
1235
+ // Handler evicted (production static slot) but static lookup missed.
1236
+ component = null;
1237
+ } else if (hasLoadingFallback) {
1238
+ const result =
1239
+ typeof handler === "function" ? handler(context) : handler;
1240
+ if (result instanceof Promise) {
1241
+ const tracked = deps.trackHandler(result, {
1242
+ segmentId: parallelId,
1243
+ segmentType: "parallel",
1244
+ });
1245
+ observeStreamedHandler(
1246
+ tracked,
1247
+ parallelId,
1248
+ "parallel",
1249
+ context.pathname,
1250
+ routeKey,
1251
+ params,
1252
+ );
1253
+ component = tracked as ReactNode;
1254
+ } else {
1255
+ component = result as ReactNode;
1256
+ }
1257
+ } else {
1258
+ component =
1259
+ typeof handler === "function" ? await handler(context) : handler;
1260
+ }
1261
+ }
1262
+
1263
+ segments.push({
1264
+ id: parallelId,
1265
+ namespace: parallelEntry.id,
1266
+ type: "parallel",
1267
+ index: 0,
1268
+ component,
1269
+ loading: parallelEntry.loading === false ? null : parallelEntry.loading,
1270
+ transition: parallelEntry.transition,
1271
+ params,
1272
+ slot,
1273
+ belongsToRoute,
1274
+ parallelName: `${parallelEntry.id}.${slot}`,
1275
+ ...(parallelEntry.mountPath
1276
+ ? { mountPath: parallelEntry.mountPath }
1277
+ : {}),
1278
+ });
1279
+ }
1280
+
1281
+ return { segments, matchedIds };
1282
+ }
1283
+
1284
+ /**
1285
+ * Resolve all segments for a route with revalidation logic (for matchPartial).
1286
+ */
1287
+ export async function resolveAllSegmentsWithRevalidation<TEnv>(
1288
+ entries: EntryData[],
1289
+ routeKey: string,
1290
+ params: Record<string, string>,
1291
+ context: HandlerContext<any, TEnv>,
1292
+ clientSegmentSet: Set<string>,
1293
+ prevParams: Record<string, string>,
1294
+ request: Request,
1295
+ prevUrl: URL,
1296
+ nextUrl: URL,
1297
+ loaderPromises: Map<string, Promise<any>>,
1298
+ actionContext: ActionContext | undefined,
1299
+ interceptResult: { intercept: any; entry: EntryData } | null,
1300
+ localRouteName: string,
1301
+ pathname: string,
1302
+ deps: SegmentResolutionDeps<TEnv>,
1303
+ stale?: boolean,
1304
+ ): Promise<{ segments: ResolvedSegment[]; matchedIds: string[] }> {
1305
+ const allSegments: ResolvedSegment[] = [];
1306
+ const matchedIds: string[] = [];
1307
+ const seenSegIds = new Set<string>();
1308
+ const seenMatchIds = new Set<string>();
1309
+
1310
+ const telemetry = getRouterContext()?.telemetry;
1311
+
1312
+ for (const entry of entries) {
1313
+ if (entry.type === "route" && interceptResult) {
1314
+ debugLog(
1315
+ "matchPartial.intercept",
1316
+ "skipping route handler during intercept",
1317
+ {
1318
+ localRouteName,
1319
+ segmentId: entry.shortCode,
1320
+ },
1321
+ );
1322
+ if (!seenMatchIds.has(entry.shortCode)) {
1323
+ seenMatchIds.add(entry.shortCode);
1324
+ matchedIds.push(entry.shortCode);
1325
+ }
1326
+ continue;
1327
+ }
1328
+
1329
+ const nonParallelEntry = entry as Exclude<EntryData, { type: "parallel" }>;
1330
+ if (entry.type === "cache") {
1331
+ const store = RSCRouterContext.getStore();
1332
+ if (store) store.insideCacheScope = true;
1333
+ }
1334
+ const doneEntry = track(`segment:${entry.id}`, 1);
1335
+ const resolved = await resolveWithErrorBoundary(
1336
+ nonParallelEntry,
1337
+ params,
1338
+ () =>
1339
+ resolveSegmentWithRevalidation(
1340
+ nonParallelEntry,
1341
+ routeKey,
1342
+ params,
1343
+ context,
1344
+ clientSegmentSet,
1345
+ prevParams,
1346
+ request,
1347
+ prevUrl,
1348
+ nextUrl,
1349
+ loaderPromises,
1350
+ deps,
1351
+ actionContext,
1352
+ stale,
1353
+ ),
1354
+ (seg) => ({ segments: [seg], matchedIds: [seg.id] }),
1355
+ deps,
1356
+ { request, url: context.url, routeKey, isPartial: true, telemetry },
1357
+ pathname,
1358
+ );
1359
+ doneEntry();
1360
+
1361
+ // Deduplicate segments and matchedIds by ID, matching resolveAllSegments.
1362
+ // include() scopes can produce entries that resolve the same shared
1363
+ // layout/loader segment. Duplicates cause React tree depth changes.
1364
+ for (const seg of resolved.segments) {
1365
+ if (!seenSegIds.has(seg.id)) {
1366
+ seenSegIds.add(seg.id);
1367
+ allSegments.push(seg);
1368
+ }
1369
+ }
1370
+ for (const id of resolved.matchedIds) {
1371
+ if (!seenMatchIds.has(id)) {
1372
+ seenMatchIds.add(id);
1373
+ matchedIds.push(id);
1374
+ }
1375
+ }
1376
+ }
1377
+
1378
+ return { segments: allSegments, matchedIds };
1379
+ }