@rangojs/router 0.0.0-experimental.8 → 0.0.0-experimental.81

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 (316) hide show
  1. package/AGENTS.md +9 -0
  2. package/README.md +942 -4
  3. package/dist/bin/rango.js +1689 -0
  4. package/dist/vite/index.js +5091 -941
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +61 -52
  7. package/skills/breadcrumbs/SKILL.md +250 -0
  8. package/skills/cache-guide/SKILL.md +294 -0
  9. package/skills/caching/SKILL.md +93 -23
  10. package/skills/composability/SKILL.md +172 -0
  11. package/skills/debug-manifest/SKILL.md +12 -8
  12. package/skills/document-cache/SKILL.md +18 -16
  13. package/skills/fonts/SKILL.md +167 -0
  14. package/skills/handler-use/SKILL.md +362 -0
  15. package/skills/hooks/SKILL.md +340 -72
  16. package/skills/host-router/SKILL.md +218 -0
  17. package/skills/intercept/SKILL.md +151 -8
  18. package/skills/layout/SKILL.md +122 -3
  19. package/skills/links/SKILL.md +92 -31
  20. package/skills/loader/SKILL.md +404 -44
  21. package/skills/middleware/SKILL.md +205 -37
  22. package/skills/migrate-nextjs/SKILL.md +560 -0
  23. package/skills/migrate-react-router/SKILL.md +765 -0
  24. package/skills/mime-routes/SKILL.md +128 -0
  25. package/skills/parallel/SKILL.md +263 -1
  26. package/skills/prerender/SKILL.md +685 -0
  27. package/skills/rango/SKILL.md +87 -16
  28. package/skills/response-routes/SKILL.md +411 -0
  29. package/skills/route/SKILL.md +281 -14
  30. package/skills/router-setup/SKILL.md +210 -32
  31. package/skills/tailwind/SKILL.md +129 -0
  32. package/skills/theme/SKILL.md +9 -8
  33. package/skills/typesafety/SKILL.md +328 -89
  34. package/skills/use-cache/SKILL.md +324 -0
  35. package/src/__internal.ts +102 -4
  36. package/src/bin/rango.ts +321 -0
  37. package/src/browser/action-coordinator.ts +97 -0
  38. package/src/browser/action-response-classifier.ts +99 -0
  39. package/src/browser/app-version.ts +14 -0
  40. package/src/browser/event-controller.ts +92 -64
  41. package/src/browser/history-state.ts +80 -0
  42. package/src/browser/intercept-utils.ts +52 -0
  43. package/src/browser/link-interceptor.ts +24 -4
  44. package/src/browser/logging.ts +55 -0
  45. package/src/browser/merge-segment-loaders.ts +20 -12
  46. package/src/browser/navigation-bridge.ts +317 -560
  47. package/src/browser/navigation-client.ts +206 -68
  48. package/src/browser/navigation-store.ts +73 -55
  49. package/src/browser/navigation-transaction.ts +297 -0
  50. package/src/browser/network-error-handler.ts +61 -0
  51. package/src/browser/partial-update.ts +343 -316
  52. package/src/browser/prefetch/cache.ts +216 -0
  53. package/src/browser/prefetch/fetch.ts +206 -0
  54. package/src/browser/prefetch/observer.ts +65 -0
  55. package/src/browser/prefetch/policy.ts +48 -0
  56. package/src/browser/prefetch/queue.ts +160 -0
  57. package/src/browser/prefetch/resource-ready.ts +77 -0
  58. package/src/browser/rango-state.ts +112 -0
  59. package/src/browser/react/Link.tsx +253 -74
  60. package/src/browser/react/NavigationProvider.tsx +91 -11
  61. package/src/browser/react/context.ts +11 -0
  62. package/src/browser/react/filter-segment-order.ts +11 -0
  63. package/src/browser/react/index.ts +12 -12
  64. package/src/browser/react/location-state-shared.ts +95 -53
  65. package/src/browser/react/location-state.ts +60 -15
  66. package/src/browser/react/mount-context.ts +6 -1
  67. package/src/browser/react/nonce-context.ts +23 -0
  68. package/src/browser/react/shallow-equal.ts +27 -0
  69. package/src/browser/react/use-action.ts +29 -51
  70. package/src/browser/react/use-client-cache.ts +5 -3
  71. package/src/browser/react/use-handle.ts +30 -126
  72. package/src/browser/react/use-href.tsx +2 -2
  73. package/src/browser/react/use-link-status.ts +6 -5
  74. package/src/browser/react/use-navigation.ts +44 -65
  75. package/src/browser/react/use-params.ts +75 -0
  76. package/src/browser/react/use-pathname.ts +47 -0
  77. package/src/browser/react/use-router.ts +76 -0
  78. package/src/browser/react/use-search-params.ts +56 -0
  79. package/src/browser/react/use-segments.ts +80 -97
  80. package/src/browser/response-adapter.ts +73 -0
  81. package/src/browser/rsc-router.tsx +214 -58
  82. package/src/browser/scroll-restoration.ts +127 -52
  83. package/src/browser/segment-reconciler.ts +243 -0
  84. package/src/browser/segment-structure-assert.ts +16 -0
  85. package/src/browser/server-action-bridge.ts +510 -603
  86. package/src/browser/shallow.ts +6 -1
  87. package/src/browser/types.ts +141 -48
  88. package/src/browser/validate-redirect-origin.ts +29 -0
  89. package/src/build/generate-manifest.ts +235 -24
  90. package/src/build/generate-route-types.ts +39 -0
  91. package/src/build/index.ts +13 -0
  92. package/src/build/route-trie.ts +291 -0
  93. package/src/build/route-types/ast-helpers.ts +25 -0
  94. package/src/build/route-types/ast-route-extraction.ts +98 -0
  95. package/src/build/route-types/codegen.ts +102 -0
  96. package/src/build/route-types/include-resolution.ts +418 -0
  97. package/src/build/route-types/param-extraction.ts +48 -0
  98. package/src/build/route-types/per-module-writer.ts +128 -0
  99. package/src/build/route-types/router-processing.ts +618 -0
  100. package/src/build/route-types/scan-filter.ts +85 -0
  101. package/src/build/runtime-discovery.ts +231 -0
  102. package/src/cache/background-task.ts +34 -0
  103. package/src/cache/cache-key-utils.ts +44 -0
  104. package/src/cache/cache-policy.ts +125 -0
  105. package/src/cache/cache-runtime.ts +342 -0
  106. package/src/cache/cache-scope.ts +167 -309
  107. package/src/cache/cf/cf-cache-store.ts +571 -17
  108. package/src/cache/cf/index.ts +13 -3
  109. package/src/cache/document-cache.ts +116 -77
  110. package/src/cache/handle-capture.ts +81 -0
  111. package/src/cache/handle-snapshot.ts +41 -0
  112. package/src/cache/index.ts +1 -15
  113. package/src/cache/memory-segment-store.ts +191 -13
  114. package/src/cache/profile-registry.ts +73 -0
  115. package/src/cache/read-through-swr.ts +134 -0
  116. package/src/cache/segment-codec.ts +256 -0
  117. package/src/cache/taint.ts +153 -0
  118. package/src/cache/types.ts +72 -122
  119. package/src/client.rsc.tsx +3 -1
  120. package/src/client.tsx +135 -301
  121. package/src/component-utils.ts +4 -4
  122. package/src/components/DefaultDocument.tsx +5 -1
  123. package/src/context-var.ts +156 -0
  124. package/src/debug.ts +19 -9
  125. package/src/errors.ts +108 -2
  126. package/src/handle.ts +55 -29
  127. package/src/handles/MetaTags.tsx +73 -20
  128. package/src/handles/breadcrumbs.ts +66 -0
  129. package/src/handles/index.ts +1 -0
  130. package/src/handles/meta.ts +30 -13
  131. package/src/host/cookie-handler.ts +21 -15
  132. package/src/host/errors.ts +8 -8
  133. package/src/host/index.ts +4 -7
  134. package/src/host/pattern-matcher.ts +27 -27
  135. package/src/host/router.ts +61 -39
  136. package/src/host/testing.ts +8 -8
  137. package/src/host/types.ts +15 -7
  138. package/src/host/utils.ts +1 -1
  139. package/src/href-client.ts +119 -29
  140. package/src/index.rsc.ts +155 -19
  141. package/src/index.ts +251 -30
  142. package/src/internal-debug.ts +11 -0
  143. package/src/loader.rsc.ts +26 -157
  144. package/src/loader.ts +27 -10
  145. package/src/network-error-thrower.tsx +3 -1
  146. package/src/outlet-provider.tsx +45 -0
  147. package/src/prerender/param-hash.ts +37 -0
  148. package/src/prerender/store.ts +186 -0
  149. package/src/prerender.ts +524 -0
  150. package/src/reverse.ts +354 -0
  151. package/src/root-error-boundary.tsx +41 -29
  152. package/src/route-content-wrapper.tsx +7 -4
  153. package/src/route-definition/dsl-helpers.ts +1121 -0
  154. package/src/route-definition/helper-factories.ts +200 -0
  155. package/src/route-definition/helpers-types.ts +478 -0
  156. package/src/route-definition/index.ts +55 -0
  157. package/src/route-definition/redirect.ts +101 -0
  158. package/src/route-definition/resolve-handler-use.ts +149 -0
  159. package/src/route-definition.ts +1 -1428
  160. package/src/route-map-builder.ts +217 -123
  161. package/src/route-name.ts +53 -0
  162. package/src/route-types.ts +77 -8
  163. package/src/router/content-negotiation.ts +215 -0
  164. package/src/router/debug-manifest.ts +72 -0
  165. package/src/router/error-handling.ts +9 -9
  166. package/src/router/find-match.ts +160 -0
  167. package/src/router/handler-context.ts +438 -86
  168. package/src/router/intercept-resolution.ts +402 -0
  169. package/src/router/lazy-includes.ts +237 -0
  170. package/src/router/loader-resolution.ts +356 -128
  171. package/src/router/logging.ts +251 -0
  172. package/src/router/manifest.ts +163 -35
  173. package/src/router/match-api.ts +555 -0
  174. package/src/router/match-context.ts +5 -3
  175. package/src/router/match-handlers.ts +440 -0
  176. package/src/router/match-middleware/background-revalidation.ts +108 -93
  177. package/src/router/match-middleware/cache-lookup.ts +460 -10
  178. package/src/router/match-middleware/cache-store.ts +98 -26
  179. package/src/router/match-middleware/intercept-resolution.ts +57 -17
  180. package/src/router/match-middleware/segment-resolution.ts +80 -6
  181. package/src/router/match-pipelines.ts +10 -45
  182. package/src/router/match-result.ts +135 -35
  183. package/src/router/metrics.ts +240 -15
  184. package/src/router/middleware-cookies.ts +55 -0
  185. package/src/router/middleware-types.ts +220 -0
  186. package/src/router/middleware.ts +324 -369
  187. package/src/router/navigation-snapshot.ts +182 -0
  188. package/src/router/pattern-matching.ts +211 -43
  189. package/src/router/prerender-match.ts +502 -0
  190. package/src/router/preview-match.ts +98 -0
  191. package/src/router/request-classification.ts +310 -0
  192. package/src/router/revalidation.ts +137 -38
  193. package/src/router/route-snapshot.ts +245 -0
  194. package/src/router/router-context.ts +41 -21
  195. package/src/router/router-interfaces.ts +484 -0
  196. package/src/router/router-options.ts +618 -0
  197. package/src/router/router-registry.ts +24 -0
  198. package/src/router/segment-resolution/fresh.ts +748 -0
  199. package/src/router/segment-resolution/helpers.ts +268 -0
  200. package/src/router/segment-resolution/loader-cache.ts +199 -0
  201. package/src/router/segment-resolution/revalidation.ts +1379 -0
  202. package/src/router/segment-resolution/static-store.ts +67 -0
  203. package/src/router/segment-resolution.ts +21 -0
  204. package/src/router/segment-wrappers.ts +291 -0
  205. package/src/router/telemetry-otel.ts +299 -0
  206. package/src/router/telemetry.ts +300 -0
  207. package/src/router/timeout.ts +148 -0
  208. package/src/router/trie-matching.ts +239 -0
  209. package/src/router/types.ts +78 -3
  210. package/src/router.ts +740 -4252
  211. package/src/rsc/handler-context.ts +45 -0
  212. package/src/rsc/handler.ts +907 -797
  213. package/src/rsc/helpers.ts +140 -6
  214. package/src/rsc/index.ts +0 -20
  215. package/src/rsc/loader-fetch.ts +229 -0
  216. package/src/rsc/manifest-init.ts +90 -0
  217. package/src/rsc/nonce.ts +14 -0
  218. package/src/rsc/origin-guard.ts +141 -0
  219. package/src/rsc/progressive-enhancement.ts +393 -0
  220. package/src/rsc/response-error.ts +37 -0
  221. package/src/rsc/response-route-handler.ts +347 -0
  222. package/src/rsc/rsc-rendering.ts +246 -0
  223. package/src/rsc/runtime-warnings.ts +42 -0
  224. package/src/rsc/server-action.ts +358 -0
  225. package/src/rsc/ssr-setup.ts +128 -0
  226. package/src/rsc/types.ts +46 -11
  227. package/src/search-params.ts +230 -0
  228. package/src/segment-content-promise.ts +67 -0
  229. package/src/segment-loader-promise.ts +122 -0
  230. package/src/segment-system.tsx +134 -36
  231. package/src/server/context.ts +341 -61
  232. package/src/server/cookie-store.ts +190 -0
  233. package/src/server/fetchable-loader-store.ts +37 -0
  234. package/src/server/handle-store.ts +113 -15
  235. package/src/server/loader-registry.ts +24 -64
  236. package/src/server/request-context.ts +607 -81
  237. package/src/server.ts +35 -130
  238. package/src/ssr/index.tsx +103 -30
  239. package/src/static-handler.ts +126 -0
  240. package/src/theme/ThemeProvider.tsx +21 -15
  241. package/src/theme/ThemeScript.tsx +5 -5
  242. package/src/theme/constants.ts +5 -2
  243. package/src/theme/index.ts +4 -14
  244. package/src/theme/theme-context.ts +4 -30
  245. package/src/theme/theme-script.ts +21 -18
  246. package/src/types/boundaries.ts +158 -0
  247. package/src/types/cache-types.ts +198 -0
  248. package/src/types/error-types.ts +192 -0
  249. package/src/types/global-namespace.ts +100 -0
  250. package/src/types/handler-context.ts +791 -0
  251. package/src/types/index.ts +88 -0
  252. package/src/types/loader-types.ts +210 -0
  253. package/src/types/route-config.ts +170 -0
  254. package/src/types/route-entry.ts +120 -0
  255. package/src/types/segments.ts +150 -0
  256. package/src/types.ts +1 -1623
  257. package/src/urls/include-helper.ts +207 -0
  258. package/src/urls/index.ts +53 -0
  259. package/src/urls/path-helper-types.ts +372 -0
  260. package/src/urls/path-helper.ts +364 -0
  261. package/src/urls/pattern-types.ts +107 -0
  262. package/src/urls/response-types.ts +116 -0
  263. package/src/urls/type-extraction.ts +372 -0
  264. package/src/urls/urls-function.ts +98 -0
  265. package/src/urls.ts +1 -802
  266. package/src/use-loader.tsx +161 -81
  267. package/src/vite/discovery/bundle-postprocess.ts +181 -0
  268. package/src/vite/discovery/discover-routers.ts +348 -0
  269. package/src/vite/discovery/prerender-collection.ts +439 -0
  270. package/src/vite/discovery/route-types-writer.ts +258 -0
  271. package/src/vite/discovery/self-gen-tracking.ts +47 -0
  272. package/src/vite/discovery/state.ts +117 -0
  273. package/src/vite/discovery/virtual-module-codegen.ts +203 -0
  274. package/src/vite/index.ts +15 -1133
  275. package/src/vite/plugin-types.ts +103 -0
  276. package/src/vite/plugins/cjs-to-esm.ts +93 -0
  277. package/src/vite/plugins/client-ref-dedup.ts +115 -0
  278. package/src/vite/plugins/client-ref-hashing.ts +105 -0
  279. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  280. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  281. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  282. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +72 -53
  283. package/src/vite/plugins/expose-id-utils.ts +299 -0
  284. package/src/vite/plugins/expose-ids/export-analysis.ts +296 -0
  285. package/src/vite/plugins/expose-ids/handler-transform.ts +209 -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 +786 -0
  290. package/src/vite/plugins/performance-tracks.ts +88 -0
  291. package/src/vite/plugins/refresh-cmd.ts +127 -0
  292. package/src/vite/plugins/use-cache-transform.ts +323 -0
  293. package/src/vite/plugins/version-injector.ts +83 -0
  294. package/src/vite/plugins/version-plugin.ts +266 -0
  295. package/src/vite/{virtual-entries.ts → plugins/virtual-entries.ts} +23 -14
  296. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  297. package/src/vite/rango.ts +462 -0
  298. package/src/vite/router-discovery.ts +977 -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/{package-resolution.ts → utils/package-resolution.ts} +25 -29
  304. package/src/vite/utils/prerender-utils.ts +221 -0
  305. package/src/vite/utils/shared-utils.ts +170 -0
  306. package/CLAUDE.md +0 -43
  307. package/src/browser/lru-cache.ts +0 -69
  308. package/src/browser/request-controller.ts +0 -164
  309. package/src/cache/memory-store.ts +0 -253
  310. package/src/href-context.ts +0 -33
  311. package/src/href.ts +0 -255
  312. package/src/server/route-manifest-cache.ts +0 -173
  313. package/src/vite/expose-handle-id.ts +0 -209
  314. package/src/vite/expose-loader-id.ts +0 -426
  315. package/src/vite/expose-location-state-id.ts +0 -177
  316. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
