@rangojs/router 0.0.0-experimental.b9cb8739 → 0.0.0-experimental.bd6e11bc

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 (285) hide show
  1. package/README.md +196 -43
  2. package/dist/bin/rango.js +277 -99
  3. package/dist/testing/vitest.js +48 -0
  4. package/dist/vite/index.js +2779 -1064
  5. package/dist/vite/index.js.bak +5448 -0
  6. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  7. package/package.json +57 -11
  8. package/skills/breadcrumbs/SKILL.md +3 -1
  9. package/skills/bundle-analysis/SKILL.md +159 -0
  10. package/skills/cache-guide/SKILL.md +243 -21
  11. package/skills/caching/SKILL.md +155 -6
  12. package/skills/composability/SKILL.md +27 -2
  13. package/skills/document-cache/SKILL.md +78 -55
  14. package/skills/handler-use/SKILL.md +364 -0
  15. package/skills/hooks/SKILL.md +229 -20
  16. package/skills/host-router/SKILL.md +45 -20
  17. package/skills/i18n/SKILL.md +276 -0
  18. package/skills/intercept/SKILL.md +46 -4
  19. package/skills/layout/SKILL.md +28 -7
  20. package/skills/links/SKILL.md +249 -17
  21. package/skills/loader/SKILL.md +273 -53
  22. package/skills/middleware/SKILL.md +49 -12
  23. package/skills/migrate-nextjs/SKILL.md +562 -0
  24. package/skills/migrate-react-router/SKILL.md +769 -0
  25. package/skills/mime-routes/SKILL.md +27 -0
  26. package/skills/observability/SKILL.md +137 -0
  27. package/skills/parallel/SKILL.md +197 -6
  28. package/skills/prerender/SKILL.md +123 -100
  29. package/skills/rango/SKILL.md +242 -22
  30. package/skills/react-compiler/SKILL.md +168 -0
  31. package/skills/response-routes/SKILL.md +66 -9
  32. package/skills/route/SKILL.md +88 -4
  33. package/skills/router-setup/SKILL.md +90 -5
  34. package/skills/server-actions/SKILL.md +751 -0
  35. package/skills/streams-and-websockets/SKILL.md +283 -0
  36. package/skills/testing/SKILL.md +716 -0
  37. package/skills/typesafety/SKILL.md +329 -27
  38. package/skills/use-cache/SKILL.md +34 -5
  39. package/skills/view-transitions/SKILL.md +294 -0
  40. package/src/__augment-tests__/augment.ts +81 -0
  41. package/src/__augment-tests__/augmented.check.ts +117 -0
  42. package/src/__internal.ts +1 -1
  43. package/src/browser/action-coordinator.ts +53 -36
  44. package/src/browser/app-shell.ts +52 -0
  45. package/src/browser/app-version.ts +14 -0
  46. package/src/browser/event-controller.ts +91 -70
  47. package/src/browser/history-state.ts +21 -0
  48. package/src/browser/index.ts +3 -3
  49. package/src/browser/navigation-bridge.ts +102 -16
  50. package/src/browser/navigation-client.ts +164 -59
  51. package/src/browser/navigation-store.ts +75 -17
  52. package/src/browser/navigation-transaction.ts +21 -37
  53. package/src/browser/partial-update.ts +139 -38
  54. package/src/browser/prefetch/cache.ts +175 -15
  55. package/src/browser/prefetch/fetch.ts +180 -33
  56. package/src/browser/prefetch/queue.ts +123 -20
  57. package/src/browser/prefetch/resource-ready.ts +77 -0
  58. package/src/browser/rango-state.ts +53 -13
  59. package/src/browser/react/Link.tsx +81 -9
  60. package/src/browser/react/NavigationProvider.tsx +110 -33
  61. package/src/browser/react/context.ts +7 -2
  62. package/src/browser/react/filter-segment-order.ts +51 -7
  63. package/src/browser/react/index.ts +3 -0
  64. package/src/browser/react/location-state-shared.ts +175 -4
  65. package/src/browser/react/location-state.ts +39 -13
  66. package/src/browser/react/use-handle.ts +23 -64
  67. package/src/browser/react/use-navigation.ts +22 -2
  68. package/src/browser/react/use-params.ts +20 -8
  69. package/src/browser/react/use-reverse.ts +106 -0
  70. package/src/browser/react/use-router.ts +43 -10
  71. package/src/browser/react/use-segments.ts +11 -8
  72. package/src/browser/response-adapter.ts +25 -0
  73. package/src/browser/rsc-router.tsx +191 -74
  74. package/src/browser/scroll-restoration.ts +41 -14
  75. package/src/browser/segment-reconciler.ts +36 -9
  76. package/src/browser/segment-structure-assert.ts +2 -2
  77. package/src/browser/server-action-bridge.ts +31 -36
  78. package/src/browser/types.ts +57 -5
  79. package/src/build/collect-fallback-refs.ts +107 -0
  80. package/src/build/generate-manifest.ts +65 -40
  81. package/src/build/generate-route-types.ts +5 -0
  82. package/src/build/index.ts +2 -0
  83. package/src/build/route-trie.ts +52 -25
  84. package/src/build/route-types/codegen.ts +4 -4
  85. package/src/build/route-types/include-resolution.ts +9 -2
  86. package/src/build/route-types/per-module-writer.ts +7 -4
  87. package/src/build/route-types/router-processing.ts +278 -88
  88. package/src/build/route-types/scan-filter.ts +9 -2
  89. package/src/build/route-types/source-scan.ts +118 -0
  90. package/src/build/runtime-discovery.ts +9 -20
  91. package/src/cache/cache-runtime.ts +15 -11
  92. package/src/cache/cache-scope.ts +76 -49
  93. package/src/cache/cf/cf-cache-store.ts +501 -18
  94. package/src/cache/cf/index.ts +5 -1
  95. package/src/cache/document-cache.ts +17 -7
  96. package/src/cache/index.ts +1 -0
  97. package/src/cache/taint.ts +55 -0
  98. package/src/client.rsc.tsx +3 -0
  99. package/src/client.tsx +94 -238
  100. package/src/context-var.ts +72 -2
  101. package/src/debug.ts +2 -2
  102. package/src/decode-loader-results.ts +36 -0
  103. package/src/errors.ts +30 -1
  104. package/src/handle.ts +65 -12
  105. package/src/host/index.ts +2 -2
  106. package/src/host/router.ts +129 -57
  107. package/src/host/types.ts +31 -2
  108. package/src/host/utils.ts +1 -1
  109. package/src/href-client.ts +140 -20
  110. package/src/index.rsc.ts +12 -5
  111. package/src/index.ts +61 -11
  112. package/src/loader-store.ts +500 -0
  113. package/src/loader.rsc.ts +2 -5
  114. package/src/loader.ts +3 -10
  115. package/src/missing-id-error.ts +68 -0
  116. package/src/outlet-context.ts +1 -1
  117. package/src/prerender/store.ts +5 -4
  118. package/src/prerender.ts +141 -80
  119. package/src/response-utils.ts +37 -0
  120. package/src/reverse.ts +65 -15
  121. package/src/route-content-wrapper.tsx +6 -28
  122. package/src/route-definition/dsl-helpers.ts +435 -260
  123. package/src/route-definition/helper-factories.ts +29 -139
  124. package/src/route-definition/helpers-types.ts +110 -34
  125. package/src/route-definition/index.ts +3 -0
  126. package/src/route-definition/redirect.ts +11 -3
  127. package/src/route-definition/resolve-handler-use.ts +155 -0
  128. package/src/route-definition/use-item-types.ts +32 -0
  129. package/src/route-map-builder.ts +7 -1
  130. package/src/route-types.ts +37 -41
  131. package/src/router/basename.ts +14 -0
  132. package/src/router/content-negotiation.ts +113 -1
  133. package/src/router/error-handling.ts +1 -1
  134. package/src/router/find-match.ts +4 -2
  135. package/src/router/handler-context.ts +77 -38
  136. package/src/router/intercept-resolution.ts +15 -22
  137. package/src/router/lazy-includes.ts +12 -9
  138. package/src/router/loader-resolution.ts +174 -22
  139. package/src/router/logging.ts +5 -2
  140. package/src/router/manifest.ts +31 -16
  141. package/src/router/match-api.ts +128 -192
  142. package/src/router/match-handlers.ts +63 -20
  143. package/src/router/match-middleware/background-revalidation.ts +30 -2
  144. package/src/router/match-middleware/cache-lookup.ts +136 -106
  145. package/src/router/match-middleware/cache-store.ts +54 -10
  146. package/src/router/match-middleware/intercept-resolution.ts +9 -7
  147. package/src/router/match-middleware/segment-resolution.ts +61 -5
  148. package/src/router/match-result.ts +125 -10
  149. package/src/router/metrics.ts +7 -2
  150. package/src/router/middleware-types.ts +21 -34
  151. package/src/router/middleware.ts +103 -90
  152. package/src/router/navigation-snapshot.ts +182 -0
  153. package/src/router/pattern-matching.ts +101 -17
  154. package/src/router/prerender-match.ts +110 -10
  155. package/src/router/preview-match.ts +32 -102
  156. package/src/router/request-classification.ts +286 -0
  157. package/src/router/revalidation.ts +58 -2
  158. package/src/router/route-snapshot.ts +245 -0
  159. package/src/router/router-context.ts +6 -1
  160. package/src/router/router-interfaces.ts +77 -28
  161. package/src/router/router-options.ts +76 -11
  162. package/src/router/router-registry.ts +2 -5
  163. package/src/router/segment-resolution/fresh.ts +223 -24
  164. package/src/router/segment-resolution/helpers.ts +29 -24
  165. package/src/router/segment-resolution/loader-cache.ts +1 -0
  166. package/src/router/segment-resolution/revalidation.ts +466 -285
  167. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  168. package/src/router/segment-wrappers.ts +2 -0
  169. package/src/router/substitute-pattern-params.ts +56 -0
  170. package/src/router/telemetry.ts +99 -0
  171. package/src/router/trie-matching.ts +18 -13
  172. package/src/router/types.ts +9 -0
  173. package/src/router/url-params.ts +49 -0
  174. package/src/router.ts +91 -23
  175. package/src/rsc/handler-context.ts +2 -2
  176. package/src/rsc/handler.ts +440 -381
  177. package/src/rsc/helpers.ts +91 -43
  178. package/src/rsc/index.ts +1 -1
  179. package/src/rsc/loader-fetch.ts +23 -3
  180. package/src/rsc/manifest-init.ts +5 -1
  181. package/src/rsc/origin-guard.ts +28 -10
  182. package/src/rsc/progressive-enhancement.ts +18 -2
  183. package/src/rsc/response-route-handler.ts +46 -53
  184. package/src/rsc/rsc-rendering.ts +41 -48
  185. package/src/rsc/runtime-warnings.ts +9 -10
  186. package/src/rsc/server-action.ts +25 -37
  187. package/src/rsc/ssr-setup.ts +18 -2
  188. package/src/rsc/types.ts +17 -3
  189. package/src/search-params.ts +4 -4
  190. package/src/segment-content-promise.ts +67 -0
  191. package/src/segment-loader-promise.ts +122 -0
  192. package/src/segment-system.tsx +219 -67
  193. package/src/serialize.ts +243 -0
  194. package/src/server/context.ts +277 -61
  195. package/src/server/cookie-store.ts +28 -4
  196. package/src/server/handle-store.ts +19 -0
  197. package/src/server/loader-registry.ts +9 -8
  198. package/src/server/request-context.ts +204 -60
  199. package/src/ssr/index.tsx +9 -1
  200. package/src/static-handler.ts +19 -7
  201. package/src/testing/cache-status.ts +166 -0
  202. package/src/testing/collect-handle.ts +63 -0
  203. package/src/testing/dispatch.ts +440 -0
  204. package/src/testing/dom.entry.ts +22 -0
  205. package/src/testing/e2e/fixture.ts +154 -0
  206. package/src/testing/e2e/index.ts +149 -0
  207. package/src/testing/e2e/matchers.ts +51 -0
  208. package/src/testing/e2e/page-helpers.ts +272 -0
  209. package/src/testing/e2e/parity.ts +306 -0
  210. package/src/testing/e2e/server.ts +183 -0
  211. package/src/testing/flight-matchers.ts +104 -0
  212. package/src/testing/flight-runtime.d.ts +21 -0
  213. package/src/testing/flight.entry.ts +22 -0
  214. package/src/testing/flight.ts +182 -0
  215. package/src/testing/generated-routes.ts +223 -0
  216. package/src/testing/index.ts +106 -0
  217. package/src/testing/internal/context.ts +255 -0
  218. package/src/testing/render-route.tsx +565 -0
  219. package/src/testing/run-loader.ts +296 -0
  220. package/src/testing/run-middleware.ts +179 -0
  221. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  222. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  223. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  224. package/src/testing/vitest-stubs/version.ts +5 -0
  225. package/src/testing/vitest.ts +183 -0
  226. package/src/types/cache-types.ts +4 -4
  227. package/src/types/global-namespace.ts +39 -26
  228. package/src/types/handler-context.ts +194 -72
  229. package/src/types/index.ts +1 -0
  230. package/src/types/loader-types.ts +41 -15
  231. package/src/types/request-scope.ts +126 -0
  232. package/src/types/route-entry.ts +19 -1
  233. package/src/types/segments.ts +37 -1
  234. package/src/urls/include-helper.ts +34 -67
  235. package/src/urls/index.ts +0 -3
  236. package/src/urls/path-helper-types.ts +50 -9
  237. package/src/urls/path-helper.ts +63 -63
  238. package/src/urls/pattern-types.ts +48 -19
  239. package/src/urls/response-types.ts +25 -22
  240. package/src/urls/type-extraction.ts +26 -116
  241. package/src/urls/urls-function.ts +1 -5
  242. package/src/use-loader.tsx +487 -44
  243. package/src/vite/debug.ts +185 -0
  244. package/src/vite/discovery/bundle-postprocess.ts +34 -37
  245. package/src/vite/discovery/discover-routers.ts +105 -51
  246. package/src/vite/discovery/discovery-errors.ts +194 -0
  247. package/src/vite/discovery/gate-state.ts +171 -0
  248. package/src/vite/discovery/prerender-collection.ts +188 -93
  249. package/src/vite/discovery/route-types-writer.ts +40 -84
  250. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  251. package/src/vite/discovery/state.ts +46 -6
  252. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  253. package/src/vite/index.ts +6 -0
  254. package/src/vite/plugin-types.ts +111 -72
  255. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  256. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  257. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  258. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  259. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  260. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  261. package/src/vite/plugins/expose-action-id.ts +55 -33
  262. package/src/vite/plugins/expose-id-utils.ts +24 -8
  263. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  264. package/src/vite/plugins/expose-ids/handler-transform.ts +12 -35
  265. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  266. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  267. package/src/vite/plugins/expose-internal-ids.ts +544 -317
  268. package/src/vite/plugins/performance-tracks.ts +92 -0
  269. package/src/vite/plugins/refresh-cmd.ts +88 -26
  270. package/src/vite/plugins/use-cache-transform.ts +65 -50
  271. package/src/vite/plugins/version-injector.ts +39 -23
  272. package/src/vite/plugins/version-plugin.ts +72 -3
  273. package/src/vite/plugins/virtual-entries.ts +2 -2
  274. package/src/vite/rango.ts +265 -226
  275. package/src/vite/router-discovery.ts +920 -137
  276. package/src/vite/utils/ast-handler-extract.ts +15 -15
  277. package/src/vite/utils/banner.ts +4 -4
  278. package/src/vite/utils/bundle-analysis.ts +4 -2
  279. package/src/vite/utils/client-chunks.ts +190 -0
  280. package/src/vite/utils/forward-user-plugins.ts +193 -0
  281. package/src/vite/utils/manifest-utils.ts +21 -5
  282. package/src/vite/utils/package-resolution.ts +41 -1
  283. package/src/vite/utils/prerender-utils.ts +38 -5
  284. package/src/vite/utils/shared-utils.ts +109 -27
  285. package/src/browser/action-response-classifier.ts +0 -99
