@rangojs/router 0.0.0-experimental.20 → 0.0.0-experimental.204030a9

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 (293) hide show
  1. package/AGENTS.md +4 -0
  2. package/README.md +242 -55
  3. package/dist/bin/rango.js +277 -99
  4. package/dist/vite/index.js +2929 -1132
  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 +68 -21
  8. package/skills/breadcrumbs/SKILL.md +252 -0
  9. package/skills/bundle-analysis/SKILL.md +159 -0
  10. package/skills/cache-guide/SKILL.md +243 -21
  11. package/skills/caching/SKILL.md +159 -10
  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 +262 -51
  16. package/skills/host-router/SKILL.md +243 -0
  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 +291 -31
  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 +125 -102
  29. package/skills/rango/SKILL.md +242 -23
  30. package/skills/react-compiler/SKILL.md +168 -0
  31. package/skills/response-routes/SKILL.md +66 -9
  32. package/skills/route/SKILL.md +91 -8
  33. package/skills/router-setup/SKILL.md +98 -8
  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 +511 -188
  37. package/skills/typesafety/SKILL.md +354 -50
  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 +92 -0
  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/link-interceptor.ts +4 -0
  50. package/src/browser/navigation-bridge.ts +183 -18
  51. package/src/browser/navigation-client.ts +187 -57
  52. package/src/browser/navigation-store.ts +75 -17
  53. package/src/browser/navigation-transaction.ts +21 -37
  54. package/src/browser/partial-update.ts +143 -40
  55. package/src/browser/prefetch/cache.ts +275 -28
  56. package/src/browser/prefetch/fetch.ts +191 -46
  57. package/src/browser/prefetch/policy.ts +6 -0
  58. package/src/browser/prefetch/queue.ts +123 -20
  59. package/src/browser/prefetch/resource-ready.ts +77 -0
  60. package/src/browser/rango-state.ts +53 -13
  61. package/src/browser/react/Link.tsx +98 -14
  62. package/src/browser/react/NavigationProvider.tsx +110 -33
  63. package/src/browser/react/context.ts +7 -2
  64. package/src/browser/react/filter-segment-order.ts +51 -7
  65. package/src/browser/react/index.ts +3 -0
  66. package/src/browser/react/location-state-shared.ts +175 -4
  67. package/src/browser/react/location-state.ts +39 -13
  68. package/src/browser/react/use-handle.ts +23 -64
  69. package/src/browser/react/use-navigation.ts +22 -2
  70. package/src/browser/react/use-params.ts +20 -8
  71. package/src/browser/react/use-reverse.ts +106 -0
  72. package/src/browser/react/use-router.ts +43 -10
  73. package/src/browser/react/use-segments.ts +11 -8
  74. package/src/browser/response-adapter.ts +25 -0
  75. package/src/browser/rsc-router.tsx +200 -75
  76. package/src/browser/scroll-restoration.ts +46 -39
  77. package/src/browser/segment-reconciler.ts +36 -9
  78. package/src/browser/segment-structure-assert.ts +2 -2
  79. package/src/browser/server-action-bridge.ts +31 -36
  80. package/src/browser/types.ts +81 -5
  81. package/src/build/collect-fallback-refs.ts +107 -0
  82. package/src/build/generate-manifest.ts +65 -40
  83. package/src/build/generate-route-types.ts +5 -0
  84. package/src/build/index.ts +2 -0
  85. package/src/build/route-trie.ts +69 -26
  86. package/src/build/route-types/codegen.ts +4 -4
  87. package/src/build/route-types/include-resolution.ts +9 -2
  88. package/src/build/route-types/per-module-writer.ts +7 -4
  89. package/src/build/route-types/router-processing.ts +278 -88
  90. package/src/build/route-types/scan-filter.ts +9 -2
  91. package/src/build/route-types/source-scan.ts +118 -0
  92. package/src/build/runtime-discovery.ts +9 -20
  93. package/src/cache/cache-runtime.ts +15 -11
  94. package/src/cache/cache-scope.ts +76 -49
  95. package/src/cache/cf/cf-cache-store.ts +501 -18
  96. package/src/cache/cf/index.ts +5 -1
  97. package/src/cache/document-cache.ts +17 -7
  98. package/src/cache/index.ts +1 -0
  99. package/src/cache/taint.ts +55 -0
  100. package/src/client.rsc.tsx +5 -1
  101. package/src/client.tsx +95 -284
  102. package/src/context-var.ts +72 -2
  103. package/src/debug.ts +2 -2
  104. package/src/decode-loader-results.ts +36 -0
  105. package/src/errors.ts +30 -1
  106. package/src/handle.ts +65 -12
  107. package/src/handles/breadcrumbs.ts +66 -0
  108. package/src/handles/index.ts +1 -0
  109. package/src/host/index.ts +2 -5
  110. package/src/host/router.ts +129 -57
  111. package/src/host/types.ts +31 -2
  112. package/src/host/utils.ts +1 -1
  113. package/src/href-client.ts +140 -20
  114. package/src/index.rsc.ts +15 -40
  115. package/src/index.ts +92 -76
  116. package/src/loader-store.ts +500 -0
  117. package/src/loader.rsc.ts +2 -5
  118. package/src/loader.ts +3 -10
  119. package/src/missing-id-error.ts +68 -0
  120. package/src/outlet-context.ts +1 -1
  121. package/src/prerender/store.ts +57 -15
  122. package/src/prerender.ts +141 -80
  123. package/src/response-utils.ts +37 -0
  124. package/src/reverse.ts +65 -15
  125. package/src/route-content-wrapper.tsx +6 -28
  126. package/src/route-definition/dsl-helpers.ts +435 -260
  127. package/src/route-definition/helper-factories.ts +29 -139
  128. package/src/route-definition/helpers-types.ts +110 -34
  129. package/src/route-definition/index.ts +3 -3
  130. package/src/route-definition/redirect.ts +11 -3
  131. package/src/route-definition/resolve-handler-use.ts +155 -0
  132. package/src/route-definition/use-item-types.ts +32 -0
  133. package/src/route-map-builder.ts +7 -1
  134. package/src/route-types.ts +37 -41
  135. package/src/router/basename.ts +14 -0
  136. package/src/router/content-negotiation.ts +113 -1
  137. package/src/router/error-handling.ts +1 -1
  138. package/src/router/find-match.ts +4 -2
  139. package/src/router/handler-context.ts +105 -39
  140. package/src/router/intercept-resolution.ts +15 -22
  141. package/src/router/lazy-includes.ts +12 -9
  142. package/src/router/loader-resolution.ts +175 -23
  143. package/src/router/logging.ts +5 -2
  144. package/src/router/manifest.ts +31 -16
  145. package/src/router/match-api.ts +129 -193
  146. package/src/router/match-handlers.ts +63 -20
  147. package/src/router/match-middleware/background-revalidation.ts +30 -2
  148. package/src/router/match-middleware/cache-lookup.ts +136 -106
  149. package/src/router/match-middleware/cache-store.ts +54 -10
  150. package/src/router/match-middleware/intercept-resolution.ts +9 -7
  151. package/src/router/match-middleware/segment-resolution.ts +61 -5
  152. package/src/router/match-result.ts +124 -18
  153. package/src/router/metrics.ts +239 -14
  154. package/src/router/middleware-types.ts +61 -31
  155. package/src/router/middleware.ts +226 -124
  156. package/src/router/navigation-snapshot.ts +182 -0
  157. package/src/router/pattern-matching.ts +118 -19
  158. package/src/router/prerender-match.ts +114 -10
  159. package/src/router/preview-match.ts +32 -102
  160. package/src/router/request-classification.ts +286 -0
  161. package/src/router/revalidation.ts +85 -9
  162. package/src/router/route-snapshot.ts +245 -0
  163. package/src/router/router-context.ts +6 -1
  164. package/src/router/router-interfaces.ts +91 -29
  165. package/src/router/router-options.ts +89 -19
  166. package/src/router/router-registry.ts +2 -5
  167. package/src/router/segment-resolution/fresh.ts +240 -23
  168. package/src/router/segment-resolution/helpers.ts +30 -25
  169. package/src/router/segment-resolution/loader-cache.ts +1 -0
  170. package/src/router/segment-resolution/revalidation.ts +483 -289
  171. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  172. package/src/router/segment-wrappers.ts +2 -0
  173. package/src/router/substitute-pattern-params.ts +56 -0
  174. package/src/router/telemetry.ts +99 -0
  175. package/src/router/trie-matching.ts +38 -15
  176. package/src/router/types.ts +9 -0
  177. package/src/router/url-params.ts +49 -0
  178. package/src/router.ts +120 -32
  179. package/src/rsc/handler-context.ts +2 -2
  180. package/src/rsc/handler.ts +524 -370
  181. package/src/rsc/helpers.ts +91 -43
  182. package/src/rsc/index.ts +1 -21
  183. package/src/rsc/loader-fetch.ts +23 -3
  184. package/src/rsc/manifest-init.ts +5 -1
  185. package/src/rsc/origin-guard.ts +28 -10
  186. package/src/rsc/progressive-enhancement.ts +39 -10
  187. package/src/rsc/response-route-handler.ts +46 -53
  188. package/src/rsc/rsc-rendering.ts +69 -89
  189. package/src/rsc/runtime-warnings.ts +9 -10
  190. package/src/rsc/server-action.ts +39 -47
  191. package/src/rsc/ssr-setup.ts +144 -0
  192. package/src/rsc/types.ts +19 -3
  193. package/src/search-params.ts +20 -17
  194. package/src/segment-content-promise.ts +67 -0
  195. package/src/segment-loader-promise.ts +122 -0
  196. package/src/segment-system.tsx +219 -67
  197. package/src/serialize.ts +243 -0
  198. package/src/server/context.ts +285 -63
  199. package/src/server/cookie-store.ts +28 -4
  200. package/src/server/handle-store.ts +19 -0
  201. package/src/server/loader-registry.ts +9 -8
  202. package/src/server/request-context.ts +228 -65
  203. package/src/server.ts +6 -0
  204. package/src/ssr/index.tsx +9 -1
  205. package/src/static-handler.ts +19 -7
  206. package/src/testing/cache-status.ts +166 -0
  207. package/src/testing/collect-handle.ts +63 -0
  208. package/src/testing/dispatch.ts +440 -0
  209. package/src/testing/dom.entry.ts +22 -0
  210. package/src/testing/e2e/fixture.ts +154 -0
  211. package/src/testing/e2e/index.ts +149 -0
  212. package/src/testing/e2e/matchers.ts +51 -0
  213. package/src/testing/e2e/page-helpers.ts +272 -0
  214. package/src/testing/e2e/parity.ts +306 -0
  215. package/src/testing/e2e/server.ts +183 -0
  216. package/src/testing/flight-matchers.ts +104 -0
  217. package/src/testing/flight-runtime.d.ts +21 -0
  218. package/src/testing/flight.entry.ts +22 -0
  219. package/src/testing/flight.ts +182 -0
  220. package/src/testing/generated-routes.ts +223 -0
  221. package/src/testing/index.ts +98 -0
  222. package/src/testing/internal/context.ts +151 -0
  223. package/src/testing/render-route.tsx +536 -0
  224. package/src/testing/run-loader.ts +296 -0
  225. package/src/testing/run-middleware.ts +170 -0
  226. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  227. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  228. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  229. package/src/testing/vitest-stubs/version.ts +5 -0
  230. package/src/testing/vitest.ts +112 -0
  231. package/src/theme/index.ts +4 -13
  232. package/src/types/cache-types.ts +4 -4
  233. package/src/types/global-namespace.ts +39 -26
  234. package/src/types/handler-context.ts +197 -79
  235. package/src/types/index.ts +1 -0
  236. package/src/types/loader-types.ts +41 -15
  237. package/src/types/request-scope.ts +126 -0
  238. package/src/types/route-config.ts +17 -8
  239. package/src/types/route-entry.ts +19 -1
  240. package/src/types/segments.ts +37 -6
  241. package/src/urls/include-helper.ts +34 -67
  242. package/src/urls/index.ts +0 -3
  243. package/src/urls/path-helper-types.ts +50 -9
  244. package/src/urls/path-helper.ts +63 -63
  245. package/src/urls/pattern-types.ts +48 -19
  246. package/src/urls/response-types.ts +25 -22
  247. package/src/urls/type-extraction.ts +26 -116
  248. package/src/urls/urls-function.ts +1 -5
  249. package/src/use-loader.tsx +487 -44
  250. package/src/vite/debug.ts +185 -0
  251. package/src/vite/discovery/bundle-postprocess.ts +63 -91
  252. package/src/vite/discovery/discover-routers.ts +106 -53
  253. package/src/vite/discovery/discovery-errors.ts +194 -0
  254. package/src/vite/discovery/gate-state.ts +171 -0
  255. package/src/vite/discovery/prerender-collection.ts +222 -107
  256. package/src/vite/discovery/route-types-writer.ts +40 -84
  257. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  258. package/src/vite/discovery/state.ts +50 -13
  259. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  260. package/src/vite/index.ts +10 -3
  261. package/src/vite/plugin-types.ts +111 -72
  262. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  263. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  264. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  265. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  266. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  267. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  268. package/src/vite/plugins/expose-action-id.ts +55 -33
  269. package/src/vite/plugins/expose-id-utils.ts +24 -8
  270. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  271. package/src/vite/plugins/expose-ids/handler-transform.ts +12 -35
  272. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  273. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  274. package/src/vite/plugins/expose-internal-ids.ts +544 -317
  275. package/src/vite/plugins/performance-tracks.ts +92 -0
  276. package/src/vite/plugins/refresh-cmd.ts +127 -0
  277. package/src/vite/plugins/use-cache-transform.ts +65 -50
  278. package/src/vite/plugins/version-injector.ts +39 -23
  279. package/src/vite/plugins/version-plugin.ts +72 -3
  280. package/src/vite/plugins/virtual-entries.ts +2 -2
  281. package/src/vite/rango.ts +265 -226
  282. package/src/vite/router-discovery.ts +924 -137
  283. package/src/vite/utils/ast-handler-extract.ts +15 -15
  284. package/src/vite/utils/banner.ts +4 -4
  285. package/src/vite/utils/bundle-analysis.ts +4 -2
  286. package/src/vite/utils/client-chunks.ts +190 -0
  287. package/src/vite/utils/forward-user-plugins.ts +193 -0
  288. package/src/vite/utils/manifest-utils.ts +21 -5
  289. package/src/vite/utils/package-resolution.ts +41 -1
  290. package/src/vite/utils/prerender-utils.ts +98 -5
  291. package/src/vite/utils/shared-utils.ts +109 -27
  292. package/src/browser/action-response-classifier.ts +0 -99
  293. package/src/route-definition/route-function.ts +0 -119
