@rangojs/router 0.0.0-experimental.fa8a383a → 0.0.0-experimental.fb4fdc18

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 (175) hide show
  1. package/README.md +188 -35
  2. package/dist/bin/rango.js +130 -47
  3. package/dist/vite/index.js +1884 -537
  4. package/dist/vite/index.js.bak +5448 -0
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +7 -5
  7. package/skills/breadcrumbs/SKILL.md +3 -1
  8. package/skills/cache-guide/SKILL.md +32 -0
  9. package/skills/caching/SKILL.md +8 -0
  10. package/skills/handler-use/SKILL.md +362 -0
  11. package/skills/hooks/SKILL.md +33 -20
  12. package/skills/i18n/SKILL.md +276 -0
  13. package/skills/intercept/SKILL.md +20 -0
  14. package/skills/layout/SKILL.md +22 -0
  15. package/skills/links/SKILL.md +93 -17
  16. package/skills/loader/SKILL.md +123 -46
  17. package/skills/middleware/SKILL.md +36 -3
  18. package/skills/migrate-nextjs/SKILL.md +562 -0
  19. package/skills/migrate-react-router/SKILL.md +769 -0
  20. package/skills/parallel/SKILL.md +133 -0
  21. package/skills/prerender/SKILL.md +110 -68
  22. package/skills/rango/SKILL.md +26 -22
  23. package/skills/response-routes/SKILL.md +8 -0
  24. package/skills/route/SKILL.md +75 -0
  25. package/skills/router-setup/SKILL.md +87 -2
  26. package/skills/server-actions/SKILL.md +739 -0
  27. package/skills/streams-and-websockets/SKILL.md +283 -0
  28. package/skills/typesafety/SKILL.md +19 -1
  29. package/src/__internal.ts +1 -1
  30. package/src/browser/app-shell.ts +52 -0
  31. package/src/browser/app-version.ts +14 -0
  32. package/src/browser/event-controller.ts +44 -4
  33. package/src/browser/navigation-bridge.ts +95 -7
  34. package/src/browser/navigation-client.ts +128 -53
  35. package/src/browser/navigation-store.ts +68 -9
  36. package/src/browser/partial-update.ts +93 -12
  37. package/src/browser/prefetch/cache.ts +129 -21
  38. package/src/browser/prefetch/fetch.ts +156 -18
  39. package/src/browser/prefetch/queue.ts +92 -29
  40. package/src/browser/prefetch/resource-ready.ts +77 -0
  41. package/src/browser/rango-state.ts +53 -13
  42. package/src/browser/react/Link.tsx +72 -8
  43. package/src/browser/react/NavigationProvider.tsx +82 -21
  44. package/src/browser/react/context.ts +7 -2
  45. package/src/browser/react/filter-segment-order.ts +51 -7
  46. package/src/browser/react/use-handle.ts +9 -58
  47. package/src/browser/react/use-navigation.ts +22 -2
  48. package/src/browser/react/use-params.ts +17 -4
  49. package/src/browser/react/use-router.ts +29 -9
  50. package/src/browser/react/use-segments.ts +11 -8
  51. package/src/browser/rsc-router.tsx +60 -9
  52. package/src/browser/scroll-restoration.ts +10 -8
  53. package/src/browser/segment-reconciler.ts +36 -14
  54. package/src/browser/server-action-bridge.ts +8 -6
  55. package/src/browser/types.ts +46 -5
  56. package/src/build/generate-manifest.ts +6 -6
  57. package/src/build/generate-route-types.ts +3 -0
  58. package/src/build/route-trie.ts +52 -25
  59. package/src/build/route-types/include-resolution.ts +8 -1
  60. package/src/build/route-types/router-processing.ts +211 -72
  61. package/src/build/route-types/scan-filter.ts +8 -1
  62. package/src/cache/cache-runtime.ts +15 -11
  63. package/src/cache/cache-scope.ts +46 -5
  64. package/src/cache/cf/cf-cache-store.ts +5 -7
  65. package/src/cache/taint.ts +55 -0
  66. package/src/client.tsx +84 -230
  67. package/src/context-var.ts +72 -2
  68. package/src/handle.ts +40 -0
  69. package/src/index.rsc.ts +6 -1
  70. package/src/index.ts +49 -6
  71. package/src/outlet-context.ts +1 -1
  72. package/src/prerender/store.ts +5 -4
  73. package/src/prerender.ts +138 -77
  74. package/src/response-utils.ts +28 -0
  75. package/src/reverse.ts +28 -2
  76. package/src/route-definition/dsl-helpers.ts +210 -35
  77. package/src/route-definition/helpers-types.ts +73 -20
  78. package/src/route-definition/index.ts +3 -0
  79. package/src/route-definition/redirect.ts +9 -1
  80. package/src/route-definition/resolve-handler-use.ts +155 -0
  81. package/src/route-types.ts +18 -0
  82. package/src/router/content-negotiation.ts +100 -1
  83. package/src/router/handler-context.ts +102 -25
  84. package/src/router/intercept-resolution.ts +9 -4
  85. package/src/router/lazy-includes.ts +6 -6
  86. package/src/router/loader-resolution.ts +159 -21
  87. package/src/router/manifest.ts +22 -13
  88. package/src/router/match-api.ts +128 -192
  89. package/src/router/match-handlers.ts +1 -0
  90. package/src/router/match-middleware/background-revalidation.ts +12 -1
  91. package/src/router/match-middleware/cache-lookup.ts +74 -14
  92. package/src/router/match-middleware/cache-store.ts +21 -4
  93. package/src/router/match-middleware/segment-resolution.ts +53 -0
  94. package/src/router/match-result.ts +112 -9
  95. package/src/router/metrics.ts +6 -1
  96. package/src/router/middleware-types.ts +20 -33
  97. package/src/router/middleware.ts +56 -12
  98. package/src/router/navigation-snapshot.ts +182 -0
  99. package/src/router/pattern-matching.ts +101 -17
  100. package/src/router/prerender-match.ts +110 -10
  101. package/src/router/preview-match.ts +30 -102
  102. package/src/router/request-classification.ts +310 -0
  103. package/src/router/revalidation.ts +15 -1
  104. package/src/router/route-snapshot.ts +245 -0
  105. package/src/router/router-context.ts +1 -0
  106. package/src/router/router-interfaces.ts +36 -4
  107. package/src/router/router-options.ts +37 -11
  108. package/src/router/segment-resolution/fresh.ts +114 -18
  109. package/src/router/segment-resolution/helpers.ts +29 -24
  110. package/src/router/segment-resolution/revalidation.ts +257 -127
  111. package/src/router/trie-matching.ts +18 -13
  112. package/src/router/types.ts +1 -0
  113. package/src/router/url-params.ts +49 -0
  114. package/src/router.ts +55 -7
  115. package/src/rsc/handler.ts +478 -383
  116. package/src/rsc/helpers.ts +69 -41
  117. package/src/rsc/loader-fetch.ts +23 -3
  118. package/src/rsc/manifest-init.ts +5 -1
  119. package/src/rsc/progressive-enhancement.ts +18 -2
  120. package/src/rsc/response-route-handler.ts +14 -1
  121. package/src/rsc/rsc-rendering.ts +20 -1
  122. package/src/rsc/server-action.ts +12 -0
  123. package/src/rsc/ssr-setup.ts +2 -2
  124. package/src/rsc/types.ts +15 -1
  125. package/src/segment-content-promise.ts +67 -0
  126. package/src/segment-loader-promise.ts +122 -0
  127. package/src/segment-system.tsx +22 -62
  128. package/src/server/context.ts +76 -4
  129. package/src/server/handle-store.ts +19 -0
  130. package/src/server/loader-registry.ts +9 -8
  131. package/src/server/request-context.ts +185 -57
  132. package/src/ssr/index.tsx +8 -1
  133. package/src/static-handler.ts +18 -6
  134. package/src/types/cache-types.ts +4 -4
  135. package/src/types/handler-context.ts +145 -68
  136. package/src/types/loader-types.ts +41 -15
  137. package/src/types/request-scope.ts +126 -0
  138. package/src/types/route-entry.ts +12 -1
  139. package/src/types/segments.ts +18 -1
  140. package/src/urls/include-helper.ts +24 -14
  141. package/src/urls/path-helper-types.ts +39 -6
  142. package/src/urls/path-helper.ts +47 -12
  143. package/src/urls/pattern-types.ts +12 -0
  144. package/src/urls/response-types.ts +18 -16
  145. package/src/use-loader.tsx +77 -5
  146. package/src/vite/debug.ts +184 -0
  147. package/src/vite/discovery/bundle-postprocess.ts +30 -33
  148. package/src/vite/discovery/discover-routers.ts +36 -4
  149. package/src/vite/discovery/gate-state.ts +171 -0
  150. package/src/vite/discovery/prerender-collection.ts +175 -74
  151. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  152. package/src/vite/discovery/state.ts +13 -4
  153. package/src/vite/index.ts +4 -0
  154. package/src/vite/plugin-types.ts +60 -5
  155. package/src/vite/plugins/cjs-to-esm.ts +5 -0
  156. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  157. package/src/vite/plugins/client-ref-hashing.ts +16 -4
  158. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  159. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  160. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  161. package/src/vite/plugins/expose-action-id.ts +52 -28
  162. package/src/vite/plugins/expose-id-utils.ts +12 -0
  163. package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
  164. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  165. package/src/vite/plugins/expose-internal-ids.ts +563 -316
  166. package/src/vite/plugins/performance-tracks.ts +96 -0
  167. package/src/vite/plugins/refresh-cmd.ts +88 -26
  168. package/src/vite/plugins/use-cache-transform.ts +56 -43
  169. package/src/vite/plugins/version-injector.ts +37 -11
  170. package/src/vite/rango.ts +63 -11
  171. package/src/vite/router-discovery.ts +732 -86
  172. package/src/vite/utils/banner.ts +1 -1
  173. package/src/vite/utils/package-resolution.ts +41 -1
  174. package/src/vite/utils/prerender-utils.ts +38 -5
  175. package/src/vite/utils/shared-utils.ts +3 -2
