@ivogt/rsc-router 0.0.0-experimental.1

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 (123) hide show
  1. package/README.md +19 -0
  2. package/package.json +131 -0
  3. package/src/__mocks__/version.ts +6 -0
  4. package/src/__tests__/route-definition.test.ts +63 -0
  5. package/src/browser/event-controller.ts +876 -0
  6. package/src/browser/index.ts +18 -0
  7. package/src/browser/link-interceptor.ts +121 -0
  8. package/src/browser/lru-cache.ts +69 -0
  9. package/src/browser/merge-segment-loaders.ts +126 -0
  10. package/src/browser/navigation-bridge.ts +891 -0
  11. package/src/browser/navigation-client.ts +155 -0
  12. package/src/browser/navigation-store.ts +823 -0
  13. package/src/browser/partial-update.ts +545 -0
  14. package/src/browser/react/Link.tsx +248 -0
  15. package/src/browser/react/NavigationProvider.tsx +228 -0
  16. package/src/browser/react/ScrollRestoration.tsx +94 -0
  17. package/src/browser/react/context.ts +53 -0
  18. package/src/browser/react/index.ts +52 -0
  19. package/src/browser/react/location-state-shared.ts +120 -0
  20. package/src/browser/react/location-state.ts +62 -0
  21. package/src/browser/react/use-action.ts +240 -0
  22. package/src/browser/react/use-client-cache.ts +56 -0
  23. package/src/browser/react/use-handle.ts +178 -0
  24. package/src/browser/react/use-link-status.ts +134 -0
  25. package/src/browser/react/use-navigation.ts +150 -0
  26. package/src/browser/react/use-segments.ts +188 -0
  27. package/src/browser/request-controller.ts +149 -0
  28. package/src/browser/rsc-router.tsx +310 -0
  29. package/src/browser/scroll-restoration.ts +324 -0
  30. package/src/browser/server-action-bridge.ts +747 -0
  31. package/src/browser/shallow.ts +35 -0
  32. package/src/browser/types.ts +443 -0
  33. package/src/cache/__tests__/memory-segment-store.test.ts +487 -0
  34. package/src/cache/__tests__/memory-store.test.ts +484 -0
  35. package/src/cache/cache-scope.ts +565 -0
  36. package/src/cache/cf/__tests__/cf-cache-store.test.ts +361 -0
  37. package/src/cache/cf/cf-cache-store.ts +274 -0
  38. package/src/cache/cf/index.ts +19 -0
  39. package/src/cache/index.ts +52 -0
  40. package/src/cache/memory-segment-store.ts +150 -0
  41. package/src/cache/memory-store.ts +253 -0
  42. package/src/cache/types.ts +366 -0
  43. package/src/client.rsc.tsx +88 -0
  44. package/src/client.tsx +609 -0
  45. package/src/components/DefaultDocument.tsx +20 -0
  46. package/src/default-error-boundary.tsx +88 -0
  47. package/src/deps/browser.ts +8 -0
  48. package/src/deps/html-stream-client.ts +2 -0
  49. package/src/deps/html-stream-server.ts +2 -0
  50. package/src/deps/rsc.ts +10 -0
  51. package/src/deps/ssr.ts +2 -0
  52. package/src/errors.ts +259 -0
  53. package/src/handle.ts +120 -0
  54. package/src/handles/MetaTags.tsx +178 -0
  55. package/src/handles/index.ts +6 -0
  56. package/src/handles/meta.ts +247 -0
  57. package/src/href-client.ts +128 -0
  58. package/src/href.ts +139 -0
  59. package/src/index.rsc.ts +69 -0
  60. package/src/index.ts +84 -0
  61. package/src/loader.rsc.ts +204 -0
  62. package/src/loader.ts +47 -0
  63. package/src/network-error-thrower.tsx +21 -0
  64. package/src/outlet-context.ts +15 -0
  65. package/src/root-error-boundary.tsx +277 -0
  66. package/src/route-content-wrapper.tsx +198 -0
  67. package/src/route-definition.ts +1333 -0
  68. package/src/route-map-builder.ts +140 -0
  69. package/src/route-types.ts +148 -0
  70. package/src/route-utils.ts +89 -0
  71. package/src/router/__tests__/match-context.test.ts +104 -0
  72. package/src/router/__tests__/match-pipelines.test.ts +537 -0
  73. package/src/router/__tests__/match-result.test.ts +566 -0
  74. package/src/router/__tests__/on-error.test.ts +935 -0
  75. package/src/router/__tests__/pattern-matching.test.ts +577 -0
  76. package/src/router/error-handling.ts +287 -0
  77. package/src/router/handler-context.ts +60 -0
  78. package/src/router/loader-resolution.ts +326 -0
  79. package/src/router/manifest.ts +116 -0
  80. package/src/router/match-context.ts +261 -0
  81. package/src/router/match-middleware/background-revalidation.ts +236 -0
  82. package/src/router/match-middleware/cache-lookup.ts +261 -0
  83. package/src/router/match-middleware/cache-store.ts +250 -0
  84. package/src/router/match-middleware/index.ts +81 -0
  85. package/src/router/match-middleware/intercept-resolution.ts +268 -0
  86. package/src/router/match-middleware/segment-resolution.ts +174 -0
  87. package/src/router/match-pipelines.ts +214 -0
  88. package/src/router/match-result.ts +212 -0
  89. package/src/router/metrics.ts +62 -0
  90. package/src/router/middleware.test.ts +1355 -0
  91. package/src/router/middleware.ts +748 -0
  92. package/src/router/pattern-matching.ts +271 -0
  93. package/src/router/revalidation.ts +190 -0
  94. package/src/router/router-context.ts +299 -0
  95. package/src/router/types.ts +96 -0
  96. package/src/router.ts +3484 -0
  97. package/src/rsc/__tests__/helpers.test.ts +175 -0
  98. package/src/rsc/handler.ts +942 -0
  99. package/src/rsc/helpers.ts +64 -0
  100. package/src/rsc/index.ts +56 -0
  101. package/src/rsc/nonce.ts +18 -0
  102. package/src/rsc/types.ts +225 -0
  103. package/src/segment-system.tsx +405 -0
  104. package/src/server/__tests__/request-context.test.ts +171 -0
  105. package/src/server/context.ts +340 -0
  106. package/src/server/handle-store.ts +230 -0
  107. package/src/server/loader-registry.ts +174 -0
  108. package/src/server/request-context.ts +470 -0
  109. package/src/server/root-layout.tsx +10 -0
  110. package/src/server/tsconfig.json +14 -0
  111. package/src/server.ts +126 -0
  112. package/src/ssr/__tests__/ssr-handler.test.tsx +188 -0
  113. package/src/ssr/index.tsx +215 -0
  114. package/src/types.ts +1473 -0
  115. package/src/use-loader.tsx +346 -0
  116. package/src/vite/__tests__/expose-loader-id.test.ts +117 -0
  117. package/src/vite/expose-action-id.ts +344 -0
  118. package/src/vite/expose-handle-id.ts +209 -0
  119. package/src/vite/expose-loader-id.ts +357 -0
  120. package/src/vite/expose-location-state-id.ts +177 -0
  121. package/src/vite/index.ts +608 -0
  122. package/src/vite/version.d.ts +12 -0
  123. package/src/vite/virtual-entries.ts +109 -0