@@ -1,226 +1,549 @@
1
1
  ---
2
2
  name: testing
3
- description: Unit test route trees with buildRouteTree()
4
- argument-hint:
3
+ description: Test @rangojs/router apps — unit (loaders/middleware/reverse/components), integration (dispatch/Flight), and e2e (dev+prod parity, progressive enhancement)
4
+ argument-hint: [layer]
5
5
  ---
6
6
 
7
- # Route Tree Unit Testing
8
-
9
- Unit test route definitions by inspecting the route tree, segment IDs, middleware, intercepts, loaders, and pattern matching without running a dev server.
10
-
11
- ## Setup
12
-
13
- The `buildRouteTree` helper lives in `src/__tests__/helpers/route-tree.ts` (not shipped with npm). Import it in your test files:
14
-
15
- ```typescript
16
- import { buildRouteTree } from "./helpers/route-tree.js";
17
- ```
18
-
19
- ## buildRouteTree(urlPatterns)
20
-
21
- Takes a `urls()` result and returns a `RouteTree` with inspection methods:
22
-
23
- ```typescript
24
- import { urls } from "@rangojs/router";
25
- import { buildRouteTree } from "./helpers/route-tree.js";
26
-
27
- const tree = buildRouteTree(
28
- urls(({ path, layout, middleware, loader, intercept, when }) => [
29
- layout(RootLayout, () => [
30
- middleware(authMiddleware),
31
- path("/", HomePage, { name: "home" }),
32
- path("/blog/:slug", BlogPost, { name: "blog.post" }, () => [
33
- loader(PostLoader),
34
- ]),
35
- ]),
36
- ]),
37
- );
38
- ```
39
-
40
- ## RouteTree API
41
-
42
- ### Route Patterns
7
+ # Testing @rangojs/router apps
8
+
9
+ Rango ships six consumer-facing testing entries, one per test runtime/dependency:
10
+ `@rangojs/router/testing` (unit + integration, under a Vite-driven Vitest
11
+ project), `@rangojs/router/testing/vitest` (the `rangoTestAliases` setup preset),
12
+ `@rangojs/router/testing/dom` (`renderRoute`, needs RTL + a DOM env),
13
+ `@rangojs/router/testing/e2e` (the Playwright harness),
14
+ `@rangojs/router/testing/flight` (real Flight, react-server condition only), and
15
+ `@rangojs/router/testing/flight-matchers` (the Flight matchers).
16
+ The hard problem in an RSC app is that the layer you reach for is dictated by
17
+ **what the behavior touches** — a pure predicate is a one-line vitest test; a
18
+ real async Server Component cannot be a plain node test at all. Pick the layer
19
+ **first**, then the primitive. Reaching one layer too high (e2e for a reverse
20
+ function) is slow; one too low (a node test for Flight) fails to compile or
21
+ silently asserts nothing.
22
+
23
+ For the prose guide with full setup and migration, see
24
+ [`docs/testing.md`](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/testing.md)
25
+ (the `docs/` directory is not shipped in the published package, so this is an
26
+ absolute link).
27
+
28
+ ## When to use
29
+
30
+ Use this skill when adding or changing tests for a Rango app: a loader,
31
+ middleware, a route map, a client component, a response route, cache/SWR
32
+ behavior, prerender, or a navigation/PE flow.
33
+
34
+ Two non-negotiable mandates (from the repo's `CLAUDE.md`, and they apply to
35
+ consumer apps too):
36
+
37
+ - **Every e2e covers BOTH dev and production.** A dev-only e2e is not
38
+ acceptable. Use `parityDescribe` — it generates the dev and production
39
+ describes from one body, so you cannot forget the prod half.
40
+ - **Progressive-enhancement parity** is a first-class assertion. A form-driven
41
+ flow must produce the same observable result with JS on and JS off. Use
42
+ `expectParity`.
43
+
44
+ ## The read-first shape
45
+
46
+ Four import roots, each matched to the dependency/runtime that can load it —
47
+ this split is forced by hard walls, not preference:
48
+
49
+ - `@rangojs/router/testing` — unit + integration primitives. Run these under a
50
+ **Vite-driven Vitest** project with the rango Vite plugin active (the router
51
+ internals import the `@rangojs/router:version` virtual module; without the
52
+ plugin, alias `@rangojs/router:version`). It references neither React,
53
+ `@testing-library/react`, Playwright, nor the RSC runtime — a unit suite
54
+ testing only loaders/middleware/`dispatch` pulls in none of them.
55
+ - `@rangojs/router/testing/dom` — `renderRoute` (the RTL component stub). Kept
56
+ separate so the unit barrel above stays free of React/RTL; it lazy-loads
57
+ `@testing-library/react` at call time and needs a DOM env (happy-dom/jsdom).
58
+ - `@rangojs/router/testing/e2e` — the Playwright harness. Kept separate so it
59
+ loads in a plain (non-Vite) Playwright runner; the unit barrel pulls in
60
+ router-manifest code that a Playwright loader cannot resolve. The helpers take
61
+ your `test`/`expect` as parameters, so this entry never imports
62
+ `@playwright/test` at runtime.
63
+ - `@rangojs/router/testing/flight` — real Flight rendering. Its serializer loads
64
+ only under the `react-server` node condition; pulling it elsewhere throws.
65
+
66
+ The single rule that drives everything:
67
+
68
+ > **If the behavior needs a real Flight render, it cannot be a plain vitest node
69
+ > test.** It is either `renderToFlightString` (under the react-server vitest
70
+ > project) or an e2e test. There is no middle ground in node.
71
+
72
+ ## Decision tree: behavior -> layer -> primitive
73
+
74
+ | The behavior is… | Layer | Primitive | Import root |
75
+ | --------------------------------------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------- | -------------------------------- |
76
+ | a pure function / `reverse` / a predicate (`revalidate`, `isAction`) | unit (node) | call it directly; `runMiddleware`/`runLoader` for ctx | `@rangojs/router/testing` |
77
+ | one loader's data logic | unit (node) | `runLoader` (pass the **raw fn**, not `createLoader`) | `@rangojs/router/testing` |
78
+ | one middleware's ordering / short-circuit / cookie+header merge | unit (node) | `runMiddleware` | `@rangojs/router/testing` |
79
+ | a CLIENT component reading router context (`useParams`/`useReverse`/`Outlet`/`useNavigation`/`useLoader`) | unit (DOM) | `renderRoute` (needs happy-dom/jsdom + `@testing-library/react`) | `@rangojs/router/testing/dom` |
80
+ | a redirect / status / headers / cookies / **response route** (json/text/html/xml/md), no Flight | integration | `dispatch` (router -> Response) | `@rangojs/router/testing` |
81
+ | a real async **Server Component** / Flight serialization shape | RSC unit | `renderToFlightString` + `toMatchFlight` | `@rangojs/router/testing/flight` |
82
+ | navigation, hydration, PE parity, view transitions, real SSR | e2e | `createRangoE2E` -> `parityDescribe`/`expectParity` | `@rangojs/router/testing/e2e` |
83
+ | cache hit/miss/stale, prerender (= a cache hit by design) | e2e + signal | `assertCacheStatus` / telemetry sink (gate on) | `@rangojs/router/testing` |
84
+ | generated route map drift vs runtime | unit (node) | `assertGeneratedRoutesMatch` | `@rangojs/router/testing` |
85
+
86
+ Cross-references: `/loader`, `/middleware`, `/server-actions`, `/caching`,
87
+ `/prerender`, `/typesafety`.
88
+
89
+ ## Unit recipes (vitest, node)
90
+
91
+ ### runMiddleware — ordering, short-circuit, cookie/header merge
92
+
93
+ Runs the chain through the router's **real** `executeMiddleware`, so
94
+ `next()`, return-Response short-circuit, throw-Response short-circuit,
95
+ double-next guards, and header/cookie merging behave exactly as in production.
96
+ `nextCalled` is `0` on short-circuit, `1` on pass-through. The returned `ctx` is
97
+ the underlying `RequestContext` — read `ctx.cookies()`, `ctx.get(...)`,
98
+ `ctx.res.headers`.
99
+
100
+ ```ts
101
+ import { describe, it, expect } from "vitest";
102
+ import { runMiddleware } from "@rangojs/router/testing";
103
+ import type { MiddlewareFn } from "@rangojs/router";
104
+
105
+ const requireUser: MiddlewareFn = async (ctx, next) => {
106
+ if (!ctx.get("user")) return new Response(null, { status: 401 });
107
+ return next();
108
+ };
109
+
110
+ it("passes through when the user is present", async () => {
111
+ const { response, nextCalled } = await runMiddleware(
112
+ requireUser,
113
+ "/dashboard",
114
+ {
115
+ vars: { user: { id: 1 } }, // object form; or [[key, value]] tuples (key may be a createVar())
116
+ },
117
+ );
118
+ expect(nextCalled).toBe(1);
119
+ expect(response.status).toBe(200);
120
+ });
43
121
 
44
- ```typescript
45
- tree.routes(); // { home: "/", "blog.post": "/blog/:slug" }
46
- tree.routeNames(); // ["home", "blog.post"]
122
+ it("short-circuits (return OR throw Response) when unauthenticated", async () => {
123
+ const { response, nextCalled } = await runMiddleware(
124
+ requireUser,
125
+ "/dashboard",
126
+ );
127
+ expect(nextCalled).toBe(0);
128
+ expect(response.status).toBe(401);
129
+ });
47
130
  ```
48
131
 
49
- ### URL Matching
50
-
51
- ```typescript
52
- const m = tree.match("/blog/hello");
53
- m.routeKey; // "blog.post"
54
- m.params; // { slug: "hello" }
55
-
56
- tree.match("/nonexistent"); // null
132
+ Seed prior-middleware state with `vars` (string key or `createVar()` handle).
133
+ Model the downstream route with `next`. Enable `ctx.reverse(...)` by passing
134
+ `routeMap` (and `routeName` for scoped `.name` resolution). Pass an array to run
135
+ several in order. Cookies set via `cookies().set(...)` surface both on
136
+ `ctx.cookies()` and on the merged response `Set-Cookie`.
137
+
138
+ ### runLoader — one loader's data logic
139
+
140
+ Pass the **RAW loader function** `(ctx) => ...`, NOT a `createLoader(...)`
141
+ handle. `createLoader` relies on the Vite `$$id` injection for RSC
142
+ registration, which does not exist in a bare vitest process — calling it gives
143
+ you a handle with no `fn` to run. `runLoader` invokes your function directly
144
+ against a real `RequestContext`, so cookies, headers, `ctx.get`, and
145
+ `ctx.reverse` resolve.
146
+
147
+ ```ts
148
+ import { runLoader } from "@rangojs/router/testing";
149
+ import { createVar } from "@rangojs/router";
150
+
151
+ // CORRECT: test the function body directly.
152
+ async function productLoaderBody(ctx) {
153
+ return { id: ctx.params.id, region: ctx.env.REGION, user: ctx.get(User) };
154
+ }
155
+
156
+ it("reads params, env, and seeded vars", async () => {
157
+ const User = createVar<{ name: string }>();
158
+ const data = await runLoader(productLoaderBody, {
159
+ params: { id: "42" },
160
+ env: { REGION: "eu" },
161
+ vars: [[User, { name: "Ada" }]],
162
+ });
163
+ expect(data).toEqual({ id: "42", region: "eu", user: { name: "Ada" } });
164
+ });
57
165
  ```