@@ -4,7 +4,6 @@ import {
4
4
  runWithPrefixes,
5
5
  getUrlPrefix,
6
6
  getNamePrefix,
7
- getRootScoped,
8
7
  } from "../server/context";
9
8
  import {
10
9
  INTERNAL_INCLUDE_SCOPE_PREFIX,
@@ -149,22 +148,32 @@ export function createIncludeHelper<TEnv>(): IncludeFn<TEnv> {
149
148
  });
150
149
  }
151
150
 
152
- // Snapshot parent's counters so lazy manifest generation starts
153
- // at the correct index, preventing shortCode collisions with
154
- // sibling entries (e.g., BlogLayout and ArticlesLayout under NavLayout).
155
- const capturedCounters = { ...ctx.counters };
156
-
157
- // Reserve a layout slot in the parent's counter so sibling lazy includes
158
- // produce different shortCode indices for their root layout.
159
- // Without this, consecutive include() calls capture identical counters
160
- // and their first child layouts get the same shortCode (e.g., both M0L0L0),
161
- // causing the client partial-update diff to see no changes on navigation.
151
+ // Allocate an include-scope token for this include() call. The token is
152
+ // appended to the parent's shortCode prefix whenever the include's
153
+ // direct-descendant shortCodes are generated (see getShortCode in
154
+ // context.ts), partitioning the parent's counter namespace so routes
155
+ // inside an include cannot collide with siblings declared outside it.
156
+ //
157
+ // Scopes compose: a nested include inside an outer include with scope
158
+ // "I0" allocates against the `${parent.shortCode}I0_include` counter
159
+ // and produces scope "I0I0", "I0I1", etc.
160
+ const parentScope = ctx.includeScope ?? "";
161
+ let includeScope = parentScope;
162
162
  if (capturedParent?.shortCode) {
163
- const layoutCounterKey = `${capturedParent.shortCode}_layout`;
164
- ctx.counters[layoutCounterKey] ??= 0;
165
- ctx.counters[layoutCounterKey]++;
163
+ const includeCounterKey = `${capturedParent.shortCode}${parentScope}_include`;
164
+ ctx.counters[includeCounterKey] ??= 0;
165
+ const includeIdx = ctx.counters[includeCounterKey];
166
+ ctx.counters[includeCounterKey] = includeIdx + 1;
167
+ includeScope = `${parentScope}I${includeIdx}`;
166
168
  }