package/src/types.ts ADDED
@@ -0,0 +1,1473 @@
1
+ import type { ReactNode } from "react";
2
+ import type { AllUseItems } from "./route-types.js";
3
+ import type { Handle } from "./handle.js";
4
+ import type { MiddlewareFn } from "./router/middleware.js";
5
+ export type { MiddlewareFn } from "./router/middleware.js";
6
+
7
+ /**
8
+ * Props for the Document component that wraps the entire application.
9
+ */
10
+ export type DocumentProps = {
11
+ children: ReactNode;
12
+ };
13
+
14
+ /**
15
+ * Global namespace for module augmentation
16
+ *
17
+ * Users can augment this to provide type-safe context globally:
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * // In router.tsx or env.d.ts
22
+ * declare global {
23
+ * namespace RSCRouter {
24
+ * interface Env extends RouterEnv<AppBindings, AppVariables> {}
25
+ * }
26
+ * }
27
+ *
28
+ * // Now all handlers have type-safe context without imports!
29
+ * export default map<typeof shopRoutes>({
30
+ * [middleware('*', 'auth')]: [
31
+ * (ctx, next) => {
32
+ * ctx.set('user', ...) // Type-safe!
33
+ * }
34
+ * ]
35
+ * })
36
+ * ```
37
+ */
38
+ declare global {
39
+ namespace RSCRouter {
40
+ // eslint-disable-next-line @typescript-eslint/no-empty-interface
41
+ interface Env {
42
+ // Empty by default - users augment with their RouterEnv
43
+ }
44
+
45
+ // eslint-disable-next-line @typescript-eslint/no-empty-interface
46
+ interface RegisteredRoutes {
47
+ // Empty by default - users augment with their merged route maps for type-safe href()
48
+ }
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Get registered routes or fallback to generic Record<string, string>
54
+ * When RSCRouter.RegisteredRoutes is augmented, provides autocomplete for route names
55
+ * When not augmented, allows any string (no autocomplete)
56
+ */
57
+ export type GetRegisteredRoutes = keyof RSCRouter.RegisteredRoutes extends never
58
+ ? Record<string, string>
59
+ : RSCRouter.RegisteredRoutes;
60
+
61
+ /**
62
+ * Default environment type - uses global augmentation if available, any otherwise
63
+ */
64
+ export type DefaultEnv = keyof RSCRouter.Env extends never ? any : RSCRouter.Env;
65
+
66
+ /**
67
+ * Router environment (Hono-inspired type-safe context)
68
+ *
69
+ * @template TBindings - Platform bindings (DB, KV, secrets, etc.)
70
+ * @template TVariables - Middleware-injected variables (user, permissions, etc.)
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * interface AppBindings {
75
+ * DB: D1Database;
76
+ * KV: KVNamespace;
77
+ * STRIPE_KEY: string;
78
+ * }
79
+ *
80
+ * interface AppVariables {
81
+ * user?: { id: string; name: string };
82
+ * permissions?: string[];
83
+ * }
84
+ *
85
+ * type AppEnv = RouterEnv<AppBindings, AppVariables>;
86
+ * const router = createRSCRouter<AppEnv>();
87
+ * ```
88
+ */
89
+ export interface RouterEnv<TBindings = {}, TVariables = {}> {
90
+ Bindings: TBindings;
91
+ Variables: TVariables;
92
+ }
93
+
94
+ /**
95
+ * Parse constraint values into a union type
96
+ * "a|b|c" → "a" | "b" | "c"
97
+ */
98
+ type ParseConstraint<T extends string> =
99
+ T extends `${infer First}|${infer Rest}`
100
+ ? First | ParseConstraint<Rest>
101
+ : T;
102
+
103
+ /**
104
+ * Extract param info from a param segment
105
+ *
106
+ * Handles:
107
+ * - :param → { name: "param", optional: false, type: string }
108
+ * - :param? → { name: "param", optional: true, type: string }
109
+ * - :param(a|b) → { name: "param", optional: false, type: "a" | "b" }
110
+ * - :param(a|b)? → { name: "param", optional: true, type: "a" | "b" }
111
+ */
112
+ type ExtractParamInfo<T extends string> =
113
+ // Optional + constrained: :param(a|b)?
114
+ T extends `${infer Name}(${infer Constraint})?`
115
+ ? { name: Name; optional: true; type: ParseConstraint<Constraint> }
116
+ // Constrained only: :param(a|b)
117
+ : T extends `${infer Name}(${infer Constraint})`
118
+ ? { name: Name; optional: false; type: ParseConstraint<Constraint> }
119
+ // Optional only: :param?
120
+ : T extends `${infer Name}?`
121
+ ? { name: Name; optional: true; type: string }
122
+ // Required: :param
123
+ : { name: T; optional: false; type: string };
124
+
125
+ /**
126
+ * Build param object from info
127
+ */
128
+ type ParamFromInfo<Info> =
129
+ Info extends { name: infer N extends string; optional: true; type: infer V }
130
+ ? { [K in N]?: V }
131
+ : Info extends { name: infer N extends string; optional: false; type: infer V }
132
+ ? { [K in N]: V }
133
+ : never;
134
+
135
+ /**
136
+ * Merge two param objects
137
+ */
138
+ type MergeParams<A, B> = {
139
+ [K in keyof A | keyof B]: K extends keyof A
140
+ ? K extends keyof B
141
+ ? A[K] | B[K]
142
+ : A[K]
143
+ : K extends keyof B
144
+ ? B[K]
145
+ : never;
146
+ };
147
+
148
+ /**
149
+ * Extract route params from a pattern with depth limit to prevent infinite recursion
150
+ *
151
+ * Supports:
152
+ * - Required params: /:slug → { slug: string }
153
+ * - Optional params: /:locale? → { locale?: string }
154
+ * - Constrained params: /:locale(en|gb) → { locale: "en" | "gb" }
155
+ * - Optional + constrained: /:locale(en|gb)? → { locale?: "en" | "gb" }
156
+ *
157
+ * @example
158
+ * ExtractParams<"/products/:id"> // { id: string }
159
+ * ExtractParams<"/:locale?/blog/:slug"> // { locale?: string; slug: string }
160
+ * ExtractParams<"/:locale(en|gb)/blog"> // { locale: "en" | "gb" }
161
+ * ExtractParams<"/:locale(en|gb)?/blog/:slug"> // { locale?: "en" | "gb"; slug: string }
162
+ */
163
+ export type ExtractParams<
164
+ T extends string,
165
+ Depth extends readonly unknown[] = []
166
+ > = Depth['length'] extends 10
167
+ ? { [key: string]: string | undefined } // Fallback to generic params if too deep
168
+ // Match param with remaining path: :param.../rest
169
+ : T extends `${infer _Start}:${infer Param}/${infer Rest}`
170
+ ? MergeParams<
171
+ ParamFromInfo<ExtractParamInfo<Param>>,
172
+ ExtractParams<`/${Rest}`, readonly [...Depth, unknown]>
173
+ >
174
+ // Match param at end: :param...
175
+ : T extends `${infer _Start}:${infer Param}`
176
+ ? ParamFromInfo<ExtractParamInfo<Param>>
177
+ : {};
178
+
179
+ /**
180
+ * Route definition - maps route names to patterns
181
+ */
182
+ /**
183
+ * Trailing slash handling mode
184
+ * - "never": Redirect URLs with trailing slash to without
185
+ * - "always": Redirect URLs without trailing slash to with
186
+ * - "ignore": Match both with and without trailing slash
187
+ */
188
+ export type TrailingSlashMode = "never" | "always" | "ignore";
189
+
190
+ /**
191
+ * Route configuration object (alternative to string path)
192
+ */
193
+ export type RouteConfig = {
194
+ path: string;
195
+ trailingSlash?: TrailingSlashMode;
196
+ };
197
+
198
+ /**
199
+ * Route definition options (global defaults)
200
+ */
201
+ export type RouteDefinitionOptions = {
202
+ trailingSlash?: TrailingSlashMode;
203
+ };
204
+
205
+ export type RouteDefinition = {
206
+ [key: string]: string | RouteConfig | RouteDefinition;
207
+ };
208
+
209
+ /**
210
+ * Recursively flatten nested routes with depth limit to prevent infinite recursion
211
+ * Transforms: { products: { detail: "/product/:slug" } } => { "products.detail": "/product/:slug" }
212
+ * Also handles RouteConfig objects: { api: { path: "/api" } } => { "api": "/api" }
213
+ */
214
+ type FlattenRoutes<
215
+ T extends RouteDefinition,
216
+ Prefix extends string = "",
217
+ Depth extends readonly unknown[] = []
218
+ > = Depth['length'] extends 5
219
+ ? never
220
+ : {
221
+ [K in keyof T]: T[K] extends string
222
+ ? Record<`${Prefix}${K & string}`, T[K]>
223
+ : T[K] extends RouteConfig
224
+ ? Record<`${Prefix}${K & string}`, T[K]['path']>
225
+ : T[K] extends RouteDefinition
226
+ ? FlattenRoutes<T[K], `${Prefix}${K & string}.`, readonly [...Depth, unknown]>
227
+ : never;
228
+ }[keyof T];
229
+
230
+ /**
231
+ * Union to intersection helper
232
+ */
233
+ type UnionToIntersection<U> = (
234
+ U extends unknown ? (k: U) => void : never
235
+ ) extends (k: infer I) => void
236
+ ? I
237
+ : never;
238
+
239
+ /**
240
+ * Resolved route map - flattened route definitions with full paths
241
+ */
242
+ export type ResolvedRouteMap<T extends RouteDefinition> = UnionToIntersection<FlattenRoutes<T>>;
243
+
244
+ /**
245
+ * Handler function that receives context and returns React content
246
+ */
247
+ export type Handler<TParams = {}, TEnv = any> = (
248
+ ctx: HandlerContext<TParams, TEnv>
249
+ ) => ReactNode | Promise<ReactNode>;
250
+
251
+ /**
252
+ * Context passed to handlers (Hono-inspired type-safe context)
253
+ *
254
+ * Provides type-safe access to:
255
+ * - Route params (from URL pattern)
256
+ * - Request data (request, searchParams, pathname, url)
257
+ * - Platform bindings (env.DB, env.KV, env.SECRETS)
258
+ * - Middleware variables (var.user, var.permissions)
259
+ * - Getter/setter for variables (get('user'), set('user', ...))
260
+ *
261
+ * **Important:** System parameters (query params starting with `_rsc`) are filtered out.
262
+ * Handlers see only user-facing query params. Access raw request via `_originalRequest`.
263
+ *
264
+ * @example
265
+ * ```typescript
266
+ * const handler = (ctx: HandlerContext<{ slug: string }, AppEnv>) => {
267
+ * ctx.params.slug // Route param (string)
268
+ * ctx.env.DB // Binding (D1Database)
269
+ * ctx.var.user // Variable (User | undefined)
270
+ * ctx.get('user') // Alternative getter
271
+ * ctx.set('user', {...}) // Setter
272
+ *
273
+ * // Clean URLs (system params filtered):
274
+ * ctx.url // No _rsc* params
275
+ * ctx.searchParams // No _rsc* params
276
+ *
277
+ * // Advanced: access raw request
278
+ * ctx._originalRequest // Full request with all params
279
+ * }
280
+ * ```
281
+ */
282
+ export type HandlerContext<TParams = {}, TEnv = any> = {
283
+ params: TParams;
284
+ request: Request;
285
+ searchParams: URLSearchParams; // Filtered (no _rsc* params)
286
+ pathname: string;
287
+ url: URL; // Filtered (no _rsc* params)
288
+ env: TEnv extends RouterEnv<infer B, any> ? B : {};
289
+ var: TEnv extends RouterEnv<any, infer V> ? V : {};
290
+ get: TEnv extends RouterEnv<any, infer V>
291
+ ? <K extends keyof V>(key: K) => V[K]
292
+ : (key: string) => any;
293
+ set: TEnv extends RouterEnv<any, infer V>
294
+ ? <K extends keyof V>(key: K, value: V[K]) => void
295
+ : (key: string, value: any) => void;
296
+ _originalRequest: Request; // Raw request (includes all system params)
297
+ /**
298
+ * Access loader data or push handle data.
299
+ *
300
+ * For loaders: Returns a promise that resolves to the loader data.
301
+ * Loaders are executed in parallel and memoized per request.
302
+ *
303
+ * For handles: Returns a push function to add data for this segment.
304
+ * Handle data accumulates across all matched route segments.
305
+ * Push accepts: direct value, Promise, or async callback (executed immediately).
306
+ *
307
+ * @example
308
+ * ```typescript
309
+ * // Loader usage
310
+ * route("cart", async (ctx) => {
311
+ * const cart = await ctx.use(CartLoader);
312
+ * return <CartPage cart={cart} />;
313
+ * });
314
+ *
315
+ * // Handle usage - direct value
316
+ * route("shop", (ctx) => {
317
+ * const push = ctx.use(Breadcrumbs);
318
+ * push({ label: "Shop", href: "/shop" });
319
+ * return <ShopPage />;
320
+ * });
321
+ *
322
+ * // Handle usage - Promise
323
+ * route("product", (ctx) => {
324
+ * const push = ctx.use(Breadcrumbs);
325
+ * push(fetchProductBreadcrumb(ctx.params.id));
326
+ * return <ProductPage />;
327
+ * });
328
+ *
329
+ * // Handle usage - async callback (executed immediately)
330
+ * route("product", (ctx) => {
331
+ * const push = ctx.use(Breadcrumbs);
332
+ * push(async () => {
333
+ * const product = await db.getProduct(ctx.params.id);
334
+ * return { label: product.name, href: `/product/${product.id}` };
335
+ * });
336
+ * return <ProductPage />;
337
+ * });
338
+ * ```
339
+ */
340
+ use: {
341
+ <T, TLoaderParams = any>(loader: LoaderDefinition<T, TLoaderParams>): Promise<T>;
342
+ <TData, TAccumulated = TData[]>(handle: Handle<TData, TAccumulated>): (
343
+ data: TData | Promise<TData> | (() => Promise<TData>)
344
+ ) => void;
345
+ };
346
+ /**
347
+ * Internal: Current segment ID for handle data attribution.
348
+ * Set by the router before calling each handler.
349
+ * @internal
350
+ */
351
+ _currentSegmentId?: string;
352
+ };
353
+
354
+ /**
355
+ * Generic params type - flexible object with string keys
356
+ * Users can narrow this by explicitly typing their params:
357
+ *
358
+ * @example
359
+ * ```typescript
360
+ * [revalidate('post')]: (({ currentParams, nextParams }: RevalidateParams<{ slug: string }>) => {
361
+ * currentParams.slug // typed as string
362
+ * return currentParams.slug !== nextParams.slug;
363
+ * })
364
+ * ```
365
+ */
366
+ export type GenericParams = { [key: string]: string | undefined };
367
+
368
+ /**
369
+ * Helper type for revalidation handler params
370
+ * Allows inline type annotation for stricter param typing
371
+ *
372
+ * @example
373
+ * ```typescript
374
+ * [revalidate('post')]: (params: RevalidateParams<{ slug: string }>) => {
375
+ * params.currentParams.slug // typed as string
376
+ * return params.defaultShouldRevalidate;
377
+ * }
378
+ * ```
379
+ */
380
+ export type RevalidateParams<TParams = GenericParams, TEnv = any> = Parameters<ShouldRevalidateFn<TParams, TEnv>>[0];
381
+
382
+ /**
383
+ * Should revalidate function signature (inspired by React Router)
384
+ *
385
+ * Determines whether a route segment should re-render during partial navigation.
386
+ * Multiple revalidation functions can be defined per route - they execute in order.
387
+ *
388
+ * **Return Types:**
389
+ * - `boolean` - Hard decision: immediately returns this value (short-circuits)
390
+ * - `{ defaultShouldRevalidate: boolean }` - Soft decision: updates suggestion for next revalidator
391
+ *
392
+ * **Execution Flow:**
393
+ * 1. Start with built-in `defaultShouldRevalidate` (true if params changed)
394
+ * 2. Execute global revalidators first, then route-specific
395
+ * 3. Hard decision (boolean): stop immediately and use that value
396
+ * 4. Soft decision (object): update suggestion and continue to next revalidator
397
+ * 5. If all return soft decisions: use the final suggestion
398
+ *
399
+ * @param args.currentParams - Previous route params (generic by default, can be narrowed)
400
+ * @param args.currentUrl - Previous URL
401
+ * @param args.nextParams - Next route params (generic by default, can be narrowed)
402
+ * @param args.nextUrl - Next URL
403
+ * @param args.defaultShouldRevalidate - Current suggestion (updated by soft decisions)
404
+ * @param args.context - App context (db, user, etc.)
405
+ * @param args.actionResult - Result from action (future support)
406
+ * @param args.formData - Form data from action (future support)
407
+ * @param args.formMethod - HTTP method from action (future support)
408
+ *
409
+ * @returns Hard decision (boolean) or soft suggestion (object)
410
+ *
411
+ * @example
412
+ * ```typescript
413
+ * // Hard decision - definitive answer
414
+ * [revalidate('post')]: ({ currentParams, nextParams }) => {
415
+ * return currentParams.slug !== nextParams.slug; // boolean - short-circuits
416
+ * }
417
+ *
418
+ * // Soft decision - allows downstream revalidators to override
419
+ * [revalidate('*', 'global')]: ({ defaultShouldRevalidate }) => {
420
+ * return { defaultShouldRevalidate: true }; // object - continues to next
421
+ * }
422
+ *
423
+ * // Explicit typing for stricter params
424
+ * [revalidate('post')]: ((params: RevalidateParams<{ slug: string }>) => {
425
+ * return params.currentParams.slug !== params.nextParams.slug;
426
+ * })
427
+ * ```
428
+ */
429
+ export type ShouldRevalidateFn<TParams = GenericParams, TEnv = any> = (args: {
430
+ currentParams: TParams;
431
+ currentUrl: URL;
432
+ nextParams: TParams;
433
+ nextUrl: URL;
434
+ defaultShouldRevalidate: boolean;
435
+ context: HandlerContext<TParams, TEnv>;
436
+ // Segment metadata (which segment is being evaluated):
437
+ segmentType: 'layout' | 'route' | 'parallel';
438
+ layoutName?: string; // Layout name (e.g., "root", "shop", "auth") - only for layouts
439
+ slotName?: string; // Slot name (e.g., "@sidebar", "@modal") - only for parallels
440
+ // Action context (populated when revalidation triggered by server action):
441
+ actionId?: string; // Action identifier (e.g., "src/actions.ts#addToCart")
442
+ actionUrl?: URL; // URL where action was executed
443
+ actionResult?: any; // Return value from action execution
444
+ formData?: FormData; // FormData from action request
445
+ method?: string; // Request method: 'GET' for navigation, 'POST' for actions
446
+ routeName?: string; // Route name where action was executed (e.g., "products.detail")
447
+ // Stale cache revalidation (SWR pattern):
448
+ stale?: boolean; // True if this is a stale cache revalidation request
449
+ }) => boolean | { defaultShouldRevalidate: boolean };
450
+
451
+ /**
452
+ * Middleware function signature
453
+ *
454
+ * Middleware can either call `next()` to continue the pipeline,
455
+ * or return a Response to short-circuit and skip remaining middleware + handler.
456
+ *
457
+ * **Short-Circuit Patterns:**
458
+ * - `return redirect('/login')` - Soft redirect (SPA navigation)
459
+ * - `return Response.redirect('/login', 302)` - Hard redirect (full page reload)
460
+ * - `return new Response('Unauthorized', { status: 401 })` - Error response
461
+ *
462
+ * @param TParams - Route params (defaults to GenericParams, can be narrowed with satisfies)
463
+ * @param TEnv - Environment type
464
+ *
465
+ * @example
466
+ * ```typescript
467
+ * [middleware('checkout.*', 'auth')]: [
468
+ * (ctx, next) => {
469
+ * if (!ctx.get('user')) {
470
+ * return redirect('/login'); // Soft redirect - short-circuit
471
+ * }
472
+ * next(); // Continue pipeline
473
+ * }
474
+ * ]
475
+ * ```
476
+ */
477
+ // MiddlewareFn is imported from "./router/middleware.js" and re-exported
478
+
479
+ /**
480
+ * Extract all route keys from a route definition (includes flattened nested routes)
481
+ */
482
+ export type RouteKeys<T extends RouteDefinition> = keyof ResolvedRouteMap<T> & string;
483
+
484
+ /**
485
+ * Valid layout value - component or handler function
486
+ * Note: Arrays are not supported. Use separate layout() declarations with unique names instead.
487
+ */
488
+ type LayoutValue<TEnv = any> =
489
+ | ReactNode
490
+ | Handler<any, TEnv>;
491
+
492
+ /**
493
+ * Helper to extract params from a route key using the resolved (flattened) route map
494
+ */
495
+ export type ExtractRouteParams<T extends RouteDefinition, K extends string> =
496
+ K extends keyof ResolvedRouteMap<T>
497
+ ? ResolvedRouteMap<T>[K] extends string
498
+ ? ExtractParams<ResolvedRouteMap<T>[K]>
499
+ : GenericParams
500
+ : GenericParams;
501
+
502
+ /**
503
+ * Handlers object that maps route names to handler functions with type-safe string patterns
504
+ */
505
+ export type HandlersForRouteMap<T extends RouteDefinition, TEnv = any> = {
506
+ // Route handlers - type-safe params extracted from route patterns
507
+ [K in RouteKeys<T>]?: Handler<ExtractRouteParams<T, K & string>, TEnv>;
508
+ } & {
509
+ // Layout patterns: $layout.{routeName}.{layoutName}
510
+ [K in `$layout.${RouteKeys<T> | '*'}.${string}`]?: LayoutValue<TEnv>;
511
+ } & {
512
+ // Parallel route patterns: $parallel.{routeName}.{parallelName}
513
+ [K in `$parallel.${RouteKeys<T>}.${string}`]?: Record<
514
+ `@${string}`,
515
+ Handler<
516
+ K extends `$parallel.${infer RouteKey}.${string}`
517
+ ? RouteKey extends RouteKeys<T>
518
+ ? ExtractRouteParams<T, RouteKey & string>
519
+ : GenericParams
520
+ : GenericParams,
521
+ TEnv
522
+ >
523
+ >;
524
+ } & {
525
+ // Global parallel routes (with '*') use GenericParams
526
+ [K in `$parallel.${"*"}.${string}`]?: Record<`@${string}`, Handler<GenericParams, TEnv>>;
527
+ } & {
528
+ // Middleware patterns: $middleware.{routeName}.{middlewareName}
529
+ [K in `$middleware.${RouteKeys<T> | '*'}.${string}`]?: MiddlewareFn<TEnv, GenericParams>[];
530
+ } & {
531
+ // Route revalidate patterns: $revalidate.route.{routeName}.{revalidateName}
532
+ [K in `$revalidate.route.${RouteKeys<T> | '*'}.${string}`]?: ShouldRevalidateFn<GenericParams, TEnv>;
533
+ } & {
534
+ // Layout revalidate patterns: $revalidate.layout.{routeName}.{layoutName}.{revalidateName}
535
+ [K in `$revalidate.layout.${RouteKeys<T> | '*'}.${string}.${string}`]?: ShouldRevalidateFn<GenericParams, TEnv>;
536
+ } & {
537
+ // Parallel revalidate patterns: $revalidate.parallel.{routeName}.{parallelName}.{slotName}.{revalidateName}
538
+ [K in `$revalidate.parallel.${RouteKeys<T> | '*'}.${string}.${string}.${string}`]?: ShouldRevalidateFn<GenericParams, TEnv>;
539
+ };
540
+
541
+ /**
542
+ * Error information passed to error boundary fallback components
543
+ */
544
+ export interface ErrorInfo {
545
+ /** Error message (always available) */
546
+ message: string;
547
+ /** Error name/type (e.g., "RouteNotFoundError", "MiddlewareError") */
548
+ name: string;
549
+ /** Optional error code for programmatic handling */
550
+ code?: string;
551
+ /** Stack trace (only in development) */
552
+ stack?: string;
553
+ /** Original error cause if available */
554
+ cause?: unknown;
555
+ /** Segment ID where the error occurred */
556
+ segmentId: string;
557
+ /** Segment type where the error occurred */
558
+ segmentType: "layout" | "route" | "parallel" | "loader" | "middleware" | "cache";
559
+ }
560
+
561
+ /**
562
+ * Props passed to server-side error boundary fallback components
563
+ *
564
+ * Server error boundaries don't have a reset function since the error
565
+ * occurred during server rendering. Users can navigate away or refresh.
566
+ *
567
+ * @example
568
+ * ```typescript
569
+ * function ProductErrorFallback({ error }: ErrorBoundaryFallbackProps) {
570
+ * return (
571
+ * <div>
572
+ * <h2>Something went wrong loading the product</h2>
573
+ * <p>{error.message}</p>
574
+ * <a href="/">Go home</a>
575
+ * </div>
576
+ * );
577
+ * }
578
+ * ```
579
+ */
580
+ export interface ErrorBoundaryFallbackProps {
581
+ /** Error information */
582
+ error: ErrorInfo;
583
+ }
584
+
585
+ /**
586
+ * Error boundary handler - receives error info and returns fallback UI
587
+ */
588
+ export type ErrorBoundaryHandler = (props: ErrorBoundaryFallbackProps) => ReactNode;
589
+
590
+ /**
591
+ * Props passed to client-side error boundary fallback components
592
+ *
593
+ * Client error boundaries have a reset function that clears the error state
594
+ * and re-renders the children.
595
+ *
596
+ * @example
597
+ * ```typescript
598
+ * function ClientErrorFallback({ error, reset }: ClientErrorBoundaryFallbackProps) {
599
+ * return (
600
+ * <div>
601
+ * <h2>Something went wrong</h2>
602
+ * <p>{error.message}</p>
603
+ * <button onClick={reset}>Try again</button>
604
+ * </div>
605
+ * );
606
+ * }
607
+ * ```
608
+ */
609
+ export interface ClientErrorBoundaryFallbackProps {
610
+ /** Error information */
611
+ error: ErrorInfo;
612
+ /** Function to reset error state and retry rendering */
613
+ reset: () => void;
614
+ }
615
+
616
+ /**
617
+ * Wrapped loader data result for deferred resolution with error handling.
618
+ * When loaders are deferred to client-side resolution, errors need to be
619
+ * wrapped so the client can handle them appropriately.
620
+ */
621
+ export type LoaderDataResult<T = unknown> =
622
+ | { __loaderResult: true; ok: true; data: T }
623
+ | { __loaderResult: true; ok: false; error: ErrorInfo; fallback: ReactNode | null };
624
+
625
+ /**
626
+ * Type guard to check if a value is a wrapped loader result
627
+ */
628
+ export function isLoaderDataResult(value: unknown): value is LoaderDataResult {
629
+ return (
630
+ typeof value === "object" &&
631
+ value !== null &&
632
+ "__loaderResult" in value &&
633
+ (value as any).__loaderResult === true
634
+ );
635
+ }
636
+
637
+ /**
638
+ * Not found information passed to notFound boundary fallback components
639
+ */
640
+ export interface NotFoundInfo {
641
+ /** Not found message */
642
+ message: string;
643
+ /** Segment ID where notFound was thrown */
644
+ segmentId: string;
645
+ /** Segment type where notFound was thrown */
646
+ segmentType: "layout" | "route" | "parallel" | "loader" | "middleware" | "cache";
647
+ /** The pathname that triggered the not found */
648
+ pathname?: string;
649
+ }
650
+
651
+ /**
652
+ * Props passed to notFound boundary fallback components
653
+ *
654
+ * @example
655
+ * ```typescript
656
+ * function ProductNotFound({ notFound }: NotFoundBoundaryFallbackProps) {
657
+ * return (
658
+ * <div>
659
+ * <h2>Product Not Found</h2>
660
+ * <p>{notFound.message}</p>
661
+ * <a href="/products">Browse all products</a>
662
+ * </div>
663
+ * );
664
+ * }
665
+ * ```
666
+ */
667
+ export interface NotFoundBoundaryFallbackProps {
668
+ /** Not found information */
669
+ notFound: NotFoundInfo;
670
+ }
671
+
672
+ /**
673
+ * NotFound boundary handler - receives not found info and returns fallback UI
674
+ */
675
+ export type NotFoundBoundaryHandler = (props: NotFoundBoundaryFallbackProps) => ReactNode;
676
+
677
+ /**
678
+ * Resolved segment with component
679
+ *
680
+ * Segment types:
681
+ * - layout: Wraps child content via <Outlet />
682
+ * - route: The leaf content for a URL
683
+ * - parallel: Named slots rendered via <ParallelOutlet name="@slot" />
684
+ * - loader: Data segment (no visual rendering, carries loaderData)
685
+ * - error: Error fallback segment (replaces failed segment with error UI)
686
+ * - notFound: Not found fallback segment (replaces segment when data not found)
687
+ */
688
+ export interface ResolvedSegment {
689
+ id: string;
690
+ namespace: string; // Optional namespace for segment (used for parallel groups)
691
+ type: "layout" | "route" | "parallel" | "loader" | "error" | "notFound";
692
+ index: number;
693
+ component: ReactNode | Promise<ReactNode>; // Component or handler promise
694
+ loading?: ReactNode; // Loading component for this segment (shown during navigation)
695
+ layout?: ReactNode; // Layout element to wrap content (used by intercept segments)
696
+ params?: Record<string, string>;
697
+ slot?: string; // For parallel segments: '@sidebar', '@modal', etc.
698
+ belongsToRoute?: boolean; // True if segment belongs to the matched route (route itself + its children)
699
+ layoutName?: string; // For layouts: the layout name identifier
700
+ parallelName?: string; // For parallels: the parallel group name (used to match with revalidations)
701
+ // Loader-specific fields
702
+ loaderId?: string; // For loaders: the loader $$id identifier
703
+ loaderData?: any; // For loaders: the resolved data from loader execution
704
+ // Intercept loader fields (for streaming loader data in parallel segments)
705
+ loaderDataPromise?: Promise<any[]> | any[]; // Loader data promise or resolved array
706
+ loaderIds?: string[]; // IDs ($$id) of loaders for this segment
707
+ // Error-specific fields
708
+ error?: ErrorInfo; // For error segments: the error information
709
+ // NotFound-specific fields
710
+ notFoundInfo?: NotFoundInfo; // For notFound segments: the not found information
711
+ }
712
+
713
+ /**
714
+ * Segment metadata (without component)
715
+ */
716
+ export interface SegmentMetadata {
717
+ id: string;
718
+ type: "layout" | "route" | "parallel" | "loader" | "error" | "notFound";
719
+ index: number;
720
+ params?: Record<string, string>;
721
+ slot?: string;
722
+ loaderId?: string;
723
+ error?: ErrorInfo;
724
+ notFoundInfo?: NotFoundInfo;
725
+ }
726
+
727
+ // Note: route symbols are now defined in route-definition.ts
728
+ // as properties on the route() function
729
+
730
+ /**
731
+ * State of a named slot (e.g., @modal, @sidebar)
732
+ * Used for intercepting routes where slots render alternative content
733
+ */
734
+ export interface SlotState {
735
+ /**
736
+ * Whether the slot is currently active (has content to render)
737
+ */
738
+ active: boolean;
739
+ /**
740
+ * Segments for this slot when active
741
+ */
742
+ segments?: ResolvedSegment[];
743
+ }
744
+
745
+ /**
746
+ * Props passed to the root layout component
747
+ */
748
+ export interface RootLayoutProps {
749
+ children: ReactNode;
750
+ }
751
+
752
+ /**
753
+ * Router match result
754
+ */
755
+ export interface MatchResult {
756
+ segments: ResolvedSegment[];
757
+ matched: string[];
758
+ diff: string[];
759
+ /**
760
+ * Merged route params from all matched segments
761
+ * Available for use by the handler after route matching
762
+ */
763
+ params: Record<string, string>;
764
+ /**
765
+ * Server-Timing header value (only present when debugPerformance is enabled)
766
+ * Can be added to response headers for DevTools integration
767
+ */
768
+ serverTiming?: string;
769
+ /**
770
+ * State of named slots for this route match
771
+ * Key is slot name (e.g., "@modal"), value is slot state
772
+ * Slots are used for intercepting routes during soft navigation
773
+ */
774
+ slots?: Record<string, SlotState>;
775
+ /**
776
+ * Redirect URL for trailing slash normalization.
777
+ * When set, the RSC handler should return a 308 redirect to this URL
778
+ * instead of rendering the page.
779
+ */
780
+ redirect?: string;
781
+ /**
782
+ * Route-level middleware collected from the matched entry tree.
783
+ * These run with the same onion-style execution as app-level middleware,
784
+ * wrapping the entire RSC response creation.
785
+ */
786
+ routeMiddleware?: Array<{
787
+ handler: import("./router/middleware.js").MiddlewareFn;
788
+ params: Record<string, string>;
789
+ }>;
790
+ }
791
+
792
+ /**
793
+ * Internal route entry stored in router
794
+ */
795
+ export interface RouteEntry<TEnv = any> {
796
+ prefix: string;
797
+ routes: ResolvedRouteMap<any>;
798
+ /**
799
+ * Trailing slash config per route key
800
+ * If not specified for a route, defaults to pattern-based detection
801
+ */
802
+ trailingSlash?: Record<string, TrailingSlashMode>;
803
+ handler: () =>
804
+ | Array<AllUseItems>
805
+ | Promise<{ default: () => Array<AllUseItems> }>
806
+ | Promise<() => Array<AllUseItems>>;
807
+ mountIndex: number;
808
+ }
809
+
810
+ /**
811
+ * Type-safe route handler helper for specific routes
812
+ *
813
+ * Automatically extracts the correct param types from your route definition.
814
+ *
815
+ * @template TRoutes - Your route definition object (e.g., typeof shopRoutes)
816
+ * @template K - The route key (e.g., "cart", "products.detail")
817
+ * @template TEnv - Environment type (defaults to global RSCRouter.Env)
818
+ *
819
+ * @example
820
+ * ```typescript
821
+ * import { RouteHandler } from "rsc-router";
822
+ * import { shopRoutes } from "./routes.js";
823
+ *
824
+ * export const cartRoute: RouteHandler<typeof shopRoutes, "cart"> = (ctx) => {
825
+ * // ctx.params is typed correctly for the cart route
826
+ * // ctx.get('user') is type-safe via global augmentation
827
+ * return <CartPage />;
828
+ * }
829
+ *
830
+ * export const productRoute: RouteHandler<typeof shopRoutes, "products.detail"> = (ctx) => {
831
+ * // ctx.params.slug is automatically typed as string
832
+ * return <ProductDetail slug={ctx.params.slug} />;
833
+ * }
834
+ * ```
835
+ */
836
+ export type RouteHandler<
837
+ TRoutes extends RouteDefinition,
838
+ K extends keyof TRoutes,
839
+ TEnv = DefaultEnv
840
+ > = Handler<ExtractRouteParams<TRoutes, K & string>, TEnv>;
841
+
842
+ /**
843
+ * Type-safe revalidation function helper for specific routes
844
+ *
845
+ * Automatically extracts the correct param types from your route definition.
846
+ *
847
+ * @template TRoutes - Your route definition object (e.g., typeof shopRoutes)
848
+ * @template K - The route key (e.g., "cart", "products.detail")
849
+ * @template TEnv - Environment type (defaults to global RSCRouter.Env)
850
+ *
851
+ * @example
852
+ * ```typescript
853
+ * import { RouteRevalidateFn } from "rsc-router";
854
+ * import { shopRoutes } from "./routes.js";
855
+ *
856
+ * export const cartRevalidation: RouteRevalidateFn<typeof shopRoutes, "cart"> = ({
857
+ * currentParams,
858
+ * nextParams
859
+ * }) => {
860
+ * // params are typed correctly for the cart route
861
+ * return true; // Always revalidate cart
862
+ * }
863
+ *
864
+ * export const productRevalidation: RouteRevalidateFn<typeof shopRoutes, "products.detail"> = ({
865
+ * currentParams,
866
+ * nextParams
867
+ * }) => {
868
+ * // currentParams.slug and nextParams.slug are automatically typed
869
+ * return currentParams.slug !== nextParams.slug;
870
+ * }
871
+ * ```
872
+ */
873
+ export type RouteRevalidateFn<
874
+ TRoutes extends RouteDefinition,
875
+ K extends keyof TRoutes,
876
+ TEnv = DefaultEnv
877
+ > = ShouldRevalidateFn<ExtractRouteParams<TRoutes, K & string>, TEnv>;
878
+
879
+ /**
880
+ * Type-safe middleware function helper for specific routes
881
+ *
882
+ * Automatically extracts the correct param types from your route definition.
883
+ *
884
+ * @template TRoutes - Your route definition object (e.g., typeof shopRoutes)
885
+ * @template K - The route key (e.g., "checkout.index", "account.orders")
886
+ * @template TEnv - Environment type (defaults to global RSCRouter.Env)
887
+ *
888
+ * @example
889
+ * ```typescript
890
+ * import { RouteMiddlewareFn } from "rsc-router";
891
+ * import { shopRoutes } from "./routes.js";
892
+ *
893
+ * export const checkoutMiddleware: RouteMiddlewareFn<typeof shopRoutes, "checkout.index"> = async (ctx, next) => {
894
+ * // ctx.params is typed correctly for checkout.index route
895
+ * // ctx.get('user') is type-safe via global augmentation
896
+ * if (!ctx.get('user')) {
897
+ * return redirect('/login');
898
+ * }
899
+ * await next();
900
+ * // ctx.res available here for header modification
901
+ * }
902
+ *
903
+ * export const productMiddleware: RouteMiddlewareFn<typeof shopRoutes, "products.detail"> = async (ctx, next) => {
904
+ * // ctx.params.slug is automatically typed as string
905
+ * console.log('Viewing product:', ctx.params.slug);
906
+ * const response = await next();
907
+ * response.headers.set('X-Product', ctx.params.slug);
908
+ * return response;
909
+ * }
910
+ * ```
911
+ */
912
+ export type RouteMiddlewareFn<
913
+ TRoutes extends RouteDefinition,
914
+ K extends keyof TRoutes,
915
+ TEnv = DefaultEnv
916
+ > = MiddlewareFn<TEnv, ExtractRouteParams<TRoutes, K & string>>;
917
+
918
+ // ============================================================================
919
+ // Cache Types
920
+ // ============================================================================
921
+
922
+ /**
923
+ * Context passed to cache condition/key/tags functions.
924
+ *
925
+ * This is a subset of RequestContext that's guaranteed to be available
926
+ * during cache key generation (before middleware runs).
927
+ *
928
+ * Note: While the full RequestContext is passed, middleware-set variables
929
+ * (ctx.var, ctx.get()) may not be populated yet since cache lookup
930
+ * happens before middleware execution.
931
+ */
932
+ export type { RequestContext as CacheContext } from "./server/request-context.js";
933
+
934
+ /**
935
+ * Cache configuration options for cache() DSL
936
+ *
937
+ * Controls how segments, layouts, and loaders are cached.
938
+ * Cache configuration inherits down the route tree unless overridden.
939
+ *
940
+ * @example
941
+ * ```typescript
942
+ * // Basic caching with TTL
943
+ * cache({ ttl: 60 }, () => [
944
+ * layout(<BlogLayout />),
945
+ * route("post/:slug"),
946
+ * ])
947
+ *
948
+ * // With stale-while-revalidate
949
+ * cache({ ttl: 60, swr: 300 }, () => [
950
+ * route("product/:id"),
951
+ * ])
952
+ *
953
+ * // Conditional caching
954
+ * cache({
955
+ * ttl: 300,
956
+ * condition: (ctx) => !ctx.request.headers.get('x-preview'),
957
+ * }, () => [...])
958
+ *
959
+ * // Custom cache key
960
+ * cache({
961
+ * ttl: 300,
962
+ * key: (ctx) => `product-${ctx.params.id}-${ctx.searchParams.get('variant')}`,
963
+ * }, () => [...])
964
+ *
965
+ * // With tags for invalidation
966
+ * cache({
967
+ * ttl: 300,
968
+ * tags: (ctx) => [`product:${ctx.params.id}`, 'products'],
969
+ * }, () => [...])
970
+ * ```
971
+ */
972
+ export interface CacheOptions<TEnv = unknown> {
973
+ /**
974
+ * Time-to-live in seconds.
975
+ * After this period, cached content is considered stale.
976
+ */
977
+ ttl: number;
978
+
979
+ /**
980
+ * Stale-while-revalidate window in seconds (after TTL).
981
+ * During this window, stale content is served immediately while
982
+ * fresh content is fetched in the background via waitUntil.
983
+ *
984
+ * @example
985
+ * // TTL: 60s, SWR: 300s
986
+ * // 0-60s: FRESH (serve from cache)
987
+ * // 60-360s: STALE (serve from cache, revalidate in background)
988
+ * // 360s+: EXPIRED (cache miss, fetch fresh)
989
+ */
990
+ swr?: number;
991
+
992
+ /**
993
+ * Override the cache store for this boundary.
994
+ * When specified, this boundary and its children use this store
995
+ * instead of the app-level store from handler config.
996
+ *
997
+ * Useful for:
998
+ * - Different backends per route section (memory vs KV vs Redis)
999
+ * - Loader-specific caching strategies
1000
+ * - Hot data in fast cache, cold data in larger/slower cache
1001
+ *
1002
+ * @example
1003
+ * ```typescript
1004
+ * const kvStore = new CloudflareKVStore(env.CACHE_KV);
1005
+ * const memoryStore = new MemorySegmentCacheStore({ defaults: { ttl: 10 } });
1006
+ *
1007
+ * // Fast memory cache for hot data
1008
+ * cache({ store: memoryStore }, () => [
1009
+ * route("dashboard"),
1010
+ * ])
1011
+ *
1012
+ * // KV for larger, less frequently accessed data
1013
+ * cache({ store: kvStore, ttl: 3600 }, () => [
1014
+ * route("archive/:year"),
1015
+ * ])
1016
+ * ```
1017
+ */
1018
+ store?: import("./cache/types.js").SegmentCacheStore;
1019
+
1020
+ /**
1021
+ * Conditional cache read function.
1022
+ * Return false to skip cache for this request (always fetch fresh).
1023
+ *
1024
+ * Has access to full RequestContext including env, request, params, cookies, etc.
1025
+ * Note: Middleware-set variables (ctx.var) may not be populated yet.
1026
+ *
1027
+ * @example
1028
+ * ```typescript
1029
+ * condition: (ctx) => {
1030
+ * // Skip cache for preview mode
1031
+ * if (ctx.request.headers.get('x-preview')) return false;
1032
+ * // Skip cache for authenticated users
1033
+ * if (ctx.request.headers.has('authorization')) return false;
1034
+ * return true;
1035
+ * }
1036
+ * ```
1037
+ */
1038
+ condition?: (ctx: import("./server/request-context.js").RequestContext<TEnv>) => boolean;
1039
+
1040
+ /**
1041
+ * Custom cache key function - FULL OVERRIDE.
1042
+ * Bypasses default key generation AND store's keyGenerator.
1043
+ *
1044
+ * Has access to full RequestContext including env, request, params, cookies, etc.
1045
+ * Note: Middleware-set variables (ctx.var) may not be populated yet.
1046
+ *
1047
+ * @example
1048
+ * ```typescript
1049
+ * // Include query params in cache key
1050
+ * key: (ctx) => `product-${ctx.params.id}-${ctx.searchParams.get('variant')}`
1051
+ *
1052
+ * // Include env bindings
1053
+ * key: (ctx) => `${ctx.env.REGION}:product:${ctx.params.id}`
1054
+ *
1055
+ * // Include cookies
1056
+ * key: (ctx) => `${ctx.cookie('locale')}:${ctx.pathname}`
1057
+ * ```
1058
+ */
1059
+ key?: (ctx: import("./server/request-context.js").RequestContext<TEnv>) => string | Promise<string>;
1060
+
1061
+ /**
1062
+ * Tags for cache invalidation.
1063
+ * Can be a static array or a function that returns tags.
1064
+ *
1065
+ * @example
1066
+ * ```typescript
1067
+ * // Static tags
1068
+ * tags: ['products', 'catalog']
1069
+ *
1070
+ * // Dynamic tags
1071
+ * tags: (ctx) => [`product:${ctx.params.id}`, 'products']
1072
+ * ```
1073
+ */
1074
+ tags?: string[] | ((ctx: import("./server/request-context.js").RequestContext<TEnv>) => string[]);
1075
+ }
1076
+
1077
+ /**
1078
+ * Partial cache options for cache() DSL.
1079
+ *
1080
+ * When `ttl` is not specified, it will use the default from cache config.
1081
+ * This allows cache() calls to inherit app-level defaults:
1082
+ *
1083
+ * @example
1084
+ * ```typescript
1085
+ * // App-level default (in handler config)
1086
+ * cache: { store: myStore, defaults: { ttl: 60 } }
1087
+ *
1088
+ * // Route-level (inherits ttl from defaults)
1089
+ * cache(() => [
1090
+ * route("products"),
1091
+ * ])
1092
+ *
1093
+ * // Override with explicit ttl
1094
+ * cache({ ttl: 300 }, () => [...])
1095
+ * ```
1096
+ */
1097
+ export type PartialCacheOptions<TEnv = unknown> = Partial<CacheOptions<TEnv>>;
1098
+
1099
+ /**
1100
+ * Cache entry configuration stored in EntryData.
1101
+ * Represents the resolved cache config for a segment.
1102
+ */
1103
+ export interface EntryCacheConfig {
1104
+ /** Cache options (false means caching disabled for this entry) - ttl is optional, uses defaults */
1105
+ options: PartialCacheOptions | false;
1106
+ }
1107
+
1108
+ // ============================================================================
1109
+ // Loader Types
1110
+ // ============================================================================
1111
+
1112
+ /**
1113
+ * Context passed to loader functions during execution
1114
+ *
1115
+ * Loaders run after middleware but before handlers, so they have access
1116
+ * to middleware-set variables via get().
1117
+ *
1118
+ * @template TParams - Route params type (e.g., { slug: string })
1119
+ * @template TEnv - Environment type for bindings/variables
1120
+ *
1121
+ * @example
1122
+ * ```typescript
1123
+ * const CartLoader = createLoader(async (ctx) => {
1124
+ * "use server";
1125
+ * const user = ctx.get("user"); // From auth middleware
1126
+ * return await db.cart.get(user.id);
1127
+ * });
1128
+ *
1129
+ * // With typed params:
1130
+ * const ProductLoader = createLoader<Product, { slug: string }>(async (ctx) => {
1131
+ * "use server";
1132
+ * const { slug } = ctx.params; // slug is typed as string
1133
+ * return await db.products.findBySlug(slug);
1134
+ * });
1135
+ * ```
1136
+ */
1137
+ export type LoaderContext<TParams = Record<string, string | undefined>, TEnv = any, TBody = unknown> = {
1138
+ params: TParams;
1139
+ request: Request;
1140
+ searchParams: URLSearchParams;
1141
+ pathname: string;
1142
+ url: URL;
1143
+ env: TEnv extends RouterEnv<infer B, any> ? B : {};
1144
+ var: TEnv extends RouterEnv<any, infer V> ? V : {};
1145
+ get: TEnv extends RouterEnv<any, infer V>
1146
+ ? <K extends keyof V>(key: K) => V[K]
1147
+ : (key: string) => any;
1148
+ /**
1149
+ * Access another loader's data (returns promise since loaders run in parallel)
1150
+ */
1151
+ use: <T, TLoaderParams = any>(loader: LoaderDefinition<T, TLoaderParams>) => Promise<T>;
1152
+ /**
1153
+ * HTTP method (GET, POST, PUT, PATCH, DELETE)
1154
+ * Available when loader is called via load({ method: "POST", ... })
1155
+ */
1156
+ method: string;
1157
+ /**
1158
+ * Request body for POST/PUT/PATCH/DELETE requests
1159
+ * Available when loader is called via load({ method: "POST", body: {...} })
1160
+ */
1161
+ body: TBody | undefined;
1162
+ };
1163
+
1164
+ /**
1165
+ * Loader function signature
1166
+ *
1167
+ * @template T - The return type of the loader
1168
+ * @template TParams - Route params type (defaults to generic Record)
1169
+ * @template TEnv - Environment type for bindings/variables
1170
+ *
1171
+ * @example
1172
+ * ```typescript
1173
+ * const myLoader: LoaderFn<{ items: Item[] }> = async (ctx) => {
1174
+ * "use server";
1175
+ * return { items: await db.items.list() };
1176
+ * };
1177
+ *
1178
+ * // With typed params:
1179
+ * const productLoader: LoaderFn<Product, { slug: string }> = async (ctx) => {
1180
+ * "use server";
1181
+ * const { slug } = ctx.params; // typed as string
1182
+ * return await db.products.findBySlug(slug);
1183
+ * };
1184
+ * ```
1185
+ */
1186
+ export type LoaderFn<T, TParams = Record<string, string | undefined>, TEnv = any> = (
1187
+ ctx: LoaderContext<TParams, TEnv>
1188
+ ) => Promise<T> | T;
1189
+
1190
+ /**
1191
+ * Loader definition object
1192
+ *
1193
+ * Created via createLoader(). Contains the loader name and function.
1194
+ * On client builds, the fn is stripped by the bundler (via "use server" directive).
1195
+ *
1196
+ * @template T - The return type of the loader
1197
+ * @template TParams - Route params type (for type-safe params access)
1198
+ *
1199
+ * @example
1200
+ * ```typescript
1201
+ * // Definition (same file works on server and client)
1202
+ * export const CartLoader = createLoader(async (ctx) => {
1203
+ * "use server";
1204
+ * return await db.cart.get(ctx.get("user").id);
1205
+ * });
1206
+ *
1207
+ * // With typed params:
1208
+ * export const ProductLoader = createLoader<Product, { slug: string }>(async (ctx) => {
1209
+ * "use server";
1210
+ * const { slug } = ctx.params; // slug is typed as string
1211
+ * return await db.products.findBySlug(slug);
1212
+ * });
1213
+ *
1214
+ * // Server usage
1215
+ * const cart = ctx.use(CartLoader);
1216
+ *
1217
+ * // Client usage (fn is stripped, only name remains)
1218
+ * const cart = useLoader(CartLoader);
1219
+ * ```
1220
+ */
1221
+ /**
1222
+ * Options for fetchable loaders
1223
+ *
1224
+ * Middleware uses the same MiddlewareFn signature as route/app middleware,
1225
+ * enabling reuse of the same middleware functions everywhere.
1226
+ */
1227
+ export type FetchableLoaderOptions = {
1228
+ fetchable?: true;
1229
+ middleware?: MiddlewareFn[];
1230
+ };
1231
+
1232
+ /**
1233
+ * Options for load() calls - type-safe union based on method
1234
+ */
1235
+ export type LoadOptions =
1236
+ | {
1237
+ method?: "GET";
1238
+ params?: Record<string, string>;
1239
+ }
1240
+ | {
1241
+ method: "POST" | "PUT" | "PATCH" | "DELETE";
1242
+ params?: Record<string, string>;
1243
+ body?: FormData | Record<string, any>;
1244
+ };
1245
+
1246
+ /**
1247
+ * Context passed to loader action on server
1248
+ */
1249
+ export type LoaderActionContext = {
1250
+ method: string;
1251
+ params: Record<string, string>;
1252
+ body?: FormData | Record<string, any>;
1253
+ formData?: FormData;
1254
+ };
1255
+
1256
+ /**
1257
+ * @deprecated Use MiddlewareFn instead for fetchable loader middleware.
1258
+ * This type is kept for backwards compatibility but will be removed in a future version.
1259
+ *
1260
+ * Fetchable loaders now use the same middleware signature as routes,
1261
+ * enabling middleware reuse across routes and loaders.
1262
+ */
1263
+ export type LoaderMiddlewareFn = (
1264
+ ctx: LoaderActionContext,
1265
+ next: () => Promise<void>
1266
+ ) => Response | Promise<Response> | void | Promise<void>;
1267
+
1268
+ /**
1269
+ * Loader action function type - server action for form-based fetching
1270
+ * This is a server action that can be passed to useActionState or form action prop.
1271
+ *
1272
+ * The signature (prevState, formData) is required for useActionState compatibility.
1273
+ * When used with useActionState, React passes the previous state as the first argument.
1274
+ */
1275
+ export type LoaderAction<T> = (prevState: T | null, formData: FormData) => Promise<T>;
1276
+
1277
+ export type LoaderDefinition<T = any, TParams = Record<string, string | undefined>> = {
1278
+ __brand: "loader";
1279
+ $$id: string; // Injected by Vite plugin (exposeLoaderId) - unique identifier
1280
+ fn?: LoaderFn<T, TParams, any>; // Optional - stripped on client via "use server"
1281
+ action?: LoaderAction<T>; // Optional - for fetchable loaders
1282
+ };
1283
+
1284
+ // ============================================================================
1285
+ // Error Handling Types
1286
+ // ============================================================================
1287
+
1288
+ /**
1289
+ * Phase where the error occurred during request handling.
1290
+ *
1291
+ * Coverage notes:
1292
+ * - "routing": Invoked when route matching fails (router.ts, rsc/handler.ts)
1293
+ * - "manifest": Reserved for manifest loading errors (not currently invoked)
1294
+ * - "middleware": Reserved for middleware execution errors (errors propagate to handler phase)
1295
+ * - "loader": Invoked when loader execution fails (router.ts via wrapLoaderWithErrorHandling, rsc/handler.ts)
1296
+ * - "handler": Invoked when route/layout handler execution fails (router.ts)
1297
+ * - "rendering": Invoked during SSR rendering errors (ssr/index.tsx, separate callback)
1298
+ * - "action": Invoked when server action execution fails (rsc/handler.ts, router.ts)
1299
+ * - "revalidation": Invoked when revalidation fails (router.ts, conditional with action)
1300
+ * - "unknown": Fallback for unclassified errors (not currently invoked)
1301
+ */
1302
+ export type ErrorPhase =
1303
+ | "routing" // During route matching
1304
+ | "manifest" // During manifest loading (reserved, not currently invoked)
1305
+ | "middleware" // During middleware execution (errors propagate to handler phase)
1306
+ | "loader" // During loader execution
1307
+ | "handler" // During route/layout handler execution
1308
+ | "rendering" // During RSC/SSR rendering (SSR handler uses separate callback)
1309
+ | "action" // During server action execution
1310
+ | "revalidation" // During revalidation evaluation
1311
+ | "unknown"; // Fallback for unclassified errors
1312
+
1313
+ /**
1314
+ * Comprehensive context passed to onError callback
1315
+ *
1316
+ * Provides all available information about where and when an error occurred
1317
+ * during request handling. The callback can use this for logging, monitoring,
1318
+ * error tracking services, or custom error responses.
1319
+ *
1320
+ * @example
1321
+ * ```typescript
1322
+ * const router = createRSCRouter<AppEnv>({
1323
+ * onError: (context) => {
1324
+ * // Log to error tracking service
1325
+ * errorTracker.capture({
1326
+ * error: context.error,
1327
+ * phase: context.phase,
1328
+ * url: context.request.url,
1329
+ * route: context.routeKey,
1330
+ * userId: context.env?.user?.id,
1331
+ * });
1332
+ *
1333
+ * // Log to console with context
1334
+ * console.error(`[${context.phase}] Error in ${context.routeKey}:`, {
1335
+ * message: context.error.message,
1336
+ * segment: context.segmentId,
1337
+ * duration: context.duration,
1338
+ * });
1339
+ * },
1340
+ * });
1341
+ * ```
1342
+ */
1343
+ export interface OnErrorContext<TEnv = any> {
1344
+ /**
1345
+ * The error that occurred
1346
+ */
1347
+ error: Error;
1348
+
1349
+ /**
1350
+ * Phase where the error occurred
1351
+ */
1352
+ phase: ErrorPhase;
1353
+
1354
+ /**
1355
+ * The original request
1356
+ */
1357
+ request: Request;
1358
+
1359
+ /**
1360
+ * Parsed URL from the request
1361
+ */
1362
+ url: URL;
1363
+
1364
+ /**
1365
+ * Request pathname
1366
+ */
1367
+ pathname: string;
1368
+
1369
+ /**
1370
+ * HTTP method
1371
+ */
1372
+ method: string;
1373
+
1374
+ /**
1375
+ * Matched route key (if available)
1376
+ * e.g., "shop.products.detail"
1377
+ */
1378
+ routeKey?: string;
1379
+
1380
+ /**
1381
+ * Route params (if available)
1382
+ * e.g., { slug: "headphones" }
1383
+ */
1384
+ params?: Record<string, string>;
1385
+
1386
+ /**
1387
+ * Segment ID where error occurred (if available)
1388
+ * e.g., "M1L0" for a layout, "M1R0" for a route
1389
+ */
1390
+ segmentId?: string;
1391
+
1392
+ /**
1393
+ * Segment type where error occurred (if available)
1394
+ */
1395
+ segmentType?: "layout" | "route" | "parallel" | "loader" | "middleware";
1396
+
1397
+ /**
1398
+ * Loader name (if error occurred in a loader)
1399
+ */
1400
+ loaderName?: string;
1401
+
1402
+ /**
1403
+ * Middleware name/id (if error occurred in middleware)
1404
+ */
1405
+ middlewareId?: string;
1406
+
1407
+ /**
1408
+ * Action ID (if error occurred during server action)
1409
+ * e.g., "src/actions.ts#addToCart"
1410
+ */
1411
+ actionId?: string;
1412
+
1413
+ /**
1414
+ * Environment/bindings (platform context)
1415
+ */
1416
+ env?: TEnv;
1417
+
1418
+ /**
1419
+ * Duration from request start to error (milliseconds)
1420
+ */
1421
+ duration?: number;
1422
+
1423
+ /**
1424
+ * Whether this is a partial/navigation request
1425
+ */
1426
+ isPartial?: boolean;
1427
+
1428
+ /**
1429
+ * Whether an error boundary caught the error
1430
+ * If true, the error was handled and a fallback UI was rendered
1431
+ */
1432
+ handledByBoundary?: boolean;
1433
+
1434
+ /**
1435
+ * Stack trace (if available)
1436
+ */
1437
+ stack?: string;
1438
+
1439
+ /**
1440
+ * Additional metadata specific to the error phase
1441
+ */
1442
+ metadata?: Record<string, unknown>;
1443
+ }
1444
+
1445
+ /**
1446
+ * Callback function for error handling
1447
+ *
1448
+ * Called whenever an error occurs during request handling.
1449
+ * The callback is for notification/logging purposes - it cannot
1450
+ * modify the error handling flow (use errorBoundary for that).
1451
+ *
1452
+ * @param context - Comprehensive error context
1453
+ *
1454
+ * @example
1455
+ * ```typescript
1456
+ * const onError: OnErrorCallback = (context) => {
1457
+ * // Send to error tracking service
1458
+ * Sentry.captureException(context.error, {
1459
+ * tags: {
1460
+ * phase: context.phase,
1461
+ * route: context.routeKey,
1462
+ * },
1463
+ * extra: {
1464
+ * url: context.url.toString(),
1465
+ * params: context.params,
1466
+ * duration: context.duration,
1467
+ * },
1468
+ * });
1469
+ * };
1470
+ * ```
1471
+ */
1472
+ export type OnErrorCallback<TEnv = any> = (context: OnErrorContext<TEnv>) => void | Promise<void>;
1473
+