58
166
 
59
- ### Segment IDs
60
-
61
- ```typescript
62
- tree.segmentId("home"); // "M0L0L0R0"
63
- tree.segmentIds(); // { home: "M0L0L0R0", "blog.post": "M0L0L0R1" }
64
- tree.segmentPath("blog.post");
65
- // [
66
- // { id: "M0L0", type: "layout" }, // synthetic root
67
- // { id: "M0L0L0", type: "layout" }, // RootLayout
68
- // { id: "M0L0L0R1", type: "route", pattern: "/blog/:slug" },
69
- // ]
167
+ Options: `params` (also surfaced as `routeParams`), `search`, `env`, `vars`,
168
+ `method`/`body`/`formData`, `routeMap`/`routeName` (for `ctx.reverse`), and
169
+ `use` (a resolver for `ctx.use(OtherLoader)` composition — without it, `ctx.use`
170
+ runs the dependency's own `fn` if it carries one).
171
+
172
+ Two unit-only limitations to document in your test, not work around:
173
+
174
+ - `ctx.reverse(...)` **throws** unless you pass `routeMap`.
175
+ - `ctx.rendered()` **throws** (the DSL render barrier only exists in a full
176
+ match) and `ctx.isAction(...)` (the action-render context) is not available —
177
+ test those with `renderToFlightString` or e2e.
178
+
179
+ If your real loader source is `export const L = createLoader(async (ctx) => {...})`,
180
+ extract the inner async function so it is importable on its own, and register
181
+ the `createLoader` wrapper in `urls()`. Then `runLoader` tests the body and the
182
+ DSL/e2e tests cover registration.
183
+
184
+ ### renderRoute — a client component reading router context
185
+
186
+ RTL-style stub. Peer of React Router's `createRoutesStub` / Expo's
187
+ `renderRouter`. It mounts the router's real `NavigationProvider` plus a
188
+ synthetic segment tree so `useParams`, `useReverse`, `useNavigation`, `Outlet`,
189
+ `usePathname`, `useSearchParams`, and `useLoader`/`useFetchLoader` (reading
190
+ **seeded** data) resolve — no server, no Vite, no Flight round-trip. It is
191
+ `async` (lazy-loads `@testing-library/react`).
192
+
193
+ ```tsx
194
+ // @vitest-environment happy-dom
195
+ import { describe, it, expect, afterEach } from "vitest";
196
+ import { cleanup } from "@testing-library/react";
197
+ import { renderRoute } from "@rangojs/router/testing/dom";
198
+ import { Outlet, useParams, useReverse } from "@rangojs/router/client";
199
+
200
+ afterEach(cleanup);
201
+
202
+ function Layout() {
203
+ return (
204
+ <div>
205
+ <span data-testid="shell">shell</span>
206
+ <Outlet />
207
+ </div>
208
+ );
209
+ }
210
+ function Product() {
211
+ const { productId } = useParams<{ productId: string }>();
212
+ const reverse = useReverse({ product: "/products/:productId" });
213
+ return (
214
+ <a data-testid="link" href={reverse("product", { productId: "2" })}>
215
+ {productId}
216
+ </a>
217
+ );
218
+ }
219
+
220
+ it("resolves params + reverse + Outlet through the layout chain", async () => {
221
+ const { getByTestId, router } = await renderRoute(
222
+ [
223
+ { path: "/products", Component: Layout }, // layout (root)
224
+ { path: "/products/:productId", Component: Product }, // leaf (last)
225
+ ],
226
+ { initialUrl: "/products/1" },
227
+ );
228
+ expect(getByTestId("shell").textContent).toBe("shell");
229
+ expect(getByTestId("link").getAttribute("href")).toBe("/products/2");
230
+
231
+ await router.navigate("/products/2"); // client-only nav, re-resolves the same routes
232
+ expect(router.pathname()).toBe("/products/2");
233
+ });
70
234
  ```
71
235
 
72
- ### Entry Access
73
-
74
- ```typescript
75
- tree.entry("blog.post"); // EntryData
76
- tree.entry("blog.post")!.parent!.type; // "layout"
77
- tree.entryByPattern("/blog/:slug"); // EntryData (lookup by URL pattern)
236
+ `RenderRouteSpec = { path, Component, layout?, loaderIds?, name? }`. The array
237
+ is the layout chain root-to-leaf; the **last** entry is the leaf route. Seed
238
+ loader reads with `options.loaderData` keyed by the loader's `$$id`; attach a
239
+ loader to a specific layout via that spec's `loaderIds`:
240
+
241
+ ```tsx
242
+ const CartLoader = {
243
+ __brand: "loader",
244
+ $$id: "loaders/cart#CartLoader",
245
+ } as any;
246
+ await renderRoute(
247
+ [
248
+ { path: "/shop", Component: CartLayout, loaderIds: [CartLoader.$$id] },
249
+ { path: "/shop/item", Component: Page },
250
+ ],
251
+ { initialUrl: "/shop/item", loaderData: { [CartLoader.$$id]: { count: 3 } } },
252
+ );
78
253
  ```
