@rangojs/router 0.0.0-experimental.002d056c

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 (305) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +899 -0
  3. package/dist/bin/rango.js +1606 -0
  4. package/dist/vite/index.js +5153 -0
  5. package/package.json +177 -0
  6. package/skills/breadcrumbs/SKILL.md +250 -0
  7. package/skills/cache-guide/SKILL.md +262 -0
  8. package/skills/caching/SKILL.md +253 -0
  9. package/skills/composability/SKILL.md +172 -0
  10. package/skills/debug-manifest/SKILL.md +112 -0
  11. package/skills/document-cache/SKILL.md +182 -0
  12. package/skills/fonts/SKILL.md +167 -0
  13. package/skills/hooks/SKILL.md +704 -0
  14. package/skills/host-router/SKILL.md +218 -0
  15. package/skills/intercept/SKILL.md +313 -0
  16. package/skills/layout/SKILL.md +310 -0
  17. package/skills/links/SKILL.md +239 -0
  18. package/skills/loader/SKILL.md +596 -0
  19. package/skills/middleware/SKILL.md +339 -0
  20. package/skills/mime-routes/SKILL.md +128 -0
  21. package/skills/parallel/SKILL.md +305 -0
  22. package/skills/prerender/SKILL.md +643 -0
  23. package/skills/rango/SKILL.md +118 -0
  24. package/skills/response-routes/SKILL.md +411 -0
  25. package/skills/route/SKILL.md +385 -0
  26. package/skills/router-setup/SKILL.md +439 -0
  27. package/skills/tailwind/SKILL.md +129 -0
  28. package/skills/theme/SKILL.md +79 -0
  29. package/skills/typesafety/SKILL.md +623 -0
  30. package/skills/use-cache/SKILL.md +324 -0
  31. package/src/__internal.ts +273 -0
  32. package/src/bin/rango.ts +321 -0
  33. package/src/browser/action-coordinator.ts +97 -0
  34. package/src/browser/action-response-classifier.ts +99 -0
  35. package/src/browser/event-controller.ts +899 -0
  36. package/src/browser/history-state.ts +80 -0
  37. package/src/browser/index.ts +18 -0
  38. package/src/browser/intercept-utils.ts +52 -0
  39. package/src/browser/link-interceptor.ts +141 -0
  40. package/src/browser/logging.ts +55 -0
  41. package/src/browser/merge-segment-loaders.ts +134 -0
  42. package/src/browser/navigation-bridge.ts +638 -0
  43. package/src/browser/navigation-client.ts +261 -0
  44. package/src/browser/navigation-store.ts +806 -0
  45. package/src/browser/navigation-transaction.ts +297 -0
  46. package/src/browser/network-error-handler.ts +61 -0
  47. package/src/browser/partial-update.ts +582 -0
  48. package/src/browser/prefetch/cache.ts +206 -0
  49. package/src/browser/prefetch/fetch.ts +145 -0
  50. package/src/browser/prefetch/observer.ts +65 -0
  51. package/src/browser/prefetch/policy.ts +48 -0
  52. package/src/browser/prefetch/queue.ts +128 -0
  53. package/src/browser/rango-state.ts +112 -0
  54. package/src/browser/react/Link.tsx +368 -0
  55. package/src/browser/react/NavigationProvider.tsx +413 -0
  56. package/src/browser/react/ScrollRestoration.tsx +94 -0
  57. package/src/browser/react/context.ts +59 -0
  58. package/src/browser/react/filter-segment-order.ts +11 -0
  59. package/src/browser/react/index.ts +52 -0
  60. package/src/browser/react/location-state-shared.ts +162 -0
  61. package/src/browser/react/location-state.ts +107 -0
  62. package/src/browser/react/mount-context.ts +37 -0
  63. package/src/browser/react/nonce-context.ts +23 -0
  64. package/src/browser/react/shallow-equal.ts +27 -0
  65. package/src/browser/react/use-action.ts +218 -0
  66. package/src/browser/react/use-client-cache.ts +58 -0
  67. package/src/browser/react/use-handle.ts +162 -0
  68. package/src/browser/react/use-href.tsx +40 -0
  69. package/src/browser/react/use-link-status.ts +135 -0
  70. package/src/browser/react/use-mount.ts +31 -0
  71. package/src/browser/react/use-navigation.ts +99 -0
  72. package/src/browser/react/use-params.ts +65 -0
  73. package/src/browser/react/use-pathname.ts +47 -0
  74. package/src/browser/react/use-router.ts +63 -0
  75. package/src/browser/react/use-search-params.ts +56 -0
  76. package/src/browser/react/use-segments.ts +171 -0
  77. package/src/browser/response-adapter.ts +73 -0
  78. package/src/browser/rsc-router.tsx +464 -0
  79. package/src/browser/scroll-restoration.ts +397 -0
  80. package/src/browser/segment-reconciler.ts +216 -0
  81. package/src/browser/segment-structure-assert.ts +83 -0
  82. package/src/browser/server-action-bridge.ts +667 -0
  83. package/src/browser/shallow.ts +40 -0
  84. package/src/browser/types.ts +547 -0
  85. package/src/browser/validate-redirect-origin.ts +29 -0
  86. package/src/build/generate-manifest.ts +438 -0
  87. package/src/build/generate-route-types.ts +36 -0
  88. package/src/build/index.ts +35 -0
  89. package/src/build/route-trie.ts +265 -0
  90. package/src/build/route-types/ast-helpers.ts +25 -0
  91. package/src/build/route-types/ast-route-extraction.ts +98 -0
  92. package/src/build/route-types/codegen.ts +102 -0
  93. package/src/build/route-types/include-resolution.ts +411 -0
  94. package/src/build/route-types/param-extraction.ts +48 -0
  95. package/src/build/route-types/per-module-writer.ts +128 -0
  96. package/src/build/route-types/router-processing.ts +479 -0
  97. package/src/build/route-types/scan-filter.ts +78 -0
  98. package/src/build/runtime-discovery.ts +231 -0
  99. package/src/cache/background-task.ts +34 -0
  100. package/src/cache/cache-key-utils.ts +44 -0
  101. package/src/cache/cache-policy.ts +125 -0
  102. package/src/cache/cache-runtime.ts +338 -0
  103. package/src/cache/cache-scope.ts +382 -0
  104. package/src/cache/cf/cf-cache-store.ts +982 -0
  105. package/src/cache/cf/index.ts +29 -0
  106. package/src/cache/document-cache.ts +369 -0
  107. package/src/cache/handle-capture.ts +81 -0
  108. package/src/cache/handle-snapshot.ts +41 -0
  109. package/src/cache/index.ts +44 -0
  110. package/src/cache/memory-segment-store.ts +328 -0
  111. package/src/cache/profile-registry.ts +73 -0
  112. package/src/cache/read-through-swr.ts +134 -0
  113. package/src/cache/segment-codec.ts +256 -0
  114. package/src/cache/taint.ts +98 -0
  115. package/src/cache/types.ts +342 -0
  116. package/src/client.rsc.tsx +85 -0
  117. package/src/client.tsx +601 -0
  118. package/src/component-utils.ts +76 -0
  119. package/src/components/DefaultDocument.tsx +27 -0
  120. package/src/context-var.ts +86 -0
  121. package/src/debug.ts +243 -0
  122. package/src/default-error-boundary.tsx +88 -0
  123. package/src/deps/browser.ts +8 -0
  124. package/src/deps/html-stream-client.ts +2 -0
  125. package/src/deps/html-stream-server.ts +2 -0
  126. package/src/deps/rsc.ts +10 -0
  127. package/src/deps/ssr.ts +2 -0
  128. package/src/errors.ts +365 -0
  129. package/src/handle.ts +135 -0
  130. package/src/handles/MetaTags.tsx +246 -0
  131. package/src/handles/breadcrumbs.ts +66 -0
  132. package/src/handles/index.ts +7 -0
  133. package/src/handles/meta.ts +264 -0
  134. package/src/host/cookie-handler.ts +165 -0
  135. package/src/host/errors.ts +97 -0
  136. package/src/host/index.ts +53 -0
  137. package/src/host/pattern-matcher.ts +214 -0
  138. package/src/host/router.ts +352 -0
  139. package/src/host/testing.ts +79 -0
  140. package/src/host/types.ts +146 -0
  141. package/src/host/utils.ts +25 -0
  142. package/src/href-client.ts +222 -0
  143. package/src/index.rsc.ts +233 -0
  144. package/src/index.ts +277 -0
  145. package/src/internal-debug.ts +11 -0
  146. package/src/loader.rsc.ts +89 -0
  147. package/src/loader.ts +64 -0
  148. package/src/network-error-thrower.tsx +23 -0
  149. package/src/outlet-context.ts +15 -0
  150. package/src/outlet-provider.tsx +45 -0
  151. package/src/prerender/param-hash.ts +37 -0
  152. package/src/prerender/store.ts +185 -0
  153. package/src/prerender.ts +463 -0
  154. package/src/reverse.ts +330 -0
  155. package/src/root-error-boundary.tsx +289 -0
  156. package/src/route-content-wrapper.tsx +196 -0
  157. package/src/route-definition/dsl-helpers.ts +934 -0
  158. package/src/route-definition/helper-factories.ts +200 -0
  159. package/src/route-definition/helpers-types.ts +430 -0
  160. package/src/route-definition/index.ts +52 -0
  161. package/src/route-definition/redirect.ts +93 -0
  162. package/src/route-definition.ts +1 -0
  163. package/src/route-map-builder.ts +281 -0
  164. package/src/route-name.ts +53 -0
  165. package/src/route-types.ts +259 -0
  166. package/src/router/content-negotiation.ts +116 -0
  167. package/src/router/debug-manifest.ts +72 -0
  168. package/src/router/error-handling.ts +287 -0
  169. package/src/router/find-match.ts +160 -0
  170. package/src/router/handler-context.ts +451 -0
  171. package/src/router/intercept-resolution.ts +397 -0
  172. package/src/router/lazy-includes.ts +236 -0
  173. package/src/router/loader-resolution.ts +420 -0
  174. package/src/router/logging.ts +251 -0
  175. package/src/router/manifest.ts +269 -0
  176. package/src/router/match-api.ts +620 -0
  177. package/src/router/match-context.ts +266 -0
  178. package/src/router/match-handlers.ts +440 -0
  179. package/src/router/match-middleware/background-revalidation.ts +223 -0
  180. package/src/router/match-middleware/cache-lookup.ts +634 -0
  181. package/src/router/match-middleware/cache-store.ts +295 -0
  182. package/src/router/match-middleware/index.ts +81 -0
  183. package/src/router/match-middleware/intercept-resolution.ts +306 -0
  184. package/src/router/match-middleware/segment-resolution.ts +193 -0
  185. package/src/router/match-pipelines.ts +179 -0
  186. package/src/router/match-result.ts +219 -0
  187. package/src/router/metrics.ts +282 -0
  188. package/src/router/middleware-cookies.ts +55 -0
  189. package/src/router/middleware-types.ts +222 -0
  190. package/src/router/middleware.ts +749 -0
  191. package/src/router/pattern-matching.ts +563 -0
  192. package/src/router/prerender-match.ts +402 -0
  193. package/src/router/preview-match.ts +170 -0
  194. package/src/router/revalidation.ts +289 -0
  195. package/src/router/router-context.ts +320 -0
  196. package/src/router/router-interfaces.ts +452 -0
  197. package/src/router/router-options.ts +592 -0
  198. package/src/router/router-registry.ts +24 -0
  199. package/src/router/segment-resolution/fresh.ts +570 -0
  200. package/src/router/segment-resolution/helpers.ts +263 -0
  201. package/src/router/segment-resolution/loader-cache.ts +198 -0
  202. package/src/router/segment-resolution/revalidation.ts +1242 -0
  203. package/src/router/segment-resolution/static-store.ts +67 -0
  204. package/src/router/segment-resolution.ts +21 -0
  205. package/src/router/segment-wrappers.ts +291 -0
  206. package/src/router/telemetry-otel.ts +299 -0
  207. package/src/router/telemetry.ts +300 -0
  208. package/src/router/timeout.ts +148 -0
  209. package/src/router/trie-matching.ts +239 -0
  210. package/src/router/types.ts +170 -0
  211. package/src/router.ts +1006 -0
  212. package/src/rsc/handler-context.ts +45 -0
  213. package/src/rsc/handler.ts +1089 -0
  214. package/src/rsc/helpers.ts +198 -0
  215. package/src/rsc/index.ts +36 -0
  216. package/src/rsc/loader-fetch.ts +209 -0
  217. package/src/rsc/manifest-init.ts +86 -0
  218. package/src/rsc/nonce.ts +32 -0
  219. package/src/rsc/origin-guard.ts +141 -0
  220. package/src/rsc/progressive-enhancement.ts +379 -0
  221. package/src/rsc/response-error.ts +37 -0
  222. package/src/rsc/response-route-handler.ts +347 -0
  223. package/src/rsc/rsc-rendering.ts +237 -0
  224. package/src/rsc/runtime-warnings.ts +42 -0
  225. package/src/rsc/server-action.ts +348 -0
  226. package/src/rsc/ssr-setup.ts +128 -0
  227. package/src/rsc/types.ts +263 -0
  228. package/src/search-params.ts +230 -0
  229. package/src/segment-system.tsx +454 -0
  230. package/src/server/context.ts +591 -0
  231. package/src/server/cookie-store.ts +190 -0
  232. package/src/server/fetchable-loader-store.ts +37 -0
  233. package/src/server/handle-store.ts +308 -0
  234. package/src/server/loader-registry.ts +133 -0
  235. package/src/server/request-context.ts +920 -0
  236. package/src/server/root-layout.tsx +10 -0
  237. package/src/server/tsconfig.json +14 -0
  238. package/src/server.ts +51 -0
  239. package/src/ssr/index.tsx +365 -0
  240. package/src/static-handler.ts +114 -0
  241. package/src/theme/ThemeProvider.tsx +297 -0
  242. package/src/theme/ThemeScript.tsx +61 -0
  243. package/src/theme/constants.ts +62 -0
  244. package/src/theme/index.ts +48 -0
  245. package/src/theme/theme-context.ts +44 -0
  246. package/src/theme/theme-script.ts +155 -0
  247. package/src/theme/types.ts +182 -0
  248. package/src/theme/use-theme.ts +44 -0
  249. package/src/types/boundaries.ts +158 -0
  250. package/src/types/cache-types.ts +198 -0
  251. package/src/types/error-types.ts +192 -0
  252. package/src/types/global-namespace.ts +100 -0
  253. package/src/types/handler-context.ts +687 -0
  254. package/src/types/index.ts +88 -0
  255. package/src/types/loader-types.ts +183 -0
  256. package/src/types/route-config.ts +170 -0
  257. package/src/types/route-entry.ts +109 -0
  258. package/src/types/segments.ts +148 -0
  259. package/src/types.ts +1 -0
  260. package/src/urls/include-helper.ts +197 -0
  261. package/src/urls/index.ts +53 -0
  262. package/src/urls/path-helper-types.ts +339 -0
  263. package/src/urls/path-helper.ts +329 -0
  264. package/src/urls/pattern-types.ts +95 -0
  265. package/src/urls/response-types.ts +106 -0
  266. package/src/urls/type-extraction.ts +372 -0
  267. package/src/urls/urls-function.ts +98 -0
  268. package/src/urls.ts +1 -0
  269. package/src/use-loader.tsx +354 -0
  270. package/src/vite/discovery/bundle-postprocess.ts +184 -0
  271. package/src/vite/discovery/discover-routers.ts +344 -0
  272. package/src/vite/discovery/prerender-collection.ts +385 -0
  273. package/src/vite/discovery/route-types-writer.ts +258 -0
  274. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  275. package/src/vite/discovery/state.ts +108 -0
  276. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  277. package/src/vite/index.ts +16 -0
  278. package/src/vite/plugin-types.ts +48 -0
  279. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  280. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  281. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  282. package/src/vite/plugins/expose-action-id.ts +363 -0
  283. package/src/vite/plugins/expose-id-utils.ts +287 -0
  284. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  285. package/src/vite/plugins/expose-ids/handler-transform.ts +179 -0
  286. package/src/vite/plugins/expose-ids/loader-transform.ts +74 -0
  287. package/src/vite/plugins/expose-ids/router-transform.ts +110 -0
  288. package/src/vite/plugins/expose-ids/types.ts +45 -0
  289. package/src/vite/plugins/expose-internal-ids.ts +569 -0
  290. package/src/vite/plugins/refresh-cmd.ts +65 -0
  291. package/src/vite/plugins/use-cache-transform.ts +323 -0
  292. package/src/vite/plugins/version-injector.ts +83 -0
  293. package/src/vite/plugins/version-plugin.ts +266 -0
  294. package/src/vite/plugins/version.d.ts +12 -0
  295. package/src/vite/plugins/virtual-entries.ts +123 -0
  296. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  297. package/src/vite/rango.ts +445 -0
  298. package/src/vite/router-discovery.ts +777 -0
  299. package/src/vite/utils/ast-handler-extract.ts +517 -0
  300. package/src/vite/utils/banner.ts +36 -0
  301. package/src/vite/utils/bundle-analysis.ts +137 -0
  302. package/src/vite/utils/manifest-utils.ts +70 -0
  303. package/src/vite/utils/package-resolution.ts +121 -0
  304. package/src/vite/utils/prerender-utils.ts +189 -0
  305. package/src/vite/utils/shared-utils.ts +169 -0
