@rangojs/router 0.0.0-experimental.d7eeaa75 → 0.0.0-experimental.d98a8e9d

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 (278) hide show
  1. package/README.md +120 -25
  2. package/dist/bin/rango.js +147 -57
  3. package/dist/testing/vitest.js +82 -0
  4. package/dist/vite/index.js +2154 -861
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +57 -11
  7. package/skills/api-client/SKILL.md +211 -0
  8. package/skills/breadcrumbs/SKILL.md +3 -1
  9. package/skills/bundle-analysis/SKILL.md +159 -0
  10. package/skills/cache-guide/SKILL.md +220 -30
  11. package/skills/caching/SKILL.md +116 -8
  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 +247 -17
  21. package/skills/loader/SKILL.md +219 -9
  22. package/skills/middleware/SKILL.md +47 -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 +71 -6
  28. package/skills/prerender/SKILL.md +14 -33
  29. package/skills/rango/SKILL.md +243 -22
  30. package/skills/react-compiler/SKILL.md +168 -0
  31. package/skills/response-routes/SKILL.md +122 -47
  32. package/skills/route/SKILL.md +57 -4
  33. package/skills/router-setup/SKILL.md +3 -3
  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 +128 -0
  37. package/skills/testing/bindings.md +89 -0
  38. package/skills/testing/cache-prerender.md +98 -0
  39. package/skills/testing/client-components.md +121 -0
  40. package/skills/testing/e2e-parity.md +124 -0
  41. package/skills/testing/flight.md +89 -0
  42. package/skills/testing/handles.md +127 -0
  43. package/skills/testing/loader.md +108 -0
  44. package/skills/testing/middleware.md +97 -0
  45. package/skills/testing/render-handler.md +102 -0
  46. package/skills/testing/response-routes.md +94 -0
  47. package/skills/testing/reverse-and-types.md +83 -0
  48. package/skills/testing/server-actions.md +89 -0
  49. package/skills/testing/server-tree.md +128 -0
  50. package/skills/testing/setup.md +120 -0
  51. package/skills/typesafety/SKILL.md +319 -27
  52. package/skills/use-cache/SKILL.md +34 -5
  53. package/skills/view-transitions/SKILL.md +294 -0
  54. package/src/__augment-tests__/augment.ts +81 -0
  55. package/src/__augment-tests__/augmented.check.ts +116 -0
  56. package/src/browser/action-coordinator.ts +53 -36
  57. package/src/browser/app-shell.ts +52 -0
  58. package/src/browser/event-controller.ts +86 -70
  59. package/src/browser/history-state.ts +21 -0
  60. package/src/browser/index.ts +3 -3
  61. package/src/browser/navigation-bridge.ts +84 -11
  62. package/src/browser/navigation-client.ts +104 -68
  63. package/src/browser/navigation-store.ts +32 -9
  64. package/src/browser/navigation-transaction.ts +10 -28
  65. package/src/browser/partial-update.ts +64 -26
  66. package/src/browser/prefetch/cache.ts +183 -44
  67. package/src/browser/prefetch/fetch.ts +228 -37
  68. package/src/browser/prefetch/queue.ts +36 -5
  69. package/src/browser/rango-state.ts +53 -13
  70. package/src/browser/react/Link.tsx +30 -2
  71. package/src/browser/react/NavigationProvider.tsx +72 -31
  72. package/src/browser/react/filter-segment-order.ts +51 -7
  73. package/src/browser/react/index.ts +3 -0
  74. package/src/browser/react/location-state-shared.ts +175 -4
  75. package/src/browser/react/location-state.ts +39 -13
  76. package/src/browser/react/use-handle.ts +17 -9
  77. package/src/browser/react/use-navigation.ts +22 -2
  78. package/src/browser/react/use-params.ts +20 -8
  79. package/src/browser/react/use-reverse.ts +106 -0
  80. package/src/browser/react/use-router.ts +22 -2
  81. package/src/browser/react/use-segments.ts +11 -8
  82. package/src/browser/response-adapter.ts +32 -1
  83. package/src/browser/rsc-router.tsx +69 -22
  84. package/src/browser/scroll-restoration.ts +22 -14
  85. package/src/browser/segment-reconciler.ts +36 -14
  86. package/src/browser/segment-structure-assert.ts +2 -2
  87. package/src/browser/server-action-bridge.ts +23 -30
  88. package/src/browser/types.ts +21 -0
  89. package/src/build/collect-fallback-refs.ts +107 -0
  90. package/src/build/generate-manifest.ts +60 -35
  91. package/src/build/generate-route-types.ts +2 -0
  92. package/src/build/index.ts +8 -1
  93. package/src/build/prefix-tree-utils.ts +123 -0
  94. package/src/build/route-trie.ts +95 -25
  95. package/src/build/route-types/codegen.ts +4 -4
  96. package/src/build/route-types/include-resolution.ts +1 -1
  97. package/src/build/route-types/per-module-writer.ts +7 -4
  98. package/src/build/route-types/router-processing.ts +55 -14
  99. package/src/build/route-types/scan-filter.ts +1 -1
  100. package/src/build/route-types/source-scan.ts +118 -0
  101. package/src/build/runtime-discovery.ts +9 -20
  102. package/src/cache/cache-scope.ts +28 -42
  103. package/src/cache/cf/cf-cache-store.ts +54 -13
  104. package/src/client.rsc.tsx +3 -0
  105. package/src/client.tsx +96 -205
  106. package/src/context-var.ts +5 -5
  107. package/src/decode-loader-results.ts +36 -0
  108. package/src/errors.ts +30 -4
  109. package/src/handle.ts +32 -14
  110. package/src/host/index.ts +2 -2
  111. package/src/host/router.ts +129 -57
  112. package/src/host/types.ts +31 -2
  113. package/src/host/utils.ts +1 -1
  114. package/src/href-client.ts +140 -21
  115. package/src/index.rsc.ts +10 -6
  116. package/src/index.ts +54 -17
  117. package/src/loader-store.ts +500 -0
  118. package/src/loader.rsc.ts +25 -7
  119. package/src/loader.ts +16 -9
  120. package/src/missing-id-error.ts +68 -0
  121. package/src/outlet-context.ts +1 -1
  122. package/src/prerender.ts +27 -6
  123. package/src/response-utils.ts +37 -0
  124. package/src/reverse.ts +65 -36
  125. package/src/route-content-wrapper.tsx +6 -28
  126. package/src/route-definition/dsl-helpers.ts +384 -257
  127. package/src/route-definition/helper-factories.ts +29 -139
  128. package/src/route-definition/helpers-types.ts +100 -28
  129. package/src/route-definition/resolve-handler-use.ts +6 -0
  130. package/src/route-definition/use-item-types.ts +32 -0
  131. package/src/route-types.ts +26 -41
  132. package/src/router/basename.ts +14 -0
  133. package/src/router/content-negotiation.ts +15 -2
  134. package/src/router/error-handling.ts +1 -1
  135. package/src/router/find-match.ts +54 -6
  136. package/src/router/handler-context.ts +21 -38
  137. package/src/router/intercept-resolution.ts +4 -18
  138. package/src/router/lazy-includes.ts +41 -22
  139. package/src/router/loader-resolution.ts +82 -36
  140. package/src/router/manifest.ts +41 -19
  141. package/src/router/match-api.ts +4 -3
  142. package/src/router/match-handlers.ts +63 -20
  143. package/src/router/match-middleware/cache-lookup.ts +44 -91
  144. package/src/router/match-middleware/cache-store.ts +3 -2
  145. package/src/router/match-result.ts +53 -32
  146. package/src/router/metrics.ts +1 -1
  147. package/src/router/middleware-types.ts +15 -26
  148. package/src/router/middleware.ts +99 -84
  149. package/src/router/pattern-matching.ts +116 -19
  150. package/src/router/prerender-match.ts +1 -1
  151. package/src/router/preview-match.ts +3 -1
  152. package/src/router/request-classification.ts +4 -28
  153. package/src/router/revalidation.ts +58 -2
  154. package/src/router/router-interfaces.ts +45 -28
  155. package/src/router/router-options.ts +40 -1
  156. package/src/router/router-registry.ts +2 -5
  157. package/src/router/segment-resolution/fresh.ts +27 -6
  158. package/src/router/segment-resolution/revalidation.ts +147 -106
  159. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  160. package/src/router/substitute-pattern-params.ts +56 -0
  161. package/src/router/telemetry.ts +99 -0
  162. package/src/router/trie-matching.ts +40 -16
  163. package/src/router/types.ts +8 -0
  164. package/src/router/url-params.ts +49 -0
  165. package/src/router.ts +52 -30
  166. package/src/rsc/handler-context.ts +2 -2
  167. package/src/rsc/handler.ts +28 -69
  168. package/src/rsc/helpers.ts +91 -43
  169. package/src/rsc/index.ts +1 -1
  170. package/src/rsc/manifest-init.ts +28 -41
  171. package/src/rsc/origin-guard.ts +28 -10
  172. package/src/rsc/progressive-enhancement.ts +4 -0
  173. package/src/rsc/response-error.ts +79 -12
  174. package/src/rsc/response-route-handler.ts +57 -61
  175. package/src/rsc/rsc-rendering.ts +35 -51
  176. package/src/rsc/runtime-warnings.ts +9 -10
  177. package/src/rsc/server-action.ts +17 -37
  178. package/src/rsc/ssr-setup.ts +16 -0
  179. package/src/rsc/types.ts +8 -2
  180. package/src/runtime-env.ts +18 -0
  181. package/src/search-params.ts +4 -4
  182. package/src/segment-content-promise.ts +67 -0
  183. package/src/segment-loader-promise.ts +122 -0
  184. package/src/segment-system.tsx +132 -116
  185. package/src/serialize.ts +243 -0
  186. package/src/server/context.ts +175 -53
  187. package/src/server/cookie-store.ts +28 -4
  188. package/src/server/request-context.ts +67 -51
  189. package/src/ssr/index.tsx +5 -1
  190. package/src/static-handler.ts +25 -3
  191. package/src/testing/cache-status.ts +166 -0
  192. package/src/testing/collect-handle.ts +63 -0
  193. package/src/testing/dispatch.ts +581 -0
  194. package/src/testing/dom.entry.ts +22 -0
  195. package/src/testing/e2e/fixture.ts +188 -0
  196. package/src/testing/e2e/index.ts +149 -0
  197. package/src/testing/e2e/matchers.ts +51 -0
  198. package/src/testing/e2e/page-helpers.ts +272 -0
  199. package/src/testing/e2e/parity.ts +326 -0
  200. package/src/testing/e2e/server.ts +195 -0
  201. package/src/testing/flight-matchers.ts +110 -0
  202. package/src/testing/flight-normalize.ts +38 -0
  203. package/src/testing/flight-runtime.d.ts +57 -0
  204. package/src/testing/flight-tree.ts +682 -0
  205. package/src/testing/flight.entry.ts +51 -0
  206. package/src/testing/flight.ts +234 -0
  207. package/src/testing/generated-routes.ts +223 -0
  208. package/src/testing/index.ts +106 -0
  209. package/src/testing/internal/context.ts +304 -0
  210. package/src/testing/internal/flight-client-globals.ts +30 -0
  211. package/src/testing/internal/seed-vars.ts +42 -0
  212. package/src/testing/render-handler.ts +323 -0
  213. package/src/testing/render-route.tsx +590 -0
  214. package/src/testing/run-loader.ts +363 -0
  215. package/src/testing/run-middleware.ts +205 -0
  216. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  217. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  218. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  219. package/src/testing/vitest-stubs/version.ts +5 -0
  220. package/src/testing/vitest.ts +285 -0
  221. package/src/types/global-namespace.ts +39 -26
  222. package/src/types/handler-context.ts +68 -50
  223. package/src/types/index.ts +1 -0
  224. package/src/types/loader-types.ts +11 -9
  225. package/src/types/request-scope.ts +126 -0
  226. package/src/types/route-entry.ts +11 -0
  227. package/src/types/segments.ts +35 -2
  228. package/src/urls/include-helper.ts +34 -67
  229. package/src/urls/index.ts +1 -5
  230. package/src/urls/path-helper-types.ts +41 -7
  231. package/src/urls/path-helper.ts +17 -52
  232. package/src/urls/pattern-types.ts +36 -19
  233. package/src/urls/response-types.ts +22 -29
  234. package/src/urls/type-extraction.ts +58 -139
  235. package/src/urls/urls-function.ts +1 -5
  236. package/src/use-loader.tsx +413 -42
  237. package/src/vite/debug.ts +185 -0
  238. package/src/vite/discovery/bundle-postprocess.ts +6 -6
  239. package/src/vite/discovery/discover-routers.ts +106 -75
  240. package/src/vite/discovery/discovery-errors.ts +194 -0
  241. package/src/vite/discovery/gate-state.ts +171 -0
  242. package/src/vite/discovery/prerender-collection.ts +67 -26
  243. package/src/vite/discovery/route-types-writer.ts +40 -84
  244. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  245. package/src/vite/discovery/state.ts +33 -0
  246. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  247. package/src/vite/index.ts +2 -0
  248. package/src/vite/plugin-types.ts +67 -0
  249. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  250. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  251. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  252. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  253. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  254. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  255. package/src/vite/plugins/expose-action-id.ts +54 -30
  256. package/src/vite/plugins/expose-id-utils.ts +12 -8
  257. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  258. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  259. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  260. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  261. package/src/vite/plugins/expose-internal-ids.ts +496 -486
  262. package/src/vite/plugins/performance-tracks.ts +29 -25
  263. package/src/vite/plugins/use-cache-transform.ts +65 -50
  264. package/src/vite/plugins/version-injector.ts +39 -23
  265. package/src/vite/plugins/version-plugin.ts +59 -2
  266. package/src/vite/plugins/virtual-entries.ts +2 -2
  267. package/src/vite/rango.ts +116 -29
  268. package/src/vite/router-discovery.ts +750 -100
  269. package/src/vite/utils/ast-handler-extract.ts +15 -15
  270. package/src/vite/utils/banner.ts +1 -1
  271. package/src/vite/utils/bundle-analysis.ts +4 -2
  272. package/src/vite/utils/client-chunks.ts +190 -0
  273. package/src/vite/utils/forward-user-plugins.ts +193 -0
  274. package/src/vite/utils/manifest-utils.ts +8 -59
  275. package/src/vite/utils/package-resolution.ts +41 -1
  276. package/src/vite/utils/prerender-utils.ts +21 -6
  277. package/src/vite/utils/shared-utils.ts +107 -26
  278. package/src/browser/action-response-classifier.ts +0 -99
