@rangojs/router 0.0.0-experimental.2

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 (155) hide show
  1. package/CLAUDE.md +7 -0
  2. package/README.md +19 -0
  3. package/dist/vite/index.js +1298 -0
  4. package/package.json +140 -0
  5. package/skills/caching/SKILL.md +319 -0
  6. package/skills/document-cache/SKILL.md +152 -0
  7. package/skills/hooks/SKILL.md +359 -0
  8. package/skills/intercept/SKILL.md +292 -0
  9. package/skills/layout/SKILL.md +216 -0
  10. package/skills/loader/SKILL.md +365 -0
  11. package/skills/middleware/SKILL.md +442 -0
  12. package/skills/parallel/SKILL.md +255 -0
  13. package/skills/route/SKILL.md +141 -0
  14. package/skills/router-setup/SKILL.md +403 -0
  15. package/skills/theme/SKILL.md +54 -0
  16. package/skills/typesafety/SKILL.md +352 -0
  17. package/src/__mocks__/version.ts +6 -0
  18. package/src/__tests__/component-utils.test.ts +76 -0
  19. package/src/__tests__/route-definition.test.ts +63 -0
  20. package/src/__tests__/urls.test.tsx +436 -0
  21. package/src/browser/event-controller.ts +876 -0
  22. package/src/browser/index.ts +18 -0
  23. package/src/browser/link-interceptor.ts +121 -0
  24. package/src/browser/lru-cache.ts +69 -0
  25. package/src/browser/merge-segment-loaders.ts +126 -0
  26. package/src/browser/navigation-bridge.ts +893 -0
  27. package/src/browser/navigation-client.ts +162 -0
  28. package/src/browser/navigation-store.ts +823 -0
  29. package/src/browser/partial-update.ts +559 -0
  30. package/src/browser/react/Link.tsx +248 -0
  31. package/src/browser/react/NavigationProvider.tsx +275 -0
  32. package/src/browser/react/ScrollRestoration.tsx +94 -0
  33. package/src/browser/react/context.ts +53 -0
  34. package/src/browser/react/index.ts +52 -0
  35. package/src/browser/react/location-state-shared.ts +120 -0
  36. package/src/browser/react/location-state.ts +62 -0
  37. package/src/browser/react/use-action.ts +240 -0
  38. package/src/browser/react/use-client-cache.ts +56 -0
  39. package/src/browser/react/use-handle.ts +178 -0
  40. package/src/browser/react/use-href.tsx +208 -0
  41. package/src/browser/react/use-link-status.ts +134 -0
  42. package/src/browser/react/use-navigation.ts +150 -0
  43. package/src/browser/react/use-segments.ts +188 -0
  44. package/src/browser/request-controller.ts +164 -0
  45. package/src/browser/rsc-router.tsx +353 -0
  46. package/src/browser/scroll-restoration.ts +324 -0
  47. package/src/browser/server-action-bridge.ts +747 -0
  48. package/src/browser/shallow.ts +35 -0
  49. package/src/browser/types.ts +464 -0
  50. package/src/cache/__tests__/document-cache.test.ts +522 -0
  51. package/src/cache/__tests__/memory-segment-store.test.ts +487 -0
  52. package/src/cache/__tests__/memory-store.test.ts +484 -0
  53. package/src/cache/cache-scope.ts +565 -0
  54. package/src/cache/cf/__tests__/cf-cache-store.test.ts +428 -0
  55. package/src/cache/cf/cf-cache-store.ts +428 -0
  56. package/src/cache/cf/index.ts +19 -0
  57. package/src/cache/document-cache.ts +340 -0
  58. package/src/cache/index.ts +58 -0
  59. package/src/cache/memory-segment-store.ts +150 -0
  60. package/src/cache/memory-store.ts +253 -0
  61. package/src/cache/types.ts +387 -0
  62. package/src/client.rsc.tsx +88 -0
  63. package/src/client.tsx +621 -0
  64. package/src/component-utils.ts +76 -0
  65. package/src/components/DefaultDocument.tsx +23 -0
  66. package/src/default-error-boundary.tsx +88 -0
  67. package/src/deps/browser.ts +8 -0
  68. package/src/deps/html-stream-client.ts +2 -0
  69. package/src/deps/html-stream-server.ts +2 -0
  70. package/src/deps/rsc.ts +10 -0
  71. package/src/deps/ssr.ts +2 -0
  72. package/src/errors.ts +259 -0
  73. package/src/handle.ts +120 -0
  74. package/src/handles/MetaTags.tsx +193 -0
  75. package/src/handles/index.ts +6 -0
  76. package/src/handles/meta.ts +247 -0
  77. package/src/href-client.ts +128 -0
  78. package/src/href-context.ts +33 -0
  79. package/src/href.ts +177 -0
  80. package/src/index.rsc.ts +79 -0
  81. package/src/index.ts +87 -0
  82. package/src/loader.rsc.ts +204 -0
  83. package/src/loader.ts +47 -0
  84. package/src/network-error-thrower.tsx +21 -0
  85. package/src/outlet-context.ts +15 -0
  86. package/src/root-error-boundary.tsx +277 -0
  87. package/src/route-content-wrapper.tsx +198 -0
  88. package/src/route-definition.ts +1371 -0
  89. package/src/route-map-builder.ts +146 -0
  90. package/src/route-types.ts +198 -0
  91. package/src/route-utils.ts +89 -0
  92. package/src/router/__tests__/match-context.test.ts +104 -0
  93. package/src/router/__tests__/match-pipelines.test.ts +537 -0
  94. package/src/router/__tests__/match-result.test.ts +566 -0
  95. package/src/router/__tests__/on-error.test.ts +935 -0
  96. package/src/router/__tests__/pattern-matching.test.ts +577 -0
  97. package/src/router/error-handling.ts +287 -0
  98. package/src/router/handler-context.ts +158 -0
  99. package/src/router/loader-resolution.ts +326 -0
  100. package/src/router/manifest.ts +138 -0
  101. package/src/router/match-context.ts +264 -0
  102. package/src/router/match-middleware/background-revalidation.ts +236 -0
  103. package/src/router/match-middleware/cache-lookup.ts +261 -0
  104. package/src/router/match-middleware/cache-store.ts +266 -0
  105. package/src/router/match-middleware/index.ts +81 -0
  106. package/src/router/match-middleware/intercept-resolution.ts +268 -0
  107. package/src/router/match-middleware/segment-resolution.ts +174 -0
  108. package/src/router/match-pipelines.ts +214 -0
  109. package/src/router/match-result.ts +214 -0
  110. package/src/router/metrics.ts +62 -0
  111. package/src/router/middleware.test.ts +1355 -0
  112. package/src/router/middleware.ts +748 -0
  113. package/src/router/pattern-matching.ts +272 -0
  114. package/src/router/revalidation.ts +190 -0
  115. package/src/router/router-context.ts +299 -0
  116. package/src/router/types.ts +96 -0
  117. package/src/router.ts +3876 -0
  118. package/src/rsc/__tests__/helpers.test.ts +175 -0
  119. package/src/rsc/handler.ts +1060 -0
  120. package/src/rsc/helpers.ts +64 -0
  121. package/src/rsc/index.ts +56 -0
  122. package/src/rsc/nonce.ts +18 -0
  123. package/src/rsc/types.ts +237 -0
  124. package/src/segment-system.tsx +456 -0
  125. package/src/server/__tests__/request-context.test.ts +171 -0
  126. package/src/server/context.ts +417 -0
  127. package/src/server/handle-store.ts +230 -0
  128. package/src/server/loader-registry.ts +174 -0
  129. package/src/server/request-context.ts +554 -0
  130. package/src/server/root-layout.tsx +10 -0
  131. package/src/server/tsconfig.json +14 -0
  132. package/src/server.ts +146 -0
  133. package/src/ssr/__tests__/ssr-handler.test.tsx +188 -0
  134. package/src/ssr/index.tsx +234 -0
  135. package/src/theme/ThemeProvider.tsx +291 -0
  136. package/src/theme/ThemeScript.tsx +61 -0
  137. package/src/theme/__tests__/theme.test.ts +120 -0
  138. package/src/theme/constants.ts +55 -0
  139. package/src/theme/index.ts +58 -0
  140. package/src/theme/theme-context.ts +70 -0
  141. package/src/theme/theme-script.ts +152 -0
  142. package/src/theme/types.ts +182 -0
  143. package/src/theme/use-theme.ts +44 -0
  144. package/src/types.ts +1561 -0
  145. package/src/urls.ts +726 -0
  146. package/src/use-loader.tsx +346 -0
  147. package/src/vite/__tests__/expose-loader-id.test.ts +117 -0
  148. package/src/vite/expose-action-id.ts +344 -0
  149. package/src/vite/expose-handle-id.ts +209 -0
  150. package/src/vite/expose-loader-id.ts +357 -0
  151. package/src/vite/expose-location-state-id.ts +177 -0
  152. package/src/vite/index.ts +787 -0
  153. package/src/vite/package-resolution.ts +125 -0
  154. package/src/vite/version.d.ts +12 -0
  155. package/src/vite/virtual-entries.ts +109 -0
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Router Loader Resolution
3
+ *
4
+ * Loader execution, memoization, and error handling utilities.
5
+ */
6
+
7
+ import type { ReactNode } from "react";
8
+ import { track } from "../server/context";
9
+ import type { EntryData } from "../server/context";
10
+ import type {
11
+ ResolvedSegment,
12
+ HandlerContext,
13
+ LoaderDefinition,
14
+ LoaderContext,
15
+ LoaderDataResult,
16
+ ErrorBoundaryHandler,
17
+ ErrorBoundaryFallbackProps,
18
+ ErrorInfo,
19
+ } from "../types";
20
+ import type { LoaderRevalidationResult, ActionContext } from "./types";
21
+ import { isHandle, type Handle } from "../handle.js";
22
+ import type { HandleStore } from "../server/handle-store.js";
23
+ import { getFetchableLoader } from "../loader.rsc.js";
24
+ import { getRequestContext } from "../server/request-context.js";
25
+
26
+ /**
27
+ * Internal callback signature for loader error notifications.
28
+ * This is a simplified callback for internal use in wrapLoaderWithErrorHandling.
29
+ * The caller (wrapLoaderPromise in router.ts) bridges this to the full OnErrorCallback.
30
+ */
31
+ export type LoaderErrorCallback = (
32
+ error: unknown,
33
+ context: {
34
+ segmentId: string;
35
+ loaderName: string;
36
+ handledByBoundary: boolean;
37
+ }
38
+ ) => void;
39
+
40
+ /**
41
+ * Wrap a loader promise with error handling for deferred client-side resolution.
42
+ * Catches errors and converts them to LoaderDataResult objects that include
43
+ * error info and pre-rendered fallback UI when an error boundary is available.
44
+ *
45
+ * @param onError - Optional callback invoked when loader errors occur.
46
+ * This has a simplified signature for internal use - the caller (typically
47
+ * wrapLoaderPromise in router.ts) is responsible for bridging to the full
48
+ * OnErrorCallback with complete request context (request, url, env, etc.).
49
+ */
50
+ export function wrapLoaderWithErrorHandling<T>(
51
+ promise: Promise<T>,
52
+ entry: EntryData,
53
+ segmentId: string,
54
+ pathname: string,
55
+ findNearestErrorBoundary: (
56
+ entry: EntryData | null
57
+ ) => ReactNode | ErrorBoundaryHandler | null,
58
+ createErrorInfo: (
59
+ error: unknown,
60
+ segmentId: string,
61
+ segmentType: ErrorInfo["segmentType"]
62
+ ) => ErrorInfo,
63
+ onError?: LoaderErrorCallback
64
+ ): Promise<LoaderDataResult<T>> {
65
+ // Extract loader name from segmentId (format: "M1L0D0.loaderName")
66
+ const loaderName = segmentId.split(".").pop() || "unknown";
67
+
68
+ return Promise.resolve(promise)
69
+ .then(
70
+ (data): LoaderDataResult<T> => ({
71
+ __loaderResult: true,
72
+ ok: true,
73
+ data,
74
+ })
75
+ )
76
+ .catch((error): LoaderDataResult<T> => {
77
+ // Find nearest error boundary
78
+ const fallback = findNearestErrorBoundary(entry);
79
+
80
+ // Create error info
81
+ const errorInfo = createErrorInfo(error, segmentId, "loader");
82
+
83
+ // Invoke onError callback if provided
84
+ onError?.(error, {
85
+ segmentId,
86
+ loaderName,
87
+ handledByBoundary: !!fallback,
88
+ });
89
+
90
+ if (!fallback) {
91
+ // No error boundary - return error result without fallback
92
+ // Client will throw this error
93
+ return {
94
+ __loaderResult: true,
95
+ ok: false,
96
+ error: errorInfo,
97
+ fallback: null,
98
+ };
99
+ }
100
+
101
+ // Render fallback on server
102
+ let renderedFallback: ReactNode;
103
+ if (typeof fallback === "function") {
104
+ // ErrorBoundaryHandler - call with error info
105
+ const props: ErrorBoundaryFallbackProps = {
106
+ error: errorInfo,
107
+ };
108
+ renderedFallback = fallback(props);
109
+ } else {
110
+ renderedFallback = fallback;
111
+ }
112
+
113
+ console.log(
114
+ `[Router] Loader error wrapped with boundary fallback in ${segmentId}:`,
115
+ errorInfo.message
116
+ );
117
+
118
+ return {
119
+ __loaderResult: true,
120
+ ok: false,
121
+ error: errorInfo,
122
+ fallback: renderedFallback,
123
+ };
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Set up the use() method on handler context to access loaders and handles.
129
+ *
130
+ * For loaders: Lazily runs loaders, memoizes results per request.
131
+ * For handles: Returns a push function bound to the current segment.
132
+ */
133
+ export function setupLoaderAccess<TEnv>(
134
+ ctx: HandlerContext<any, TEnv>,
135
+ loaderPromises: Map<string, Promise<any>>
136
+ ): void {
137
+ // Get HandleStore from request context
138
+ const getHandleStore = (): HandleStore | undefined => {
139
+ return getRequestContext()?._handleStore;
140
+ };
141
+
142
+ // The use() function handles both loaders and handles
143
+ ctx.use = ((item: LoaderDefinition<any, any> | Handle<any, any>) => {
144
+ // Handle case: return a push function
145
+ if (isHandle(item)) {
146
+ const handle = item;
147
+ const store = getHandleStore();
148
+ const segmentId = ctx._currentSegmentId;
149
+
150
+ if (!segmentId) {
151
+ throw new Error(
152
+ `Handle "${handle.$$id}" used outside of handler context. ` +
153
+ `Handles must be used within route/layout handlers.`
154
+ );
155
+ }
156
+
157
+ // Return a push function bound to this handle and segment
158
+ // Accepts: value, Promise, or async callback (executed immediately)
159
+ // Promises are pushed directly - RSC will serialize and stream them
160
+ return (dataOrFn: unknown | Promise<unknown> | (() => Promise<unknown>)) => {
161
+ if (!store) return;
162
+
163
+ // If it's a function, call it immediately to get the promise
164
+ const valueOrPromise = typeof dataOrFn === "function"
165
+ ? (dataOrFn as () => Promise<unknown>)()
166
+ : dataOrFn;
167
+
168
+ // Push directly - promises will be serialized by RSC and streamed
169
+ store.push(handle.$$id, segmentId, valueOrPromise);
170
+ };
171
+ }
172
+
173
+ // Loader case: existing behavior
174
+ const loader = item as LoaderDefinition<any, any>;
175
+
176
+ // Return cached promise if already started
177
+ if (loaderPromises.has(loader.$$id)) {
178
+ return loaderPromises.get(loader.$$id);
179
+ }
180
+
181
+ // Get loader function - either from loader object or fetchable registry
182
+ // Fetchable loaders store fn in registry (not on object) to avoid client bundling issues
183
+ let loaderFn = loader.fn;
184
+ if (!loaderFn) {
185
+ const fetchable = getFetchableLoader(loader.$$id);
186
+ if (fetchable) {
187
+ loaderFn = fetchable.fn;
188
+ }
189
+ }
190
+
191
+ // Ensure loader has a function
192
+ if (!loaderFn) {
193
+ throw new Error(
194
+ `Loader "${loader.$$id}" has no function. This usually means the loader was defined without "use server" and the function was not included in the build.`
195
+ );
196
+ }
197
+
198
+ // Create loader context with recursive use() support
199
+ const loaderCtx: LoaderContext<Record<string, string | undefined>, TEnv> = {
200
+ params: ctx.params,
201
+ request: ctx.request,
202
+ searchParams: ctx.searchParams,
203
+ pathname: ctx.pathname,
204
+ url: ctx.url,
205
+ env: ctx.env,
206
+ var: ctx.var,
207
+ get: ctx.get,
208
+ use: <TDep, TDepParams = any>(
209
+ dep: LoaderDefinition<TDep, TDepParams>
210
+ ): Promise<TDep> => {
211
+ // Recursive call - will start dep loader if not already started
212
+ return ctx.use(dep);
213
+ },
214
+ // Default to GET for loaders called through route handlers
215
+ method: "GET",
216
+ body: undefined,
217
+ };
218
+
219
+ // Start loader execution with tracking
220
+ const doneLoader = track(`loader:${loader.$$id}`);
221
+ const promise = Promise.resolve(
222
+ loaderFn(loaderCtx as LoaderContext<any, TEnv>)
223
+ ).finally(() => {
224
+ doneLoader();
225
+ });
226
+
227
+ // Memoize for subsequent calls
228
+ loaderPromises.set(loader.$$id, promise);
229
+
230
+ return promise;
231
+ }) as typeof ctx.use;
232
+ }
233
+
234
+ /**
235
+ * Set up ctx.use() for proactive caching (silent mode).
236
+ * Handles are silently ignored (no push to HandleStore).
237
+ * Loaders work normally but with fresh memoization.
238
+ *
239
+ * This prevents duplicate handle data (breadcrumbs, meta) from being
240
+ * pushed to the response stream during background proactive caching.
241
+ */
242
+ export function setupLoaderAccessSilent<TEnv>(
243
+ ctx: HandlerContext<any, TEnv>,
244
+ loaderPromises: Map<string, Promise<any>>
245
+ ): void {
246
+ ctx.use = ((item: LoaderDefinition<any, any> | Handle<any, any>) => {
247
+ // Handle case: return a no-op push function
248
+ if (isHandle(item)) {
249
+ // Silent mode - return a function that does nothing
250
+ return (_dataOrFn: unknown) => {
251
+ // Intentionally empty - don't push handle data during proactive caching
252
+ };
253
+ }
254
+
255
+ // Loader case: same as setupLoaderAccess
256
+ const loader = item as LoaderDefinition<any, any>;
257
+
258
+ // Return cached promise if already started
259
+ if (loaderPromises.has(loader.$$id)) {
260
+ return loaderPromises.get(loader.$$id);
261
+ }
262
+
263
+ // Get loader function
264
+ let loaderFn = loader.fn;
265
+ if (!loaderFn) {
266
+ const fetchable = getFetchableLoader(loader.$$id);
267
+ if (fetchable) {
268
+ loaderFn = fetchable.fn;
269
+ }
270
+ }
271
+
272
+ if (!loaderFn) {
273
+ throw new Error(
274
+ `Loader "${loader.$$id}" has no function. This usually means the loader was defined without "use server" and the function was not included in the build.`
275
+ );
276
+ }
277
+
278
+ // Create loader context with recursive use() support
279
+ const loaderCtx: LoaderContext<Record<string, string | undefined>, TEnv> = {
280
+ params: ctx.params,
281
+ request: ctx.request,
282
+ searchParams: ctx.searchParams,
283
+ pathname: ctx.pathname,
284
+ url: ctx.url,
285
+ env: ctx.env,
286
+ var: ctx.var,
287
+ get: ctx.get,
288
+ use: <TDep, TDepParams = any>(
289
+ dep: LoaderDefinition<TDep, TDepParams>
290
+ ): Promise<TDep> => {
291
+ return ctx.use(dep);
292
+ },
293
+ method: "GET",
294
+ body: undefined,
295
+ };
296
+
297
+ // Start loader execution with tracking
298
+ const doneLoader = track(`loader:${loader.$$id}`);
299
+ const promise = Promise.resolve(
300
+ loaderFn(loaderCtx as LoaderContext<any, TEnv>)
301
+ ).finally(() => {
302
+ doneLoader();
303
+ });
304
+
305
+ loaderPromises.set(loader.$$id, promise);
306
+ return promise;
307
+ }) as typeof ctx.use;
308
+ }
309
+
310
+ /**
311
+ * Conditional execution based on revalidation
312
+ * Evaluates revalidation logic lazily, then executes appropriate callback
313
+ *
314
+ * @param shouldRevalidate - Async function that determines if revalidation is needed
315
+ * @param onRevalidate - Callback executed if revalidation returns true
316
+ * @param onSkip - Callback executed if revalidation returns false
317
+ * @returns Result from either onRevalidate or onSkip
318
+ */
319
+ export async function revalidate<T>(
320
+ shouldRevalidate: () => Promise<boolean>,
321
+ onRevalidate: () => Promise<T>,
322
+ onSkip: () => T
323
+ ): Promise<T> {
324
+ const needsRevalidation = await shouldRevalidate();
325
+ return needsRevalidation ? await onRevalidate() : onSkip();
326
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Router Manifest Loading
3
+ *
4
+ * Handles lazy loading and validation of route manifests.
5
+ */
6
+
7
+ import { invariant, RouteNotFoundError } from "../errors";
8
+ import { createRouteHelpers } from "../route-definition";
9
+ import { getContext, type EntryData, type MetricsStore } from "../server/context";
10
+ import MapRootLayout from "../server/root-layout";
11
+ import type { RouteEntry } from "../types";
12
+
13
+ /**
14
+ * Module-level cache for manifests per mount index.
15
+ * Only used in production - dev mode skips caching for HMR support.
16
+ */
17
+ const manifestCache = new Map<number, Map<string, EntryData>>();
18
+
19
+ /**
20
+ * Load manifest from route entry with AsyncLocalStorage context
21
+ * Handles lazy imports, unwrapping, and validation
22
+ */
23
+ export async function loadManifest(
24
+ entry: RouteEntry<any>,
25
+ routeKey: string,
26
+ path: string,
27
+ metricsStore?: MetricsStore,
28
+ isSSR?: boolean
29
+ ): Promise<EntryData> {
30
+ const mountIndex = entry.mountIndex;
31
+ const isDev = process.env.NODE_ENV !== "production";
32
+
33
+ // In production, check cache first
34
+ if (!isDev) {
35
+ const cachedManifest = manifestCache.get(mountIndex);
36
+ if (cachedManifest && cachedManifest.has(routeKey)) {
37
+ return cachedManifest.get(routeKey)!;
38
+ }
39
+ }
40
+
41
+ const Store = getContext().getOrCreateStore(routeKey);
42
+
43
+ // Set mount index in store for unique shortCode prefixes
44
+ Store.mountIndex = mountIndex;
45
+
46
+ // Set isSSR flag so loading() can check if we're in SSR
47
+ Store.isSSR = isSSR;
48
+
49
+ // Attach metrics store to context if provided
50
+ if (metricsStore) {
51
+ Store.metrics = metricsStore;
52
+ }
53
+
54
+ // Clear manifest before rebuilding to prevent stale entry mutations
55
+ Store.manifest.clear();
56
+
57
+ try {
58
+ // Include mountIndex in namespace to ensure unique cache keys per mount
59
+ const namespaceWithMount = mountIndex !== undefined
60
+ ? `#router.M${mountIndex}`
61
+ : "#router";
62
+
63
+ const useItems = await getContext().runWithStore(
64
+ Store,
65
+ Store.namespace || namespaceWithMount,
66
+ Store.parent,
67
+ async () => {
68
+ // Create helpers for lazy-loaded handlers that need them
69
+ const helpers = createRouteHelpers();
70
+
71
+ // Call handler - urls() API handlers don't need helpers,
72
+ // legacy map() handlers ignore extra args
73
+ const result = entry.handler();
74
+
75
+ // Handle based on return type
76
+ if (result instanceof Promise) {
77
+ // Lazy: () => import(...) - returns Promise
78
+ const load = await result;
79
+ if (
80
+ load &&
81
+ load !== null &&
82
+ typeof load === "object" &&
83
+ "default" in load
84
+ ) {
85
+ // Promise<{ default: () => Array }> - e.g., dynamic import
86
+ // Lazy-loaded handlers may need helpers (passed as optional arg)
87
+ return (load.default as (h?: any) => any)(helpers);
88
+ }
89
+ if (typeof load === "function") {
90
+ // Promise<() => Array>
91
+ return (load as (h?: any) => any)(helpers);
92
+ }
93
+ // Promise<Array> - direct array from async handler
94
+ return load;
95
+ }
96
+
97
+ // Inline: ({ route }) => [...] - returns Array directly
98
+ // Wrap with layout (like map() from route-definition does)
99
+ // Flatten nested arrays from layout/route definitions
100
+ return [helpers.layout(MapRootLayout, () => result)].flat(3);
101
+ }
102
+ );
103
+
104
+ invariant(
105
+ useItems && useItems.length > 0,
106
+ "Did not receive any handler from router.map()"
107
+ );
108
+ invariant(
109
+ useItems.some((item: { type: string }) => item.type === "layout"),
110
+ "Top-level handler must be a layout"
111
+ );
112
+
113
+ invariant(
114
+ Store.manifest.has(routeKey),
115
+ `Route must be registered for ${routeKey}`
116
+ );
117
+
118
+ // Cache manifest in production after successful build
119
+ if (!isDev) {
120
+ manifestCache.set(mountIndex, new Map(Store.manifest));
121
+ }
122
+
123
+ return Store.manifest.get(routeKey)!;
124
+ } catch (e) {
125
+ throw new RouteNotFoundError(
126
+ `Failed to load route handlers for ${path}: ${(e as Error).message}`,
127
+ {
128
+ cause: {
129
+ error: e,
130
+ state: {
131
+ path,
132
+ routeKey,
133
+ },
134
+ },
135
+ }
136
+ );
137
+ }
138
+ }