79
254
 
80
- ### Middleware
81
-
82
- ```typescript
83
- tree.hasMiddleware("home"); // true (inherited from layout)
84
- tree.middleware("home"); // [authMiddleware] (direct only)
85
- tree.middlewareChain("home");
86
- // [{ segmentId: "M0L0L0", count: 1 }] // all middleware root-to-route
255
+ FIDELITY CAVEAT — this is the **client tree only**. It does NOT catch
256
+ server/client boundary reference-identity remount bugs, real Flight
257
+ serialization errors, loader execution, middleware, or handler ordering. Those
258
+ are `renderToFlightString` / e2e territory. Loader data is seeded, never run.
259
+ Needs a DOM env (`// @vitest-environment happy-dom`, or jsdom) and the consumer
260
+ must install `@testing-library/react` (optional peer).
261
+
262
+ CATCH — streaming `use(promise)` Suspense content (e.g. an async breadcrumb
263
+ `content: Promise<ReactNode>`): a plain `Promise.resolve(node)` does NOT flush
264
+ its Suspense retry in RTL/happy-dom (renderRoute renders internally, not inside
265
+ an awaited `act`), so the DOM stays on the fallback. Assert the **pending**
266
+ fallback with a never-resolving `new Promise(() => {})`; for the **arrived**
267
+ state pass an already-settled promise so `use()` reads it synchronously:
268
+ `const p = Promise.resolve(node) as any; p.status = "fulfilled"; p.value = node;`.
269
+ The real pending→resolved transition is an e2e concern.
270
+
271
+ ### Type-level test: a reverse misuse should fail to compile
272
+
273
+ `reverse`/`href` are compile-time checked (`/typesafety`). Pin that contract
274
+ with `@ts-expect-error` — a _runtime_ test cannot.
275
+
276
+ ```ts
277
+ import { useReverse } from "@rangojs/router/client";
278
+ const reverse = useReverse({ product: "/products/:productId" });
279
+ reverse("product", { productId: "2" }); // ok
280
+ // @ts-expect-error missing required param
281
+ reverse("product", {});
282
+ // @ts-expect-error unknown route name
283
+ reverse("nope", {});
87
284
  ```