@@ -0,0 +1,920 @@
1
+ /**
2
+ * Request Context - AsyncLocalStorage for passing request-scoped data throughout rendering
3
+ *
4
+ * This is the unified context used everywhere:
5
+ * - Middleware execution
6
+ * - Route handlers and loaders
7
+ * - Server components during rendering
8
+ * - Error boundaries and streaming
9
+ *
10
+ * Available via getRequestContext() anywhere in the request lifecycle.
11
+ */
12
+
13
+ import { AsyncLocalStorage } from "node:async_hooks";
14
+ import type { CookieOptions } from "../router/middleware.js";
15
+ import type { LoaderDefinition, LoaderContext } from "../types.js";
16
+ import type { ScopedReverseFunction } from "../reverse.js";
17
+ import type {
18
+ DefaultEnv,
19
+ DefaultReverseRouteMap,
20
+ DefaultRouteName,
21
+ } from "../types/global-namespace.js";
22
+ import type { Handle } from "../handle.js";
23
+ import { type ContextVar, contextGet, contextSet } from "../context-var.js";
24
+ import { createHandleStore, type HandleStore } from "./handle-store.js";
25
+ import { isHandle } from "../handle.js";
26
+ import { track, type MetricsStore } from "./context.js";
27
+ import { getFetchableLoader } from "./fetchable-loader-store.js";
28
+ import type { SegmentCacheStore } from "../cache/types.js";
29
+ import type { Theme, ResolvedThemeConfig } from "../theme/types.js";
30
+ import { THEME_COOKIE } from "../theme/constants.js";
31
+ import type { LocationStateEntry } from "../browser/react/location-state-shared.js";
32
+ import { NOCACHE_SYMBOL, assertNotInsideCacheExec } from "../cache/taint.js";
33
+ import {
34
+ createReverseFunction,
35
+ stripInternalParams,
36
+ } from "../router/handler-context.js";
37
+ import { getGlobalRouteMap, isRouteRootScoped } from "../route-map-builder.js";
38
+ import { invariant } from "../errors.js";
39
+ import { isAutoGeneratedRouteName } from "../route-name.js";
40
+
41
+ /**
42
+ * Unified request context available via getRequestContext()
43
+ *
44
+ * This is the same context passed to middleware and handlers.
45
+ * Use this when you need access to request data outside of route handlers.
46
+ */
47
+ export interface RequestContext<
48
+ TEnv = DefaultEnv,
49
+ TParams = Record<string, string>,
50
+ > {
51
+ /** Platform bindings (Cloudflare env, etc.) */
52
+ env: TEnv;
53
+ /** Original HTTP request */
54
+ request: Request;
55
+ /** Parsed URL (with internal `_rsc*` params stripped) */
56
+ url: URL;
57
+ /**
58
+ * The original request URL with all parameters intact, including
59
+ * internal `_rsc*` transport params.
60
+ */
61
+ originalUrl: URL;
62
+ /** URL pathname */
63
+ pathname: string;
64
+ /** URL search params (with internal `_rsc*` params stripped, same as `url.searchParams`) */
65
+ searchParams: URLSearchParams;
66
+ /** Variables set by middleware (same as ctx.var) */
67
+ var: Record<string, any>;
68
+ /** Get a variable set by middleware */
69
+ get: {
70
+ <T>(contextVar: ContextVar<T>): T | undefined;
71
+ <K extends string>(key: K): any;
72
+ };
73
+ /** Set a variable (shared with middleware and handlers) */
74
+ set: {
75
+ <T>(contextVar: ContextVar<T>, value: T): void;
76
+ <K extends string>(key: K, value: any): void;
77
+ };
78
+ /**
79
+ * Route params (populated after route matching)
80
+ * Initially empty, then set to matched params
81
+ */
82
+ params: TParams;
83
+ /** @internal Stub response for collecting headers/cookies. Use ctx.headers or ctx.header() instead. */
84
+ readonly res: Response;
85
+
86
+ /** @internal Get a cookie value (effective: request + response mutations). Use cookies().get() instead. */
87
+ cookie(name: string): string | undefined;
88
+ /** @internal Get all cookies (effective merged view). Use cookies().getAll() instead. */
89
+ cookies(): Record<string, string>;
90
+ /** @internal Set a cookie on the response. Use cookies().set() instead. */
91
+ setCookie(name: string, value: string, options?: CookieOptions): void;
92
+ /** @internal Delete a cookie. Use cookies().delete() instead. */
93
+ deleteCookie(
94
+ name: string,
95
+ options?: Pick<CookieOptions, "domain" | "path">,
96
+ ): void;
97
+ /** Set a response header */
98
+ header(name: string, value: string): void;
99
+ /** Set the response status code */
100
+ setStatus(status: number): void;
101
+ /** @internal Set status bypassing cache-exec guard (for framework error handling) */
102
+ _setStatus(status: number): void;
103
+
104
+ /**
105
+ * Access loader data or push handle data.
106
+ *
107
+ * For loaders: Returns a promise that resolves to the loader data.
108
+ * Loaders are executed in parallel and memoized per request.
109
+ *
110
+ * For handles: Returns a push function to add data for this segment.
111
+ * Handle data accumulates across all matched route segments.
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * // Loader usage
116
+ * const cart = await ctx.use(CartLoader);
117
+ *
118
+ * // Handle usage
119
+ * const push = ctx.use(Breadcrumbs);
120
+ * push({ label: "Shop", href: "/shop" });
121
+ * ```
122
+ */
123
+ use: {
124
+ <T, TLoaderParams = any>(
125
+ loader: LoaderDefinition<T, TLoaderParams>,
126
+ ): Promise<T>;
127
+ <TData, TAccumulated = TData[]>(
128
+ handle: Handle<TData, TAccumulated>,
129
+ ): (data: TData | Promise<TData> | (() => Promise<TData>)) => void;
130
+ };
131
+
132
+ /** HTTP method (GET, POST, PUT, PATCH, DELETE, etc.) */
133
+ method: string;
134
+
135
+ /** @internal Handle store for tracking handle data across segments */
136
+ _handleStore: HandleStore;
137
+
138
+ /** @internal Cache store for segment caching (optional, used by CacheScope) */
139
+ _cacheStore?: SegmentCacheStore;
140
+
141
+ /** @internal Cache profiles for "use cache" profile resolution (per-router) */
142
+ _cacheProfiles?: Record<
143
+ string,
144
+ import("../cache/profile-registry.js").CacheProfile
145
+ >;
146
+
147
+ /**
148
+ * Schedule work to run after the response is sent.
149
+ * On Cloudflare Workers, uses ctx.waitUntil().
150
+ * On Node.js, runs as fire-and-forget.
151
+ *
152
+ * @example
153
+ * ```typescript
154
+ * ctx.waitUntil(async () => {
155
+ * await cacheStore.set(key, data, ttl);
156
+ * });
157
+ * ```
158
+ */
159
+ waitUntil(fn: () => Promise<void>): void;
160
+
161
+ /**
162
+ * Register a callback to run when the response is created.
163
+ * Callbacks are sync and receive the response. They can:
164
+ * - Inspect response status/headers
165
+ * - Return a modified response
166
+ * - Schedule async work via waitUntil
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * ctx.onResponse((res) => {
171
+ * if (res.status === 200) {
172
+ * ctx.waitUntil(async () => await cacheIt());
173
+ * }
174
+ * return res;
175
+ * });
176
+ * ```
177
+ */
178
+ onResponse(callback: (response: Response) => Response): void;
179
+
180
+ /** @internal Registered onResponse callbacks */
181
+ _onResponseCallbacks: Array<(response: Response) => Response>;
182
+
183
+ /**
184
+ * Current theme setting (only available when theme is enabled in router config)
185
+ *
186
+ * Returns the theme value from the cookie, or the default theme if not set.
187
+ * This is the user's preference ("light", "dark", or "system"), not the resolved value.
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * route("settings", (ctx) => {
192
+ * const currentTheme = ctx.theme; // "light" | "dark" | "system" | undefined
193
+ * return <SettingsPage theme={currentTheme} />;
194
+ * });
195
+ * ```
196
+ */
197
+ theme?: Theme;
198
+
199
+ /**
200
+ * Set the theme (only available when theme is enabled in router config)
201
+ *
202
+ * Sets a cookie with the new theme value. The change takes effect on the next request.
203
+ *
204
+ * @example
205
+ * ```typescript
206
+ * route("settings", (ctx) => {
207
+ * if (ctx.method === "POST") {
208
+ * const formData = await ctx.request.formData();
209
+ * const newTheme = formData.get("theme") as Theme;
210
+ * ctx.setTheme(newTheme);
211
+ * }
212
+ * return <SettingsPage />;
213
+ * });
214
+ * ```
215
+ */
216
+ setTheme?: (theme: Theme) => void;
217
+
218
+ /** @internal Theme configuration (null if theme not enabled) */
219
+ _themeConfig?: ResolvedThemeConfig | null;
220
+
221
+ /**
222
+ * Attach location state entries to the current response.
223
+ *
224
+ * For partial (SPA) requests, the state is included in the RSC payload
225
+ * metadata and merged into history.pushState on the client. For redirect
226
+ * responses, the state travels through the redirect payload so the target
227
+ * page can read it via useLocationState.
228
+ *
229
+ * Multiple calls accumulate entries.
230
+ *
231
+ * @example
232
+ * ```typescript
233
+ * ctx.setLocationState(Flash({ text: "Item saved!" }));
234
+ * ```
235
+ */
236
+ setLocationState(entries: LocationStateEntry | LocationStateEntry[]): void;
237
+
238
+ /** @internal Accumulated location state entries */
239
+ _locationState?: LocationStateEntry[];
240
+
241
+ /**
242
+ * The matched route name, if the route has an explicit name.
243
+ * Undefined before route matching or for unnamed routes.
244
+ * Includes the namespace prefix from include() (e.g., "blog.post").
245
+ */
246
+ routeName?: DefaultRouteName;
247
+
248
+ /**
249
+ * Generate URLs from route names.
250
+ * Uses the global route map. After route matching, scoped (`.name`) resolution
251
+ * works within the matched include() scope.
252
+ */
253
+ reverse: ScopedReverseFunction<
254
+ Record<string, string>,
255
+ DefaultReverseRouteMap
256
+ >;
257
+
258
+ /** @internal Route name from route matching, used for scoped reverse resolution */
259
+ _routeName?: string;
260
+
261
+ /** @internal Previous route key (from the navigation source), used for revalidation */
262
+ _prevRouteKey?: string;
263
+
264
+ /** @internal Per-request error dedup set for onError reporting */
265
+ _reportedErrors: WeakSet<object>;
266
+
267
+ /**
268
+ * @internal Report a non-fatal background error through the router's
269
+ * onError callback. Wired by the RSC handler / router during request
270
+ * creation. Cache-runtime and other subsystems call this to surface
271
+ * errors without failing the response.
272
+ */
273
+ _reportBackgroundError?: (error: unknown, category: string) => void;
274
+
275
+ /** @internal Per-request debug performance override (set via ctx.debugPerformance()) */
276
+ _debugPerformance?: boolean;
277
+
278
+ /** @internal Request-scoped performance metrics store */
279
+ _metricsStore?: MetricsStore;
280
+ }
281
+
282
+ /**
283
+ * Public view of RequestContext, without internal methods and fields.
284
+ *
285
+ * This is the type exported to library consumers. Internal code should
286
+ * use the full RequestContext interface directly.
287
+ */
288
+ export type PublicRequestContext<
289
+ TEnv = DefaultEnv,
290
+ TParams = Record<string, string>,
291
+ > = Omit<
292
+ RequestContext<TEnv, TParams>,
293
+ | "cookie"
294
+ | "cookies"
295
+ | "setCookie"
296
+ | "deleteCookie"
297
+ | "_handleStore"
298
+ | "_cacheStore"
299
+ | "_cacheProfiles"
300
+ | "_onResponseCallbacks"
301
+ | "_themeConfig"
302
+ | "_locationState"
303
+ | "_routeName"
304
+ | "_prevRouteKey"
305
+ | "_reportedErrors"
306
+ | "_reportBackgroundError"
307
+ | "_debugPerformance"
308
+ | "_metricsStore"
309
+ | "_setStatus"
310
+ | "res"
311
+ >;
312
+
313
+ // AsyncLocalStorage instance for request context
314
+ const requestContextStorage = new AsyncLocalStorage<RequestContext<any>>();
315
+
316
+ /**
317
+ * Run a function within a request context
318
+ * Used by the RSC handler to provide context to server actions
319
+ */
320
+ export function runWithRequestContext<TEnv, T>(
321
+ context: RequestContext<TEnv>,
322
+ fn: () => T,
323
+ ): T {
324
+ return requestContextStorage.run(context, fn);
325
+ }
326
+
327
+ /**
328
+ * Get the current request context
329
+ * Throws if called outside of a request context
330
+ */
331
+ export function getRequestContext<TEnv = DefaultEnv>(): RequestContext<TEnv> {
332
+ const ctx = requestContextStorage.getStore() as
333
+ | RequestContext<TEnv>
334
+ | undefined;
335
+ invariant(
336
+ ctx,
337
+ "getRequestContext() called outside of a request context. " +
338
+ "This function must be called from within a route handler, loader, middleware, " +
339
+ "server action, or server component.",
340
+ );
341
+ return ctx;
342
+ }
343
+
344
+ /**
345
+ * @internal Get the request context without throwing — for internal code that
346
+ * may run outside a request context (cache stores, optional handle lookups, etc.)
347
+ */
348
+ export function _getRequestContext<TEnv = DefaultEnv>():
349
+ | RequestContext<TEnv>
350
+ | undefined {
351
+ return requestContextStorage.getStore() as RequestContext<TEnv> | undefined;
352
+ }
353
+
354
+ /**
355
+ * Update params on the current request context
356
+ * Called after route matching to populate route params and route name
357
+ */
358
+ export function setRequestContextParams(
359
+ params: Record<string, string>,
360
+ routeName?: string,
361
+ ): void {
362
+ const ctx = requestContextStorage.getStore();
363
+ if (ctx) {
364
+ ctx.params = params;
365
+ if (routeName !== undefined) {
366
+ ctx._routeName = routeName;
367
+ ctx.routeName = (
368
+ routeName && !isAutoGeneratedRouteName(routeName)
369
+ ? routeName
370
+ : undefined
371
+ ) as DefaultRouteName | undefined;
372
+ }
373
+ // Update reverse with scoped resolution now that route is known
374
+ ctx.reverse = createReverseFunction(
375
+ getGlobalRouteMap(),
376
+ routeName,
377
+ params,
378
+ routeName ? isRouteRootScoped(routeName) : undefined,
379
+ );
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Store the previous route key on the request context.
385
+ * Called during partial-match context creation to make the navigation source
386
+ * route key available for revalidation and intercept evaluation.
387
+ * @internal
388
+ */
389
+ export function setRequestContextPrevRouteKey(
390
+ prevRouteKey: string | undefined,
391
+ ): void {
392
+ const ctx = requestContextStorage.getStore();
393
+ if (ctx && prevRouteKey !== undefined) {
394
+ ctx._prevRouteKey = prevRouteKey;
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Get accumulated location state entries from the current request context.
400
+ * Returns undefined if no state has been set.
401
+ *
402
+ * @internal Used by the RSC handler to include state in payload metadata.
403
+ */
404
+ export function getLocationState(): LocationStateEntry[] | undefined {
405
+ const ctx = getRequestContext();
406
+ return ctx?._locationState;
407
+ }
408
+
409
+ /**
410
+ * Get the current request context, throwing if not available
411
+ * @deprecated Use getRequestContext() directly — it now throws if outside context
412
+ */
413
+ export function requireRequestContext<
414
+ TEnv = DefaultEnv,
415
+ >(): RequestContext<TEnv> {
416
+ return getRequestContext<TEnv>();
417
+ }
418
+
419
+ /**
420
+ * Cloudflare Workers ExecutionContext (subset we need)
421
+ */
422
+ export interface ExecutionContext {
423
+ waitUntil(promise: Promise<any>): void;
424
+ passThroughOnException(): void;
425
+ }
426
+
427
+ /**
428
+ * Options for creating a request context
429
+ */
430
+ export interface CreateRequestContextOptions<TEnv> {
431
+ env: TEnv;
432
+ request: Request;
433
+ url: URL;
434
+ variables: Record<string, any>;
435
+ /** Optional initial response stub headers/status to seed effective cookie reads */
436
+ initialResponse?: Response;
437
+ /** Optional cache store for segment caching (used by CacheScope) */
438
+ cacheStore?: SegmentCacheStore;
439
+ /** Optional cache profiles for "use cache" resolution (per-router) */
440
+ cacheProfiles?: Record<
441
+ string,
442
+ import("../cache/profile-registry.js").CacheProfile
443
+ >;
444
+ /** Optional Cloudflare execution context for waitUntil support */
445
+ executionContext?: ExecutionContext;
446
+ /** Optional theme configuration (enables ctx.theme and ctx.setTheme) */
447
+ themeConfig?: ResolvedThemeConfig | null;
448
+ }
449
+
450
+ /**
451
+ * Create a full request context with all methods implemented
452
+ *
453
+ * This is used by the RSC handler to create the unified context that's:
454
+ * - Available via getRequestContext() throughout the request
455
+ * - Passed to middleware as ctx
456
+ * - Passed to handlers as ctx
457
+ */
458
+ export function createRequestContext<TEnv>(
459
+ options: CreateRequestContextOptions<TEnv>,
460
+ ): RequestContext<TEnv> {
461
+ const {
462
+ env,
463
+ request,
464
+ url,
465
+ variables,
466
+ initialResponse,
467
+ cacheStore,
468
+ cacheProfiles,
469
+ executionContext,
470
+ themeConfig,
471
+ } = options;
472
+ const cookieHeader = request.headers.get("Cookie");
473
+ let parsedCookies: Record<string, string> | null = null;
474
+
475
+ // Create stub response for collecting headers/cookies.
476
+ // All cookie/header mutations go here; cookie reads derive from it.
477
+ let stubResponse = initialResponse
478
+ ? new Response(null, {
479
+ status: initialResponse.status,
480
+ statusText: initialResponse.statusText,
481
+ headers: new Headers(initialResponse.headers),
482
+ })
483
+ : new Response(null, { status: 200 });
484
+
485
+ // Create handle store and loader memoization for this request
486
+ const handleStore = createHandleStore();
487
+ const loaderPromises = new Map<string, Promise<any>>();
488
+
489
+ // Lazy parse cookies from the original Cookie header
490
+ const getParsedCookies = (): Record<string, string> => {
491
+ if (!parsedCookies) {
492
+ parsedCookies = parseCookiesFromHeader(cookieHeader);
493
+ }
494
+ return parsedCookies;
495
+ };
496
+
497
+ // Cached response cookie mutations — invalidated on setCookie/deleteCookie/setTheme
498
+ let responseCookieCache: Map<string, string | null> | null = null;
499
+ const getResponseCookies = (): Map<string, string | null> => {
500
+ if (!responseCookieCache) {
501
+ responseCookieCache = parseResponseCookies(stubResponse);
502
+ }
503
+ return responseCookieCache;
504
+ };
505
+ const invalidateResponseCookieCache = () => {
506
+ responseCookieCache = null;
507
+ };
508
+
509
+ // Effective cookie read: response stub Set-Cookie wins, then original header.
510
+ // The stub IS the source of truth for same-request mutations.
511
+ const effectiveCookie = (name: string): string | undefined => {
512
+ const mutations = getResponseCookies();
513
+ if (mutations.has(name)) {
514
+ const v = mutations.get(name);
515
+ return v === null ? undefined : v;
516
+ }
517
+ return getParsedCookies()[name];
518
+ };
519
+
520
+ // Theme helpers (only used when themeConfig is provided)
521
+ const getTheme = (): Theme | undefined => {
522
+ if (!themeConfig) return undefined;
523
+
524
+ // Use overlay-aware read so setTheme() in the same request is reflected
525
+ const stored = effectiveCookie(themeConfig.storageKey);
526
+ if (stored) {
527
+ // Validate stored value
528
+ if (stored === "system" && themeConfig.enableSystem) {
529
+ return "system";
530
+ }
531
+ if (themeConfig.themes.includes(stored)) {
532
+ return stored as Theme;
533
+ }
534
+ }
535
+ return themeConfig.defaultTheme;
536
+ };
537
+
538
+ const setTheme = (theme: Theme): void => {
539
+ if (!themeConfig) return;
540
+
541
+ // Validate theme value
542
+ if (theme !== "system" && !themeConfig.themes.includes(theme)) {
543
+ console.warn(
544
+ `[Theme] Invalid theme value: "${theme}". Valid values: system, ${themeConfig.themes.join(", ")}`,
545
+ );
546
+ return;
547
+ }
548
+
549
+ // Write to stub — effectiveCookie() will pick it up on next read
550
+ stubResponse.headers.append(
551
+ "Set-Cookie",
552
+ serializeCookieValue(themeConfig.storageKey, theme, {
553
+ path: THEME_COOKIE.path,
554
+ maxAge: THEME_COOKIE.maxAge,
555
+ sameSite: THEME_COOKIE.sameSite,
556
+ }),
557
+ );
558
+ invalidateResponseCookieCache();
559
+ };
560
+
561
+ // Strip internal _rsc* params so userland sees a clean URL.
562
+ const cleanUrl = stripInternalParams(url);
563
+
564
+ // Build the context object first (without use), then add use
565
+ const ctx: RequestContext<TEnv> = {
566
+ env,
567
+ request,
568
+ url: cleanUrl,
569
+ originalUrl: new URL(request.url),
570
+ pathname: url.pathname,
571
+ searchParams: cleanUrl.searchParams,
572
+ var: variables,
573
+ get: ((keyOrVar: any) =>
574
+ contextGet(variables, keyOrVar)) as RequestContext<TEnv>["get"],
575
+ set: ((keyOrVar: any, value: any) => {
576
+ assertNotInsideCacheExec(ctx, "set");
577
+ contextSet(variables, keyOrVar, value);
578
+ }) as RequestContext<TEnv>["set"],
579
+ params: {} as Record<string, string>,
580
+
581
+ get res(): Response {
582
+ return stubResponse;
583
+ },
584
+ set res(_: Response) {
585
+ throw new Error(
586
+ "ctx.res is read-only. Use ctx.header() to set response headers, or cookies() for cookie mutations.",
587
+ );
588
+ },
589
+
590
+ cookie(name: string): string | undefined {
591
+ return effectiveCookie(name);
592
+ },
593
+
594
+ cookies(): Record<string, string> {
595
+ const parsed = getParsedCookies();
596
+ const mutations = getResponseCookies();
597
+ if (mutations.size === 0) return { ...parsed };
598
+ // Build result without delete (avoids V8 dictionary-mode de-opt)
599
+ const deleted = new Set<string>();
600
+ for (const [k, v] of mutations) {
601
+ if (v === null) deleted.add(k);
602
+ }
603
+ const result: Record<string, string> = {};
604
+ for (const key of Object.keys(parsed)) {
605
+ if (!deleted.has(key)) result[key] = parsed[key];
606
+ }
607
+ for (const [k, v] of mutations) {
608
+ if (v !== null) result[k] = v;
609
+ }
610
+ return result;
611
+ },
612
+
613
+ setCookie(name: string, value: string, options?: CookieOptions): void {
614
+ assertNotInsideCacheExec(ctx, "setCookie");
615
+ stubResponse.headers.append(
616
+ "Set-Cookie",
617
+ serializeCookieValue(name, value, options),
618
+ );
619
+ invalidateResponseCookieCache();
620
+ },
621
+
622
+ deleteCookie(
623
+ name: string,
624
+ options?: Pick<CookieOptions, "domain" | "path">,
625
+ ): void {
626
+ assertNotInsideCacheExec(ctx, "deleteCookie");
627
+ stubResponse.headers.append(
628
+ "Set-Cookie",
629
+ serializeCookieValue(name, "", { ...options, maxAge: 0 }),
630
+ );
631
+ invalidateResponseCookieCache();
632
+ },
633
+
634
+ header(name: string, value: string): void {
635
+ assertNotInsideCacheExec(ctx, "header");
636
+ stubResponse.headers.set(name, value);
637
+ },
638
+
639
+ setStatus(status: number): void {
640
+ assertNotInsideCacheExec(ctx, "setStatus");
641
+ stubResponse = new Response(null, {
642
+ status,
643
+ headers: stubResponse.headers,
644
+ });
645
+ },
646
+
647
+ _setStatus(status: number): void {
648
+ stubResponse = new Response(null, {
649
+ status,
650
+ headers: stubResponse.headers,
651
+ });
652
+ },
653
+
654
+ // Placeholder - will be replaced below
655
+ use: null as any,
656
+
657
+ method: request.method,
658
+
659
+ _handleStore: handleStore,
660
+ _cacheStore: cacheStore,
661
+ _cacheProfiles: cacheProfiles,
662
+
663
+ waitUntil(fn: () => Promise<void>): void {
664
+ if (executionContext?.waitUntil) {
665
+ // Cloudflare Workers: use native waitUntil
666
+ executionContext.waitUntil(fn());
667
+ } else {
668
+ // Node.js / dev: fire-and-forget with error logging
669
+ fn().catch((err) =>
670
+ console.error("[waitUntil] Background task failed:", err),
671
+ );
672
+ }
673
+ },
674
+
675
+ _onResponseCallbacks: [],
676
+
677
+ onResponse(callback: (response: Response) => Response): void {
678
+ assertNotInsideCacheExec(ctx, "onResponse");
679
+ this._onResponseCallbacks.push(callback);
680
+ },
681
+
682
+ // Theme properties (only set when themeConfig is provided)
683
+ get theme() {
684
+ return themeConfig ? getTheme() : undefined;
685
+ },
686
+ setTheme: themeConfig
687
+ ? (theme: Theme) => {
688
+ assertNotInsideCacheExec(ctx, "setTheme");
689
+ setTheme(theme);
690
+ }
691
+ : undefined,
692
+ _themeConfig: themeConfig,
693
+
694
+ setLocationState(entries: LocationStateEntry | LocationStateEntry[]): void {
695
+ assertNotInsideCacheExec(ctx, "setLocationState");
696
+ const arr = Array.isArray(entries) ? entries : [entries];
697
+ this._locationState = this._locationState
698
+ ? [...this._locationState, ...arr]
699
+ : arr;
700
+ },
701
+ _locationState: undefined,
702
+
703
+ _reportedErrors: new WeakSet<object>(),
704
+ _metricsStore: undefined,
705
+
706
+ reverse: createReverseFunction(getGlobalRouteMap(), undefined, {}),
707
+ };
708
+
709
+ // Now create use() with access to ctx
710
+ ctx.use = createUseFunction({
711
+ handleStore,
712
+ loaderPromises,
713
+ getContext: () => ctx,
714
+ });
715
+
716
+ // Brand with taint symbol so "use cache" excludes ctx from cache keys
717
+ (ctx as any)[NOCACHE_SYMBOL] = true;
718
+ return ctx;
719
+ }
720
+
721
+ /**
722
+ * Parse Set-Cookie headers from a response into effective cookie state.
723
+ * Returns a map of cookie name -> value (string) or name -> null (deleted).
724
+ * Last-write-wins: later Set-Cookie entries for the same name overwrite earlier ones.
725
+ * Max-Age=0 is treated as a delete.
726
+ */
727
+ const MAX_AGE_ZERO_RE = /;\s*Max-Age\s*=\s*0/i;
728
+
729
+ function parseResponseCookies(response: Response): Map<string, string | null> {
730
+ const result = new Map<string, string | null>();
731
+ const setCookies = response.headers.getSetCookie();
732
+
733
+ for (const header of setCookies) {
734
+ // First segment before ';' is the name=value pair
735
+ const semiIdx = header.indexOf(";");
736
+ const pair = semiIdx === -1 ? header : header.substring(0, semiIdx);
737
+ const eqIdx = pair.indexOf("=");
738
+ if (eqIdx === -1) continue;
739
+
740
+ let name: string;
741
+ let value: string;
742
+ try {
743
+ name = decodeURIComponent(pair.substring(0, eqIdx).trim());
744
+ value = decodeURIComponent(pair.substring(eqIdx + 1).trim());
745
+ } catch {
746
+ // Malformed encoding — skip this entry
747
+ continue;
748
+ }
749
+
750
+ // Max-Age=0 means the cookie is being deleted
751
+ const isDeleted = MAX_AGE_ZERO_RE.test(header);
752
+ result.set(name, isDeleted ? null : value);
753
+ }
754
+
755
+ return result;
756
+ }
757
+
758
+ /**
759
+ * Parse cookies from Cookie header
760
+ */
761
+ function parseCookiesFromHeader(
762
+ cookieHeader: string | null,
763
+ ): Record<string, string> {
764
+ if (!cookieHeader) return {};
765
+
766
+ const cookies: Record<string, string> = {};
767
+ const pairs = cookieHeader.split(";");
768
+
769
+ for (const pair of pairs) {
770
+ const [name, ...rest] = pair.trim().split("=");
771
+ if (name) {
772
+ const raw = rest.join("=");
773
+ try {
774
+ cookies[name] = decodeURIComponent(raw);
775
+ } catch {
776
+ // Malformed percent-encoded value (e.g. %zz, %2) - fall back to raw value
777
+ cookies[name] = raw;
778
+ }
779
+ }
780
+ }
781
+
782
+ return cookies;
783
+ }
784
+
785
+ /**
786
+ * Serialize a cookie for Set-Cookie header
787
+ */
788
+ function serializeCookieValue(
789
+ name: string,
790
+ value: string,
791
+ options: CookieOptions = {},
792
+ ): string {
793
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
794
+
795
+ if (options.domain) cookie += `; Domain=${options.domain}`;
796
+ if (options.path) cookie += `; Path=${options.path}`;
797
+ if (options.maxAge !== undefined) cookie += `; Max-Age=${options.maxAge}`;
798
+ if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
799
+ if (options.httpOnly) cookie += "; HttpOnly";
800
+ if (options.secure) cookie += "; Secure";
801
+ if (options.sameSite) cookie += `; SameSite=${options.sameSite}`;
802
+
803
+ return cookie;
804
+ }
805
+
806
+ /**
807
+ * Options for creating the use() function
808
+ */
809
+ export interface CreateUseFunctionOptions<TEnv> {
810
+ handleStore: HandleStore;
811
+ loaderPromises: Map<string, Promise<any>>;
812
+ getContext: () => RequestContext<TEnv>;
813
+ }
814
+
815
+ /**
816
+ * Create the use() function for loader and handle composition.
817
+ *
818
+ * This is the unified implementation used by both RequestContext and HandlerContext.
819
+ * - For loaders: executes and memoizes loader functions
820
+ * - For handles: returns a push function to add handle data
821
+ */
822
+ export function createUseFunction<TEnv>(
823
+ options: CreateUseFunctionOptions<TEnv>,
824
+ ): RequestContext["use"] {
825
+ const { handleStore, loaderPromises, getContext } = options;
826
+
827
+ return ((item: LoaderDefinition<any, any> | Handle<any, any>) => {
828
+ // Handle case: return a push function
829
+ if (isHandle(item)) {
830
+ const handle = item;
831
+ const ctx = getContext();
832
+ const segmentId = (ctx as any)._currentSegmentId;
833
+
834
+ if (!segmentId) {
835
+ throw new Error(
836
+ `Handle "${handle.$$id}" used outside of handler context. ` +
837
+ `Handles must be used within route/layout handlers.`,
838
+ );
839
+ }
840
+
841
+ // Return a push function bound to this handle and segment
842
+ return (
843
+ dataOrFn: unknown | Promise<unknown> | (() => Promise<unknown>),
844
+ ) => {
845
+ // If it's a function, call it immediately to get the promise
846
+ const valueOrPromise =
847
+ typeof dataOrFn === "function"
848
+ ? (dataOrFn as () => Promise<unknown>)()
849
+ : dataOrFn;
850
+
851
+ // Push directly - promises will be serialized by RSC and streamed
852
+ handleStore.push(handle.$$id, segmentId, valueOrPromise);
853
+ };
854
+ }
855
+
856
+ // Loader case
857
+ const loader = item as LoaderDefinition<any, any>;
858
+
859
+ // Return cached promise if already started
860
+ if (loaderPromises.has(loader.$$id)) {
861
+ return loaderPromises.get(loader.$$id);
862
+ }
863
+
864
+ // Get loader function - either from loader object or fetchable registry
865
+ let loaderFn = loader.fn;
866
+ if (!loaderFn) {
867
+ const fetchable = getFetchableLoader(loader.$$id);
868
+ if (fetchable) {
869
+ loaderFn = fetchable.fn;
870
+ }
871
+ }
872
+
873
+ if (!loaderFn) {
874
+ throw new Error(
875
+ `Loader "${loader.$$id}" has no function. This usually means the loader was defined without "use server" and the function was not included in the build.`,
876
+ );
877
+ }
878
+
879
+ const ctx = getContext();
880
+
881
+ // Create loader context with recursive use() support
882
+ const loaderCtx: LoaderContext<Record<string, string | undefined>, TEnv> = {
883
+ params: ctx.params,
884
+ routeParams: (ctx.params ?? {}) as Record<string, string>,
885
+ request: ctx.request,
886
+ searchParams: ctx.searchParams,
887
+ search: (ctx as any).search ?? {},
888
+ pathname: ctx.pathname,
889
+ url: ctx.url,
890
+ env: ctx.env as any,
891
+ var: ctx.var as any,
892
+ get: ctx.get as any,
893
+ use: <TDep, TDepParams = any>(
894
+ dep: LoaderDefinition<TDep, TDepParams>,
895
+ ): Promise<TDep> => {
896
+ // Recursive call - will start dep loader if not already started
897
+ return ctx.use(dep);
898
+ },
899
+ method: "GET",
900
+ body: undefined,
901
+ reverse: createReverseFunction(
902
+ getGlobalRouteMap(),
903
+ ctx._routeName,
904
+ ctx.params as Record<string, string>,
905
+ ctx._routeName ? isRouteRootScoped(ctx._routeName) : undefined,
906
+ ),
907
+ };
908
+
909
+ // Start loader execution with tracking
910
+ const doneLoader = track(`loader:${loader.$$id}`, 2);
911
+ const promise = Promise.resolve(loaderFn(loaderCtx)).finally(() => {
912
+ doneLoader();
913
+ });
914
+
915
+ // Memoize for subsequent calls
916
+ loaderPromises.set(loader.$$id, promise);
917
+
918
+ return promise;
919
+ }) as RequestContext["use"];
920
+ }