167
169
 
170
+ // Snapshot parent's counters AFTER allocating the include scope so lazy
171
+ // manifest generation starts with the same counter state this include
172
+ // observed — its descendants still get fresh per-scope counters because
173
+ // they key off `${parent.shortCode}${includeScope}_*` (not shared with
174
+ // siblings outside the include).
175
+ const capturedCounters = { ...ctx.counters };
176
+
168
177
  // Compute rootScoped at capture time, mirroring the logic in runWithPrefixes.
169
178
  // This ensures lazy evaluation restores the correct scope state.
170
179
  const parentRootScoped = ctx.rootScoped;
@@ -191,6 +200,7 @@ export function createIncludeHelper<TEnv>(): IncludeFn<TEnv> {
191
200
  counters: capturedCounters,
192
201
  cacheProfiles: ctx.cacheProfiles,
193
202
  rootScoped: capturedRootScoped,
203
+ includeScope,
194
204
  },
195
205
  } as IncludeItem;
196
206
  };
@@ -37,7 +37,10 @@ import type {
37
37
  UseItems,
38
38
  } from "../route-types.js";
39
39
  import type { SearchSchema } from "../search-params.js";
40
- import type { PrerenderHandlerDefinition } from "../prerender.js";
40
+ import type {
41
+ PrerenderHandlerDefinition,
42
+ PassthroughHandlerDefinition,
43
+ } from "../prerender.js";
41
44
  import type { StaticHandlerDefinition } from "../static-handler.js";
42
45
  import type { InterceptWhenFn } from "../server/context";
43
46
  import type {
@@ -70,6 +73,7 @@ export type PathFn<TEnv> = <
70
73
  ctx: HandlerContext<TParams, TEnv, TSearch>,
71
74
  ) => ReactNode | Promise<ReactNode> | Response | Promise<Response>)
72
75
  | PrerenderHandlerDefinition<TParams>
76
+ | PassthroughHandlerDefinition<TParams, TEnv>
73
77
  | StaticHandlerDefinition<TParams>,
74
78
  optionsOrUse?: PathOptions<TName, TSearch> | (() => UseItems<RouteUseItem>),
75
79
  use?: () => UseItems<RouteUseItem>,