88
285
 
89
- ### Loaders
90
-
91
- ```typescript
92
- tree.hasLoaders("blog.post"); // true
93
- tree.loaders("blog.post"); // [LoaderEntry { loader, revalidate, cache? }]
286
+ ## Integration recipes
287
+
288
+ ### dispatch — request -> Response, without Flight
289
+
290
+ In-process matching + middleware, no RSC render. Covers `308` redirects
291
+ (trailing slash etc.) with `Location`, `404`, response routes
292
+ (json/text/html/xml/md with content negotiation), and **global + route-level
293
+ middleware** short-circuits with full `next()`/throw/header+cookie fidelity. It
294
+ reuses the router's own `previewMatch`, so middleware collection is the router's,
295
+ not a re-implementation. Hitting an RSC (component) route throws a clear
296
+ directive error.
297
+
298
+ SETUP CAVEAT (use the preset): `@rangojs/router` resolves to server-only STUBS
299
+ outside the `react-server` condition (urls/createRouter/cookies/getRequestContext
300
+ throw), and importing your router also pulls `@vitejs/plugin-rsc/rsc` (whose body
301
+ imports Vite virtuals). Vitest does not apply the `react-server` condition to
302
+ bare-package resolution. The preset `@rangojs/router/testing/vitest` handles all
303
+ of it — alias `@rangojs/router` to real impls + stub the virtuals — so no
304
+ per-file `vi.mock` is needed:
305
+
306
+ ```ts
307
+ // vitest.config.ts
308
+ import { defineConfig } from "vitest/config";
309
+ import { rangoTestAliases } from "@rangojs/router/testing/vitest";
310
+ export default defineConfig({
311
+ test: {
312
+ globals: true,
313
+ include: ["test/**/*.test.{ts,tsx}"],
314
+ environment: "node",
315
+ },
316
+ resolve: { alias: rangoTestAliases({ cloudflare: true }) },
317
+ });
94
318
  ```
95
319
 
96
- ### Intercepts
320
+ LIMITATION: the FULL router usually can't be imported in a bare test —
321
+ `Prerender()`/`createLoader()` need the plugin-injected `$$id` (real `Prerender()`
322
+ throws "missing $$id"). Build a router from a `Prerender`-free include (your API
323
+ routes); `dispatch` accepts the public router type with no cast:
97
324
 
98
- ```typescript
99
- tree.intercepts("home");
100
- // [{ slotName: "@modal", routeName: "card", hasWhen: true, whenCount: 1, hasLoader: false, hasMiddleware: false }]
101
- tree.interceptEntries("home"); // raw InterceptEntry[]
102
- ```
103
-
104
- ### Parallel Slots
325
+ ```ts
326
+ import { describe, it, expect } from "vitest";
327
+ import { dispatch } from "@rangojs/router/testing";
328
+ import { createRouter } from "@rangojs/router";
329
+ import { apiPatterns } from "../src/api/urls"; // path.json(...) routes only
105
330
 
