@rangojs/router 0.0.0-experimental.79 → 0.0.0-experimental.7d061845

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 (252) 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 +2138 -841
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +68 -21
  7. package/skills/breadcrumbs/SKILL.md +3 -1
  8. package/skills/bundle-analysis/SKILL.md +159 -0
  9. package/skills/cache-guide/SKILL.md +220 -30
  10. package/skills/caching/SKILL.md +116 -8
  11. package/skills/composability/SKILL.md +27 -2
  12. package/skills/document-cache/SKILL.md +78 -55
  13. package/skills/handler-use/SKILL.md +3 -1
  14. package/skills/hooks/SKILL.md +229 -20
  15. package/skills/host-router/SKILL.md +45 -20
  16. package/skills/i18n/SKILL.md +276 -0
  17. package/skills/intercept/SKILL.md +26 -4
  18. package/skills/layout/SKILL.md +6 -7
  19. package/skills/links/SKILL.md +247 -17
  20. package/skills/loader/SKILL.md +219 -9
  21. package/skills/middleware/SKILL.md +15 -9
  22. package/skills/migrate-nextjs/SKILL.md +4 -2
  23. package/skills/migrate-react-router/SKILL.md +5 -0
  24. package/skills/mime-routes/SKILL.md +27 -0
  25. package/skills/observability/SKILL.md +137 -0
  26. package/skills/parallel/SKILL.md +12 -6
  27. package/skills/prerender/SKILL.md +14 -33
  28. package/skills/rango/SKILL.md +242 -24
  29. package/skills/react-compiler/SKILL.md +168 -0
  30. package/skills/response-routes/SKILL.md +66 -9
  31. package/skills/route/SKILL.md +33 -4
  32. package/skills/router-setup/SKILL.md +3 -3
  33. package/skills/server-actions/SKILL.md +751 -0
  34. package/skills/streams-and-websockets/SKILL.md +283 -0
  35. package/skills/testing/SKILL.md +816 -0
  36. package/skills/typesafety/SKILL.md +319 -27
  37. package/skills/use-cache/SKILL.md +34 -5
  38. package/skills/view-transitions/SKILL.md +294 -0
  39. package/src/__augment-tests__/augment.ts +81 -0
  40. package/src/__augment-tests__/augmented.check.ts +117 -0
  41. package/src/browser/action-coordinator.ts +53 -36
  42. package/src/browser/app-shell.ts +52 -0
  43. package/src/browser/event-controller.ts +86 -70
  44. package/src/browser/history-state.ts +21 -0
  45. package/src/browser/index.ts +3 -3
  46. package/src/browser/navigation-bridge.ts +65 -9
  47. package/src/browser/navigation-client.ts +45 -25
  48. package/src/browser/navigation-store.ts +32 -9
  49. package/src/browser/navigation-transaction.ts +10 -28
  50. package/src/browser/partial-update.ts +52 -26
  51. package/src/browser/prefetch/cache.ts +124 -26
  52. package/src/browser/prefetch/fetch.ts +114 -38
  53. package/src/browser/prefetch/queue.ts +36 -5
  54. package/src/browser/rango-state.ts +53 -13
  55. package/src/browser/react/Link.tsx +18 -13
  56. package/src/browser/react/NavigationProvider.tsx +72 -31
  57. package/src/browser/react/filter-segment-order.ts +51 -7
  58. package/src/browser/react/index.ts +3 -0
  59. package/src/browser/react/location-state-shared.ts +175 -4
  60. package/src/browser/react/location-state.ts +39 -13
  61. package/src/browser/react/use-handle.ts +17 -9
  62. package/src/browser/react/use-navigation.ts +22 -2
  63. package/src/browser/react/use-params.ts +20 -8
  64. package/src/browser/react/use-reverse.ts +106 -0
  65. package/src/browser/react/use-router.ts +22 -2
  66. package/src/browser/react/use-segments.ts +11 -8
  67. package/src/browser/response-adapter.ts +25 -0
  68. package/src/browser/rsc-router.tsx +64 -22
  69. package/src/browser/scroll-restoration.ts +22 -14
  70. package/src/browser/segment-structure-assert.ts +2 -2
  71. package/src/browser/server-action-bridge.ts +23 -30
  72. package/src/browser/types.ts +21 -0
  73. package/src/build/collect-fallback-refs.ts +107 -0
  74. package/src/build/generate-manifest.ts +60 -35
  75. package/src/build/generate-route-types.ts +2 -0
  76. package/src/build/index.ts +2 -0
  77. package/src/build/route-trie.ts +2 -1
  78. package/src/build/route-types/codegen.ts +4 -4
  79. package/src/build/route-types/include-resolution.ts +1 -1
  80. package/src/build/route-types/per-module-writer.ts +7 -4
  81. package/src/build/route-types/router-processing.ts +55 -14
  82. package/src/build/route-types/scan-filter.ts +1 -1
  83. package/src/build/route-types/source-scan.ts +118 -0
  84. package/src/build/runtime-discovery.ts +9 -20
  85. package/src/cache/cache-scope.ts +28 -42
  86. package/src/cache/cf/cf-cache-store.ts +54 -13
  87. package/src/client.rsc.tsx +3 -0
  88. package/src/client.tsx +10 -8
  89. package/src/context-var.ts +5 -5
  90. package/src/decode-loader-results.ts +36 -0
  91. package/src/errors.ts +30 -1
  92. package/src/handle.ts +26 -13
  93. package/src/host/index.ts +2 -2
  94. package/src/host/router.ts +129 -57
  95. package/src/host/types.ts +31 -2
  96. package/src/host/utils.ts +1 -1
  97. package/src/href-client.ts +140 -20
  98. package/src/index.rsc.ts +9 -4
  99. package/src/index.ts +16 -6
  100. package/src/loader-store.ts +500 -0
  101. package/src/loader.rsc.ts +21 -6
  102. package/src/loader.ts +3 -10
  103. package/src/missing-id-error.ts +68 -0
  104. package/src/outlet-context.ts +1 -1
  105. package/src/prerender.ts +4 -4
  106. package/src/response-utils.ts +37 -0
  107. package/src/reverse.ts +65 -39
  108. package/src/route-content-wrapper.tsx +6 -28
  109. package/src/route-definition/dsl-helpers.ts +253 -265
  110. package/src/route-definition/helper-factories.ts +29 -139
  111. package/src/route-definition/helpers-types.ts +43 -15
  112. package/src/route-definition/resolve-handler-use.ts +6 -0
  113. package/src/route-definition/use-item-types.ts +32 -0
  114. package/src/route-types.ts +19 -41
  115. package/src/router/basename.ts +14 -0
  116. package/src/router/content-negotiation.ts +15 -2
  117. package/src/router/error-handling.ts +1 -1
  118. package/src/router/handler-context.ts +21 -41
  119. package/src/router/intercept-resolution.ts +4 -18
  120. package/src/router/lazy-includes.ts +3 -3
  121. package/src/router/loader-resolution.ts +19 -2
  122. package/src/router/match-api.ts +4 -3
  123. package/src/router/match-handlers.ts +63 -20
  124. package/src/router/match-middleware/cache-lookup.ts +44 -91
  125. package/src/router/match-middleware/cache-store.ts +3 -2
  126. package/src/router/match-result.ts +53 -32
  127. package/src/router/metrics.ts +1 -1
  128. package/src/router/middleware-types.ts +15 -26
  129. package/src/router/middleware.ts +99 -84
  130. package/src/router/pattern-matching.ts +101 -17
  131. package/src/router/prerender-match.ts +1 -1
  132. package/src/router/preview-match.ts +3 -1
  133. package/src/router/request-classification.ts +4 -28
  134. package/src/router/revalidation.ts +58 -2
  135. package/src/router/router-interfaces.ts +45 -28
  136. package/src/router/router-options.ts +40 -1
  137. package/src/router/router-registry.ts +2 -5
  138. package/src/router/segment-resolution/fresh.ts +27 -6
  139. package/src/router/segment-resolution/revalidation.ts +147 -106
  140. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  141. package/src/router/substitute-pattern-params.ts +56 -0
  142. package/src/router/telemetry.ts +99 -0
  143. package/src/router/trie-matching.ts +18 -13
  144. package/src/router/types.ts +8 -0
  145. package/src/router/url-params.ts +49 -0
  146. package/src/router.ts +38 -23
  147. package/src/rsc/handler-context.ts +2 -2
  148. package/src/rsc/handler.ts +28 -69
  149. package/src/rsc/helpers.ts +91 -43
  150. package/src/rsc/index.ts +1 -1
  151. package/src/rsc/origin-guard.ts +28 -10
  152. package/src/rsc/progressive-enhancement.ts +4 -0
  153. package/src/rsc/response-route-handler.ts +46 -53
  154. package/src/rsc/rsc-rendering.ts +35 -51
  155. package/src/rsc/runtime-warnings.ts +9 -10
  156. package/src/rsc/server-action.ts +17 -37
  157. package/src/rsc/ssr-setup.ts +16 -0
  158. package/src/rsc/types.ts +8 -2
  159. package/src/search-params.ts +4 -4
  160. package/src/segment-system.tsx +122 -56
  161. package/src/serialize.ts +243 -0
  162. package/src/server/context.ts +118 -51
  163. package/src/server/cookie-store.ts +28 -4
  164. package/src/server/request-context.ts +20 -42
  165. package/src/ssr/index.tsx +5 -1
  166. package/src/static-handler.ts +1 -1
  167. package/src/testing/cache-status.ts +166 -0
  168. package/src/testing/collect-handle.ts +63 -0
  169. package/src/testing/dispatch.ts +440 -0
  170. package/src/testing/dom.entry.ts +22 -0
  171. package/src/testing/e2e/fixture.ts +154 -0
  172. package/src/testing/e2e/index.ts +149 -0
  173. package/src/testing/e2e/matchers.ts +51 -0
  174. package/src/testing/e2e/page-helpers.ts +272 -0
  175. package/src/testing/e2e/parity.ts +306 -0
  176. package/src/testing/e2e/server.ts +183 -0
  177. package/src/testing/flight-matchers.ts +104 -0
  178. package/src/testing/flight-runtime.d.ts +57 -0
  179. package/src/testing/flight-tree.ts +332 -0
  180. package/src/testing/flight.entry.ts +46 -0
  181. package/src/testing/flight.ts +224 -0
  182. package/src/testing/generated-routes.ts +223 -0
  183. package/src/testing/index.ts +106 -0
  184. package/src/testing/internal/context.ts +304 -0
  185. package/src/testing/internal/flight-client-globals.ts +30 -0
  186. package/src/testing/internal/seed-vars.ts +42 -0
  187. package/src/testing/render-handler.ts +267 -0
  188. package/src/testing/render-route.tsx +565 -0
  189. package/src/testing/run-loader.ts +341 -0
  190. package/src/testing/run-middleware.ts +188 -0
  191. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  192. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  193. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  194. package/src/testing/vitest-stubs/version.ts +5 -0
  195. package/src/testing/vitest.ts +270 -0
  196. package/src/types/global-namespace.ts +39 -26
  197. package/src/types/handler-context.ts +68 -50
  198. package/src/types/index.ts +1 -0
  199. package/src/types/loader-types.ts +5 -6
  200. package/src/types/request-scope.ts +126 -0
  201. package/src/types/segments.ts +35 -1
  202. package/src/urls/include-helper.ts +10 -53
  203. package/src/urls/index.ts +0 -3
  204. package/src/urls/path-helper-types.ts +11 -3
  205. package/src/urls/path-helper.ts +17 -52
  206. package/src/urls/pattern-types.ts +36 -19
  207. package/src/urls/response-types.ts +22 -29
  208. package/src/urls/type-extraction.ts +26 -116
  209. package/src/urls/urls-function.ts +1 -5
  210. package/src/use-loader.tsx +413 -42
  211. package/src/vite/debug.ts +185 -0
  212. package/src/vite/discovery/bundle-postprocess.ts +6 -6
  213. package/src/vite/discovery/discover-routers.ts +101 -51
  214. package/src/vite/discovery/discovery-errors.ts +194 -0
  215. package/src/vite/discovery/gate-state.ts +171 -0
  216. package/src/vite/discovery/prerender-collection.ts +67 -26
  217. package/src/vite/discovery/route-types-writer.ts +40 -84
  218. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  219. package/src/vite/discovery/state.ts +33 -0
  220. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  221. package/src/vite/index.ts +2 -0
  222. package/src/vite/plugin-types.ts +67 -0
  223. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  224. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  225. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  226. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  227. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  228. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  229. package/src/vite/plugins/expose-action-id.ts +54 -30
  230. package/src/vite/plugins/expose-id-utils.ts +12 -8
  231. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  232. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  233. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  234. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  235. package/src/vite/plugins/expose-internal-ids.ts +496 -486
  236. package/src/vite/plugins/performance-tracks.ts +29 -25
  237. package/src/vite/plugins/use-cache-transform.ts +65 -50
  238. package/src/vite/plugins/version-injector.ts +39 -23
  239. package/src/vite/plugins/version-plugin.ts +59 -2
  240. package/src/vite/plugins/virtual-entries.ts +2 -2
  241. package/src/vite/rango.ts +116 -29
  242. package/src/vite/router-discovery.ts +750 -100
  243. package/src/vite/utils/ast-handler-extract.ts +15 -15
  244. package/src/vite/utils/banner.ts +1 -1
  245. package/src/vite/utils/bundle-analysis.ts +4 -2
  246. package/src/vite/utils/client-chunks.ts +190 -0
  247. package/src/vite/utils/forward-user-plugins.ts +193 -0
  248. package/src/vite/utils/manifest-utils.ts +21 -5
  249. package/src/vite/utils/package-resolution.ts +41 -1
  250. package/src/vite/utils/prerender-utils.ts +5 -4
  251. package/src/vite/utils/shared-utils.ts +107 -26
  252. package/src/browser/action-response-classifier.ts +0 -99
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Variable seeding shared by the node/DOM testing tier (internal/context.ts)
3
+ * AND the react-server Flight tier (flight.ts). Depends only on the
4
+ * dependency-free `context-var` module, so it is safe to import under the
5
+ * `react-server` condition (unlike internal/context.ts, which pulls
6
+ * client/browser modules).
7
+ */
8
+ import { contextSet, type ContextVar } from "../../context-var.js";
9
+
10
+ /**
11
+ * Initializer for seeded context variables (as a prior middleware would have
12
+ * set, or a server component would read during render). Either a plain object
13
+ * keyed by var name (the common, best-inferring form: `{ user: u }`) or a list
14
+ * of `[key, value]` tuples where the key may be a `createVar()` handle or a
15
+ * string (`[[userVar, u], ["flag", true]]`).
16
+ */
17
+ export type VarsInit =
18
+ | Record<string, unknown>
19
+ | ReadonlyArray<readonly [ContextVar<unknown> | string, unknown]>;
20
+
21
+ /**
22
+ * Preload variables as if set by upstream middleware (or visible to a rendered
23
+ * server tree). Accepts entries keyed by either a ContextVar (from createVar) or
24
+ * a string, matching ctx.set().
25
+ */
26
+ export function seedVariables(
27
+ variables: Record<string, unknown>,
28
+ vars?: VarsInit,
29
+ ): Record<string, unknown> {
30
+ if (!vars) return variables;
31
+ // Array/iterable form -> use the tuples as-is; plain object -> its entries.
32
+ const entries: Iterable<readonly [ContextVar<unknown> | string, unknown]> =
33
+ Symbol.iterator in (vars as object)
34
+ ? (vars as ReadonlyArray<
35
+ readonly [ContextVar<unknown> | string, unknown]
36
+ >)
37
+ : Object.entries(vars as Record<string, unknown>);
38
+ for (const [key, value] of entries) {
39
+ contextSet(variables, key as ContextVar<unknown>, value);
40
+ }
41
+ return variables;
42
+ }
@@ -0,0 +1,267 @@
1
+ /// <reference path="./flight-runtime.d.ts" />
2
+ /**
3
+ * renderHandler — run a REAL route handler and assert what it renders.
4
+ *
5
+ * A Rango route handler is a pure function `(ctx) => RSC` (what you pass to
6
+ * `path("/p/:slug", ProductPage)`), NOT a component. To test one faithfully you
7
+ * must give it the HandlerContext the router builds at runtime, so `ctx.params`,
8
+ * `ctx.use(Loader)`, `ctx.use(Meta)` / `ctx.use(Breadcrumbs)` (handles),
9
+ * `ctx.reverse`, `ctx.get`/`ctx.header`/`cookies()` all work. renderHandler does
10
+ * exactly that, then serializes the handler's returned RSC and deserializes it
11
+ * to an inspectable tree (same serialize/deserialize core as renderServerTree).
12
+ *
13
+ * Loaders are SEEDED (no real loader execution) the same way `runLoader` seeds
14
+ * them — pass `loaders: [[ProductLoader, data]]`. Handle pushes
15
+ * (`ctx.use(Meta)({...})`) are captured on `result.handles`. The handler's
16
+ * cookie/header/flash effects and a thrown/returned redirect are surfaced too
17
+ * (like `runInRequestContext`). If the handler returns/throws a `Response`
18
+ * (a response route / `throw redirect()`), there is no RSC `tree`.
19
+ *
20
+ * Must run under the `react-server` export condition (the rsc Vitest project).
21
+ * Wire `rangoUseClientTransform()` so `"use client"` islands in the handler's RSC
22
+ * auto-register (or pass `clientComponents`).
23
+ */
24
+ import type { ReactNode } from "react";
25
+ import {
26
+ createRequestContext,
27
+ runWithRequestContext,
28
+ setRequestContextParams,
29
+ type RequestContext,
30
+ } from "../server/request-context.js";
31
+ import { createHandlerContext } from "../router/handler-context.js";
32
+ import { resolveLocationStateEntries } from "../browser/react/location-state-shared.js";
33
+ import { isHandle, type Handle } from "../handle.js";
34
+ import type { HandlerContext } from "../types/handler-context.js";
35
+ import type { LoaderDefinition } from "../types.js";
36
+ import { seedVariables, type VarsInit } from "./internal/seed-vars.js";
37
+ import { serializeNodeToFlight } from "./flight.js";
38
+ import {
39
+ deserializeFlight,
40
+ makeClientManifest,
41
+ registerClientComponents,
42
+ } from "./flight-tree.js";
43
+
44
+ const DEFAULT_URL = "http://localhost/";
45
+
46
+ /** A route handler under test: the `(ctx) => RSC | Response` function you pass to `path(...)`. */
47
+ export type TestableHandler<TEnv = any> = (
48
+ ctx: HandlerContext<any, TEnv>,
49
+ ) => ReactNode | Promise<ReactNode> | Response | Promise<Response>;
50
+
51
+ /** Options for {@link renderHandler}. */
52
+ export interface RenderHandlerOptions<TEnv = any> {
53
+ /** Route params surfaced as `ctx.params`. */
54
+ params?: Record<string, string>;
55
+ /** Environment bindings surfaced as `ctx.env`. */
56
+ env?: TEnv;
57
+ /** Backing Request (string or Request); defaults to a localhost GET. */
58
+ request?: Request | string;
59
+ /** Request headers (e.g. Cookie) the handler reads via `cookies()`. */
60
+ headers?: HeadersInit;
61
+ /** Variables a prior middleware set, read via `ctx.get(...)`. Object or tuples. */
62
+ vars?: VarsInit;
63
+ /** Matched route name (drives `ctx.routeName` and scoped reverse). */
64
+ routeName?: string;
65
+ /** Route name -> pattern map enabling `ctx.reverse()`. */
66
+ routeMap?: Record<string, string>;
67
+ /**
68
+ * Seed the data `ctx.use(SomeLoader)` returns — NO real loader runs (same model
69
+ * as `runLoader`'s `loaders`). Matched by loader reference, so a real
70
+ * `createLoader()` handle resolves regardless of its build-injected `$$id`.
71
+ */
72
+ loaders?: ReadonlyArray<readonly [LoaderDefinition<any, any>, unknown]>;
73
+ /**
74
+ * `"use client"` components in the handler's RSC, so they serialize as real
75
+ * boundaries when `rangoUseClientTransform()` is not wired. Keyed by name; see
76
+ * renderServerTree's `clientComponents`.
77
+ */
78
+ clientComponents?: Record<string, unknown>;
79
+ }
80
+
81
+ /** Result of {@link renderHandler}. */
82
+ export interface RenderHandlerResult {
83
+ /**
84
+ * The deserialized RSC the handler returned, as an inspectable React element
85
+ * tree — `undefined` when the handler returned or threw a `Response`. Use
86
+ * `findClientBoundaries` (from testing/flight) to locate client islands.
87
+ */
88
+ tree: unknown;
89
+ /** The raw Flight wire string; `undefined` when the handler produced a `Response`. */
90
+ flight: string | undefined;
91
+ /** The value the handler THREW (a `redirect()`/`notFound()` Response), captured not re-thrown. */
92
+ thrown: unknown;
93
+ /** The merged Response (status + headers + Set-Cookie); a thrown/returned redirect merged with accumulated effects. */
94
+ response: Response;
95
+ /** Effective cookie view after the handler ran, as `{ name: value }`. */
96
+ cookies: Record<string, string>;
97
+ /** Response headers as `{ name: value }` (excludes set-cookie; includes a redirect Location). */
98
+ headers: Record<string, string>;
99
+ /** Location state the handler set (`ctx.setLocationState`/`redirect({ state })`), as `{ key: value }`. */
100
+ locationState: Record<string, unknown>;
101
+ /** What the handler pushed via `ctx.use(Handle)(...)` (e.g. Meta, Breadcrumbs), keyed by handle. */
102
+ handles: Map<Handle<any, any>, unknown[]>;
103
+ }
104
+
105
+ /**
106
+ * A renderHandler MISCONFIGURATION (e.g. an unseeded loader) — distinct from a
107
+ * value the handler intentionally threw (a redirect). Setup errors REJECT;
108
+ * handler throws are captured on `result.thrown`.
109
+ */
110
+ class RenderHandlerSetupError extends Error {}
111
+
112
+ function headersToObject(headers: Headers): Record<string, string> {
113
+ const out: Record<string, string> = {};
114
+ headers.forEach((value, name) => {
115
+ if (name.toLowerCase() !== "set-cookie") out[name] = value;
116
+ });
117
+ return out;
118
+ }
119
+
120
+ function toRequest(
121
+ request: Request | string | undefined,
122
+ headers?: HeadersInit,
123
+ ): Request {
124
+ if (request instanceof Request) return request;
125
+ if (typeof request === "string") {
126
+ return new Request(new URL(request, DEFAULT_URL), { headers });
127
+ }
128
+ return new Request(DEFAULT_URL, { headers });
129
+ }
130
+
131
+ function buildResponse(reqCtx: RequestContext<any>, thrown: unknown): Response {
132
+ const stub = reqCtx.res;
133
+ if (thrown instanceof Response) {
134
+ const merged = new Headers(thrown.headers);
135
+ for (const cookie of stub.headers.getSetCookie()) {
136
+ merged.append("set-cookie", cookie);
137
+ }
138
+ stub.headers.forEach((value, name) => {
139
+ if (name.toLowerCase() === "set-cookie") return;
140
+ if (!merged.has(name)) merged.set(name, value);
141
+ });
142
+ return new Response(null, { status: thrown.status, headers: merged });
143
+ }
144
+ return new Response(null, { status: stub.status, headers: stub.headers });
145
+ }
146
+
147
+ /**
148
+ * Run a route handler with a seeded HandlerContext and return its rendered RSC
149
+ * (deserialized tree) plus the effects it produced. See the module header.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * // ProductPage is the real handler: (ctx) => <main>{ctx.params.slug}...</main>
154
+ * const { tree, handles } = await renderHandler(ProductPage, {
155
+ * params: { slug: "wine" },
156
+ * loaders: [[ProductLoader, { name: "Wine", price: 9 }]],
157
+ * vars: [[Tenant, tenant]],
158
+ * routeMap: { product: "/p/:slug" },
159
+ * });
160
+ * ```
161
+ */
162
+ export async function renderHandler<TEnv = any>(
163
+ handler: TestableHandler<TEnv>,
164
+ opts: RenderHandlerOptions<TEnv> = {},
165
+ ): Promise<RenderHandlerResult> {
166
+ if (opts.clientComponents) registerClientComponents(opts.clientComponents);
167
+ const request = toRequest(opts.request, opts.headers);
168
+ const url = new URL(request.url);
169
+ const reqCtx = createRequestContext<TEnv>({
170
+ env: (opts.env ?? {}) as TEnv,
171
+ request,
172
+ url,
173
+ variables: seedVariables({}, opts.vars),
174
+ });
175
+
176
+ const loaderSeeds = new Map<unknown, unknown>(opts.loaders ?? []);
177
+ const handlePushes = new Map<Handle<any, any>, unknown[]>();
178
+
179
+ let out: ReactNode | Response | undefined;
180
+ let flight: string | undefined;
181
+ let thrown: unknown;
182
+ let didThrow = false;
183
+
184
+ await runWithRequestContext(reqCtx as RequestContext<TEnv>, async () => {
185
+ setRequestContextParams(opts.params ?? {}, opts.routeName);
186
+ const hctx = createHandlerContext<TEnv>(
187
+ opts.params ?? {},
188
+ reqCtx.request,
189
+ reqCtx.searchParams,
190
+ reqCtx.pathname,
191
+ reqCtx.url,
192
+ reqCtx.env,
193
+ opts.routeMap ?? {},
194
+ opts.routeName,
195
+ );
196
+ // Seed ctx.use: a handle returns a push fn that RECORDS (so ctx.use(Meta)
197
+ // doesn't crash and pushes are assertable); a loader returns its seeded data
198
+ // (no real loader run).
199
+ (hctx as { use: unknown }).use = (item: unknown) => {
200
+ if (isHandle(item)) {
201
+ const handle = item as Handle<any, any>;
202
+ return (value: unknown) => {
203
+ const pushed = handlePushes.get(handle) ?? [];
204
+ pushed.push(value);
205
+ handlePushes.set(handle, pushed);
206
+ };
207
+ }
208
+ if (loaderSeeds.has(item)) return loaderSeeds.get(item);
209
+ throw new RenderHandlerSetupError(
210
+ `renderHandler: ctx.use(loader) was not seeded. Pass ` +
211
+ `{ loaders: [[YourLoader, data]] } for each loader the handler reads.`,
212
+ );
213
+ };
214
+ (hctx as { _currentSegmentId?: string })._currentSegmentId = "test.segment";
215
+
216
+ try {
217
+ out = await handler(hctx as HandlerContext<any, TEnv>);
218
+ // Serialize the RSC in THIS context, so nested async server components see
219
+ // getRequestContext()/cookies()/vars while they render.
220
+ if (out !== undefined && !(out instanceof Response)) {
221
+ flight = await serializeNodeToFlight(
222
+ out as ReactNode,
223
+ makeClientManifest(),
224
+ url.pathname,
225
+ );
226
+ }
227
+ } catch (error) {
228
+ // A harness misconfiguration (unseeded loader) is the consumer's mistake —
229
+ // surface it as a rejection, not as a captured handler throw.
230
+ if (error instanceof RenderHandlerSetupError) throw error;
231
+ // Otherwise captured, NOT re-thrown: a handler's success path is often
232
+ // `throw redirect(...)`; its cookies/flash must stay observable.
233
+ didThrow = true;
234
+ thrown = error;
235
+ }
236
+ });
237
+
238
+ const cookies = { ...reqCtx.cookies() };
239
+ const responseSource = didThrow
240
+ ? thrown
241
+ : out instanceof Response
242
+ ? out
243
+ : undefined;
244
+ const response = buildResponse(reqCtx as RequestContext<any>, responseSource);
245
+ const headers = headersToObject(response.headers);
246
+ const locationState = resolveLocationStateEntries(
247
+ (
248
+ reqCtx as {
249
+ _locationState?: Parameters<typeof resolveLocationStateEntries>[0];
250
+ }
251
+ )._locationState ?? [],
252
+ );
253
+ // Deserialize outside the context (the client deserializer needs no ctx).
254
+ const tree =
255
+ flight !== undefined ? await deserializeFlight(flight) : undefined;
256
+
257
+ return {
258
+ tree,
259
+ flight,
260
+ thrown,
261
+ response,
262
+ cookies,
263
+ headers,
264
+ locationState,
265
+ handles: handlePushes,
266
+ };
267
+ }