@rangojs/router 0.0.0-experimental.7 → 0.0.0-experimental.71

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 (307) 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 +4951 -930
  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/hooks/SKILL.md +334 -72
  14. package/skills/host-router/SKILL.md +218 -0
  15. package/skills/intercept/SKILL.md +131 -8
  16. package/skills/layout/SKILL.md +100 -3
  17. package/skills/links/SKILL.md +92 -31
  18. package/skills/loader/SKILL.md +404 -44
  19. package/skills/middleware/SKILL.md +173 -34
  20. package/skills/mime-routes/SKILL.md +128 -0
  21. package/skills/parallel/SKILL.md +204 -1
  22. package/skills/prerender/SKILL.md +685 -0
  23. package/skills/rango/SKILL.md +85 -16
  24. package/skills/response-routes/SKILL.md +411 -0
  25. package/skills/route/SKILL.md +257 -14
  26. package/skills/router-setup/SKILL.md +210 -32
  27. package/skills/tailwind/SKILL.md +129 -0
  28. package/skills/theme/SKILL.md +9 -8
  29. package/skills/typesafety/SKILL.md +328 -89
  30. package/skills/use-cache/SKILL.md +324 -0
  31. package/src/__internal.ts +102 -4
  32. package/src/bin/rango.ts +321 -0
  33. package/src/browser/action-coordinator.ts +97 -0
  34. package/src/browser/action-response-classifier.ts +99 -0
  35. package/src/browser/app-version.ts +14 -0
  36. package/src/browser/event-controller.ts +92 -64
  37. package/src/browser/history-state.ts +80 -0
  38. package/src/browser/intercept-utils.ts +52 -0
  39. package/src/browser/link-interceptor.ts +24 -4
  40. package/src/browser/logging.ts +55 -0
  41. package/src/browser/merge-segment-loaders.ts +20 -12
  42. package/src/browser/navigation-bridge.ts +296 -558
  43. package/src/browser/navigation-client.ts +179 -69
  44. package/src/browser/navigation-store.ts +73 -55
  45. package/src/browser/navigation-transaction.ts +297 -0
  46. package/src/browser/network-error-handler.ts +61 -0
  47. package/src/browser/partial-update.ts +328 -313
  48. package/src/browser/prefetch/cache.ts +206 -0
  49. package/src/browser/prefetch/fetch.ts +150 -0
  50. package/src/browser/prefetch/observer.ts +65 -0
  51. package/src/browser/prefetch/policy.ts +48 -0
  52. package/src/browser/prefetch/queue.ts +160 -0
  53. package/src/browser/prefetch/resource-ready.ts +77 -0
  54. package/src/browser/rango-state.ts +112 -0
  55. package/src/browser/react/Link.tsx +230 -74
  56. package/src/browser/react/NavigationProvider.tsx +87 -11
  57. package/src/browser/react/context.ts +11 -0
  58. package/src/browser/react/filter-segment-order.ts +11 -0
  59. package/src/browser/react/index.ts +12 -12
  60. package/src/browser/react/location-state-shared.ts +95 -53
  61. package/src/browser/react/location-state.ts +60 -15
  62. package/src/browser/react/mount-context.ts +6 -1
  63. package/src/browser/react/nonce-context.ts +23 -0
  64. package/src/browser/react/shallow-equal.ts +27 -0
  65. package/src/browser/react/use-action.ts +29 -51
  66. package/src/browser/react/use-client-cache.ts +5 -3
  67. package/src/browser/react/use-handle.ts +30 -126
  68. package/src/browser/react/use-href.tsx +2 -2
  69. package/src/browser/react/use-link-status.ts +6 -5
  70. package/src/browser/react/use-navigation.ts +22 -63
  71. package/src/browser/react/use-params.ts +65 -0
  72. package/src/browser/react/use-pathname.ts +47 -0
  73. package/src/browser/react/use-router.ts +76 -0
  74. package/src/browser/react/use-search-params.ts +56 -0
  75. package/src/browser/react/use-segments.ts +80 -97
  76. package/src/browser/response-adapter.ts +73 -0
  77. package/src/browser/rsc-router.tsx +214 -58
  78. package/src/browser/scroll-restoration.ts +127 -52
  79. package/src/browser/segment-reconciler.ts +221 -0
  80. package/src/browser/segment-structure-assert.ts +16 -0
  81. package/src/browser/server-action-bridge.ts +510 -603
  82. package/src/browser/shallow.ts +6 -1
  83. package/src/browser/types.ts +141 -48
  84. package/src/browser/validate-redirect-origin.ts +29 -0
  85. package/src/build/generate-manifest.ts +235 -24
  86. package/src/build/generate-route-types.ts +39 -0
  87. package/src/build/index.ts +13 -0
  88. package/src/build/route-trie.ts +265 -0
  89. package/src/build/route-types/ast-helpers.ts +25 -0
  90. package/src/build/route-types/ast-route-extraction.ts +98 -0
  91. package/src/build/route-types/codegen.ts +102 -0
  92. package/src/build/route-types/include-resolution.ts +418 -0
  93. package/src/build/route-types/param-extraction.ts +48 -0
  94. package/src/build/route-types/per-module-writer.ts +128 -0
  95. package/src/build/route-types/router-processing.ts +618 -0
  96. package/src/build/route-types/scan-filter.ts +85 -0
  97. package/src/build/runtime-discovery.ts +231 -0
  98. package/src/cache/background-task.ts +34 -0
  99. package/src/cache/cache-key-utils.ts +44 -0
  100. package/src/cache/cache-policy.ts +125 -0
  101. package/src/cache/cache-runtime.ts +342 -0
  102. package/src/cache/cache-scope.ts +167 -309
  103. package/src/cache/cf/cf-cache-store.ts +571 -17
  104. package/src/cache/cf/index.ts +13 -3
  105. package/src/cache/document-cache.ts +116 -77
  106. package/src/cache/handle-capture.ts +81 -0
  107. package/src/cache/handle-snapshot.ts +41 -0
  108. package/src/cache/index.ts +1 -15
  109. package/src/cache/memory-segment-store.ts +191 -13
  110. package/src/cache/profile-registry.ts +73 -0
  111. package/src/cache/read-through-swr.ts +134 -0
  112. package/src/cache/segment-codec.ts +256 -0
  113. package/src/cache/taint.ts +153 -0
  114. package/src/cache/types.ts +72 -122
  115. package/src/client.rsc.tsx +3 -1
  116. package/src/client.tsx +105 -179
  117. package/src/component-utils.ts +4 -4
  118. package/src/components/DefaultDocument.tsx +5 -1
  119. package/src/context-var.ts +156 -0
  120. package/src/debug.ts +19 -9
  121. package/src/errors.ts +108 -2
  122. package/src/handle.ts +55 -29
  123. package/src/handles/MetaTags.tsx +73 -20
  124. package/src/handles/breadcrumbs.ts +66 -0
  125. package/src/handles/index.ts +1 -0
  126. package/src/handles/meta.ts +30 -13
  127. package/src/host/cookie-handler.ts +21 -15
  128. package/src/host/errors.ts +8 -8
  129. package/src/host/index.ts +4 -7
  130. package/src/host/pattern-matcher.ts +27 -27
  131. package/src/host/router.ts +61 -39
  132. package/src/host/testing.ts +8 -8
  133. package/src/host/types.ts +15 -7
  134. package/src/host/utils.ts +1 -1
  135. package/src/href-client.ts +119 -29
  136. package/src/index.rsc.ts +155 -19
  137. package/src/index.ts +223 -30
  138. package/src/internal-debug.ts +11 -0
  139. package/src/loader.rsc.ts +26 -157
  140. package/src/loader.ts +27 -10
  141. package/src/network-error-thrower.tsx +3 -1
  142. package/src/outlet-provider.tsx +45 -0
  143. package/src/prerender/param-hash.ts +37 -0
  144. package/src/prerender/store.ts +186 -0
  145. package/src/prerender.ts +524 -0
  146. package/src/reverse.ts +351 -0
  147. package/src/root-error-boundary.tsx +41 -29
  148. package/src/route-content-wrapper.tsx +7 -4
  149. package/src/route-definition/dsl-helpers.ts +982 -0
  150. package/src/route-definition/helper-factories.ts +200 -0
  151. package/src/route-definition/helpers-types.ts +434 -0
  152. package/src/route-definition/index.ts +55 -0
  153. package/src/route-definition/redirect.ts +101 -0
  154. package/src/route-definition/resolve-handler-use.ts +149 -0
  155. package/src/route-definition.ts +1 -1428
  156. package/src/route-map-builder.ts +217 -123
  157. package/src/route-name.ts +53 -0
  158. package/src/route-types.ts +70 -8
  159. package/src/router/content-negotiation.ts +215 -0
  160. package/src/router/debug-manifest.ts +72 -0
  161. package/src/router/error-handling.ts +9 -9
  162. package/src/router/find-match.ts +160 -0
  163. package/src/router/handler-context.ts +435 -86
  164. package/src/router/intercept-resolution.ts +402 -0
  165. package/src/router/lazy-includes.ts +237 -0
  166. package/src/router/loader-resolution.ts +356 -128
  167. package/src/router/logging.ts +251 -0
  168. package/src/router/manifest.ts +154 -35
  169. package/src/router/match-api.ts +555 -0
  170. package/src/router/match-context.ts +5 -3
  171. package/src/router/match-handlers.ts +440 -0
  172. package/src/router/match-middleware/background-revalidation.ts +108 -93
  173. package/src/router/match-middleware/cache-lookup.ts +459 -10
  174. package/src/router/match-middleware/cache-store.ts +98 -26
  175. package/src/router/match-middleware/intercept-resolution.ts +57 -17
  176. package/src/router/match-middleware/segment-resolution.ts +80 -6
  177. package/src/router/match-pipelines.ts +10 -45
  178. package/src/router/match-result.ts +135 -35
  179. package/src/router/metrics.ts +240 -15
  180. package/src/router/middleware-cookies.ts +55 -0
  181. package/src/router/middleware-types.ts +220 -0
  182. package/src/router/middleware.ts +324 -369
  183. package/src/router/navigation-snapshot.ts +182 -0
  184. package/src/router/pattern-matching.ts +211 -43
  185. package/src/router/prerender-match.ts +502 -0
  186. package/src/router/preview-match.ts +98 -0
  187. package/src/router/request-classification.ts +310 -0
  188. package/src/router/revalidation.ts +137 -38
  189. package/src/router/route-snapshot.ts +245 -0
  190. package/src/router/router-context.ts +41 -21
  191. package/src/router/router-interfaces.ts +484 -0
  192. package/src/router/router-options.ts +618 -0
  193. package/src/router/router-registry.ts +24 -0
  194. package/src/router/segment-resolution/fresh.ts +748 -0
  195. package/src/router/segment-resolution/helpers.ts +268 -0
  196. package/src/router/segment-resolution/loader-cache.ts +199 -0
  197. package/src/router/segment-resolution/revalidation.ts +1379 -0
  198. package/src/router/segment-resolution/static-store.ts +67 -0
  199. package/src/router/segment-resolution.ts +21 -0
  200. package/src/router/segment-wrappers.ts +291 -0
  201. package/src/router/telemetry-otel.ts +299 -0
  202. package/src/router/telemetry.ts +300 -0
  203. package/src/router/timeout.ts +148 -0
  204. package/src/router/trie-matching.ts +239 -0
  205. package/src/router/types.ts +78 -3
  206. package/src/router.ts +740 -4252
  207. package/src/rsc/handler-context.ts +45 -0
  208. package/src/rsc/handler.ts +907 -797
  209. package/src/rsc/helpers.ts +140 -6
  210. package/src/rsc/index.ts +0 -20
  211. package/src/rsc/loader-fetch.ts +229 -0
  212. package/src/rsc/manifest-init.ts +90 -0
  213. package/src/rsc/nonce.ts +14 -0
  214. package/src/rsc/origin-guard.ts +141 -0
  215. package/src/rsc/progressive-enhancement.ts +391 -0
  216. package/src/rsc/response-error.ts +37 -0
  217. package/src/rsc/response-route-handler.ts +347 -0
  218. package/src/rsc/rsc-rendering.ts +246 -0
  219. package/src/rsc/runtime-warnings.ts +42 -0
  220. package/src/rsc/server-action.ts +356 -0
  221. package/src/rsc/ssr-setup.ts +128 -0
  222. package/src/rsc/types.ts +46 -11
  223. package/src/search-params.ts +230 -0
  224. package/src/segment-system.tsx +165 -17
  225. package/src/server/context.ts +315 -58
  226. package/src/server/cookie-store.ts +190 -0
  227. package/src/server/fetchable-loader-store.ts +37 -0
  228. package/src/server/handle-store.ts +113 -15
  229. package/src/server/loader-registry.ts +24 -64
  230. package/src/server/request-context.ts +607 -81
  231. package/src/server.ts +35 -130
  232. package/src/ssr/index.tsx +103 -30
  233. package/src/static-handler.ts +126 -0
  234. package/src/theme/ThemeProvider.tsx +21 -15
  235. package/src/theme/ThemeScript.tsx +5 -5
  236. package/src/theme/constants.ts +5 -2
  237. package/src/theme/index.ts +4 -14
  238. package/src/theme/theme-context.ts +4 -30
  239. package/src/theme/theme-script.ts +21 -18
  240. package/src/types/boundaries.ts +158 -0
  241. package/src/types/cache-types.ts +198 -0
  242. package/src/types/error-types.ts +192 -0
  243. package/src/types/global-namespace.ts +100 -0
  244. package/src/types/handler-context.ts +791 -0
  245. package/src/types/index.ts +88 -0
  246. package/src/types/loader-types.ts +210 -0
  247. package/src/types/route-config.ts +170 -0
  248. package/src/types/route-entry.ts +109 -0
  249. package/src/types/segments.ts +151 -0
  250. package/src/types.ts +1 -1623
  251. package/src/urls/include-helper.ts +197 -0
  252. package/src/urls/index.ts +53 -0
  253. package/src/urls/path-helper-types.ts +346 -0
  254. package/src/urls/path-helper.ts +364 -0
  255. package/src/urls/pattern-types.ts +107 -0
  256. package/src/urls/response-types.ts +116 -0
  257. package/src/urls/type-extraction.ts +372 -0
  258. package/src/urls/urls-function.ts +98 -0
  259. package/src/urls.ts +1 -802
  260. package/src/use-loader.tsx +161 -81
  261. package/src/vite/discovery/bundle-postprocess.ts +181 -0
  262. package/src/vite/discovery/discover-routers.ts +348 -0
  263. package/src/vite/discovery/prerender-collection.ts +439 -0
  264. package/src/vite/discovery/route-types-writer.ts +258 -0
  265. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  266. package/src/vite/discovery/state.ts +117 -0
  267. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  268. package/src/vite/index.ts +15 -1129
  269. package/src/vite/plugin-types.ts +103 -0
  270. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  271. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  272. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  273. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -53
  274. package/src/vite/plugins/expose-id-utils.ts +299 -0
  275. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  276. package/src/vite/plugins/expose-ids/handler-transform.ts +209 -0
  277. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  278. package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
  279. package/src/vite/plugins/expose-ids/types.ts +45 -0
  280. package/src/vite/plugins/expose-internal-ids.ts +786 -0
  281. package/src/vite/plugins/performance-tracks.ts +88 -0
  282. package/src/vite/plugins/refresh-cmd.ts +127 -0
  283. package/src/vite/plugins/use-cache-transform.ts +323 -0
  284. package/src/vite/plugins/version-injector.ts +83 -0
  285. package/src/vite/plugins/version-plugin.ts +266 -0
  286. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  287. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  288. package/src/vite/rango.ts +462 -0
  289. package/src/vite/router-discovery.ts +918 -0
  290. package/src/vite/utils/ast-handler-extract.ts +517 -0
  291. package/src/vite/utils/banner.ts +36 -0
  292. package/src/vite/utils/bundle-analysis.ts +137 -0
  293. package/src/vite/utils/manifest-utils.ts +70 -0
  294. package/src/vite/{package-resolution.ts → utils/package-resolution.ts} +25 -29
  295. package/src/vite/utils/prerender-utils.ts +207 -0
  296. package/src/vite/utils/shared-utils.ts +170 -0
  297. package/CLAUDE.md +0 -43
  298. package/src/browser/lru-cache.ts +0 -69
  299. package/src/browser/request-controller.ts +0 -164
  300. package/src/cache/memory-store.ts +0 -253
  301. package/src/href-context.ts +0 -33
  302. package/src/href.ts +0 -255
  303. package/src/server/route-manifest-cache.ts +0 -173
  304. package/src/vite/expose-handle-id.ts +0 -209
  305. package/src/vite/expose-loader-id.ts +0 -426
  306. package/src/vite/expose-location-state-id.ts +0 -177
  307. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