106
- ```typescript
107
- tree.parallelSlots("home"); // EntryData[] of type="parallel"
108
- tree.parallelSlotNames("home"); // ["@sidebar", "@main"]
109
- ```
331
+ const router = createRouter().routes(apiPatterns);
110
332
 
111
- ### Boundaries
333
+ it("serializes a JSON response route (auto-wrapped under data)", async () => {
334
+ const res = await dispatch(router, "/health");
335
+ expect(res.status).toBe(200);
336
+ expect(await res.json()).toEqual({ data: { status: "ok" } });
337
+ });
112
338
 
113
- ```typescript
114
- tree.hasErrorBoundary("home"); // boolean
115
- tree.hasNotFoundBoundary("home"); // boolean
339
+ it("maps a thrown RouterError to its status + typed JSON envelope", async () => {
340
+ const res = await dispatch(router, "/products/999");
341
+ expect(res.status).toBe(404);
342
+ expect((await res.json()).error.code).toBe("NOT_FOUND");
343
+ });
116
344
  ```
117
345
 
118
- ### Cache & Loading
346
+ ### renderToFlightString — real async Server Component
347
+
348
+ A REAL Flight render of an async Server Component, in plain node — but ONLY
349
+ under the `react-server` condition (see the next section for the vitest
350
+ project). The render runs inside a request context, so async components can call
351
+ `getRequestContext()`, read params, cookies, etc.
352
+
353
+ ```tsx
354
+ // flight.rsc-test.tsx (note the *.rsc-test suffix)
355
+ import { describe, it, expect } from "vitest";
356
+ import { renderToFlightString } from "@rangojs/router/testing/flight";
357
+ // Matchers are a SEPARATE subpath (they import vitest); renderToFlightString does not.
358
+ import { flightMatchers } from "@rangojs/router/testing/flight-matchers";
359
+
360
+ expect.extend(flightMatchers);
361
+
362
+ // Keep components PURE leaves: take data as props. Do NOT import a server API
363
+ // (getRequestContext, cookies) from the `@rangojs/router` barrel — under the
364
+ // react-server condition the bare specifier resolves to the throwing stub, so
365
+ // it cannot be flight-tested in a bare consumer project.
366
+ async function Greeting({ name }: { name: string }) {
367
+ await Promise.resolve();
368
+ return <div>Hello {name}!</div>;
369
+ }
370
+ async function ItemView({ id }: { id: string }) {
371
+ return <span>id={id}</span>;
372
+ }
373
+
374
+ it("renders text and props", async () => {
375
+ expect(await renderToFlightString(<Greeting name="Ada" />)).toMatchFlight(
376
+ "Ada",
377
+ );
378
+ expect(await renderToFlightString(<ItemView id="42" />)).toMatchFlight("42");
379
+ });
119
380
 
120
- ```typescript
121
- tree.hasCache("home"); // boolean
122
- tree.hasLoading("home"); // boolean
381
+ it("matches a normalized snapshot", async () => {
382
+ expect(
383
+ await renderToFlightString(<Greeting name="World" />),
384
+ ).toMatchFlightSnapshot();
385
+ });
123
386
  ```
124
387
 
125
- ### Debug
126
-
127
- ```typescript
128
- console.log(tree.debug());
129
- // Route Tree:
130
- // home: / [M0L0L0R0] (M0L0 > M0L0L0 > M0L0L0R0) {mw:1}
131
- // blog.post: /blog/:slug [M0L0L0R1] (M0L0 > M0L0L0 > M0L0L0R1) {mw:1, ld:1}
388
+ `toMatchFlight(substring)` asserts the normalized Flight string CONTAINS the
389
+ substring (containment, not equality — the row framing is an internal serializer
390
+ detail). `toMatchFlightSnapshot()` snapshots the normalized payload. SCOPE:
391
+ server-only / leaf trees — a client component emits an unresolved `I[...]` import
392
+ row against the empty client manifest (fine for snapshotting shape, not
393
+ hydratable). A true interactive, clickable DOM `renderServer` is a DEFERRED
394
+ follow-up: the react-server-vs-default condition wall requires a two-environment
395
+ setup. For interactive server-component behavior today, use e2e.
396
+
397
+ ## E2E recipes (Playwright)
398
+
399
+ Wire the harness once, passing your own Playwright `test`/`expect` (so
400
+ `@rangojs/router/testing/e2e` never imports `@playwright/test` at runtime — it is
401
+ an optional peer you install). Import the harness from the **`/e2e` entry** — the
402
+ unit barrel is not loadable in a plain Playwright runner:
403
+
404
+ ```ts
405
+ // e2e/helper.ts
406
+ import { test, expect } from "@playwright/test";
407
+ import { createRangoE2E } from "@rangojs/router/testing/e2e";
408
+
409
+ export const e2e = createRangoE2E({
410
+ test,
411
+ expect,
412
+ defaultRoot: new URL("..", import.meta.url).pathname, // your app root
413
+ });
414
+ export const { useFixture, parityDescribe, expectParity, rangoMatchers } = e2e;
132
415
  ```