@@ -229,12 +233,27 @@ export type PathHelpers<TEnv> = {
229
233
  include: IncludeFn<TEnv>;
230
234
 
231
235
  /**
232
- * Define parallel routes that render simultaneously in named slots
236
+ * Define parallel routes that render simultaneously in named slots.
237
+ *
238
+ * A slot value can be a Handler / ReactNode / StaticHandlerDefinition
239
+ * (legacy form, broadcast use applies to every slot) or a slot descriptor
240
+ * `{ handler, use? }` whose `use` is scoped to that slot only. Per-slot
241
+ * merge order is `handler.use` → shared `use` → slot-local `use`, with
242
+ * narrowest scope winning for last-write-wins items like `loading()`.
233
243
  */
234
244
  parallel: <
235
245
  TSlots extends Record<
236
246
  `@${string}`,
237
- Handler<any, any, TEnv> | ReactNode | StaticHandlerDefinition
247
+ | Handler<any, any, TEnv>
248
+ | ReactNode
249
+ | StaticHandlerDefinition
250
+ | {
251
+ handler:
252
+ | Handler<any, any, TEnv>
253
+ | ReactNode
254
+ | StaticHandlerDefinition;
255
+ use?: () => ParallelUseItem[];
256
+ }
238
257
  >,
239
258
  >(
240
259
  slots: TSlots,
@@ -260,9 +279,20 @@ export type PathHelpers<TEnv> = {
260
279
  ) => InterceptItem;
261
280
 
262
281
  /**
263
- * Attach middleware to the current route/layout
282
+ * Attach middleware to the current route/layout, or wrap child segments
264
283
  */
265
- middleware: (...fns: MiddlewareFn<TEnv>[]) => MiddlewareItem;
284
+ middleware: {
285
+ (fn: MiddlewareFn<TEnv>): MiddlewareItem;
286
+ (
287
+ fn: MiddlewareFn<TEnv>,
288
+ children: () => UseItems<LayoutUseItem>,
289
+ ): MiddlewareItem;
290
+ (fns: MiddlewareFn<TEnv>[]): MiddlewareItem;
291
+ (
292
+ fns: MiddlewareFn<TEnv>[],
293
+ children: () => UseItems<LayoutUseItem>,
294
+ ): MiddlewareItem;
295
+ };
266
296
 
267
297
  /**
268
298
  * Control when a segment should revalidate during navigation
@@ -280,7 +310,10 @@ export type PathHelpers<TEnv> = {
280
310
  /**
281
311
  * Attach a loading component to the current route/layout
282
312
  */
283
- loading: (component: ReactNode, options?: { ssr?: boolean }) => LoadingItem;
313
+ loading: (
314
+ component: ReactNode | (() => ReactNode),
315
+ options?: { ssr?: boolean },
316
+ ) => LoadingItem;
284
317
 
285
318
  /**
286
319
  * Attach an error boundary to catch errors in this segment
@@ -12,10 +12,11 @@ import {
12
12
  getNamePrefix,
13
13
  getRootScoped,
14
14
  } from "../server/context";
15
- import { invariant } from "../errors";
15
+ import { invariant, DataNotFoundError } from "../errors";
16
16
  import { validateUserRouteName } from "../route-name.js";
17
17
  import {
18
18
  isPrerenderHandler,
19
+ isPassthroughHandler,
19
20
  type PrerenderHandlerDefinition,
20
21
  } from "../prerender.js";
21
22
  import {
@@ -34,6 +35,10 @@ import type {
34
35
  JsonResponsePathFn,
35
36
  TextResponsePathFn,
36
37
  } from "./path-helper-types.js";
38
+ import {
39
+ resolveHandlerUse,
40
+ mergeHandlerUse,
41
+ } from "../route-definition/resolve-handler-use.js";
37
42
 
38
43
  /**
39
44
  * Check if a value is a valid use item
@@ -142,6 +147,12 @@ export function createPathHelper<TEnv>(): PathFn<TEnv> {
142
147
  use = maybeUse;
143
148
  }
144
149
 
150
+ // Merge handler.use() defaults with explicit use()
151
+ // Response routes (path.json, path.text, etc.) only allow middleware + cache
152
+ const handlerUseFn = resolveHandlerUse(handler);
153
+ const mountSite = resolveResponseType(options) ? "response" : "path";
154
+ const mergedUse = mergeHandlerUse(handlerUseFn, use, mountSite);
155
+
145
156
  // Get prefixes from context (set by include())
146
157
  const urlPrefix = getUrlPrefix();
147
158
  const namePrefix = getNamePrefix();
@@ -176,14 +187,31 @@ export function createPathHelper<TEnv>(): PathFn<TEnv> {
176
187
  }
177
188
 
178
189
  // Ensure handler is always a function (wrap ReactNode or extract from prerender/static def)
190
+ // For prerender stubs (production builds where handler code is evicted),
191
+ // handler.handler is undefined — provide a notFound fallback so requests
192
+ // for non-prerendered params get 404 instead of "handler is not a function".
179
193
  const wrappedHandler: Handler<any, any, TEnv> =
180
194
  typeof handler === "function"
181
195
  ? (handler as Handler<any, any, TEnv>)
182
- : isPrerenderHandler(handler)
183
- ? (handler.handler as Handler<any, any, TEnv>)
184
- : isStaticHandler(handler)
185
- ? (handler.handler as Handler<any, any, TEnv>)
186
- : () => handler;
196
+ : isPassthroughHandler(handler)
197
+ ? typeof handler.prerenderDef.handler === "function"
198
+ ? (handler.prerenderDef.handler as Handler<any, any, TEnv>)
199
+ : () => {
200
+ throw new DataNotFoundError(
201
+ "No prerender data found for this route",
202
+ );
203
+ }
204
+ : isPrerenderHandler(handler)
205
+ ? typeof handler.handler === "function"
206
+ ? (handler.handler as Handler<any, any, TEnv>)
207
+ : () => {
208
+ throw new DataNotFoundError(
209
+ "No prerender data found for this route",
210
+ );
211
+ }
212
+ : isStaticHandler(handler)
213
+ ? (handler.handler as Handler<any, any, TEnv>)
214
+ : () => handler;
187
215
 
188
216
  const entry = {
189
217
  id: namespace,
@@ -203,12 +231,19 @@ export function createPathHelper<TEnv>(): PathFn<TEnv> {
203
231
  intercept: [],
204
232
  loader: [],
205
233
  ...(urlPrefix ? { mountPath: urlPrefix } : {}),
206
- ...(isPrerenderHandler(handler)
234
+ ...(isPassthroughHandler(handler)
207
235
  ? {
208
236
  isPrerender: true as const,
209
- prerenderDef: handler as PrerenderHandlerDefinition,
237
+ prerenderDef: handler.prerenderDef as PrerenderHandlerDefinition,
238
+ isPassthrough: true as const,
239
+ liveHandler: handler.liveHandler as Handler<any, any, TEnv>,
210
240
  }
211
- : {}),
241
+ : isPrerenderHandler(handler)
242
+ ? {
243
+ isPrerender: true as const,
244
+ prerenderDef: handler as PrerenderHandlerDefinition,
245
+ }
246
+ : {}),
212
247
  ...(isStaticHandler(handler)
213
248
  ? {
214
249
  isStaticPrerender: true as const,
@@ -264,9 +299,9 @@ export function createPathHelper<TEnv>(): PathFn<TEnv> {
264
299
  registerSearchSchema(routeName, options.search);
265
300
  }
266
301
 
267
- // Run use callback if provided
268
- if (use && typeof use === "function") {
269
- const result = store.run(namespace, entry, use)?.flat(3);
302
+ // Run merged use callback (handler.use defaults + explicit use) if present
303
+ if (mergedUse) {
304
+ const result = store.run(namespace, entry, mergedUse)?.flat(3);
270
305
  invariant(
271
306
  Array.isArray(result) && result.every((item) => isValidUseItem(item)),
272
307
  `path() use() callback must return an array of use items [${namespace}]`,
@@ -7,6 +7,18 @@ import type {
7
7
  } from "../route-types.js";
8
8
  import type { SearchSchema } from "../search-params.js";
9
9
  import { RESPONSE_TYPE } from "./response-types.js";
10
+ import type { DefaultEnv } from "../types.js";
11
+ import type { PathHelpers } from "./path-helper-types.js";
12
+
13
+ /**
14
+ * Builder function accepted by urls() and as a shorthand for routes()/urls option.
15
+ * When passed directly to routes() or createRouter({ urls }), it is wrapped in urls() automatically.
16
+ */
17
+ export type UrlBuilder<
18
+ TEnv = DefaultEnv,
19
+ TItems extends readonly (AllUseItems | readonly AllUseItems[])[] =
20
+ readonly AllUseItems[],
21
+ > = (helpers: PathHelpers<TEnv>) => TItems;
10
22
 
11
23
  /**
12
24
  * Sentinel type for unnamed routes.
@@ -4,6 +4,8 @@ import type {
4
4
  DefaultReverseRouteMap,
5
5
  DefaultVars,
6
6
  } from "../types/global-namespace.js";
7
+ import type { UseItems, ResponseRouteUseItem } from "../route-types.js";
8
+ import type { RequestScope } from "../types/request-scope.js";
7
9
 
8
10
  /**
9
11
  * Reverse function for response handler contexts.
@@ -38,9 +40,12 @@ export const RESPONSE_TYPE: unique symbol = Symbol.for(
38
40
  * Handler that must return Response (not ReactNode).
39
41
  * Used by path.image(), path.stream(), path.any() (binary/streaming data).
40
42
  */
41
- export type ResponseHandler<TParams = Record<string, string>, TEnv = any> = (
43
+ export type ResponseHandler<TParams = Record<string, string>, TEnv = any> = ((
42
44
  ctx: ResponseHandlerContext<TParams, TEnv>,
43
- ) => Response | Promise<Response>;
45
+ ) => Response | Promise<Response>) & {
46
+ /** Composable default DSL items merged when the handler is mounted. */
47
+ use?: () => UseItems<ResponseRouteUseItem>;
48
+ };
44
49
 
45
50
  /**
46
51
  * JSON-serializable value type for auto-wrap support.
@@ -60,9 +65,12 @@ export type JsonValue =
60
65
  export type JsonResponseHandler<
61
66
  TParams = Record<string, string>,
62
67
  TEnv = any,
63
- > = (
68
+ > = ((
64
69
  ctx: ResponseHandlerContext<TParams, TEnv>,
65
- ) => JsonValue | Response | Promise<JsonValue | Response>;
70
+ ) => JsonValue | Response | Promise<JsonValue | Response>) & {
71
+ /** Composable default DSL items merged when the handler is mounted. */
72
+ use?: () => UseItems<ResponseRouteUseItem>;
73
+ };
66
74
 
67
75
  /**
68
76
  * Handler for text-based response routes (text, html, xml).
@@ -71,9 +79,12 @@ export type JsonResponseHandler<
71
79
  export type TextResponseHandler<
72
80
  TParams = Record<string, string>,
73
81
  TEnv = any,
74
- > = (
82
+ > = ((
75
83
  ctx: ResponseHandlerContext<TParams, TEnv>,
76
- ) => string | Response | Promise<string | Response>;
84
+ ) => string | Response | Promise<string | Response>) & {
85
+ /** Composable default DSL items merged when the handler is mounted. */
86
+ use?: () => UseItems<ResponseRouteUseItem>;
87
+ };
77
88
 