@@ -0,0 +1,791 @@
1
+ import type { ReactNode } from "react";
2
+ import type { Handle } from "../handle.js";
3
+ import type { ContextVar } from "../context-var.js";
4
+ import type { MiddlewareFn } from "../router/middleware.js";
5
+ import type { Theme } from "../theme/types.js";
6
+ import type { ScopedReverseFunction } from "../reverse.js";
7
+ import type { SearchSchema, ResolveSearchSchema } from "../search-params.js";
8
+ import type { LocationStateEntry } from "../browser/react/location-state-shared.js";
9
+ import type {
10
+ DefaultEnv,
11
+ DefaultHandlerRouteMap,
12
+ DefaultReverseRouteMap,
13
+ DefaultRouteName,
14
+ DefaultVars,
15
+ } from "./global-namespace.js";
16
+ import type {
17
+ ExtractParams,
18
+ RouteDefinition,
19
+ ResolvedRouteMap,
20
+ } from "./route-config.js";
21
+ import type { LoaderDefinition } from "./loader-types.js";
22
+ import type { UseItems, HandlerUseItem } from "../route-types.js";
23
+
24
+ // Re-export MiddlewareFn for internal/advanced use
25
+ export type { MiddlewareFn } from "../router/middleware.js";
26
+
27
+ /**
28
+ * Create a scoped view of a route map by stripping a name prefix.
29
+ * Useful for handlers in modules mounted via include() -- use the local
30
+ * route name instead of the fully qualified global name.
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * // Given GeneratedRouteMap: { "blog.index": "/blog"; "blog.post": "/blog/:postId"; ... }
35
+ * type BlogRoutes = ScopedRouteMap<"blog">;
36
+ * // Resolves to: { "index": "/blog"; "post": "/blog/:postId" }
37
+ *
38
+ * const handler: Handler<"post", BlogRoutes> = (ctx) => {
39
+ * ctx.params.postId // string
40
+ * };
41
+ * ```
42
+ */
43
+ export type ScopedRouteMap<
44
+ TPrefix extends string,
45
+ TMap = RSCRouter.GeneratedRouteMap,
46
+ > = {
47
+ [K in keyof TMap as K extends `${TPrefix}.${infer Rest}`
48
+ ? Rest
49
+ : never]: TMap[K];
50
+ };
51
+
52
+ /**
53
+ * Extract the search schema from a route map entry.
54
+ * - string value (old format): no search schema -> {}
55
+ * - { path, search } value: extract search
56
+ * - { path, response } value (no search): -> {}
57
+ */
58
+ /** Extract params from a route map entry (string pattern or { path } object). */
59
+ type ExtractParamsFromEntry<TEntry, TFallback> = TEntry extends string
60
+ ? ExtractParams<TEntry>
61
+ : TEntry extends { readonly path: infer P extends string }
62
+ ? ExtractParams<P>
63
+ : TFallback;
64
+
65
+ /** Extract search schema from a route map entry. */
66
+ type ExtractSearchFromEntry<TMap, TKey> = TKey extends keyof TMap
67
+ ? TMap[TKey] extends { readonly search: infer S extends SearchSchema }
68
+ ? S
69
+ : {}
70
+ : {};
71
+
72
+ type IsEmptyObject<T> = keyof T extends never ? true : false;
73
+
74
+ type AutofillParamsFromEntry<TEntry> = TEntry extends string
75
+ ? string extends TEntry
76
+ ? Record<string, string>
77
+ : Partial<ExtractParams<TEntry>>
78
+ : TEntry extends { readonly path: infer P extends string }
79
+ ? string extends P
80
+ ? Record<string, string>
81
+ : Partial<ExtractParams<P>>
82
+ : Record<string, string>;
83
+
84
+ type AutofillSearchFromEntry<TMap, TKey> = TKey extends keyof TMap
85
+ ? TMap[TKey] extends { readonly search: infer S extends SearchSchema }
86
+ ? ResolveSearchSchema<S>
87
+ : Record<string, unknown>
88
+ : Record<string, unknown>;
89
+
90
+ type AutofillAwareReverseFunction<TLocalRoutes, TGlobalRoutes> =
91
+ ScopedReverseFunction<TLocalRoutes, TGlobalRoutes> & {
92
+ <TName extends keyof TGlobalRoutes & string>(
93
+ name: TName,
94
+ params?: AutofillParamsFromEntry<TGlobalRoutes[TName]>,
95
+ search?: AutofillSearchFromEntry<TGlobalRoutes, TName>,
96
+ ): string;
97
+ <TName extends keyof TLocalRoutes & string>(
98
+ name: `.${TName}`,
99
+ params?: AutofillParamsFromEntry<TLocalRoutes[TName]>,
100
+ search?: AutofillSearchFromEntry<TLocalRoutes, TName>,
101
+ ): string;
102
+ };
103
+
104
+ type StrictLocalParamsWithExtras<TEntry> =
105
+ IsEmptyObject<ExtractParamsFromEntry<TEntry, {}>> extends true
106
+ ? Record<string, string>
107
+ : ExtractParamsFromEntry<TEntry, {}> & Record<string, string>;
108
+
109
+ // HandlerContext.reverse is the only reverse surface with runtime param autofill
110
+ // from the current matched request. Middleware/loaders/request context do not
111
+ // have the same local-route guarantees, so they keep plain ScopedReverseFunction.
112
+ //
113
+ // When a handler has an explicit local route map, enforce that local route
114
+ // params declared by that map are present while still allowing extra mount
115
+ // params to be passed through. Global names remain autofill-friendly because
116
+ // parent include() params are often unknown at the module definition site.
117
+ type StrictLocalAutofillGlobalReverseFunction<TLocalRoutes, TGlobalRoutes> =
118
+ ScopedReverseFunction<TLocalRoutes, TGlobalRoutes> & {
119
+ <TName extends keyof TGlobalRoutes & string>(
120
+ name: TName,
121
+ params?: AutofillParamsFromEntry<TGlobalRoutes[TName]>,
122
+ search?: AutofillSearchFromEntry<TGlobalRoutes, TName>,
123
+ ): string;
124
+ <TName extends keyof TLocalRoutes & string>(
125
+ name: `.${TName}`,
126
+ params: StrictLocalParamsWithExtras<TLocalRoutes[TName]>,
127
+ search?: AutofillSearchFromEntry<TLocalRoutes, TName>,
128
+ ): string;
129
+ };
130
+
131
+ export type Handler<
132
+ T extends
133
+ | keyof DefaultHandlerRouteMap
134
+ | `.${keyof TRouteMap & string}`
135
+ | `/${string}`
136
+ | Record<string, any> = {},
137
+ TRouteMap extends {} = DefaultHandlerRouteMap,
138
+ TEnv = DefaultEnv,
139
+ > = ((
140
+ ctx: HandlerContext<
141
+ T extends `.${infer Local}`
142
+ ? Local extends keyof TRouteMap
143
+ ? ExtractParamsFromEntry<
144
+ TRouteMap[Local],
145
+ T extends string ? ExtractParams<T> : T
146
+ >
147
+ : T extends string
148
+ ? ExtractParams<T>
149
+ : T
150
+ : T extends keyof DefaultHandlerRouteMap
151
+ ? ExtractParamsFromEntry<
152
+ DefaultHandlerRouteMap[T],
153
+ T extends string ? ExtractParams<T> : T
154
+ >
155
+ : T extends string
156
+ ? ExtractParams<T>
157
+ : T,
158
+ TEnv,
159
+ T extends `.${infer Local}`
160
+ ? ExtractSearchFromEntry<TRouteMap, Local>
161
+ : ExtractSearchFromEntry<DefaultHandlerRouteMap, T>,
162
+ TRouteMap extends DefaultHandlerRouteMap ? never : TRouteMap
163
+ >,
164
+ ) => ReactNode | Promise<ReactNode> | Response | Promise<Response>) & {
165
+ /** Composable default DSL items merged when the handler is mounted. */
166
+ use?: () => UseItems<HandlerUseItem>;
167
+ };
168
+
169
+ /**
170
+ * Context passed to handlers (Hono-inspired type-safe context)
171
+ *
172
+ * Provides type-safe access to:
173
+ * - Route params (from URL pattern)
174
+ * - Cleaned route URL (`url`, `searchParams`, `pathname` — no `_rsc*` params)
175
+ * - Original request (`request` — raw transport URL, headers, method, body)
176
+ * - Platform bindings (env.DB, env.KV, env.SECRETS)
177
+ * - Middleware variables (`get("user")`, `get("permissions")`)
178
+ * - Getter/setter for variables (get('user'), set('user', ...))
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * const handler = (ctx: HandlerContext<{ slug: string }, AppEnv>) => {
183
+ * ctx.params.slug // Route param (string)
184
+ * ctx.env.DB // Binding (D1Database)
185
+ * ctx.get('user') // Variable (User | undefined)
186
+ * ctx.set('user', {...}) // Setter
187
+ * ctx.url // Clean URL (no _rsc* params)
188
+ * ctx.searchParams // Clean params (no _rsc* params)
189
+ * ctx.request // Raw transport request (original URL intact)
190
+ * }
191
+ * ```
192
+ */
193
+ export type HandlerContext<
194
+ TParams = {},
195
+ TEnv = DefaultEnv,
196
+ TSearch extends SearchSchema = {},
197
+ TRouteMap = never,
198
+ > = {
199
+ /**
200
+ * Route parameters extracted from the URL pattern.
201
+ * Type-safe when using Handler<"/path/:param"> or Handler<{ param: string }>.
202
+ */
203
+ params: TParams;
204
+ /** @internal Phantom property for params type invariance. Prevents mounting handlers on wrong routes. */
205
+ readonly _paramCheck?: (params: TParams) => TParams;
206
+ /**
207
+ * True during build-time pre-rendering, false at runtime.
208
+ * Build-time collection and dev on-demand prerender use `true`.
209
+ * Live request rendering, including passthrough fallback, uses `false`.
210
+ */
211
+ build: boolean;
212
+ /**
213
+ * True when running in Vite dev mode, false during production build or
214
+ * live request rendering. Use this to branch on runtime mode without
215
+ * changing build semantics (e.g., skip expensive operations in dev).
216
+ */
217
+ dev: boolean;
218
+ /**
219
+ * The original incoming Request object (transport URL intact).
220
+ * Use `ctx.url` / `ctx.searchParams` for application logic — those have
221
+ * internal `_rsc*` params stripped. `ctx.request` preserves the raw URL
222
+ * for cases where you need original headers, method, or body.
223
+ */
224
+ request: Request;
225
+ /**
226
+ * Query parameters from the URL (system params like `_rsc*` are filtered).
227
+ * Always a standard URLSearchParams instance.
228
+ */
229
+ searchParams: URLSearchParams;
230
+ /**
231
+ * Typed search parameters parsed from URL query string via the route's
232
+ * search schema. Empty object when no schema is defined.
233
+ */
234
+ search: {} extends TSearch ? {} : ResolveSearchSchema<TSearch>;
235
+ /**
236
+ * The pathname portion of the request URL.
237
+ */
238
+ pathname: string;
239
+ /**
240
+ * The full URL object (with internal `_rsc*` params stripped).
241
+ * Use this for application logic — routing, link generation, display.
242
+ */
243
+ url: URL;
244
+ /**
245
+ * The original request URL with all parameters intact, including
246
+ * internal `_rsc*` transport params. Use `ctx.url` for application
247
+ * logic — this is only needed for advanced cases like debugging
248
+ * or custom cache keying.
249
+ */
250
+ originalUrl: URL;
251
+ /**
252
+ * Platform bindings (DB, KV, secrets, etc.).
253
+ * Access resources like `ctx.env.DB`, `ctx.env.KV`.
254
+ */
255
+ env: TEnv;
256
+ /**
257
+ * Type-safe getter for middleware variables.
258
+ * Preferred way to read middleware-injected variables.
259
+ *
260
+ * @example
261
+ * ```typescript
262
+ * const user = ctx.get("user"); // Type-safe!
263
+ * ```
264
+ */
265
+ get: {
266
+ <T>(contextVar: ContextVar<T>): T | undefined;
267
+ } & (<K extends keyof DefaultVars>(key: K) => DefaultVars[K]);
268
+ /**
269
+ * Type-safe setter for middleware variables.
270
+ * Use in middleware to pass data to handlers.
271
+ *
272
+ * @example
273
+ * ```typescript
274
+ * ctx.set("user", { id: "123", name: "John" }); // Type-safe!
275
+ * ctx.set(MyVar, { ... }); // Type-safe via ContextVar token!
276
+ * ```
277
+ */
278
+ set: {
279
+ <T>(
280
+ contextVar: ContextVar<T>,
281
+ value: T,
282
+ options?: { cache?: boolean },
283
+ ): void;
284
+ } & (<K extends keyof DefaultVars>(
285
+ key: K,
286
+ value: DefaultVars[K],
287
+ options?: { cache?: boolean },
288
+ ) => void);
289
+ /**
290
+ * Response headers. Headers set here are merged into the final response.
291
+ *
292
+ * @example
293
+ * ```typescript
294
+ * route("product", (ctx) => {
295
+ * ctx.headers.set("Cache-Control", "s-maxage=60");
296
+ * return <ProductPage />;
297
+ * });
298
+ * ```
299
+ */
300
+ headers: Headers;
301
+ /**
302
+ * Access loader data or push handle data.
303
+ *
304
+ * Available in route handlers, layout handlers, middleware, server actions,
305
+ * and server components rendered within the request context.
306
+ *
307
+ * For loaders: Returns a promise that resolves to the loader data.
308
+ * Loaders are executed in parallel and memoized per request.
309
+ * Prefer DSL `loader()` + client `useLoader()` over `ctx.use(Loader)` —
310
+ * DSL loaders are always fresh and cache-safe. Use `ctx.use(Loader)` only
311
+ * when you need loader data in the handler itself (e.g., to set context
312
+ * variables or make routing decisions).
313
+ *
314
+ * For handles: Returns a push function to add data for this segment.
315
+ * Handle data accumulates across all matched route segments.
316
+ * Push accepts: direct value, Promise, or async callback (executed immediately).
317
+ *
318
+ * @example
319
+ * ```typescript
320
+ * // Loader escape hatch — use when handler needs the data directly
321
+ * route("product", async (ctx) => {
322
+ * const { product } = await ctx.use(ProductLoader);
323
+ * ctx.set(Product, product); // make available to children
324
+ * return <ProductPage />;
325
+ * });
326
+ *
327
+ * // Handle usage - direct value
328
+ * route("shop", (ctx) => {
329
+ * const push = ctx.use(Breadcrumbs);
330
+ * push({ label: "Shop", href: "/shop" });
331
+ * return <ShopPage />;
332
+ * });
333
+ *
334
+ * // Handle usage - Promise
335
+ * route("product", (ctx) => {
336
+ * const push = ctx.use(Breadcrumbs);
337
+ * push(fetchProductBreadcrumb(ctx.params.id));
338
+ * return <ProductPage />;
339
+ * });
340
+ *
341
+ * // Handle usage - async callback (executed immediately)
342
+ * route("product", (ctx) => {
343
+ * const push = ctx.use(Breadcrumbs);
344
+ * push(async () => {
345
+ * const product = await db.getProduct(ctx.params.id);
346
+ * return { label: product.name, href: `/product/${product.id}` };
347
+ * });
348
+ * return <ProductPage />;
349
+ * });
350
+ * ```
351
+ */
352
+ use: {
353
+ <T, TLoaderParams = any>(
354
+ loader: LoaderDefinition<T, TLoaderParams>,
355
+ ): Promise<T>;
356
+ <TData, TAccumulated = TData[]>(
357
+ handle: Handle<TData, TAccumulated>,
358
+ ): (data: TData | Promise<TData> | (() => Promise<TData>)) => void;
359
+ };
360
+ /**
361
+ * Current theme (from cookie or default).
362
+ * Only available when theme is enabled in router config.
363
+ *
364
+ * @example
365
+ * ```typescript
366
+ * route("settings", (ctx) => {
367
+ * const currentTheme = ctx.theme; // "light" | "dark" | "system" | undefined
368
+ * return <SettingsPage theme={currentTheme} />;
369
+ * });
370
+ * ```
371
+ */
372
+ theme?: Theme;
373
+ /**
374
+ * Set the theme (only available when theme is enabled in router config).
375
+ * Sets a cookie with the new theme value.
376
+ *
377
+ * @example
378
+ * ```typescript
379
+ * route("settings", async (ctx) => {
380
+ * if (ctx.request.method === "POST") {
381
+ * const formData = await ctx.request.formData();
382
+ * const newTheme = formData.get("theme") as Theme;
383
+ * ctx.setTheme?.(newTheme);
384
+ * }
385
+ * return <SettingsPage />;
386
+ * });
387
+ * ```
388
+ */
389
+ setTheme?: (theme: Theme) => void;
390
+ /**
391
+ * Attach location state entries to this response.
392
+ * State is delivered to the client via history.pushState and accessible
393
+ * through the useLocationState() hook.
394
+ *
395
+ * @example
396
+ * ```typescript
397
+ * route("product", (ctx) => {
398
+ * ctx.setLocationState(ServerInfo({ data: "value" }));
399
+ * return <ProductPage />;
400
+ * });
401
+ * ```
402
+ */
403
+ setLocationState(entries: LocationStateEntry | LocationStateEntry[]): void;
404
+ /**
405
+ * The matched route name, if the route has an explicit name.
406
+ * Undefined for unnamed routes (those without a `name` option in path()).
407
+ * Includes the namespace prefix from include() (e.g., "blog.post").
408
+ *
409
+ * @example
410
+ * ```typescript
411
+ * route("product", (ctx) => {
412
+ * ctx.routeName // "product"
413
+ * return <ProductPage />;
414
+ * });
415
+ * ```
416
+ */
417
+ routeName?: DefaultRouteName;
418
+ /**
419
+ * Generate URLs from route names.
420
+ *
421
+ * - `.name` -- local route, resolved within current include() scope
422
+ * - `name` -- global route, from the named-routes definition
423
+ *
424
+ * @example
425
+ * ```typescript
426
+ * ctx.reverse(".article", { slug: "hello" }) // Local: magazine.article
427
+ * ctx.reverse(".index") // Local: magazine.index
428
+ * ctx.reverse("magazine.index") // Global: magazine.index
429
+ * ctx.reverse("blog.post", { slug: "hello" }) // Global: blog.post
430
+ * ```
431
+ */
432
+ reverse: [TRouteMap] extends [never]
433
+ ? AutofillAwareReverseFunction<
434
+ Record<string, string>,
435
+ DefaultReverseRouteMap
436
+ >
437
+ : StrictLocalAutofillGlobalReverseFunction<
438
+ TRouteMap,
439
+ DefaultReverseRouteMap
440
+ >;
441
+ };
442
+
443
+ /**
444
+ * Internal handler context with additional props for router internals.
445
+ * Use `HandlerContext` for user-facing code.
446
+ * @internal
447
+ */
448
+ export type InternalHandlerContext<
449
+ TParams = {},
450
+ TEnv = DefaultEnv,
451
+ TSearch extends SearchSchema = {},
452
+ > = HandlerContext<TParams, TEnv, TSearch> & {
453
+ /** @internal Stub response for collecting headers/cookies. */
454
+ res: Response;
455
+ /** @internal Shared variable backing store for ctx.get()/ctx.set(). */
456
+ _variables: Record<string, any>;
457
+ /** Prerender-only control flow helper, attached when the runtime context supports it. */
458
+ passthrough?: () => unknown;
459
+ /** Current segment ID for handle data attribution. */
460
+ _currentSegmentId?: string;
461
+ /** Response type tag (json, text, html, etc.) for cache key differentiation. */
462
+ _responseType?: string;
463
+ /** Route name for cache key scoping (prevents cross-route collisions). */
464
+ _routeName?: string;
465
+ };
466
+
467
+ /**
468
+ * Generic params type - flexible object with string keys
469
+ * Users can narrow this by explicitly typing their params:
470
+ *
471
+ * @example
472
+ * ```typescript
473
+ * [revalidate('post')]: (({ currentParams, nextParams }: RevalidateParams<{ slug: string }>) => {
474
+ * currentParams.slug // typed as string
475
+ * return currentParams.slug !== nextParams.slug;
476
+ * })
477
+ * ```
478
+ */
479
+ export type GenericParams = { [key: string]: string | undefined };
480
+
481
+ /**
482
+ * Helper type for revalidation handler params
483
+ * Allows inline type annotation for stricter param typing
484
+ *
485
+ * @example
486
+ * ```typescript
487
+ * [revalidate('post')]: (params: RevalidateParams<{ slug: string }>) => {
488
+ * params.currentParams.slug // typed as string
489
+ * return params.defaultShouldRevalidate;
490
+ * }
491
+ * ```
492
+ */
493
+ export type RevalidateParams<TParams = GenericParams, TEnv = any> = Parameters<
494
+ ShouldRevalidateFn<TParams, TEnv>
495
+ >[0];
496
+
497
+ /**
498
+ * Should revalidate function signature (inspired by React Router)
499
+ *
500
+ * Determines whether a route segment should re-render during partial navigation.
501
+ * Multiple revalidation functions can be defined per route - they execute in order.
502
+ *
503
+ * **Return Types:**
504
+ * - `boolean` - Hard decision: immediately returns this value (short-circuits)
505
+ * - `{ defaultShouldRevalidate: boolean }` - Soft decision: updates suggestion for next revalidator
506
+ *
507
+ * **Execution Flow:**
508
+ * 1. Start with built-in `defaultShouldRevalidate` (true if params changed)
509
+ * 2. Execute global revalidators first, then route-specific
510
+ * 3. Hard decision (boolean): stop immediately and use that value
511
+ * 4. Soft decision (object): update suggestion and continue to next revalidator
512
+ * 5. If all return soft decisions: use the final suggestion
513
+ *
514
+ * @param args.currentParams - Previous route params (generic by default, can be narrowed)
515
+ * @param args.currentUrl - Previous URL
516
+ * @param args.nextParams - Next route params (generic by default, can be narrowed)
517
+ * @param args.nextUrl - Next URL
518
+ * @param args.defaultShouldRevalidate - Current suggestion (updated by soft decisions)
519
+ * @param args.context - App context (db, user, etc.)
520
+ * @param args.actionResult - Result from action (future support)
521
+ * @param args.formData - Form data from action (future support)
522
+ * @param args.formMethod - HTTP method from action (future support)
523
+ *
524
+ * @returns Hard decision (boolean) or soft suggestion (object)
525
+ *
526
+ * @example
527
+ * ```typescript
528
+ * // Hard decision - definitive answer
529
+ * [revalidate('post')]: ({ currentParams, nextParams }) => {
530
+ * return currentParams.slug !== nextParams.slug; // boolean - short-circuits
531
+ * }
532
+ *
533
+ * // Soft decision - allows downstream revalidators to override
534
+ * [revalidate('*', 'global')]: ({ defaultShouldRevalidate }) => {
535
+ * return { defaultShouldRevalidate: true }; // object - continues to next
536
+ * }
537
+ *
538
+ * // Explicit typing for stricter params
539
+ * [revalidate('post')]: ((params: RevalidateParams<{ slug: string }>) => {
540
+ * return params.currentParams.slug !== params.nextParams.slug;
541
+ * })
542
+ * ```
543
+ */
544
+ /**
545
+ * Revalidation function called during client-side navigation to decide whether
546
+ * a segment (layout, route, parallel slot, or loader) should be re-rendered.
547
+ *
548
+ * Return `true` to re-render, `false` to skip (keep client's current version),
549
+ * or `{ defaultShouldRevalidate: boolean }` to override the default for
550
+ * downstream segments.
551
+ *
552
+ * @example
553
+ * ```ts
554
+ * // Re-render only when a cart action happened or browser signals staleness
555
+ * revalidate(({ actionId, stale }) =>
556
+ * actionId?.includes("cart") || stale || false
557
+ * )
558
+ *
559
+ * // Always re-render when params change (default behavior made explicit)
560
+ * revalidate(({ defaultShouldRevalidate }) => defaultShouldRevalidate)
561
+ * ```
562
+ */
563
+ export type ShouldRevalidateFn<TParams = GenericParams, TEnv = any> = (args: {
564
+ /** Route params from the page being navigated away from. */
565
+ currentParams: TParams;
566
+ /** Full URL of the page being navigated away from. */
567
+ currentUrl: URL;
568
+ /** Route params for the navigation target. */
569
+ nextParams: TParams;
570
+ /** Full URL of the navigation target. */
571
+ nextUrl: URL;
572
+ /**
573
+ * The router's default revalidation decision for this segment.
574
+ * `true` when params changed or the segment is new to the client.
575
+ * Return this when you want default behavior plus your own conditions.
576
+ */
577
+ defaultShouldRevalidate: boolean;
578
+ /** Full handler context — access to `ctx.use()`, `ctx.env`, `ctx.params`, etc. */
579
+ context: HandlerContext<TParams, TEnv>;
580
+
581
+ // ── Segment metadata (which segment is being evaluated) ──────────────
582
+
583
+ /** The type of segment being revalidated. */
584
+ segmentType: "layout" | "route" | "parallel";
585
+ /** Layout name (e.g., `"root"`, `"shop"`, `"auth"`). Only set for layout segments. */
586
+ layoutName?: string;
587
+ /** Slot name (e.g., `"@sidebar"`, `"@modal"`). Only set for parallel segments. */
588
+ slotName?: string;
589
+
590
+ // ── Action context (populated when revalidation is triggered by a server action) ──
591
+
592
+ /**
593
+ * Identifier of the server action that triggered revalidation.
594
+ * `undefined` during normal navigation (no action involved).
595
+ *
596
+ * Format: `"src/<path>#<exportName>"` — the file path is the source path
597
+ * relative to the project root, followed by `#` and the exported function name.
598
+ *
599
+ * This is stable and can be used for path-based matching to revalidate
600
+ * when any action in a module or directory fires:
601
+ *
602
+ * @example
603
+ * ```ts
604
+ * // Match a specific action
605
+ * revalidate(({ actionId }) => actionId === "src/actions/cart.ts#addToCart")
606
+ *
607
+ * // Match any action in the cart module
608
+ * revalidate(({ actionId }) => actionId?.includes("cart") ?? false)
609
+ *
610
+ * // Match any action under src/apps/store/actions/
611
+ * revalidate(({ actionId }) => actionId?.startsWith("src/apps/store/actions/") ?? false)
612
+ * ```
613
+ */
614
+ actionId?: string;
615
+ /** URL where the action was executed (the page the user was on when they triggered the action). */
616
+ actionUrl?: URL;
617
+ /** Return value from the action execution. Can be used to conditionally revalidate based on the action's outcome. */
618
+ actionResult?: any;
619
+ /** FormData from the action request body. Only set for form-based actions (not inline `"use server"` actions). */
620
+ formData?: FormData;
621
+ /** HTTP method: `"GET"` for navigation, `"POST"` for server actions. */
622
+ method?: string;
623
+
624
+ // ── Route identity ───────────────────────────────────────────────────
625
+
626
+ /** Route name of the navigation target. Alias for `toRouteName`. */
627
+ routeName?: DefaultRouteName;
628
+ /**
629
+ * Route name being navigated away from.
630
+ * `undefined` for unnamed internal routes (those without a `name` option).
631
+ */
632
+ fromRouteName?: DefaultRouteName;
633
+ /**
634
+ * Route name being navigated to.
635
+ * `undefined` for unnamed internal routes (those without a `name` option).
636
+ */
637
+ toRouteName?: DefaultRouteName;
638
+
639
+ // ── Staleness signal ─────────────────────────────────────────────────
640
+
641
+ /**
642
+ * `true` when the browser signals that data may be stale — typically because
643
+ * a server action was executed in this or another tab (`_rsc_stale` header).
644
+ *
645
+ * This is NOT segment cache staleness (loaders are never segment-cached).
646
+ * Use this to decide whether loader data should be re-fetched after an
647
+ * action that may have mutated backend state.
648
+ */
649
+ stale?: boolean;
650
+ }) => boolean | { defaultShouldRevalidate: boolean };
651
+
652
+ // MiddlewareFn is imported from "../router/middleware.js" and re-exported
653
+
654
+ /**
655
+ * Extract all route keys from a route definition (includes flattened nested routes)
656
+ */
657
+ export type RouteKeys<T extends RouteDefinition> = keyof ResolvedRouteMap<T> &
658
+ string;
659
+
660
+ /**
661
+ * Valid layout value - component or handler function
662
+ * Note: Arrays are not supported. Use separate layout() declarations with unique names instead.
663
+ */
664
+ type LayoutValue<TEnv = any> = ReactNode | Handler<any, any, TEnv>;
665
+
666
+ /**
667
+ * Helper to extract params from a route key using the resolved (flattened) route map
668
+ */
669
+ export type ExtractRouteParams<
670
+ T extends RouteDefinition,
671
+ K extends string,
672
+ > = K extends keyof ResolvedRouteMap<T>
673
+ ? ResolvedRouteMap<T>[K] extends string
674
+ ? ExtractParams<ResolvedRouteMap<T>[K]>
675
+ : GenericParams
676
+ : GenericParams;
677
+
678
+ /**
679
+ * Handlers object that maps route names to handler functions with type-safe string patterns
680
+ */
681
+ export type HandlersForRouteMap<T extends RouteDefinition, TEnv = any> = {
682
+ // Route handlers - type-safe params extracted from route patterns
683
+ [K in RouteKeys<T>]?: Handler<ExtractRouteParams<T, K & string>, any, TEnv>;
684
+ } & {
685
+ // Layout patterns: $layout.{routeName}.{layoutName}
686
+ [K in `$layout.${RouteKeys<T> | "*"}.${string}`]?: LayoutValue<TEnv>;
687
+ } & {
688
+ // Parallel route patterns: $parallel.{routeName}.{parallelName}
689
+ [K in `$parallel.${RouteKeys<T>}.${string}`]?: Record<
690
+ `@${string}`,
691
+ Handler<
692
+ K extends `$parallel.${infer RouteKey}.${string}`
693
+ ? RouteKey extends RouteKeys<T>
694
+ ? ExtractRouteParams<T, RouteKey & string>
695
+ : GenericParams
696
+ : GenericParams,
697
+ any,
698
+ TEnv
699
+ >
700
+ >;
701
+ } & {
702
+ // Global parallel routes (with '*') use GenericParams
703
+ [K in `$parallel.${"*"}.${string}`]?: Record<
704
+ `@${string}`,
705
+ Handler<GenericParams, any, TEnv>
706
+ >;
707
+ } & {
708
+ // Middleware patterns: $middleware.{routeName}.{middlewareName}
709
+ [K in `$middleware.${RouteKeys<T> | "*"}.${string}`]?: MiddlewareFn<
710
+ TEnv,
711
+ GenericParams
712
+ >[];
713
+ } & {
714
+ // Route revalidate patterns: $revalidate.route.{routeName}.{revalidateName}
715
+ [K in `$revalidate.route.${RouteKeys<T> | "*"}.${string}`]?: ShouldRevalidateFn<
716
+ GenericParams,
717
+ TEnv
718
+ >;
719
+ } & {
720
+ // Layout revalidate patterns: $revalidate.layout.{routeName}.{layoutName}.{revalidateName}
721
+ [K in `$revalidate.layout.${RouteKeys<T> | "*"}.${string}.${string}`]?: ShouldRevalidateFn<
722
+ GenericParams,
723
+ TEnv
724
+ >;
725
+ } & {
726
+ // Parallel revalidate patterns: $revalidate.parallel.{routeName}.{parallelName}.{slotName}.{revalidateName}
727
+ [K in `$revalidate.parallel.${RouteKeys<T> | "*"}.${string}.${string}.${string}`]?: ShouldRevalidateFn<
728
+ GenericParams,
729
+ TEnv
730
+ >;
731
+ };
732
+
733
+ /**
734
+ * Revalidation function with typed params
735
+ *
736
+ * @template T - Params object
737
+ * @template TEnv - Environment type
738
+ *
739
+ * @example
740
+ * ```typescript
741
+ * const revalidate: Revalidate<{ slug: string }> = ({ currentParams, nextParams }) => {
742
+ * return currentParams.slug !== nextParams.slug;
743
+ * }
744
+ * ```
745
+ */
746
+ export type Revalidate<
747
+ T = GenericParams,
748
+ TEnv = DefaultEnv,
749
+ > = ShouldRevalidateFn<T, TEnv>;
750
+
751
+ /**
752
+ * Middleware function with typed params and environment
753
+ *
754
+ * @template TParams - Params object (defaults to generic)
755
+ * @template TEnv - Environment type (defaults to global RSCRouter.Env)
756
+ *
757
+ * Note: Middleware cannot directly use route names for params typing because
758
+ * middleware is defined during router setup, before RegisteredRoutes is populated.
759
+ * Use ExtractParams<"/path/:id"> for typed params from a path pattern.
760
+ *
761
+ * @example
762
+ * ```typescript
763
+ * // Basic middleware (uses global RSCRouter.Env via module augmentation)
764
+ * const middleware: Middleware = async (ctx, next) => {
765
+ * ctx.set("user", { id: "123" }); // Type-safe!
766
+ * await next();
767
+ * }
768
+ *
769
+ * // With explicit params (most common)
770
+ * const middleware: Middleware<{ id: string }> = async (ctx, next) => {
771
+ * console.log(ctx.params.id);
772
+ * await next();
773
+ * }
774
+ *
775
+ * // With params from path pattern
776
+ * const middleware: Middleware<ExtractParams<"/products/:id">> = async (ctx, next) => {
777
+ * console.log(ctx.params.id);
778
+ * await next();
779
+ * }
780
+ *
781
+ * // With both params and explicit env
782
+ * const middleware: Middleware<{ id: string }, AppEnv> = async (ctx, next) => {
783
+ * ctx.set("user", { id: ctx.params.id });
784
+ * await next();
785
+ * }
786
+ * ```
787
+ */
788
+ export type Middleware<
789
+ TParams = GenericParams,
790
+ TEnv = DefaultEnv,
791
+ > = MiddlewareFn<TEnv, TParams>;