133
416
 
134
- ## Segment ID Format
135
-
136
- | Prefix | Meaning |
137
- | ------ | ----------------------------- |
138
- | `M0` | Mount index (router instance) |
139
- | `L` | Layout |
140
- | `R` | Route |
141
- | `P` | Parallel slot |
142
- | `D` | Loader (data) |
143
- | `C` | Cache boundary |
144
-
145
- Example: `M0L0L0R1` = mount 0, synthetic root layout, user layout, second route.
146
-
147
- ## Examples
148
-
149
- ### include() with prefix
150
-
151
- ```typescript
152
- const blogPatterns = urls(({ path }) => [
153
- path("/", BlogIndex, { name: "index" }),
154
- path("/:slug", BlogPost, { name: "post" }),
155
- ]);
156
-
157
- const tree = buildRouteTree(
158
- urls(({ path, include }) => [
159
- path("/", HomePage, { name: "home" }),
160
- include("/blog", blogPatterns, { name: "blog" }),
161
- ]),
162
- );
163
-
164
- expect(tree.routes()).toEqual({
165
- home: "/",
166
- "blog.index": "/blog",
167
- "blog.post": "/blog/:slug",
417
+ ### parityDescribe REPLACES hand-titling `(production)`
418
+
419
+ This is THE mechanism that satisfies the dev+prod mandate structurally. One
420
+ declaration registers a dev describe (`name`) AND a production describe
421
+ (`` `${name} (production)` ``) from one body — the `(production)` suffix is
422
+ generated, so the prod suite can never drift into the dev bucket. Use `f.url(...)`
423
+ for navigation.
424
+
425
+ ```ts
426
+ import { test, expect } from "@playwright/test";
427
+ import { parityDescribe, rangoMatchers } from "./helper";
428
+ // rangoMatchers ships the type augmentation, so `expect(page).toHaveRangoPathname`
429
+ // is typed after extend.
430
+ expect.extend(rangoMatchers);
431
+
432
+ parityDescribe("product navigation", (f) => {
433
+ test("navigates to a product and updates the pathname", async ({ page }) => {
434
+ await page.goto(f.url("/"));
435
+ await page.getByTestId("product-link").click();
436
+ await expect(page).toHaveRangoPathname("/products/1");
437
+ });
168
438
  });
169
439
  ```
170
440
 
171
- ### Middleware chain
172
-
173
- ```typescript
174
- const authMw = async (ctx, next) => next();
175
- const logMw = async (ctx, next) => next();
176
-
177
- const tree = buildRouteTree(
178
- urls(({ path, layout, middleware }) => [
179
- layout(RootLayout, () => [
180
- middleware(logMw),
181
- layout(AuthLayout, () => [
182
- middleware(authMw),
183
- path("/dashboard", Dashboard, { name: "dashboard" }),
184
- ]),
185
- ]),
186
- ]),
187
- );
188
-
189
- expect(tree.middlewareChain("dashboard")).toEqual([
190
- { segmentId: "M0L0L0", count: 1 }, // logMw on RootLayout
191
- { segmentId: "M0L0L0L0", count: 1 }, // authMw on AuthLayout
192
- ]);
441
+ The body runs verbatim against a dev server (`pnpm dev`) and a built+previewed
442
+ server (`pnpm build` + `pnpm preview`). `useFixture` handles spawn, dep-optimizer
443
+ warmup, cross-platform process-group kill, and teardown.
444
+
445
+ ### expectParity — JS path vs no-JS progressive enhancement
446
+
447
+ Runs one intent over the JS path and a fresh no-JS context, asserting the
448
+ observed testids, pathname, and cookies match. CONTRACT: PE parity only holds if
449
+ the submit target is a real `<form>` (no-JS does a native POST). Cookie
450
+ observation is `document.cookie` (non-HttpOnly only) in v1.
451
+
452
+ ```ts
453
+ parityDescribe("add to cart parity", (f) => {
454
+ test("JS and no-JS produce the same result", async ({ page }) => {
455
+ await page.goto(f.url("/products/1"));
456
+ await expectParity(
457
+ page,
458
+ { submit: { testId: "add-to-cart-form", data: { qty: "2" } } },
459
+ { observe: ["cart-count", "flash"] },
460
+ );
461
+ });
462
+ });
193
463
  ```