78
89
  /**
79
90
  * Lighter handler context for response routes.
@@ -83,19 +94,10 @@ export type TextResponseHandler<
83
94
  export interface ResponseHandlerContext<
84
95
  TParams = Record<string, string>,
85
96
  TEnv = any,
86
- > {
87
- request: Request;
97
+ > extends RequestScope<TEnv> {
88
98
  params: TParams;
89
99
  /** @internal Phantom property for params type invariance. Prevents mounting handlers on wrong routes. */
90
100
  readonly _paramCheck?: (params: TParams) => TParams;
91
- /** Platform bindings (DB, KV, secrets, etc.). */
92
- env: TEnv;
93
- /** Query parameters from the URL (system params like `_rsc*` are filtered). */
94
- searchParams: URLSearchParams;
95
- /** The full URL object (with system params filtered). */
96
- url: URL;
97
- /** The pathname portion of the request URL. */
98
- pathname: string;
99
101
  reverse: ResponseReverseFunction;
100
102
  /** Read a variable set by middleware via ctx.set(key, value) or ctx.set(ContextVar, value). */
101
103
  get: {
@@ -1,9 +1,71 @@
1
1
  "use client";
2
2
 
3
- import { useCallback, useContext, useEffect, useRef, useState } from "react";
3
+ import {
4
+ isValidElement,
5
+ startTransition,
6
+ useCallback,
7
+ useContext,
8
+ useEffect,
9
+ useMemo,
10
+ useRef,
11
+ useState,
12
+ type ReactNode,
13
+ } from "react";
4
14
  import { OutletContext, type OutletContextValue } from "./outlet-context.js";
5
15
  import type { LoaderDefinition, LoadOptions } from "./types.js";
6
16
 
17
+ /**
18
+ * Extract a specific loader's data from a content ReactNode.
19
+ *
20
+ * When a route registers loaders via loader(), the resolved data lives in
21
+ * the route's OutletProvider (rendered as <Outlet /> content). Parallel
22
+ * slots are siblings of <Outlet />, so they can't find it by walking
23
+ * the parent context chain. This helper traverses wrapper elements
24
+ * (MountContextProvider, ViewTransition, etc.) to reach the OutletProvider
25
+ * and extract the loader data directly.
26
+ */
27
+ const NOT_FOUND = Symbol("not-found");
28
+
29
+ function extractContentLoaderData(
30
+ node: ReactNode,
31
+ loaderId: string,
32
+ ): unknown | typeof NOT_FOUND {
33
+ if (!isValidElement(node)) return NOT_FOUND;
34
+ const props = node.props as Record<string, any> | undefined;
35
+ if (!props) return NOT_FOUND;
36
+
37
+ // Direct OutletProvider with loaderData
38
+ if (props.loaderData && loaderId in props.loaderData) {
39
+ return props.loaderData[loaderId];
40
+ }
41
+
42
+ // LoaderBoundary: loaderIds + loaderDataPromise (already resolved array).
43
+ // When the segment has loading(), loaderData is resolved inside
44
+ // LoaderBoundary via use(). If the promise was pre-awaited (forceAwait
45
+ // or isAction), the prop is a raw array we can index into.
46
+ if (
47
+ props.loaderIds &&
48
+ Array.isArray(props.loaderIds) &&
49
+ props.loaderDataPromise &&
50
+ !(props.loaderDataPromise instanceof Promise)
51
+ ) {
52
+ const idx = (props.loaderIds as string[]).indexOf(loaderId);
53
+ if (idx !== -1) {
54
+ const data = (props.loaderDataPromise as any[])[idx];
55
+ // loaderDataPromise entries may be { ok, data } result objects
56
+ if (data && typeof data === "object" && "ok" in data) {
57
+ return data.ok ? data.data : NOT_FOUND;
58
+ }
59
+ return data;
60
+ }
61
+ }
62
+
63
+ // Traverse into wrapper elements (MountContextProvider, ViewTransition,
64
+ // Suspense wrappers, etc.)
65
+ if (props.children) return extractContentLoaderData(props.children, loaderId);
66
+ return NOT_FOUND;
67
+ }
68
+
7
69
  /**
8
70
  * Payload returned by loader RSC requests
9
71
  */
@@ -71,19 +133,27 @@ function useLoaderInternal<T>(
71
133
  const context = useContext(OutletContext);
72
134
 
73
135
  // Get data from context (SSR/navigation)
74
- const getContextData = useCallback((): T | undefined => {
136
+ const contextData = useMemo((): T | undefined => {
75
137
  let current: OutletContextValue | null | undefined = context;
76
138
  while (current) {
77
139
  if (current.loaderData && loader.$$id in current.loaderData) {
78
140
  return current.loaderData[loader.$$id] as T;
79
141
  }
142
+ // Check content element — the route's OutletProvider is rendered as
143
+ // <Outlet /> content (a child), so its loaderData isn't in the parent
144
+ // chain. Parallel slots need to reach into it to find route-level loaders.
145
+ const contentData = extractContentLoaderData(
146
+ current.content,
147
+ loader.$$id,
148
+ );
149
+ if (contentData !== NOT_FOUND) {
150
+ return contentData as T;
151
+ }
80
152
  current = current.parent;
81
153
  }
82
154
  return undefined;
83
155
  }, [context, loader.$$id]);
84
156
 
85
- const contextData = getContextData();
86
-
87
157
  // Local state for fetched data (from load() calls)
88
158
  const [fetchedData, setFetchedData] = useState<T | undefined>(undefined);
89
159
  const [isLoading, setIsLoading] = useState(false);
@@ -215,7 +285,9 @@ function useLoaderInternal<T>(
215
285
 
216
286
  const result = payload.loaderResult;
217
287
  if (requestId === requestIdRef.current) {
218
- setFetchedData(result);
288
+ startTransition(() => {
289
+ setFetchedData(result);
290
+ });
219
291
  }
220
292
  return result;
221
293
  } catch (e) {
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Debug logging for the Rango Vite plugin.
3
+ *
4
+ * Thin wrapper over the `debug` package (the same one Vite uses for its
5
+ * own `vite:*` namespaces). Enable with either:
6
+ *
7
+ * DEBUG='rango:*' vite dev
8
+ * vite --debug rango:* # vite prepends `vite:`, we bridge it
9
+ *
10
+ * Returns `undefined` when no matching namespace is enabled, so call sites
11
+ * can guard expensive diagnostics with a simple truthiness check:
12
+ *
13
+ * const debug = createRangoDebugger(NS.routes);
14
+ * if (debug) debug("built manifest (%d routes) in %dms", n, ms);
15
+ *
16
+ * Back-compat: INTERNAL_RANGO_DEBUG=1 still enables all rango namespaces.
17
+ *
18
+ * Vite CLI note: `vite --debug <feat>` rewrites to `DEBUG=vite:<feat>` — it
19
+ * always prefixes with `vite:` and cannot enable bare `rango:*` namespaces.
20
+ * We work around this by registering a shadow `vite:rango:*` instance for
21
+ * each debugger, so either invocation works.
22
+ */
23
+
24
+ import debugFactory from "debug";
25
+
26
+ /**
27
+ * Canonical debug namespaces. Import as `NS.xxx` instead of string literals
28
+ * so typos become type errors and the full set lives in one place.
29
+ */
30
+ export const NS = {
31
+ config: "rango:config",
32
+ discovery: "rango:discovery",
33
+ routes: "rango:routes",
34
+ prerender: "rango:prerender",
35
+ build: "rango:build",
36
+ dev: "rango:dev",
37
+ transform: "rango:transform",
38
+ } as const;
39
+
40
+ // Back-compat: the legacy INTERNAL_RANGO_DEBUG env var enabled per-site
41
+ // console.logs in this plugin. Map it to `rango:*` so those call sites can
42
+ // be migrated to the `debug` pipeline without breaking existing setups.
43
+ // Uses debug.enable() rather than mutating process.env because the `debug`
44
+ // package already snapshotted DEBUG when it was imported above.
45
+ if (process.env.INTERNAL_RANGO_DEBUG) {
46
+ const existing = debugFactory.disable();
47
+ debugFactory.enable(existing ? `${existing},rango:*` : "rango:*");
48
+ }
49
+
50
+ export type Debugger = (formatter: string, ...args: unknown[]) => void;
51
+
52
+ export function createRangoDebugger(namespace: string): Debugger | undefined {
53
+ const primary = debugFactory(namespace);
54
+ // Shadow namespace so `vite --debug rango:*` (which expands to
55
+ // DEBUG=vite:rango:*) and `vite --debug` (DEBUG=vite:*) both pick us up.
56
+ const shadow = debugFactory(`vite:${namespace}`);
57
+ if (primary.enabled) return primary as Debugger;
58
+ if (shadow.enabled) return shadow as Debugger;
59
+ return undefined;
60
+ }
61
+
62
+ /**
63
+ * Measure an async block and log its duration via `debug`. No-ops (still
64
+ * runs `fn`) when the namespace is disabled, so production cost is a single
65
+ * `.enabled` check per call.
66
+ *
67
+ * await timed(debug, "discover routers", () => discoverRouters(state));
68
+ */
69
+ export async function timed<T>(
70
+ debug: Debugger | undefined,
71
+ label: string,
72
+ fn: () => T | Promise<T>,
73
+ ): Promise<T> {
74
+ if (!debug) return await fn();
75
+ const start = performance.now();
76
+ try {
77
+ return await fn();
78
+ } finally {
79
+ debug("%s (%sms)", label, (performance.now() - start).toFixed(1));
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Synchronous variant of `timed`. Use for sync call sites — wrapping them
85
+ * with the async `timed` would create a floating promise that discards any
86
+ * throw, bypassing the surrounding try/catch.
87
+ */
88
+ export function timedSync<T>(
89
+ debug: Debugger | undefined,
90
+ label: string,
91
+ fn: () => T,
92
+ ): T {
93
+ if (!debug) return fn();
94
+ const start = performance.now();
95
+ try {
96
+ return fn();
97
+ } finally {
98
+ debug("%s (%sms)", label, (performance.now() - start).toFixed(1));
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Aggregate counter for high-frequency call sites (typically Vite
104
+ * `transform` hooks that run on many files). Per-call logging would
105
+ * drown real signal; this collects totals and reports once on flush.
106
+ *
107
+ * const counter = createCounter(debug, "use-cache-transform");
108
+ * // inside transform():
109
+ * return counter?.time(id, () => doWork()) ?? doWork();
110
+ * // or manually:
111
+ * counter?.record(id, ms);
112
+ * // flush on buildEnd (counter resets, so multi-env builds each get
113
+ * // their own summary line):
114
+ * counter?.flush();
115
+ *
116
+ * Returns `undefined` when the namespace is disabled so call sites pay
117
+ * nothing when off.
118
+ */
119
+ export interface Counter {
120
+ record(file: string, ms: number): void;
121
+ /**
122
+ * Convenience: time a sync or async block and record it. Propagates
123
+ * throws; records regardless of outcome. Returns the function's result.
124
+ */
125
+ time<T>(file: string, fn: () => T): T;
126
+ time<T>(file: string, fn: () => Promise<T>): Promise<T>;
127
+ flush(): void;
128
+ }
129
+
130
+ export function createCounter(
131
+ debug: Debugger | undefined,
132
+ label: string,
133
+ ): Counter | undefined {
134
+ if (!debug) return undefined;
135
+ let n = 0;
136
+ let totalMs = 0;
137
+ let slowestMs = 0;
138
+ let slowestFile = "";
139
+ const record = (file: string, ms: number): void => {
140
+ n++;
141
+ totalMs += ms;
142
+ if (ms > slowestMs) {
143
+ slowestMs = ms;
144
+ slowestFile = file;
145
+ }
146
+ };
147
+ return {
148
+ record,
149
+ time<T>(file: string, fn: () => T | Promise<T>): T | Promise<T> {
150
+ const start = performance.now();
151
+ let out: T | Promise<T>;
152
+ try {
153
+ out = fn();
154
+ } catch (err) {
155
+ record(file, performance.now() - start);
156
+ throw err;
157
+ }
158
+ if (out && typeof (out as any).then === "function") {
159
+ return (out as Promise<T>).finally(() =>
160
+ record(file, performance.now() - start),
161
+ );
162
+ }
163
+ record(file, performance.now() - start);
164
+ return out;
165
+ },
166
+ flush(): void {
167
+ if (n === 0) return;
168
+ debug(
169
+ "%s: %d files, %sms total, slowest %sms %s",
170
+ label,
171
+ n,
172
+ totalMs.toFixed(1),
173
+ slowestMs.toFixed(1),
174
+ slowestFile,
175
+ );
176
+ // Reset so buildEnd firing once per environment (Vite 6+ multi-env)
177
+ // gives one log line per env rather than silently dropping later data.
178
+ n = 0;
179
+ totalMs = 0;
180
+ slowestMs = 0;
181
+ slowestFile = "";
182
+ },
183
+ };
184
+ }