@@ -0,0 +1,982 @@
1
+ import type { ReactNode } from "react";
2
+ import type {
3
+ PartialCacheOptions,
4
+ Handler,
5
+ LoaderDefinition,
6
+ MiddlewareFn,
7
+ ShouldRevalidateFn,
8
+ TransitionConfig,
9
+ } from "../types.js";
10
+ import {
11
+ getContext,
12
+ getNamePrefix,
13
+ getUrlPrefix,
14
+ type EntryData,
15
+ type InterceptEntry,
16
+ } from "../server/context";
17
+ import { invariant } from "../errors";
18
+ import { isCachedFunction } from "../cache/taint.js";
19
+ import { RSCRouterContext } from "../server/context";
20
+ import { isStaticHandler } from "../static-handler.js";
21
+ import RootLayout from "../server/root-layout";
22
+ import type {
23
+ AllUseItems,
24
+ RouteItem,
25
+ ParallelItem,
26
+ InterceptItem,
27
+ MiddlewareItem,
28
+ RevalidateItem,
29
+ LoaderItem,
30
+ LoadingItem,
31
+ ErrorBoundaryItem,
32
+ NotFoundBoundaryItem,
33
+ LayoutItem,
34
+ WhenItem,
35
+ CacheItem,
36
+ TransitionItem,
37
+ UseItems,
38
+ } from "../route-types.js";
39
+ import type { RouteHelpers } from "./helpers-types.js";
40
+ import { resolveHandlerUse, mergeHandlerUse } from "./resolve-handler-use.js";
41
+
42
+ /**
43
+ * Check if an item contains routes (directly or inside nested structures like cache).
44
+ * Used to determine if a layout or cache should be treated as an orphan.
45
+ */
46
+ const hasRoutesInItem = (item: AllUseItems): boolean => {
47
+ if (item.type === "route") return true;
48
+ // Lazy includes contain deferred routes — treat them as having routes
49
+ // to prevent the parent layout from being misclassified as orphan,
50
+ // which would clear its parent pointer and break the middleware chain.
51
+ if (item.type === "include") return true;
52
+ if (item.type === "cache" && item.uses) {
53
+ return item.uses.some((child) => hasRoutesInItem(child));
54
+ }
55
+ if (item.type === "layout" && item.uses) {
56
+ return item.uses.some((child) => hasRoutesInItem(child));
57
+ }
58
+ return false;
59
+ };
60
+
61
+ const revalidate: RouteHelpers<any, any>["revalidate"] = (fn) => {
62
+ const ctx = getContext().getStore();
63
+ if (!ctx) throw new Error("revalidate() must be called inside map()");
64
+
65
+ // Attach to last entry in stack
66
+ const parent = ctx.parent;
67
+ if (!parent || !("revalidate" in parent)) {
68
+ invariant(false, "No parent entry available for revalidate()");
69
+ }
70
+ const name = `$${getContext().getNextIndex("revalidate")}`;
71
+ parent.revalidate.push(fn);
72
+ return { name, type: "revalidate" } as RevalidateItem;
73
+ };
74
+
75
+ /**
76
+ * Error boundary helper - attaches an error fallback to the current entry
77
+ *
78
+ * When an error occurs during rendering of this segment or its children,
79
+ * the fallback will be rendered instead. The fallback can be:
80
+ * - A static ReactNode (e.g., <ErrorPage />)
81
+ * - A handler function that receives error info and reset function
82
+ *
83
+ * Error boundaries catch errors from:
84
+ * - Middleware execution
85
+ * - Loader execution
86
+ * - Handler/component rendering
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * layout(<ShopLayout />, () => [
91
+ * errorBoundary(<ShopErrorFallback />),
92
+ * route("products.detail", ProductDetail),
93
+ * ])
94
+ *
95
+ * // Or with handler for dynamic error UI:
96
+ * route("products.detail", ProductDetail, () => [
97
+ * errorBoundary(({ error, reset }) => (
98
+ * <div>
99
+ * <h2>Product failed to load</h2>
100
+ * <p>{error.message}</p>
101
+ * <button onClick={reset}>Retry</button>
102
+ * </div>
103
+ * )),
104
+ * ])
105
+ * ```
106
+ */
107
+ const errorBoundary: RouteHelpers<any, any>["errorBoundary"] = (fallback) => {
108
+ const ctx = getContext().getStore();
109
+ if (!ctx) throw new Error("errorBoundary() must be called inside map()");
110
+
111
+ // Attach to parent entry in stack
112
+ const parent = ctx.parent;
113
+ if (!parent || !("errorBoundary" in parent)) {
114
+ invariant(false, "No parent entry available for errorBoundary()");
115
+ }
116
+ const name = `$${getContext().getNextIndex("errorBoundary")}`;
117
+ parent.errorBoundary.push(fallback);
118
+ return { name, type: "errorBoundary" } as ErrorBoundaryItem;
119
+ };
120
+
121
+ /**
122
+ * NotFound boundary helper - attaches a not-found fallback to the current entry
123
+ *
124
+ * When a DataNotFoundError is thrown (via notFound()) during rendering of this
125
+ * segment or its children, the fallback will be rendered instead. The fallback can be:
126
+ * - A static ReactNode (e.g., <ProductNotFound />)
127
+ * - A handler function that receives not found info
128
+ *
129
+ * NotFound boundaries catch DataNotFoundError from:
130
+ * - Loader execution
131
+ * - Handler/component rendering
132
+ *
133
+ * @example
134
+ * ```typescript
135
+ * layout(<ShopLayout />, () => [
136
+ * notFoundBoundary(<ProductNotFound />),
137
+ * route("products.detail", ProductDetail),
138
+ * ])
139
+ *
140
+ * // Or with handler for dynamic not found UI:
141
+ * route("products.detail", ProductDetail, () => [
142
+ * notFoundBoundary(({ notFound }) => (
143
+ * <div>
144
+ * <h2>Product not found</h2>
145
+ * <p>{notFound.message}</p>
146
+ * <a href="/products">Browse all products</a>
147
+ * </div>
148
+ * )),
149
+ * ])
150
+ * ```
151
+ */
152
+ const notFoundBoundary: RouteHelpers<any, any>["notFoundBoundary"] = (
153
+ fallback,
154
+ ) => {
155
+ const ctx = getContext().getStore();
156
+ if (!ctx) throw new Error("notFoundBoundary() must be called inside map()");
157
+
158
+ // Attach to parent entry in stack
159
+ const parent = ctx.parent;
160
+ if (!parent || !("notFoundBoundary" in parent)) {
161
+ invariant(false, "No parent entry available for notFoundBoundary()");
162
+ }
163
+ const name = `$${getContext().getNextIndex("notFoundBoundary")}`;
164
+ parent.notFoundBoundary.push(fallback);
165
+ return { name, type: "notFoundBoundary" } as NotFoundBoundaryItem;
166
+ };
167
+
168
+ /**
169
+ * When helper - defines a condition for intercept activation
170
+ *
171
+ * Only valid inside intercept() use() callback. The when() function
172
+ * is captured by the intercept and stored in its `when` array.
173
+ * During soft navigation, all when() conditions must return true
174
+ * for the intercept to activate.
175
+ */
176
+ const when: RouteHelpers<any, any>["when"] = (fn) => {
177
+ const ctx = getContext().getStore();
178
+ if (!ctx) throw new Error("when() must be called inside intercept()");
179
+
180
+ // The when() function needs to be captured by the intercept's tempParent
181
+ // which should have a `when` array. If not present, we're not inside intercept()
182
+ const parent = ctx.parent as any;
183
+ if (!parent || !("when" in parent)) {
184
+ invariant(
185
+ false,
186
+ "when() can only be used inside intercept() use() callback",
187
+ );
188
+ }
189
+
190
+ const name = `$${getContext().getNextIndex("when")}`;
191
+ parent.when.push(fn);
192
+ return { name, type: "when" } as WhenItem;
193
+ };
194
+
195
+ /**
196
+ * Cache helper - defines caching configuration for segments
197
+ *
198
+ * Creates a cache boundary that applies to all children unless overridden.
199
+ * When used without children, attaches cache config to the parent entry
200
+ * (e.g., for loader-specific caching).
201
+ *
202
+ * Supports these call signatures:
203
+ * - cache() - no args, uses app-level defaults (for loader caching)
204
+ * - cache(() => [...]) - wraps children with app-level defaults
205
+ * - cache('profileName') - uses a named cache profile
206
+ * - cache('profileName', () => [...]) - named profile with children
207
+ * - cache({ ttl: 60 }, () => [...]) - with explicit options
208
+ */
209
+ const cache: RouteHelpers<any, any>["cache"] = (
210
+ optionsOrChildren?:
211
+ | PartialCacheOptions
212
+ | false
213
+ | string
214
+ | (() => UseItems<AllUseItems>),
215
+ maybeChildren?: () => UseItems<AllUseItems>,
216
+ ) => {
217
+ const store = getContext();
218
+ const ctx = store.getStore();
219
+ if (!ctx) throw new Error("cache() must be called inside map()");
220
+
221
+ // Handle overloaded signature
222
+ let options: PartialCacheOptions | false;
223
+ let children: (() => UseItems<AllUseItems>) | undefined;
224
+
225
+ if (optionsOrChildren === undefined) {
226
+ // cache() - no args, use defaults
227
+ options = {};
228
+ children = undefined;
229
+ } else if (typeof optionsOrChildren === "string") {
230
+ // cache('profileName') or cache('profileName', () => [...])
231
+ // Resolve from context-scoped profiles (set per-router via HelperContext).
232
+ const ctxStore = RSCRouterContext.getStore();
233
+ const profile = ctxStore?.cacheProfiles?.[optionsOrChildren];
234
+ invariant(
235
+ profile,
236
+ `cache("${optionsOrChildren}"): unknown cache profile. ` +
237
+ `Define it in createRouter({ cacheProfiles: { "${optionsOrChildren}": { ttl: ... } } }).`,
238
+ );
239
+ options = { ttl: profile.ttl, swr: profile.swr, tags: profile.tags };
240
+ children = maybeChildren;
241
+ } else if (typeof optionsOrChildren === "function") {
242
+ // cache(() => [...]) - use empty options (will use defaults)
243
+ options = {};
244
+ children = optionsOrChildren;
245
+ } else {
246
+ // cache(options, children) - explicit options
247
+ options = optionsOrChildren;
248
+ children = maybeChildren;
249
+ }
250
+
251
+ // Allocate a single index for this cache() call (used in all paths)
252
+ const cacheIndex = store.getNextIndex("cache");
253
+ const name = `$${cacheIndex}`;
254
+ const cacheConfig = { options };
255
+
256
+ // If no children, create an orphan cache entry (like orphan layouts)
257
+ // This allows cache() to wrap subsequent siblings
258
+ if (!children) {
259
+ const parent = ctx.parent as any;
260
+
261
+ // Check if we're inside a loader() use() callback - special case for loader caching
262
+ if (parent && parent.type === "loader") {
263
+ // Direct assignment to loader entry's cache field
264
+ parent.cache = cacheConfig;
265
+ return { name, type: "cache" } as CacheItem;
266
+ }
267
+
268
+ // Create orphan cache entry (like orphan layout)
269
+ // Subsequent siblings in the same array will attach to this entry
270
+ const namespace = `${ctx.namespace}.${cacheIndex}`;
271
+ const cacheUrlPrefix = getUrlPrefix();
272
+
273
+ const entry = {
274
+ id: namespace,
275
+ shortCode: store.getShortCode("cache"),
276
+ type: "cache",
277
+ parent: parent, // link to current parent for hierarchy
278
+ cache: cacheConfig,
279
+ handler: RootLayout,
280
+ loading: undefined, // Allow loading() to attach loading state
281
+ middleware: [],
282
+ revalidate: [],
283
+ errorBoundary: [],
284
+ notFoundBoundary: [],
285
+ layout: [],
286
+ parallel: {},
287
+ intercept: [],
288
+ loader: [],
289
+ ...(cacheUrlPrefix ? { mountPath: cacheUrlPrefix } : {}),
290
+ } as EntryData;
291
+
292
+ // Attach to parent's layout array (cache entries are structural like layouts)
293
+ if (parent && "layout" in parent) {
294
+ parent.layout.push(entry);
295
+ }
296
+
297
+ // Update context parent so subsequent siblings attach to this cache entry
298
+ // This makes cache() act as sugar for cache(() => [...])
299
+ ctx.parent = entry;
300
+
301
+ return { name: namespace, type: "cache" } as CacheItem;
302
+ }
303
+
304
+ // With children: create a cache entry (like layout with caching semantics)
305
+ const namespace = `${ctx.namespace}.${cacheIndex}`;
306
+ const cacheShortCode = store.getShortCode("cache");
307
+
308
+ const cacheUrlPrefix2 = getUrlPrefix();
309
+
310
+ const entry = {
311
+ id: namespace,
312
+ shortCode: cacheShortCode,
313
+ type: "cache",
314
+ parent: ctx.parent,
315
+ cache: cacheConfig,
316
+ // Cache entries render like layouts (with Outlet as default handler)
317
+ handler: RootLayout, // RootLayout just renders <Outlet />
318
+ loading: undefined, // Allow loading() to attach loading state
319
+ middleware: [],
320
+ revalidate: [],
321
+ errorBoundary: [],
322
+ notFoundBoundary: [],
323
+ layout: [],
324
+ parallel: {},
325
+ intercept: [],
326
+ loader: [],
327
+ ...(cacheUrlPrefix2 ? { mountPath: cacheUrlPrefix2 } : {}),
328
+ } as EntryData;
329
+
330
+ // Run children with cache entry as parent
331
+ const result = store.run(namespace, entry, children)?.flat(3);
332
+
333
+ invariant(
334
+ Array.isArray(result) && result.every((item) => isValidUseItem(item)),
335
+ `cache() children callback must return an array of use items [${namespace}]`,
336
+ );
337
+
338
+ // Check if this cache has routes (including nested caches/layouts)
339
+ const hasRoutes =
340
+ result &&
341
+ Array.isArray(result) &&
342
+ result.some((item) => hasRoutesInItem(item));
343
+
344
+ if (!hasRoutes) {
345
+ const parent = ctx.parent;
346
+ if (parent && "layout" in parent) {
347
+ // Attach to parent's layout array (cache entries are structural like layouts)
348
+ entry.parent = null;
349
+ parent.layout.push(entry);
350
+ }
351
+ }
352
+
353
+ return { name: namespace, type: "cache", uses: result } as CacheItem;
354
+ };
355
+
356
+ const middleware: RouteHelpers<any, any>["middleware"] = (...fn) => {
357
+ // Prevent "use cache" functions from being used as middleware.
358
+ // Checked before context validation — this is a static invariant.
359
+ for (const f of fn) {
360
+ if (isCachedFunction(f)) {
361
+ throw new Error(
362
+ `A "use cache" function cannot be used as middleware. ` +
363
+ `Cached functions return data and do not participate in the ` +
364
+ `middleware chain. Remove the "use cache" directive or use a ` +
365
+ `regular middleware function instead.`,
366
+ );
367
+ }
368
+ }
369
+
370
+ const ctx = getContext().getStore();
371
+ if (!ctx) throw new Error("middleware() must be called inside map()");
372
+
373
+ // Attach to last entry in stack
374
+ const parent = ctx.parent;
375
+ if (!parent || !("middleware" in parent)) {
376
+ invariant(false, "No parent entry available for middleware()");
377
+ }
378
+ const name = `$${getContext().getNextIndex("middleware")}`;
379
+ parent.middleware.push(...fn);
380
+ return { name, type: "middleware" } as MiddlewareItem;
381
+ };
382
+
383
+ const parallel: RouteHelpers<any, any>["parallel"] = (slots, use) => {
384
+ const store = getContext();
385
+ const ctx = store.getStore();
386
+ if (!ctx) throw new Error("parallel() must be called inside map()");
387
+
388
+ if (!ctx.parent || !ctx.parent?.parallel) {
389
+ invariant(false, "No parent entry available for parallel()");
390
+ }
391
+
392
+ invariant(
393
+ ctx.parent.type !== "parallel",
394
+ "parallel() cannot be nested inside another parallel()",
395
+ );
396
+
397
+ const slotNames = Object.keys(slots as Record<string, any>) as `@${string}`[];
398
+
399
+ const namespace = `${ctx.namespace}.$${store.getNextIndex("parallel")}`;
400
+
401
+ // Unwrap any static handler definitions in parallel slots
402
+ const unwrappedSlots: Record<string, any> = {};
403
+ let hasStaticSlot = false;
404
+ const staticSlotIds: Record<string, string> = {};
405
+ for (const [slotName, slotHandler] of Object.entries(
406
+ slots as Record<string, any>,
407
+ )) {
408
+ if (isStaticHandler(slotHandler)) {
409
+ hasStaticSlot = true;
410
+ unwrappedSlots[slotName] = slotHandler.handler;
411
+ if (slotHandler.$$id) {
412
+ staticSlotIds[slotName] = slotHandler.$$id;
413
+ // Capture namespace prefix for build-time reverse() resolution
414
+ if (ctx.namePrefix) {
415
+ (slotHandler as any).$$routePrefix = ctx.namePrefix;
416
+ }
417
+ }
418
+ } else {
419
+ unwrappedSlots[slotName] = slotHandler;
420
+ }
421
+ }
422
+
423
+ // Create full EntryData for parallel with its own loaders/revalidate/loading
424
+ const parallelUrlPrefix = getUrlPrefix();
425
+ const entry = {
426
+ id: namespace,
427
+ shortCode: store.getShortCode("parallel"),
428
+ type: "parallel",
429
+ parent: null, // Parallels don't participate in parent chain traversal
430
+ handler: unwrappedSlots,
431
+ loading: undefined, // Allow loading() to attach loading state
432
+ middleware: [],
433
+ revalidate: [],
434
+ errorBoundary: [],
435
+ notFoundBoundary: [],
436
+ layout: [],
437
+ parallel: {},
438
+ intercept: [],
439
+ loader: [],
440
+ ...(parallelUrlPrefix ? { mountPath: parallelUrlPrefix } : {}),
441
+ ...(hasStaticSlot
442
+ ? {
443
+ isStaticPrerender: true as const,
444
+ ...(Object.keys(staticSlotIds).length > 0
445
+ ? { staticHandlerIds: staticSlotIds }
446
+ : {}),
447
+ }
448
+ : {}),
449
+ } satisfies EntryData;
450
+
451
+ for (const slotName of slotNames) {
452
+ const slotEntry = {
453
+ ...entry,
454
+ handler: { [slotName]: unwrappedSlots[slotName]! },
455
+ middleware: [...entry.middleware],
456
+ revalidate: [...entry.revalidate],
457
+ errorBoundary: [...entry.errorBoundary],
458
+ notFoundBoundary: [...entry.notFoundBoundary],
459
+ layout: [...entry.layout],
460
+ parallel: { ...entry.parallel },
461
+ intercept: [...entry.intercept],
462
+ loader: [...entry.loader],
463
+ ...(entry.staticHandlerIds?.[slotName]
464
+ ? {
465
+ isStaticPrerender: true as const,
466
+ staticHandlerIds: { [slotName]: entry.staticHandlerIds[slotName]! },
467
+ }
468
+ : {
469
+ isStaticPrerender: undefined,
470
+ staticHandlerIds: undefined,
471
+ }),
472
+ } satisfies EntryData;
473
+
474
+ // Per-slot: handler.use defaults first, then explicit use second.
475
+ // This matches the "defaults first, overrides second" rule used by
476
+ // path(), layout(), and intercept(). Each slot's handler.use is
477
+ // scoped to its own entry (no cross-slot bleed).
478
+ const slotHandler = (slots as Record<string, any>)[slotName];
479
+ const slotHandlerUse = resolveHandlerUse(slotHandler);
480
+ const slotMergedUse = mergeHandlerUse(slotHandlerUse, use, "parallel");
481
+ if (slotMergedUse) {
482
+ const result = store.run(namespace, slotEntry, slotMergedUse)?.flat(3);
483
+ invariant(
484
+ Array.isArray(result) && result.every((item) => isValidUseItem(item)),
485
+ `parallel() use() callback must return an array of use items [${namespace}]`,
486
+ );
487
+ }
488
+
489
+ ctx.parent.parallel[slotName] = slotEntry;
490
+ }
491
+ return { name: namespace, type: "parallel" } as ParallelItem;
492
+ };
493
+
494
+ /**
495
+ * Intercept helper - defines an intercepting route for soft navigation
496
+ */
497
+ const intercept = (
498
+ slotName: `@${string}`,
499
+ routeName: string,
500
+ handler: any,
501
+ use?: () => any[],
502
+ ) => {
503
+ const store = getContext();
504
+ const ctx = store.getStore();
505
+ if (!ctx) throw new Error("intercept() must be called inside map()");
506
+
507
+ if (!ctx.parent || !ctx.parent?.intercept) {
508
+ invariant(false, "No parent entry available for intercept()");
509
+ }
510
+
511
+ invariant(
512
+ ctx.parent.type !== "parallel",
513
+ "intercept() cannot be used inside parallel()",
514
+ );
515
+
516
+ const namespace = `${ctx.namespace}.$${store.getNextIndex("intercept")}.${slotName}`;
517
+
518
+ // Dot-prefixed = local (add include prefix), unprefixed = global (use as-is)
519
+ const isLocal = typeof routeName === "string" && routeName.startsWith(".");
520
+ const bareRouteName = isLocal ? routeName.slice(1) : routeName;
521
+ const namePrefix = getNamePrefix();
522
+ const prefixedRouteName =
523
+ isLocal && namePrefix ? `${namePrefix}.${bareRouteName}` : bareRouteName;
524
+
525
+ // Create intercept entry with its own loaders/revalidate/middleware/when
526
+ const entry: InterceptEntry = {
527
+ slotName: slotName as `@${string}`,
528
+ routeName: prefixedRouteName,
529
+ handler,
530
+ middleware: [],
531
+ revalidate: [],
532
+ errorBoundary: [],
533
+ notFoundBoundary: [],
534
+ loader: [],
535
+ when: [], // Selector conditions for conditional interception
536
+ };
537
+
538
+ // Merge handler.use defaults with explicit use
539
+ const handlerUseFn = resolveHandlerUse(handler);
540
+ const mergedUse = mergeHandlerUse(handlerUseFn, use, "intercept");
541
+
542
+ // Run merged use callback to collect loaders, revalidate, middleware, etc.
543
+ if (mergedUse) {
544
+ // Create a temporary parent context for the use() callback
545
+ // so that middleware, loader, revalidate attach to the intercept entry
546
+ const originalParent = ctx.parent;
547
+
548
+ // Capture layouts in a temporary array
549
+ const capturedLayouts: EntryData[] = [];
550
+
551
+ const tempParent = {
552
+ ...originalParent,
553
+ middleware: entry.middleware,
554
+ revalidate: entry.revalidate,
555
+ errorBoundary: entry.errorBoundary,
556
+ notFoundBoundary: entry.notFoundBoundary,
557
+ loader: entry.loader,
558
+ layout: capturedLayouts, // Capture layout() calls
559
+ when: entry.when, // Capture when() conditions
560
+ // Use getter/setter to capture loading on the entry
561
+ get loading() {
562
+ return entry.loading;
563
+ },
564
+ set loading(value: ReactNode | false | undefined) {
565
+ entry.loading = value;
566
+ },
567
+ };
568
+ ctx.parent = tempParent as EntryData;
569
+
570
+ const result = mergedUse()?.flat(3);
571
+
572
+ // Restore original parent
573
+ ctx.parent = originalParent;
574
+
575
+ // Extract layout from captured layouts (use first one if multiple)
576
+ // Layout inside intercept should always be ReactNode or Handler, not Record slots
577
+ if (capturedLayouts.length > 0 && capturedLayouts[0].type === "layout") {
578
+ entry.layout = capturedLayouts[0].handler as
579
+ | ReactNode
580
+ | Handler<any, any, any>;
581
+ }
582
+
583
+ invariant(
584
+ Array.isArray(result) && result.every((item) => isValidUseItem(item)),
585
+ `intercept() use() callback must return an array of use items [${namespace}]`,
586
+ );
587
+ }
588
+
589
+ ctx.parent.intercept.push(entry);
590
+ return { name: namespace, type: "intercept" } as InterceptItem;
591
+ };
592
+
593
+ /**
594
+ * Loader helper - attaches a loader to the current entry
595
+ */
596
+ const loaderFn: RouteHelpers<any, any>["loader"] = (loaderDef, use) => {
597
+ const store = getContext();
598
+ const ctx = store.getStore();
599
+ if (!ctx) throw new Error("loader() must be called inside map()");
600
+
601
+ // Attach to last entry in stack
602
+ if (!ctx.parent || !ctx.parent?.loader) {
603
+ invariant(false, "No parent entry available for loader()");
604
+ }
605
+
606
+ const name = `${ctx.namespace}.$${store.getNextIndex("loader")}`;
607
+
608
+ // Create loader entry with empty revalidate array
609
+ const loaderEntry = {
610
+ loader: loaderDef,
611
+ revalidate: [] as ShouldRevalidateFn<any, any>[],
612
+ };
613
+
614
+ // If use() callback provided, run it to collect revalidation rules and cache config
615
+ if (use && typeof use === "function") {
616
+ // Temporarily set context for revalidate()/cache() calls to target this loader
617
+ const originalParent = ctx.parent;
618
+ // Create a temporary "parent" with type "loader" so cache() can detect it.
619
+ // Save existing .cache to distinguish inherited config from newly set config.
620
+ const parentCache = (originalParent as any).cache;
621
+ const tempParent = {
622
+ ...originalParent,
623
+ type: "loader",
624
+ revalidate: loaderEntry.revalidate,
625
+ };
626
+ ctx.parent = tempParent as EntryData;
627
+
628
+ const result = use()?.flat(3);
629
+
630
+ // Copy cache config only if cache() was called during the use() callback.
631
+ // The spread from originalParent may carry an inherited .cache from
632
+ // a parent cache() boundary — only copy if it was newly set.
633
+ if (
634
+ (tempParent as any).cache &&
635
+ (tempParent as any).cache !== parentCache
636
+ ) {
637
+ (loaderEntry as any).cache = (tempParent as any).cache;
638
+ }
639
+
640
+ // Restore original parent
641
+ ctx.parent = originalParent;
642
+
643
+ invariant(
644
+ Array.isArray(result) && result.every((item) => isValidUseItem(item)),
645
+ `loader() use() callback must return an array of use items [${name}]`,
646
+ );
647
+ }
648
+
649
+ ctx.parent.loader.push(loaderEntry);
650
+ return { name, type: "loader" } as LoaderItem;
651
+ };
652
+
653
+ /**
654
+ * Loading helper - attaches a loading component to the current entry
655
+ * Loading components are static (no context) and shown during navigation
656
+ */
657
+ const loadingFn: RouteHelpers<any, any>["loading"] = (component, options) => {
658
+ const store = getContext();
659
+ const ctx = store.getStore();
660
+ if (!ctx) throw new Error("loading() must be called inside map()");
661
+
662
+ const parent = ctx.parent;
663
+ if (!parent || !("loading" in parent)) {
664
+ invariant(false, "No parent entry available for loading()");
665
+ }
666
+
667
+ // Unwrap function form: loading(() => <Skeleton />) → loading(<Skeleton />)
668
+ const resolved =
669
+ typeof component === "function" ? (component as () => any)() : component;
670
+
671
+ // If ssr: false and we're in SSR, set loading to false
672
+ if (options?.ssr === false && ctx.isSSR) {
673
+ parent.loading = false;
674
+ } else {
675
+ parent.loading = resolved;
676
+ }
677
+
678
+ const name = `$${store.getNextIndex("loading")}`;
679
+ return { name, type: "loading" } as LoadingItem;
680
+ };
681
+
682
+ /**
683
+ * Transition helper - attaches a ViewTransition config to the current entry
684
+ * or wraps a group of routes in a transparent layout with ViewTransition
685
+ */
686
+ const transitionFn = (
687
+ configOrChildren?: TransitionConfig | (() => UseItems<AllUseItems>),
688
+ maybeChildren?: () => UseItems<AllUseItems>,
689
+ ): TransitionItem => {
690
+ // Resolve overloaded arguments:
691
+ // transition() -> config={}, children=undefined
692
+ // transition(config) -> config=config, children=undefined
693
+ // transition(children) -> config={}, children=children
694
+ // transition(config, children) -> config=config, children=children
695
+ const config: TransitionConfig =
696
+ typeof configOrChildren === "function" ? {} : (configOrChildren ?? {});
697
+ const children: (() => UseItems<AllUseItems>) | undefined =
698
+ typeof configOrChildren === "function" ? configOrChildren : maybeChildren;
699
+
700
+ const store = getContext();
701
+ const ctx = store.getStore();
702
+ if (!ctx) throw new Error("transition() must be called inside map()");
703
+
704
+ const name = `$${store.getNextIndex("transition")}`;
705
+
706
+ if (!children) {
707
+ // Position 1: child of path() — attach to parent entry
708
+ const parent = ctx.parent;
709
+ if (!parent || !("loading" in parent)) {
710
+ invariant(false, "No parent entry available for transition()");
711
+ }
712
+ parent.transition = config;
713
+ return { name, type: "transition" } as TransitionItem;
714
+ }
715
+
716
+ // Position 2: wrapper — create a transparent layout with transition config
717
+ const namespace = `${ctx.namespace}.${store.getNextIndex("transition")}`;
718
+ const entry = {
719
+ id: namespace,
720
+ shortCode: store.getShortCode("layout"),
721
+ type: "layout",
722
+ parent: ctx.parent,
723
+ handler: RootLayout,
724
+ loading: undefined,
725
+ transition: config,
726
+ middleware: [],
727
+ revalidate: [],
728
+ errorBoundary: [],
729
+ notFoundBoundary: [],
730
+ layout: [],
731
+ parallel: {},
732
+ intercept: [],
733
+ loader: [],
734
+ } as EntryData;
735
+
736
+ const result = store.run(namespace, entry, children)?.flat(3);
737
+
738
+ invariant(
739
+ Array.isArray(result) && result.every((item) => isValidUseItem(item)),
740
+ `transition() children callback must return an array of use items [${namespace}]`,
741
+ );
742
+
743
+ const hasRoutes =
744
+ result &&
745
+ Array.isArray(result) &&
746
+ result.some((item) => hasRoutesInItem(item));
747
+
748
+ if (!hasRoutes) {
749
+ const parent = ctx.parent;
750
+ if (parent && "layout" in parent) {
751
+ entry.parent = null;
752
+ parent.layout.push(entry);
753
+ }
754
+ }
755
+
756
+ return { name: namespace, type: "transition" } as TransitionItem;
757
+ };
758
+
759
+ const routeFn: RouteHelpers<any, any>["route"] = (name, handler, use) => {
760
+ const store = getContext();
761
+ const ctx = store.getStore();
762
+ if (!ctx) throw new Error("route() must be called inside map()");
763
+
764
+ const namespace = `${ctx.namespace}.${store.getNextIndex("route")}.${name}`;
765
+
766
+ const entry = {
767
+ id: namespace,
768
+ shortCode: store.getShortCode("route"),
769
+ type: "route",
770
+ parent: ctx.parent,
771
+ handler: handler as unknown as Handler<any, any, any>,
772
+ loading: undefined, // Allow loading() to attach loading state
773
+ middleware: [],
774
+ revalidate: [],
775
+ errorBoundary: [],
776
+ notFoundBoundary: [],
777
+ layout: [],
778
+ parallel: {},
779
+ intercept: [],
780
+ loader: [],
781
+ } satisfies EntryData;
782
+
783
+ /* We will throw if user is registring same route name twice */
784
+ invariant(
785
+ ctx.manifest.get(name) === undefined,
786
+ `Duplicate route name: ${name} at ${namespace}`,
787
+ );
788
+ /* Register route entry */
789
+ ctx.manifest.set(name, entry);
790
+ /* Merge handler.use defaults with explicit use */
791
+ const handlerUseFn = resolveHandlerUse(handler);
792
+ const mergedUse = mergeHandlerUse(handlerUseFn, use, "route");
793
+ /* Run use and attach handlers */
794
+ if (mergedUse) {
795
+ const result = store.run(namespace, entry, mergedUse)?.flat(3);
796
+ invariant(
797
+ Array.isArray(result) && result.every((item) => isValidUseItem(item)),
798
+ `route() use() callback must return an array of use items [${namespace}]`,
799
+ );
800
+ return { name: namespace, type: "route", uses: result } as RouteItem;
801
+ }
802
+
803
+ /* typesafe item */
804
+ return { name: namespace, type: "route" } as RouteItem;
805
+ };
806
+
807
+ const layout: RouteHelpers<any, any>["layout"] = (handler, use) => {
808
+ const store = getContext();
809
+ const ctx = store.getStore();
810
+ if (!ctx) throw new Error("layout() must be called inside map()");
811
+
812
+ invariant(
813
+ !ctx.parent || ctx.parent.type !== "parallel",
814
+ "layout() cannot be used inside parallel()",
815
+ );
816
+
817
+ const isRoot = !ctx.parent || ctx.parent === null;
818
+ const nextIndex = isRoot ? "$root" : store.getNextIndex("layout");
819
+ const namespace = `${ctx.namespace}.${nextIndex}`;
820
+ const shortCode = store.getShortCode("layout");
821
+
822
+ // Unwrap static handler definition, extract the actual handler function
823
+ const isStatic = isStaticHandler(handler);
824
+ const unwrappedHandler = isStatic ? handler.handler : handler;
825
+
826
+ const urlPrefix = getUrlPrefix();
827
+ const entry = {
828
+ id: namespace,
829
+ shortCode,
830
+ type: "layout",
831
+ parent: ctx.parent,
832
+ handler: unwrappedHandler,
833
+ loading: undefined, // Allow loading() to attach loading state
834
+ middleware: [],
835
+ revalidate: [],
836
+ errorBoundary: [],
837
+ notFoundBoundary: [],
838
+ parallel: {},
839
+ intercept: [],
840
+ layout: [],
841
+ loader: [],
842
+ ...(urlPrefix ? { mountPath: urlPrefix } : {}),
843
+ ...(isStatic
844
+ ? {
845
+ isStaticPrerender: true as const,
846
+ ...(handler.$$id ? { staticHandlerId: handler.$$id } : {}),
847
+ }
848
+ : {}),
849
+ } satisfies EntryData;
850
+
851
+ // Capture namespace prefix on static handler for build-time reverse() resolution
852
+ if (isStatic && handler.$$id && ctx.namePrefix) {
853
+ (handler as any).$$routePrefix = ctx.namePrefix;
854
+ }
855
+
856
+ // Merge handler.use defaults with explicit use
857
+ const handlerUseFn = resolveHandlerUse(handler);
858
+ const mergedUse = mergeHandlerUse(handlerUseFn, use, "layout");
859
+
860
+ // Run merged use callback if present
861
+ let result: AllUseItems[] | undefined;
862
+ if (mergedUse) {
863
+ result = store.run(namespace, entry, mergedUse)?.flat(3);
864
+
865
+ invariant(
866
+ Array.isArray(result) && result.every((item) => isValidUseItem(item)),
867
+ `layout() use() callback must return an array of use items [${namespace}]`,
868
+ );
869
+ }
870
+
871
+ // Check if this is an orphan layout (no routes in children, including nested caches)
872
+ const hasRoutes =
873
+ result &&
874
+ Array.isArray(result) &&
875
+ result.some((item) => hasRoutesInItem(item));
876
+
877
+ if (!hasRoutes) {
878
+ // Orphan layouts must not contain other layouts as children.
879
+ // If we're here, all child layouts are also orphan (if any had routes,
880
+ // hasRoutesInItem would have returned true). Nested orphan chains are
881
+ // confusing — use sibling orphan layouts instead.
882
+ if (result) {
883
+ invariant(
884
+ !result.some((item) => item?.type === "layout"),
885
+ `orphan layout cannot contain other layouts as children [${namespace}]`,
886
+ );
887
+ }
888
+
889
+ const parent = ctx.parent;
890
+
891
+ // Allow orphan layouts at root level if they're part of map() builder result
892
+ if (!parent || parent === null) {
893
+ if (!isRoot) {
894
+ invariant(
895
+ false,
896
+ `Orphan layout cannot be used at non-root level without parent [${namespace}]`,
897
+ );
898
+ }
899
+ // Root-level orphan is allowed (e.g., sibling layouts in map() builder)
900
+ } else {
901
+ // Has parent - register as orphan layout
902
+ invariant(
903
+ parent.type === "route" ||
904
+ parent.type === "layout" ||
905
+ parent.type === "cache",
906
+ `Orphan layouts can only be defined inside route or layout > check [${namespace}]`,
907
+ );
908
+
909
+ // Clear parent pointer for orphan layouts to prevent duplicate processing
910
+ entry.parent = null;
911
+ parent.layout.push(entry);
912
+ }
913
+ }
914
+
915
+ if (result) {
916
+ return { name: namespace, type: "layout", uses: result } as LayoutItem;
917
+ }
918
+ return {
919
+ name: namespace,
920
+ type: "layout",
921
+ } as LayoutItem;
922
+ };
923
+
924
+ const isValidUseItem = (item: any): item is AllUseItems | undefined | null => {
925
+ return (
926
+ typeof item === "undefined" ||
927
+ item === null ||
928
+ (item &&
929
+ typeof item === "object" &&
930
+ "type" in item &&
931
+ [
932
+ "layout",
933
+ "route",
934
+ "middleware",
935
+ "revalidate",
936
+ "parallel",
937
+ "intercept",
938
+ "loader",
939
+ "loading",
940
+ "errorBoundary",
941
+ "notFoundBoundary",
942
+ "when",
943
+ "cache",
944
+ "transition",
945
+ "include", // For urls() include() helper
946
+ ].includes(item.type))
947
+ );
948
+ };
949
+
950
+ // Global helper exports for direct import from @rangojs/router
951
+ export {
952
+ layout,
953
+ cache,
954
+ middleware,
955
+ revalidate,
956
+ parallel,
957
+ intercept,
958
+ when,
959
+ errorBoundary,
960
+ notFoundBoundary,
961
+ loaderFn as loader,
962
+ loadingFn as loading,
963
+ transitionFn as transition,
964
+ };
965
+
966
+ const isOrphanLayout = (item: AllUseItems): boolean => {
967
+ return (
968
+ item.type === "layout" &&
969
+ !item.uses?.some((child) => hasRoutesInItem(child))
970
+ );
971
+ };
972
+
973
+ // Internal exports used by helper-factories.ts
974
+ export {
975
+ routeFn,
976
+ loaderFn,
977
+ loadingFn,
978
+ transitionFn,
979
+ hasRoutesInItem,
980
+ isValidUseItem,
981
+ isOrphanLayout,
982
+ };