194
464
 
195
- ### Intercepts with when()
196
-
197
- ```typescript
198
- const tree = buildRouteTree(
199
- urls(({ path, layout, intercept, when }) => [
200
- layout(ShopLayout, () => [
201
- path("/products", ProductList, { name: "products" }),
202
- path("/products/:id", ProductDetail, { name: "product.detail" }),
203
- intercept("@modal", "product.detail", ProductModal, () => [
204
- when((ctx) => ctx.from.pathname.startsWith("/products")),
205
- ]),
206
- ]),
207
- ]),
208
- );
209
-
210
- const intercepts = tree.intercepts("products");
211
- // Note: intercepts are on the parent where intercept() is called
465
+ `intent` is `{ navigate: string }` or `{ submit: { testId, data? } }`. Other
466
+ helpers from `createRangoE2E`: `waitForHydration`, `expectNoReload`,
467
+ `expectNoPageError`, `testId`, `waitForNavigation`, `goBack`/`goForward`,
468
+ `testNoJs` (a `test` with JS disabled). `rangoMatchers` ships
469
+ `toHaveRangoPathname` only — `toHaveSegments`/`toHaveParams` are a documented
470
+ future addition (they need a client-emitted signal that does not exist yet; do
471
+ not assume them).
472
+
473
+ ## Cache / SWR / prerender recipes
474
+
475
+ The `X-Rango-Cache` header is emitted **only** when the gate is on:
476
+ `createRouter({ debugCacheSignal: true })` or `process.env.RANGO_TEST_SIGNALS === "1"`.
477
+ Off by default — zero production surface. v1 status is COARSE (route-level, keyed
478
+ by the route key — the route NAME, e.g. `product.detail`, NOT the URL pattern),
479
+ not per-individual-segment. `assertCacheStatus` reads that header.
480
+
481
+ ```ts
482
+ // In a Playwright e2e, import cache-status helpers from the e2e entry (the
483
+ // `@rangojs/router/testing` barrel is Vitest-only — it pulls a build virtual).
484
+ import { assertCacheStatus } from "@rangojs/router/testing/e2e";
485
+
486
+ // e2e (the gate must be enabled on the app under test). The segment key is the
487
+ // route NAME the header carries, not the URL pattern ("/products/:id").
488
+ const res = await page.request.get(f.url("/products/1"));
489
+ assertCacheStatus(res, "product.detail", "miss");
490
+ const res2 = await page.request.get(f.url("/products/1"));
491
+ assertCacheStatus(res2, "product.detail", "hit");
212
492
  ```
213
493
 
214
- ### Constrained parameters
494
+ Statuses: `"hit" | "miss" | "stale" | "prerendered" | "passthrough"`.
215
495
 
216
- ```typescript
217
- const tree = buildRouteTree(
218
- urls(({ path }) => [
219
- path("/:locale(en|fr)?/about", AboutPage, { name: "about" }),
220
- ]),
221
- );
496
+ Zero-prod-surface alternative — the telemetry sink (no header at all):
222
497
 
223
- expect(tree.match("/about")).not.toBeNull();
224
- expect(tree.match("/fr/about")!.params).toEqual({ locale: "fr" });
225
- expect(tree.match("/de/about")).toBeNull();
498
+ ```ts
499
+ import { createCacheSink, filterCacheDecisions } from "@rangojs/router/testing";
500
+ const { sink, events } = createCacheSink();
501
+ const router = createRouter({ telemetry: sink /* ... */ }).routes(urlpatterns);
502
+ // ...drive a request...
503
+ const decisions = filterCacheDecisions(events);
504
+ expect(decisions[0].segments?.[0].cacheStatus).toBe("hit");
226
505
  ```
506
+
507
+ PRERENDER: a pre-rendered route is **indistinguishable from a cache hit by
508
+ design** — the worker handles every request and looks up a stored Flight payload
509
+ (see `/prerender`). The browser cannot tell. So you cannot assert "prerendered"
510
+ from the rendered DOM; assert it via the signal (`assertCacheStatus(res, seg,
511
+ "prerendered")`), and run prerender assertions in **production** mode (build-time
512
+ artifacts only exist after `pnpm build`).
513
+
514
+ ## Anti-patterns and gotchas
515
+
516
+ - **No dev-only e2e.** A `useFixture({ mode: "build" })` describe whose title
517
+ omits `(production)` silently lands in the dev bucket — prod coverage lost,
518
+ no error. Always use `parityDescribe`; never hand-title. `(prod)`,
519
+ `-build`, `-prod` do NOT count — the bucketing matches the literal
520
+ `(production)`.
521
+ - **Don't hand-mock the router provider** to test a client component — use
522
+ `renderRoute`, which mounts the real `NavigationProvider`.
523
+ - **Don't call `createLoader(...)` in a unit test** and try to invoke it.
524
+ Extract the body and pass it to `runLoader`.
525
+ - **`dispatch` needs the plugin-rsc mock** (or a Vite-RSC env). A bare import of
526
+ your router throws on Vite virtual modules otherwise.
527
+ - **`renderToFlightString` is not a node test.** It only runs under the
528
+ react-server vitest project; name files `*.rsc-test.{ts,tsx}` and run
529
+ `pnpm test:unit:rsc`. The main vitest project must NOT set the react-server
530
+ condition (it would flip React to the no-hooks server build and break every
531
+ `renderRoute`/client test).
532
+ - **Running an e2e subset:** add `--no-deps` — `--grep` does NOT filter
533
+ dependency projects, so grepping one production test otherwise pulls in the
534
+ whole dev suite. And `--grep` is a regex: a pasted title containing
535
+ `(production)` / `:locale?` / `[...]` mis-matches; grep a metacharacter-free
536
+ fragment.
537
+
538
+ ## Pre-push checklist (mirror CLAUDE.md)
539
+
540
+ Before pushing, run all of these and fix any failure:
541
+
542
+ 1. `pnpm run typecheck` (or `pnpm exec tsc --noEmit`)
543
+ 2. `pnpm run test:unit` (node + DOM vitest)
544
+ 3. `pnpm run test:unit:rsc` (the react-server Flight project)
545
+ 4. `pnpm run lint`
546
+ 5. `pnpm run format`
547
+
548
+ And: **every e2e has a production counterpart.** `parityDescribe` makes this
549
+ automatic — if you wrote a plain `test.describe` for a behavior, convert it.