@@ -0,0 +1,363 @@
1
+ /**
2
+ * runLoader — unit-test a loader function in isolation.
3
+ *
4
+ * Pass the RAW async loader body `(ctx) => ...`, or a registered `createLoader()`
5
+ * handle (its fn is recovered from the fetchable registry by `$$id`). The raw
6
+ * body needs no build step; the handle works because `createLoader` assigns a
7
+ * runtime-fallback `$$id` and registers its fn even without the Vite plugin (when
8
+ * imported through the server build — the consumer's `@rangojs/router` under the
9
+ * `rangoTestConfig()` preset). Either way the function is invoked directly with a
10
+ * constructed LoaderContext.
11
+ *
12
+ * The LoaderContext mirrors the canonical shape the router builds at runtime
13
+ * (see createUseFunction in server/request-context.ts). The loader runs inside
14
+ * runWithRequestContext so getRequestContext(), cookie reads, and header
15
+ * mutations resolve exactly as in production.
16
+ *
17
+ * Limitations (v1):
18
+ * - `ctx.rendered()` is not available — it requires the DSL render barrier,
19
+ * which only exists inside a full match. Calling it throws.
20
+ * - `ctx.reverse()` throws unless `routeMap` is provided (it does NOT fall back
21
+ * to the global route map — that would leak whichever routes another test
22
+ * registered).
23
+ * - `ctx.use(handle)` follows the production rule: reading a handle before
24
+ * `await ctx.rendered()` throws (pass `rendered` to mock the barrier).
25
+ * - `use cache` functions only cache (and only fire their taint/profile guards)
26
+ * when a `cacheStore` is provided — without one, registerCachedFunction
27
+ * bypasses (it checks for a store first). Pass `cacheStore`/`cacheProfiles`
28
+ * to exercise cached loaders; otherwise such a call runs uncached, like an
29
+ * app with no cache configured.
30
+ * - `formData` is exposed verbatim; no multipart parsing is performed.
31
+ * - Scoped dot-local reverse (`.sibling`) uses only the supplied `routeMap`;
32
+ * the production root-scoping signal (derived from the global registry) is
33
+ * not modeled, so a dotted name resolves against `routeMap` as given.
34
+ */
35
+
36
+ import {
37
+ runWithRequestContext,
38
+ type RequestContext,
39
+ } from "../server/request-context.js";
40
+ import { createReverseFunction } from "../router/handler-context.js";
41
+ import { getFetchableLoader } from "../server/fetchable-loader-store.js";
42
+ import type { LoaderContext, LoaderDefinition } from "../types.js";
43
+ import type { ContextVar } from "../context-var.js";
44
+ import { isHandle, type Handle } from "../handle.js";
45
+ import { collectHandle } from "./collect-handle.js";
46
+ import type { ThemeConfig } from "../theme/types.js";
47
+ import type { SegmentCacheStore } from "../cache/types.js";
48
+ import type { CacheProfile } from "../cache/profile-registry.js";
49
+ import {
50
+ createTestRequestContext,
51
+ type CreateTestContextOptions,
52
+ type VarsInit,
53
+ } from "./internal/context.js";
54
+
55
+ /**
56
+ * The loader context surfaced to a `runLoader` body. It mirrors the runtime
57
+ * LoaderContext but RELAXES the two members that are otherwise bound to the
58
+ * app's global route/var augmentation, because in a unit test they are driven by
59
+ * the `routeMap` / `vars` options instead:
60
+ * - `reverse` accepts any route name (the names come from `routeMap`, not the
61
+ * registered route map), and
62
+ * - `get` accepts any string key or ContextVar (keys come from `vars`).
63
+ */
64
+ export type TestLoaderContext<TEnv = any> = Omit<
65
+ LoaderContext<any, TEnv>,
66
+ "reverse" | "get"
67
+ > & {
68
+ reverse: (
69
+ name: string,
70
+ params?: Record<string, string>,
71
+ search?: Record<string, unknown>,
72
+ ) => string;
73
+ get: {
74
+ <T>(contextVar: ContextVar<T>): T | undefined;
75
+ <T = unknown>(key: string): T | undefined;
76
+ };
77
+ };
78
+
79
+ /**
80
+ * A resolver for `ctx.use(OtherLoader)` composition. Receives the dependency
81
+ * loader definition and returns its data (or a promise of it). When omitted,
82
+ * `ctx.use` delegates to the real request-context use(), which executes the
83
+ * dependency's own `fn` if present.
84
+ */
85
+ export type UseResolver = <T>(
86
+ loader: LoaderDefinition<T, any>,
87
+ ) => Promise<T> | T;
88
+
89
+ /**
90
+ * Options for runLoader.
91
+ */
92
+ export interface RunLoaderOptions<TEnv = any> {
93
+ /** Route params surfaced as `ctx.params` and `ctx.routeParams`. */
94
+ params?: Record<string, string>;
95
+ /** Search params; merged into the request URL so `ctx.searchParams` reflects them. */
96
+ search?: Record<string, string>;
97
+ /**
98
+ * The TYPED `ctx.search` object a route's search schema would produce. Distinct
99
+ * from `search` (which sets the raw `ctx.searchParams`): a loader on a typed
100
+ * search route reads `ctx.search`, which is otherwise `{}` in a test.
101
+ */
102
+ searchData?: Record<string, unknown>;
103
+ /** Router basename surfaced on the context (drives redirect() prefixing). */
104
+ basename?: string;
105
+ /**
106
+ * Theme config in the same shape `createRouter({ theme })` takes (e.g. `true`
107
+ * or `{ themes: [...] }`). Without it `ctx.theme`/`ctx.setTheme` are inert.
108
+ */
109
+ theme?: ThemeConfig | true;
110
+ /** Environment bindings surfaced as `ctx.env`. */
111
+ env?: TEnv;
112
+ /** Override the backing Request (string or Request). Defaults to a localhost GET. */
113
+ request?: Request | string;
114
+ /** Variables a prior middleware would have set (object or [key, value] list). */
115
+ vars?: VarsInit;
116
+ /** Route name -> pattern map enabling `ctx.reverse()`. */
117
+ routeMap?: Record<string, string>;
118
+ /** Matched route name for scoped `.name` reverse resolution. */
119
+ routeName?: string;
120
+ /** HTTP method surfaced as `ctx.method`. Defaults to "GET". */
121
+ method?: string;
122
+ /** Request body surfaced as `ctx.body`. */
123
+ body?: unknown;
124
+ /** Form data surfaced as `ctx.formData`. */
125
+ formData?: FormData;
126
+ /**
127
+ * Seed the data `ctx.use(OtherLoader)` returns, by loader REFERENCE — the same
128
+ * tuple form `renderHandler` / `renderRoute` use (`[[OtherLoader, data]]`).
129
+ * Matched by reference, so a real `createLoader()` handle resolves regardless
130
+ * of its build-injected `$$id`. For dynamic resolution (compute per dependency)
131
+ * use `use` instead; `loaders` is checked first.
132
+ */
133
+ loaders?: ReadonlyArray<readonly [LoaderDefinition<any, any>, unknown]>;
134
+ /** Resolver for `ctx.use(OtherLoader)` composition (dynamic; `loaders` wins if both match). */
135
+ use?: UseResolver;
136
+ /**
137
+ * Cache store backing `use cache` functions the loader invokes. Without it,
138
+ * a cached function bypasses (registerCachedFunction checks for a store
139
+ * first) and runs uncached — its taint/profile guards never fire. Pass one
140
+ * (e.g. `new MemorySegmentCacheStore()`) to test a cached loader.
141
+ */
142
+ cacheStore?: SegmentCacheStore;
143
+ /** Cache profiles (the `createRouter({ cacheProfiles })` shape). */
144
+ cacheProfiles?: Record<string, CacheProfile>;
145
+ /**
146
+ * Mock the `ctx.rendered()` render barrier so a loader that does
147
+ * `await ctx.rendered()` (to read handle data pushed during render) can be
148
+ * unit-tested. By default `ctx.rendered()` throws, because the real barrier
149
+ * only exists during a full route match. Pass `true` to resolve it
150
+ * immediately, or a function to control its timing/side effects.
151
+ *
152
+ * This tests the loader's POST-barrier compute logic against the seeded
153
+ * `handles` below — it does NOT exercise the real push -> accumulate -> barrier
154
+ * wiring (that stays e2e). Pair with `handles` to feed `ctx.use(SomeHandle)`.
155
+ */
156
+ rendered?: boolean | (() => void | Promise<void>);
157
+ /**
158
+ * Seed the values `ctx.use(SomeHandle)` returns — the ACCUMULATED handle data a
159
+ * loader reads after `await ctx.rendered()`. Matched by handle reference, so a
160
+ * real handle works regardless of its (build-injected) `$$id`.
161
+ *
162
+ * @example
163
+ * await runLoader(livePricesBody, {
164
+ * rendered: true,
165
+ * handles: [[RenderedProducts, ["widget-a", "widget-b"]]],
166
+ * });
167
+ */
168
+ handles?: ReadonlyArray<readonly [Handle<any, any>, unknown]>;
169
+ }
170
+
171
+ /**
172
+ * Merge `search` into a request's URL, returning a value `toRequest` can build.
173
+ * Keeps the original method/headers/body when a Request was passed.
174
+ */
175
+ function withSearch(
176
+ request: Request | string | undefined,
177
+ search: Record<string, string> | undefined,
178
+ ): Request | string | undefined {
179
+ if (!search) return request;
180
+ const DEFAULT_ORIGIN = "http://localhost/";
181
+ if (request instanceof Request) {
182
+ const url = new URL(request.url);
183
+ for (const [key, value] of Object.entries(search)) {
184
+ url.searchParams.set(key, value);
185
+ }
186
+ return new Request(url, request);
187
+ }
188
+ const url = new URL(request ?? DEFAULT_ORIGIN, DEFAULT_ORIGIN);
189
+ for (const [key, value] of Object.entries(search)) {
190
+ url.searchParams.set(key, value);
191
+ }
192
+ return url.toString();
193
+ }
194
+
195
+ /** A raw loader body, or a registered `createLoader()` handle (its fn is recovered). */
196
+ export type RunnableLoader<T> =
197
+ | ((ctx: TestLoaderContext) => Promise<T> | T)
198
+ | LoaderDefinition<T, any>;
199
+
200
+ /**
201
+ * Resolve the function to run from either a raw body or a `createLoader()` handle.
202
+ *
203
+ * A handle carries no inline body (`createLoader` registers it in the fetchable
204
+ * registry by `$$id`), so recover it from there — `def.fn` first (a hand-built
205
+ * def), then the registry. This works when the handle resolves through the
206
+ * SERVER build (the consumer's `@rangojs/router` under `rangoTestConfig`, which
207
+ * registers the fn); the CLIENT stub drops the body, so a handle imported that
208
+ * way is unrecoverable and we say so explicitly.
209
+ */
210
+ function resolveLoaderFn<T>(
211
+ loader: RunnableLoader<T>,
212
+ ): (ctx: TestLoaderContext) => Promise<T> | T {
213
+ if (typeof loader === "function") {
214
+ return loader as (ctx: TestLoaderContext) => Promise<T> | T;
215
+ }
216
+ const def = loader as LoaderDefinition<T, any>;
217
+ const fn = def.fn ?? getFetchableLoader(def.$$id)?.fn;
218
+ if (!fn) {
219
+ throw new Error(
220
+ `runLoader() received a createLoader() handle whose function could not be ` +
221
+ `recovered (id "${def.$$id || "<empty>"}"). The loader was likely imported ` +
222
+ `through the CLIENT build, which drops the body. Either import it through ` +
223
+ `@rangojs/router with the rangoTestConfig() preset (resolves to the server ` +
224
+ `build that registers the fn), or pass the raw loader body directly: ` +
225
+ `runLoader((ctx) => ...).`,
226
+ );
227
+ }
228
+ return fn as (ctx: TestLoaderContext) => Promise<T> | T;
229
+ }
230
+
231
+ /**
232
+ * Run a loader and return its resolved data. Pass the RAW loader body, or a
233
+ * registered `createLoader()` handle (its fn is recovered from the registry).
234
+ *
235
+ * @example
236
+ * ```ts
237
+ * // raw body
238
+ * const a = await runLoader(
239
+ * async (ctx) => ({ id: ctx.params.id, user: ctx.get("user") }),
240
+ * { params: { id: "42" }, vars: { user: { name: "Ada" } } },
241
+ * );
242
+ * // registered createLoader() handle (recovered from the registry)
243
+ * const b = await runLoader(ProductLoader, { params: { id: "42" } });
244
+ * ```
245
+ */
246
+ export async function runLoader<T>(
247
+ loader: RunnableLoader<T>,
248
+ opts: RunLoaderOptions = {},
249
+ ): Promise<T> {
250
+ const loaderFn = resolveLoaderFn(loader);
251
+ const ctxOpts: CreateTestContextOptions<any> = {
252
+ env: opts.env,
253
+ // Bake opts.search into the request URL itself so ctx.request.url, ctx.url,
254
+ // and ctx.searchParams all agree (production carries the query string on the
255
+ // real request — a loader reading ctx.request.url must see it too).
256
+ request: withSearch(opts.request, opts.search),
257
+ requestInit: opts.method ? { method: opts.method } : undefined,
258
+ vars: opts.vars,
259
+ routeMap: opts.routeMap,
260
+ routeName: opts.routeName,
261
+ params: opts.params,
262
+ basename: opts.basename,
263
+ theme: opts.theme,
264
+ cacheStore: opts.cacheStore,
265
+ cacheProfiles: opts.cacheProfiles,
266
+ };
267
+
268
+ const { ctx } = createTestRequestContext(ctxOpts);
269
+
270
+ const reqCtx = ctx as RequestContext<any>;
271
+
272
+ // Seed values for ctx.use(SomeHandle), matched by handle reference (so a real
273
+ // handle resolves regardless of its build-injected $$id).
274
+ const handleSeeds = new Map<unknown, unknown>(opts.handles ?? []);
275
+
276
+ // Seed values for ctx.use(OtherLoader), matched by loader reference (same model
277
+ // as renderHandler/renderRoute). Checked before the `use` resolver.
278
+ const loaderSeeds = new Map<unknown, unknown>(opts.loaders ?? []);
279
+
280
+ // Tracks whether the mocked render barrier has settled. ctx.use(handle)
281
+ // reads are gated on this, matching production (loader-resolution.ts).
282
+ let renderedResolved = false;
283
+
284
+ return runWithRequestContext(reqCtx, () => {
285
+ const reverse = opts.routeMap
286
+ ? createReverseFunction(opts.routeMap, opts.routeName, opts.params ?? {})
287
+ : ((() => {
288
+ // Documented contract: reverse requires routeMap. Do NOT fall back to
289
+ // reqCtx.reverse (the global route map) — that leaks whichever routes
290
+ // another test registered and contradicts the documented behavior.
291
+ throw new Error(
292
+ "ctx.reverse() requires the `routeMap` option in runLoader(). " +
293
+ "Pass { routeMap: { name: pattern, ... } } to enable reverse().",
294
+ );
295
+ }) as TestLoaderContext["reverse"]);
296
+
297
+ const loaderCtx: TestLoaderContext = {
298
+ params: opts.params ?? {},
299
+ routeParams: (opts.params ?? {}) as Record<string, string>,
300
+ request: reqCtx.request,
301
+ searchParams: ctx.searchParams,
302
+ search: opts.searchData ?? {},
303
+ pathname: reqCtx.pathname,
304
+ url: reqCtx.url,
305
+ originalUrl: reqCtx.originalUrl,
306
+ env: reqCtx.env,
307
+ waitUntil: reqCtx.waitUntil.bind(reqCtx),
308
+ executionContext: reqCtx.executionContext,
309
+ get: reqCtx.get as TestLoaderContext["get"],
310
+ use: ((dep: LoaderDefinition<any, any> | Handle<any, any>) => {
311
+ // Match production (loader-resolution.ts): reading a handle in a loader
312
+ // requires the render barrier to have settled. Gate BEFORE returning a
313
+ // seed, so a loader that forgets `await ctx.rendered()` fails in the
314
+ // test exactly as it would at runtime.
315
+ if (isHandle(dep) && !renderedResolved) {
316
+ throw new Error(
317
+ `ctx.use(handle) in a loader requires "await ctx.rendered()" first. ` +
318
+ `Handle "${(dep as Handle<any, any>).$$id}" cannot be read until ` +
319
+ `the render tree has settled.`,
320
+ );
321
+ }
322
+ // Handle reads (ctx.use(SomeHandle)) resolve from the seeded map first.
323
+ if (handleSeeds.has(dep)) return handleSeeds.get(dep);
324
+ // Post-barrier, an UNSEEDED handle must match production
325
+ // (loader-resolution.ts -> collectHandleData), which runs the handle's
326
+ // registered collect over empty segments (collect([])) rather than
327
+ // throwing or leaking into the loader resolver. Resolve it via
328
+ // collectHandle, which recovers and runs that same collect.
329
+ if (isHandle(dep)) return collectHandle(dep, []);
330
+ // Loader reads (ctx.use(OtherLoader)) resolve from the seeded map next,
331
+ // then the dynamic `use` resolver, then the real request-context use().
332
+ if (loaderSeeds.has(dep)) return loaderSeeds.get(dep);
333
+ if (opts.use) return opts.use(dep as LoaderDefinition<any, any>);
334
+ return reqCtx.use(dep as LoaderDefinition<any, any>);
335
+ }) as LoaderContext<any, any>["use"],
336
+ method: opts.method ?? "GET",
337
+ body: opts.body,
338
+ formData: opts.formData,
339
+ reverse: reverse as TestLoaderContext["reverse"],
340
+ rendered:
341
+ opts.rendered !== undefined && opts.rendered !== false
342
+ ? async () => {
343
+ if (typeof opts.rendered === "function") {
344
+ await opts.rendered();
345
+ }
346
+ // Barrier has settled: subsequent ctx.use(handle) reads resolve.
347
+ renderedResolved = true;
348
+ }
349
+ : () => {
350
+ throw new Error(
351
+ "ctx.rendered() is not available in runLoader() by default. It " +
352
+ "requires the DSL render barrier, which only exists during a " +
353
+ "full route match. To unit-test a loader's post-barrier logic, " +
354
+ "pass { rendered: true } to mock the barrier and { handles: " +
355
+ "[[SomeHandle, accumulatedData]] } to seed ctx.use(SomeHandle). " +
356
+ "For the real push/accumulate/barrier wiring, use an e2e test.",
357
+ );
358
+ },
359
+ };
360
+
361
+ return Promise.resolve(loaderFn(loaderCtx));
362
+ });
363
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * runMiddleware — unit-test one or more middleware functions in isolation.
3
+ *
4
+ * Executes the middleware chain via the SAME executeLoaderMiddleware the router
5
+ * uses, so ordering, `next()`, short-circuit (return OR throw Response),
6
+ * double-next guards, and header/cookie merging behave identically to
7
+ * production. The chain runs inside runWithRequestContext, so cookie/header
8
+ * mutations and getRequestContext() resolve.
9
+ *
10
+ * The returned `ctx` is the underlying RequestContext (not the per-middleware
11
+ * MiddlewareContext), exposing `ctx.cookies()`, `ctx.get()`, and
12
+ * `ctx.res.headers` for assertions on what the chain produced.
13
+ *
14
+ * `nextCalled` counts how many times the terminal `next()` (the finalHandler)
15
+ * ran: 0 when the chain short-circuited, 1 when it ran to completion.
16
+ */
17
+
18
+ import {
19
+ runWithRequestContext,
20
+ type RequestContext,
21
+ } from "../server/request-context.js";
22
+ import { executeLoaderMiddleware } from "../router/middleware.js";
23
+ import { createReverseFunction } from "../router/handler-context.js";
24
+ import type { MiddlewareFn } from "../router/middleware-types.js";
25
+ import {
26
+ createTestRequestContext,
27
+ headersToObject,
28
+ snapshotRunEffects,
29
+ type CreateTestContextOptions,
30
+ type VarsInit,
31
+ } from "./internal/context.js";
32
+ import type { ThemeConfig } from "../theme/types.js";
33
+ import type { SegmentCacheStore } from "../cache/types.js";
34
+ import type { CacheProfile } from "../cache/profile-registry.js";
35
+
36
+ /**
37
+ * Options for runMiddleware.
38
+ */
39
+ export interface RunMiddlewareOptions<TEnv = any> {
40
+ /**
41
+ * The request the chain runs under: a `Request`, or a URL string (absolute or
42
+ * path). Optional for parity with `runLoader`/`runInRequestContext` — when
43
+ * omitted it defaults to `http://localhost/`. Pass it for path-, header-, or
44
+ * cookie-driven middleware.
45
+ */
46
+ request?: Request | string;
47
+ /** Environment bindings surfaced as `ctx.env`. */
48
+ env?: TEnv;
49
+ /** Route params surfaced as `ctx.params`. */
50
+ params?: Record<string, string>;
51
+ /** Variables a prior middleware would have set (object or [key, value] list). */
52
+ vars?: VarsInit;
53
+ /** Route name -> pattern map enabling `ctx.reverse()`. */
54
+ routeMap?: Record<string, string>;
55
+ /**
56
+ * Matched route name surfaced as `ctx.routeName`. Does NOT scope `.name`
57
+ * reverse: the chain receives a map-only `reverse` (built from `routeMap`
58
+ * alone), matching production app/response middleware — see the reverse
59
+ * construction below.
60
+ */
61
+ routeName?: string;
62
+ /** Router basename surfaced on the context (drives redirect() prefixing). */
63
+ basename?: string;
64
+ /** Theme config in the `createRouter({ theme })` shape (enables ctx.theme). */
65
+ theme?: ThemeConfig | true;
66
+ /**
67
+ * Terminal handler invoked when the chain calls `next()` all the way through.
68
+ * Defaults to a 200 empty Response. Use this to model the downstream
69
+ * route/handler response.
70
+ */
71
+ next?: () => Promise<Response>;
72
+ /**
73
+ * Cache store backing any `use cache` function a middleware invokes. Without
74
+ * it, registerCachedFunction bypasses (it checks for a store first), so the
75
+ * cached function runs uncached and its taint/profile guards never fire.
76
+ */
77
+ cacheStore?: SegmentCacheStore;
78
+ /** Cache profiles (the `createRouter({ cacheProfiles })` shape). */
79
+ cacheProfiles?: Record<string, CacheProfile>;
80
+ }
81
+
82
+ /**
83
+ * Result of runMiddleware.
84
+ */
85
+ export interface RunMiddlewareResult<TEnv = any> {
86
+ /** The final Response (downstream response, or a middleware short-circuit). */
87
+ response: Response;
88
+ /**
89
+ * The underlying RequestContext. Read `ctx.cookies()`, `ctx.get(...)`, and
90
+ * `ctx.res.headers` to assert on the chain's effects. (This is always the
91
+ * RequestContext the chain ran under — not a per-middleware MiddlewareContext —
92
+ * so `ctx.cookies()` and the other RequestContext accessors are available.)
93
+ */
94
+ ctx: RequestContext<TEnv>;
95
+ /** Number of times the terminal handler ran (0 = short-circuited, 1 = passed through). */
96
+ nextCalled: number;
97
+ /**
98
+ * The effective cookie view after the chain ran: request cookies merged with
99
+ * anything the chain set or deleted (last-write-wins), as `{ name: value }`.
100
+ * The public way to assert a cookie a middleware set, without casting through
101
+ * the `@internal` `ctx.cookies()`. Set-Cookie headers are also on `response`.
102
+ */
103
+ cookies: Record<string, string>;
104
+ /**
105
+ * The final response's headers as a plain `{ name: value }` object (the same
106
+ * view as `response.headers`), EXCLUDING `set-cookie` (use `cookies`). The
107
+ * public way to assert a header a middleware set (e.g. a security header)
108
+ * without reading `ctx.res.headers`. Header names are lowercased.
109
+ */
110
+ headers: Record<string, string>;
111
+ /**
112
+ * Location state the chain set via `ctx.setLocationState()` / `redirect({ state })`,
113
+ * resolved to the flat `{ key: value }` shape the client reads off
114
+ * `history.state` (empty object when none) — parity with `runInRequestContext`
115
+ * and `renderHandler`.
116
+ */
117
+ locationState: Record<string, unknown>;
118
+ }
119
+
120
+ /**
121
+ * Run a middleware chain and return the response plus observable context.
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * const { response, ctx, nextCalled } = await runMiddleware(
126
+ * async (ctx, next) => {
127
+ * if (!ctx.get("user")) return new Response(null, { status: 401 });
128
+ * return next();
129
+ * },
130
+ * { request: "/dashboard", vars: [["user", { id: 1 }]] },
131
+ * );
132
+ * // nextCalled === 1, response.status === 200
133
+ * ```
134
+ */
135
+ export async function runMiddleware<TEnv = any>(
136
+ mw: MiddlewareFn<TEnv> | MiddlewareFn<TEnv>[],
137
+ opts: RunMiddlewareOptions<TEnv>,
138
+ ): Promise<RunMiddlewareResult<TEnv>> {
139
+ const mwArray = Array.isArray(mw) ? mw : [mw];
140
+
141
+ const ctxOpts: CreateTestContextOptions<TEnv> = {
142
+ env: opts.env,
143
+ request: opts.request,
144
+ vars: opts.vars,
145
+ routeMap: opts.routeMap,
146
+ routeName: opts.routeName,
147
+ params: opts.params,
148
+ basename: opts.basename,
149
+ theme: opts.theme,
150
+ cacheStore: opts.cacheStore,
151
+ cacheProfiles: opts.cacheProfiles,
152
+ };
153
+
154
+ const {
155
+ ctx,
156
+ request: builtRequest,
157
+ variables,
158
+ } = createTestRequestContext<TEnv>(ctxOpts);
159
+
160
+ let nextCalled = 0;
161
+ const finalHandler = async (): Promise<Response> => {
162
+ nextCalled++;
163
+ return opts.next?.() ?? new Response(null, { status: 200 });
164
+ };
165
+
166
+ // Match production: app/response middleware receive ctx.reverse built from the
167
+ // route map ALONE (no matched route name or current params), so reversing a
168
+ // parameterized route without explicit params does NOT auto-fill from the
169
+ // current request. Passing routeName/params here would recreate the
170
+ // false-confidence class fixed in dispatch.
171
+ const reverse = opts.routeMap
172
+ ? (createReverseFunction(opts.routeMap) as (
173
+ name: string,
174
+ params?: Record<string, string>,
175
+ search?: Record<string, unknown>,
176
+ ) => string)
177
+ : undefined;
178
+
179
+ // Keep the RETURNED ctx.reverse consistent with the map-only reverse the
180
+ // chain receives. createTestRequestContext installs an auto-fill reverse
181
+ // (correct for the loader phase) when routeName/params are passed, but
182
+ // production app/response middleware see a map-only reverse. Without this,
183
+ // a middleware reading getRequestContext().reverse — or a consumer asserting
184
+ // on result.ctx.reverse — would observe auto-fill that production never does.
185
+ if (reverse) {
186
+ (ctx as RequestContext<TEnv>).reverse =
187
+ reverse as RequestContext<TEnv>["reverse"];
188
+ }
189
+
190
+ const response = await runWithRequestContext(ctx, () =>
191
+ executeLoaderMiddleware<TEnv>(
192
+ mwArray,
193
+ builtRequest,
194
+ (opts.env ?? {}) as TEnv,
195
+ opts.params ?? {},
196
+ variables,
197
+ finalHandler,
198
+ reverse,
199
+ ),
200
+ );
201
+
202
+ const { cookies, locationState } = snapshotRunEffects(ctx);
203
+ const headers = headersToObject(response.headers);
204
+ return { response, ctx, nextCalled, cookies, headers, locationState };
205
+ }
@@ -0,0 +1,9 @@
1
+ // Stub for the `cloudflare:email` runtime virtual, shipped for Cloudflare
2
+ // consumers (enable via `rangoTestAliases({ preset: "cloudflare" })`).
3
+ export class EmailMessage {
4
+ constructor(
5
+ public from: string,
6
+ public to: string,
7
+ public raw: unknown,
8
+ ) {}
9
+ }
@@ -0,0 +1,21 @@
1
+ // Stub for the `cloudflare:workers` runtime virtual, shipped for Cloudflare
2
+ // consumers (enable via `rangoTestAliases({ preset: "cloudflare" })`). A CF app's
3
+ // route tree commonly imports `cloudflare:workers` (e.g. `import { env } from
4
+ // "cloudflare:workers"`), which does not resolve in a bare Vitest process.
5
+ export const env: Record<string, unknown> = {};
6
+
7
+ export class DurableObject<Env = unknown> {
8
+ constructor(
9
+ public ctx: unknown,
10
+ public env: Env,
11
+ ) {}
12
+ }
13
+
14
+ export class WorkerEntrypoint<Env = unknown> {
15
+ constructor(
16
+ public ctx: unknown,
17
+ public env: Env,
18
+ ) {}
19
+ }
20
+
21
+ export class RpcTarget {}
@@ -0,0 +1,16 @@
1
+ // Stub for `@vitejs/plugin-rsc/rsc`, shipped so consumers do not have to write a
2
+ // per-file `vi.mock(...)`. Importing a router internal transitively pulls this
3
+ // module, whose real top-level body imports Vite virtuals that do not resolve in
4
+ // plain node. The unit/integration primitives (dispatch/runLoader/runMiddleware)
5
+ // never render RSC, so empty fns suffice.
6
+ export const createFromReadableStream = (): never => {
7
+ throw new Error("plugin-rsc stub: createFromReadableStream not available");
8
+ };
9
+ export const renderToReadableStream = (): never => {
10
+ throw new Error("plugin-rsc stub: renderToReadableStream not available");
11
+ };
12
+ export const loadServerAction = (): undefined => undefined;
13
+ export const decodeReply = (): undefined => undefined;
14
+ export const decodeAction = (): undefined => undefined;
15
+ export const decodeFormState = (): undefined => undefined;
16
+ export const createTemporaryReferenceSet = (): Record<string, never> => ({});
@@ -0,0 +1,5 @@
1
+ // Stub for the build-only `@rangojs/router:version` virtual module, shipped so
2
+ // consumers do not have to author it. The rango Vite plugin injects this at
3
+ // build time; in a bare Vitest process it must be aliased to a stub. Empty
4
+ // string keeps generated URLs free of a version path segment.
5
+ export const VERSION = "";