@@ -10,7 +10,11 @@
10
10
  */
11
11
 
12
12
  // Public API
13
- export { CFCacheStore, type CFCacheStoreOptions } from "./cf-cache-store.js";
13
+ export {
14
+ CFCacheStore,
15
+ type CFCacheStoreOptions,
16
+ type KVNamespace,
17
+ } from "./cf-cache-store.js";
14
18
 
15
19
  // Header constants for debugging and inspection
16
20
  export {
@@ -13,6 +13,7 @@
13
13
 
14
14
  import type { MiddlewareFn, MiddlewareContext } from "../router/middleware.js";
15
15
  import { getRequestContext } from "../server/request-context.js";
16
+ import { mayNeedSSR } from "../rsc/ssr-setup.js";
16
17
  import { sortedSearchString } from "./cache-key-utils.js";
17
18
  import { runBackground } from "./background-task.js";
18
19
 
@@ -204,18 +205,24 @@ export function createDocumentCacheMiddleware<TEnv = any>(
204
205
  ): Promise<Response> {
205
206
  const url = ctx.url;
206
207
 
208
+ // Use the original request URL for _rsc* param detection and cache key
209
+ // differentiation. ctx.url is stripped of _rsc* params by the middleware
210
+ // pipeline (stripInternalParams), so _rsc_partial, _rsc_segments, etc.
211
+ // are not visible on ctx.url in production.
212
+ const rawUrl = new URL(ctx.request.url);
213
+
207
214
  // Only cache GET requests — mutations and other methods must not be cached
208
215
  if (ctx.request.method !== "GET") {
209
216
  return next();
210
217
  }
211
218
 
212
219
  // Skip RSC action requests (mutations shouldn't be cached)
213
- if (url.searchParams.has("_rsc_action")) {
220
+ if (rawUrl.searchParams.has("_rsc_action")) {
214
221
  return next();
215
222
  }
216
223
 
217
224
  // Skip loader requests (have their own caching)
218
- if (url.searchParams.has("_rsc_loader")) {
225
+ if (rawUrl.searchParams.has("_rsc_loader")) {
219
226
  return next();
220
227
  }
221
228
 
@@ -241,9 +248,12 @@ export function createDocumentCacheMiddleware<TEnv = any>(
241
248
  return next();
242
249
  }
243
250
 
244
- // Determine request type for cache key differentiation
245
- const isPartial = url.searchParams.has("_rsc_partial");
246
- const typeLabel = isPartial ? "RSC" : "HTML";
251
+ // Determine request type for cache key differentiation.
252
+ // Uses rawUrl for _rsc* param checks and mayNeedSSR for Accept-based
253
+ // detection. Full-document RSC fetches must not share the HTML cache slot.
254
+ const isPartial = rawUrl.searchParams.has("_rsc_partial");
255
+ const isRscRequest = !mayNeedSSR(ctx.request, rawUrl);
256
+ const typeLabel = isRscRequest ? "RSC" : "HTML";
247
257
 
248
258
  // Track whether next() has been called so the catch block knows
249
259
  // whether it is safe to fall through to the handler.
@@ -254,10 +264,10 @@ export function createDocumentCacheMiddleware<TEnv = any>(
254
264
  // gracefully to the origin handler instead of rejecting the request.
255
265
  // This is a deliberate fail-open-to-origin policy: the fallback is
256
266
  // "serve uncached from origin", not "use a different cache key".
257
- const clientSegments = url.searchParams.get("_rsc_segments") || "";
267
+ const clientSegments = rawUrl.searchParams.get("_rsc_segments") || "";
258
268
  const segmentHash =
259
269
  isPartial && clientSegments ? `:${hashSegmentIds(clientSegments)}` : "";
260
- const typeSuffix = isPartial ? ":rsc" : ":html";
270
+ const typeSuffix = isRscRequest ? ":rsc" : ":html";
261
271
 
262
272
  let searchSuffix = "";
263
273
  if (!keyGenerator) {
@@ -29,6 +29,7 @@ export { MemorySegmentCacheStore } from "./memory-segment-store.js";
29
29
  export {
30
30
  CFCacheStore,
31
31
  type CFCacheStoreOptions,
32
+ type KVNamespace,
32
33
  CACHE_STALE_AT_HEADER,
33
34
  CACHE_STATUS_HEADER,
34
35
  } from "./cf/index.js";
@@ -81,6 +81,61 @@ export function assertNotInsideCacheExec(
81
81
  }
82
82
  }
83
83
 
84
+ /**
85
+ * Symbol stamped on ctx when resolving handlers inside a cache() DSL boundary.
86
+ * Separate from INSIDE_CACHE_EXEC ("use cache") because cache() allows
87
+ * ctx.set() (children are also cached) but blocks response-level side effects
88
+ * (headers, cookies, status) which are lost on cache hit.
89
+ */
90
+ export const INSIDE_CACHE_SCOPE: unique symbol = Symbol.for(
91
+ "rango:inside-cache-scope",
92
+ ) as any;
93
+
94
+ /**
95
+ * Mark ctx as inside a cache() scope. Must be paired with unstampCacheScope.
96
+ */
97
+ export function stampCacheScope(obj: object): void {
98
+ const current = (obj as any)[INSIDE_CACHE_SCOPE] ?? 0;
99
+ (obj as any)[INSIDE_CACHE_SCOPE] = current + 1;
100
+ }
101
+
102
+ /**
103
+ * Remove cache() scope mark.
104
+ */
105
+ export function unstampCacheScope(obj: object): void {
106
+ const current = (obj as any)[INSIDE_CACHE_SCOPE] ?? 0;
107
+ if (current <= 1) {
108
+ delete (obj as any)[INSIDE_CACHE_SCOPE];
109
+ } else {
110
+ (obj as any)[INSIDE_CACHE_SCOPE] = current - 1;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Throw if ctx is inside a cache() DSL boundary.
116
+ * Call from response-level side effects (header, setCookie, setStatus, etc.)
117
+ * which are lost on cache hit because the handler body is skipped.
118
+ * ctx.set() is allowed inside cache() — children are also cached and can
119
+ * read the value.
120
+ */
121
+ export function assertNotInsideCacheScope(
122
+ ctx: unknown,
123
+ methodName: string,
124
+ ): void {
125
+ if (
126
+ ctx !== null &&
127
+ ctx !== undefined &&
128
+ typeof ctx === "object" &&
129
+ (INSIDE_CACHE_SCOPE as symbol) in (ctx as Record<symbol, unknown>)
130
+ ) {
131
+ throw new Error(
132
+ `ctx.${methodName}() cannot be called inside a cache() boundary. ` +
133
+ `On cache hit the handler is skipped, so this side effect would be lost. ` +
134
+ `Move ctx.${methodName}() to a middleware or layout outside the cache() scope.`,
135
+ );
136
+ }
137
+ }
138
+
84
139
  /**
85
140
  * Brand symbol for functions wrapped by registerCachedFunction().
86
141
  * Used at runtime to detect when a "use cache" function is misused
@@ -78,6 +78,9 @@ export {
78
78
  // Re-export useHref - it's a "use client" hook
79
79
  export { useHref } from "./browser/react/use-href.js";
80
80
 
81
+ // Re-export useReverse - it's a "use client" hook
82
+ export { useReverse } from "./browser/react/use-reverse.js";
83
+
81
84
  // Re-export useHandle - it's a "use client" hook
82
85
  export { useHandle } from "./browser/react/use-handle.js";
83
86
 
package/src/client.tsx CHANGED
@@ -13,7 +13,6 @@ import {
13
13
  type ClientErrorBoundaryFallbackProps,
14
14
  type ErrorInfo,
15
15
  type LoaderDefinition,
16
- type LoaderFn,
17
16
  type ResolvedSegment,
18
17
  } from "./types";
19
18
  import {
@@ -22,6 +21,83 @@ import {
22
21
  } from "./route-content-wrapper.js";
23
22
  import { OutletProvider } from "./outlet-provider.js";
24
23
  import { MountContextProvider } from "./browser/react/mount-context.js";
24
+ import { getMemoizedContentPromise } from "./segment-content-promise.js";
25
+
26
+ /**
27
+ * Render the content for a named parallel/intercept slot segment.
28
+ *
29
+ * Shared by Outlet (with `name` prop) and ParallelOutlet — both resolve a
30
+ * segment from context.parallel by slot name and then render it through the
31
+ * same layout/loader/mountPath wrapping pipeline.
32
+ */
33
+ function renderSlotContent(segment: ResolvedSegment | null): ReactNode {
34
+ if (!segment) return null;
35
+
36
+ const content: ReactNode =
37
+ segment.loading || segment.component instanceof Promise ? (
38
+ <RouteContentWrapper
39
+ content={getMemoizedContentPromise(segment.component)}
40
+ fallback={segment.loading}
41
+ segmentId={segment.id}
42
+ />
43
+ ) : (
44
+ (segment.component ?? null)
45
+ );
46
+
47
+ const hasOwnLoaders = !!(segment.loaderDataPromise && segment.loaderIds);
48
+ const loaderWrapped = hasOwnLoaders ? (
49
+ <LoaderBoundary
50
+ loaderDataPromise={segment.loaderDataPromise!}
51
+ loaderIds={segment.loaderIds!}
52
+ fallback={segment.loading}
53
+ outletKey={segment.id + "-loader"}
54
+ outletContent={null}
55
+ segment={segment}
56
+ >
57
+ {content}
58
+ </LoaderBoundary>
59
+ ) : null;
60
+
61
+ let result: ReactNode;
62
+ if (segment.layout) {
63
+ // Layout renders immediately; if loaders exist, the LoaderBoundary becomes
64
+ // the outlet content so layout's <Outlet /> suspends until loaders resolve.
65
+ result = (
66
+ <OutletProvider
67
+ content={hasOwnLoaders ? loaderWrapped : content}
68
+ segment={segment}
69
+ >
70
+ {segment.layout}
71
+ </OutletProvider>
72
+ );
73
+ } else if (hasOwnLoaders) {
74
+ // No layout but has loaders — wrap content with LoaderBoundary for useLoader context.
75
+ // Common for intercept routes that use useLoader without a custom layout.
76
+ result = loaderWrapped;
77
+ } else {
78
+ result = content;
79
+ }
80
+
81
+ if (segment.mountPath) {
82
+ return (
83
+ <MountContextProvider value={segment.mountPath}>
84
+ {result}
85
+ </MountContextProvider>
86
+ );
87
+ }
88
+
89
+ return result;
90
+ }
91
+
92
+ function useSlotSegment(
93
+ context: OutletContextValue | null,
94
+ name: `@${string}` | undefined,
95
+ ): ResolvedSegment | null {
96
+ return useMemo(() => {
97
+ if (!name || !context?.parallel) return null;
98
+ return context.parallel.find((seg) => seg.slot === name) ?? null;
99
+ }, [context, name]);
100
+ }
25
101
 
26
102
  /**
27
103
  * Outlet component - renders child content in layouts
@@ -62,95 +138,10 @@ import { MountContextProvider } from "./browser/react/mount-context.js";
62
138
  */
63
139
  export function Outlet({ name }: { name?: `@${string}` } = {}): ReactNode {
64
140
  const context = useContext(OutletContext);
141
+ const namedSegment = useSlotSegment(context, name);
65
142
 
66
- // If name provided, render parallel/intercept content for that slot
67
143
  if (name) {
68
- const segment = context?.parallel?.find((seg) => seg.slot === name) ?? null;
69
-
70
- if (!segment) return null;
71
-
72
- // Determine the content to render
73
- let content: ReactNode;
74
- if (segment.loading || segment.component instanceof Promise) {
75
- // Use RouteContentWrapper to handle Suspense wrapping properly
76
- content = (
77
- <RouteContentWrapper
78
- content={
79
- segment.component instanceof Promise
80
- ? segment.component
81
- : Promise.resolve(segment.component)
82
- }
83
- fallback={segment.loading}
84
- segmentId={segment.id}
85
- />
86
- );
87
- } else {
88
- content = segment.component ?? null;
89
- }
90
-
91
- let result: ReactNode;
92
-
93
- // If segment has a layout, wrap appropriately
94
- if (segment.layout) {
95
- // Check if this segment has loaders that need streaming
96
- // The layout renders immediately, LoaderBoundary becomes the outlet content
97
- // When layout renders <Outlet />, it gets the LoaderBoundary which suspends
98
- if (segment.loaderDataPromise && segment.loaderIds) {
99
- const loaderAwareContent = (
100
- <LoaderBoundary
101
- loaderDataPromise={segment.loaderDataPromise}
102
- loaderIds={segment.loaderIds}
103
- fallback={segment.loading}
104
- outletKey={segment.id + "-loader"}
105
- outletContent={null}
106
- segment={segment}
107
- >
108
- {content}
109
- </LoaderBoundary>
110
- );
111
-
112
- result = (
113
- <OutletProvider content={loaderAwareContent} segment={segment}>
114
- {segment.layout}
115
- </OutletProvider>
116
- );
117
- } else {
118
- // No loaders - wrap in OutletProvider so layout can use <Outlet />
119
- result = (
120
- <OutletProvider content={content} segment={segment}>
121
- {segment.layout}
122
- </OutletProvider>
123
- );
124
- }
125
- } else if (segment.loaderDataPromise && segment.loaderIds) {
126
- // No layout but has loaders - wrap content with LoaderBoundary for useLoader context
127
- // This is common for intercept routes that use useLoader without a custom layout
128
- result = (
129
- <LoaderBoundary
130
- loaderDataPromise={segment.loaderDataPromise}
131
- loaderIds={segment.loaderIds}
132
- fallback={segment.loading}
133
- outletKey={segment.id + "-loader"}
134
- outletContent={null}
135
- segment={segment}
136
- >
137
- {content}
138
- </LoaderBoundary>
139
- );
140
- } else {
141
- result = content;
142
- }
143
-
144
- // Wrap with MountContextProvider for include() scoped parallel/intercept slots
145
- if (segment.mountPath) {
146
- return (
147
- <MountContextProvider value={segment.mountPath}>
148
- {result}
149
- </MountContextProvider>
150
- );
151
- }
152
-
153
- return result;
144
+ return renderSlotContent(namedSegment);
154
145
  }
155
146
 
156
147
  // Default: render child content
@@ -164,6 +155,7 @@ export function Outlet({ name }: { name?: `@${string}` } = {}): ReactNode {
164
155
 
165
156
  return content;
166
157
  }
158
+
167
159
  /**
168
160
  * ParallelOutlet component - renders content for a named parallel slot
169
161
  *
@@ -188,94 +180,9 @@ export function Outlet({ name }: { name?: `@${string}` } = {}): ReactNode {
188
180
  */
189
181
  export function ParallelOutlet({ name }: { name: `@${string}` }): ReactNode {
190
182
  const context = useContext(OutletContext);
191
- const segment = useMemo(() => {
192
- if (!context?.parallel) return null;
193
- return context.parallel.find((seg) => seg.slot === name) ?? null;
194
- }, [context, name]);
195
-
196
- if (!segment) return null;
183
+ const segment = useSlotSegment(context, name);
197
184
 
198
- // Determine the content to render
199
- let content: ReactNode;
200
- if (segment.loading || segment.component instanceof Promise) {
201
- // Use RouteContentWrapper to handle Suspense wrapping properly
202
- content = (
203
- <RouteContentWrapper
204
- content={
205
- segment.component instanceof Promise
206
- ? segment.component
207
- : Promise.resolve(segment.component)
208
- }
209
- fallback={segment.loading}
210
- segmentId={segment.id}
211
- />
212
- );
213
- } else {
214
- content = segment.component ?? null;
215
- }
216
-
217
- let result: ReactNode;
218
-
219
- // If segment has a layout, wrap appropriately
220
- if (segment.layout) {
221
- // Check if this segment has loaders that need streaming
222
- // The layout renders immediately, LoaderBoundary becomes the outlet content
223
- if (segment.loaderDataPromise && segment.loaderIds) {
224
- const loaderAwareContent = (
225
- <LoaderBoundary
226
- loaderDataPromise={segment.loaderDataPromise}
227
- loaderIds={segment.loaderIds}
228
- fallback={segment.loading}
229
- outletKey={segment.id + "-loader"}
230
- outletContent={null}
231
- segment={segment}
232
- >
233
- {content}
234
- </LoaderBoundary>
235
- );
236
-
237
- result = (
238
- <OutletProvider content={loaderAwareContent} segment={segment}>
239
- {segment.layout}
240
- </OutletProvider>
241
- );
242
- } else {
243
- // No loaders - wrap in OutletProvider so layout can use <Outlet />
244
- result = (
245
- <OutletProvider content={content} segment={segment}>
246
- {segment.layout}
247
- </OutletProvider>
248
- );
249
- }
250
- } else if (segment.loaderDataPromise && segment.loaderIds) {
251
- // No layout but has loaders - wrap content with LoaderBoundary for useLoader context
252
- // This is common for intercept routes that use useLoader without a custom layout
253
- result = (
254
- <LoaderBoundary
255
- loaderDataPromise={segment.loaderDataPromise}
256
- loaderIds={segment.loaderIds}
257
- fallback={segment.loading}
258
- outletKey={segment.id + "-loader"}
259
- outletContent={null}
260
- segment={segment}
261
- >
262
- {content}
263
- </LoaderBoundary>
264
- );
265
- } else {
266
- result = content;
267
- }
268
-
269
- // Wrap with MountContextProvider for include() scoped parallel/intercept slots
270
- if (segment.mountPath) {
271
- return (
272
- <MountContextProvider value={segment.mountPath}>
273
- {result}
274
- </MountContextProvider>
275
- );
276
- }
277
-
278
- return result;
185
+ return renderSlotContent(segment);
279
186
  }
280
187
 
281
188
  // OutletProvider is defined in outlet-provider.tsx to break a circular
@@ -307,63 +214,13 @@ export function useOutlet(): ReactNode {
307
214
  export {
308
215
  useLoader,
309
216
  useFetchLoader,
217
+ useRefreshLoaders,
310
218
  type LoadFunction,
311
219
  type UseLoaderResult,
312
220
  type UseFetchLoaderResult,
313
221
  type UseLoaderOptions,
314
222
  } from "./use-loader.js";
315
223
 
316
- /**
317
- * Client-safe createLoader factory
318
- *
319
- * Creates a loader definition that can be used with useLoader().
320
- * This is the client-side version that only stores the $$id - the function
321
- * is ignored since loaders only execute on the server.
322
- *
323
- * The $$id is injected by the exposeLoaderId Vite plugin. In most cases,
324
- * you should import the loader directly from the server file rather than
325
- * creating a reference manually.
326
- *
327
- * @param fn - Loader function (ignored on client, kept for API compatibility)
328
- * @param _fetchable - Optional fetchable flag (ignored on client)
329
- * @param __injectedId - $$id injected by Vite plugin
330
- *
331
- * @example
332
- * ```tsx
333
- * "use client";
334
- * import { useLoader } from "rsc-router/client";
335
- * import { CartLoader } from "../loaders/cart"; // Import from server file
336
- *
337
- * export function CartIcon() {
338
- * const cart = useLoader(CartLoader);
339
- * return <span>Cart ({cart?.items.length ?? 0})</span>;
340
- * }
341
- * ```
342
- */
343
- // Overload 1: With function only (not fetchable)
344
- export function createLoader<T>(
345
- fn: LoaderFn<T, Record<string, string | undefined>, any>,
346
- ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>>;
347
-
348
- // Overload 2: With function and fetchable flag
349
- export function createLoader<T>(
350
- fn: LoaderFn<T, Record<string, string | undefined>, any>,
351
- fetchable: true,
352
- ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>>;
353
-
354
- // Implementation - function is ignored at runtime on client
355
- // The $$id is injected by Vite plugin as hidden third parameter
356
- export function createLoader(
357
- _fn: LoaderFn<any, Record<string, string | undefined>, any>,
358
- _fetchable?: true,
359
- __injectedId?: string,
360
- ): LoaderDefinition<any, Record<string, string | undefined>> {
361
- return {
362
- __brand: "loader",
363
- $$id: __injectedId || "",
364
- };
365
- }
366
-
367
224
  /**
368
225
  * Props for the ErrorBoundary component
369
226
  */
@@ -534,10 +391,8 @@ export {
534
391
  type ScrollRestorationProps,
535
392
  } from "./browser/react/ScrollRestoration.js";
536
393
 
537
- // Handle API - for accumulating data across route segments
538
- export { createHandle, isHandle, type Handle } from "./handle.js";
539
-
540
- // Handle data hook
394
+ // Handle data hook (client-side only createHandle/isHandle are server APIs from the root export)
395
+ export { type Handle } from "./handle.js";
541
396
  export { useHandle } from "./browser/react/use-handle.js";
542
397
 
543
398
  // Built-in handles
@@ -555,13 +410,10 @@ export {
555
410
  type LocationStateOptions,
556
411
  } from "./browser/react/location-state.js";
557
412
 
558
- // Type-safe href for client-side path validation
559
- export {
560
- href,
561
- type ValidPaths,
562
- type PatternToPath,
563
- type PathResponse,
564
- } from "./href-client.js";
413
+ // Type-safe href for client-side path validation. The path and response types
414
+ // are ambient as `Rango.Path` / `Rango.PathResponse` (declared in
415
+ // href-client.ts) — no import needed.
416
+ export { href, type PatternToPath } from "./href-client.js";
565
417
 
566
418
  // Response envelope types for consuming JSON response routes
567
419
  export type { ResponseEnvelope, ResponseError } from "./urls.js";
@@ -594,8 +446,12 @@ export { MountContext } from "./browser/react/mount-context.js";
594
446
  // Mount-aware href hook - auto-prefixes paths with include() mount
595
447
  export { useHref } from "./browser/react/use-href.js";
596
448
 
449
+ // Mount-aware reverse hook - resolves dot-prefixed names against an imported
450
+ // generated routes map (from a urls() module's .gen.ts).
451
+ export { useReverse } from "./browser/react/use-reverse.js";
452
+
597
453
  // Type-safe scoped reverse function for scopedReverse<typeof patterns>()
598
- export type { ScopedReverseFunction } from "./reverse.js";
454
+ export type { ScopedReverseFunction, LocalReverseFunction } from "./reverse.js";
599
455
 
600
456
  // Loader definition type - for typing loader props in client components
601
457
  export type { LoaderDefinition } from "./types.js";
@@ -12,6 +12,9 @@
12
12
  * interface PaginationData { current: number; total: number }
13
13
  * export const Pagination = createVar<PaginationData>();
14
14
  *
15
+ * // Non-cacheable var — ctx.get(User) throws inside a cache() boundary
16
+ * export const User = createVar<UserData>({ cache: false });
17
+ *
15
18
  * // handler
16
19
  * ctx.set(Pagination, { current: 1, total: 4 });
17
20
  *
@@ -23,18 +26,36 @@
23
26
  export interface ContextVar<T> {
24
27
  readonly __brand: "context-var";
25
28
  readonly key: symbol;
29
+ /** When false, ctx.get(var) throws inside a cache() boundary. */
30
+ readonly cache: boolean;
26
31
  /** Phantom field to carry the type parameter. Never set at runtime. */
27
32
  readonly __type?: T;
28
33
  }
29
34
 
35
+ export interface ContextVarOptions {
36
+ /**
37
+ * When false, marks this variable as non-cacheable.
38
+ * Reading this var with ctx.get() inside a cache() boundary throws. Use for
39
+ * inherently request-specific data (user sessions, auth tokens, etc.) that
40
+ * must never be baked into cached segments.
41
+ *
42
+ * @default true
43
+ */
44
+ cache?: boolean;
45
+ }
46
+
30
47
  /**
31
48
  * Create a typed context variable token.
32
49
  *
33
50
  * The returned object is used with ctx.set(token, value) and ctx.get(token)
34
51
  * for compile-time-checked data flow between handlers, layouts, and middleware.
35
52
  */
36
- export function createVar<T>(): ContextVar<T> {
37
- return { __brand: "context-var" as const, key: Symbol() };
53
+ export function createVar<T>(options?: ContextVarOptions): ContextVar<T> {
54
+ return {
55
+ __brand: "context-var" as const,
56
+ key: Symbol(),
57
+ cache: options?.cache !== false,
58
+ };
38
59
  }
39
60
 
40
61
  /**
@@ -49,6 +70,36 @@ export function isContextVar(value: unknown): value is ContextVar<unknown> {
49
70
  );
50
71
  }
51
72
 
73
+ /**
74
+ * Symbol used as a Set stored on the variables object to track
75
+ * which keys hold non-cacheable values (from write-level { cache: false }).
76
+ */
77
+ const NON_CACHEABLE_KEYS: unique symbol = Symbol.for(
78
+ "rango:non-cacheable-keys",
79
+ ) as any;
80
+
81
+ function getNonCacheableKeys(variables: any): Set<string | symbol> {
82
+ if (!variables[NON_CACHEABLE_KEYS]) {
83
+ variables[NON_CACHEABLE_KEYS] = new Set();
84
+ }
85
+ return variables[NON_CACHEABLE_KEYS];
86
+ }
87
+
88
+ /**
89
+ * Check if a variable value is non-cacheable (either var-level or write-level).
90
+ */
91
+ export function isNonCacheable(
92
+ variables: any,
93
+ keyOrVar: string | ContextVar<any>,
94
+ ): boolean {
95
+ if (typeof keyOrVar !== "string" && !keyOrVar.cache) {
96
+ return true; // var-level policy
97
+ }
98
+ const key = typeof keyOrVar === "string" ? keyOrVar : keyOrVar.key;
99
+ const set = variables[NON_CACHEABLE_KEYS] as Set<string | symbol> | undefined;
100
+ return set?.has(key) ?? false; // write-level policy
101
+ }
102
+
52
103
  /**
53
104
  * Read a variable from the variables store.
54
105
  * Accepts either a string key (legacy) or a ContextVar token (typed).
@@ -64,6 +115,17 @@ export function contextGet(
64
115
  /** Keys that must never be used as string variable names */
65
116
  const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
66
117
 
118
+ export interface ContextSetOptions {
119
+ /**
120
+ * When false, marks this specific write as non-cacheable.
121
+ * "Least cacheable wins" — if either the var definition or this option
122
+ * says cache: false, the value is non-cacheable.
123
+ *
124
+ * @default true (inherits from createVar)
125
+ */
126
+ cache?: boolean;
127
+ }
128
+
67
129
  /**
68
130
  * Write a variable to the variables store.
69
131
  * Accepts either a string key (legacy) or a ContextVar token (typed).
@@ -72,6 +134,7 @@ export function contextSet(
72
134
  variables: any,
73
135
  keyOrVar: string | ContextVar<any>,
74
136
  value: any,
137
+ options?: ContextSetOptions,
75
138
  ): void {
76
139
  if (typeof keyOrVar === "string") {
77
140
  if (FORBIDDEN_KEYS.has(keyOrVar)) {
@@ -80,7 +143,14 @@ export function contextSet(
80
143
  );
81
144
  }
82
145
  variables[keyOrVar] = value;
146
+ if (options?.cache === false) {
147
+ getNonCacheableKeys(variables).add(keyOrVar);
148
+ }
83
149
  } else {
84
150
  variables[keyOrVar.key] = value;
151
+ // Track write-level non-cacheable (var-level is checked via keyOrVar.cache)
152
+ if (options?.cache === false) {
153
+ getNonCacheableKeys(variables).add(keyOrVar.key);
154
+ }
85
155
  }
86
156
  }