@rangojs/router 0.0.0-experimental.debug-cache-fix → 0.0.0-experimental.dfdb0387

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 (115) hide show
  1. package/README.md +76 -18
  2. package/dist/bin/rango.js +130 -47
  3. package/dist/vite/index.js +702 -231
  4. package/package.json +2 -2
  5. package/skills/cache-guide/SKILL.md +32 -0
  6. package/skills/caching/SKILL.md +8 -0
  7. package/skills/links/SKILL.md +3 -1
  8. package/skills/loader/SKILL.md +53 -43
  9. package/skills/middleware/SKILL.md +2 -0
  10. package/skills/prerender/SKILL.md +110 -68
  11. package/skills/route/SKILL.md +31 -0
  12. package/skills/router-setup/SKILL.md +87 -2
  13. package/skills/typesafety/SKILL.md +10 -0
  14. package/src/__internal.ts +1 -1
  15. package/src/browser/app-version.ts +14 -0
  16. package/src/browser/navigation-bridge.ts +16 -3
  17. package/src/browser/navigation-client.ts +98 -46
  18. package/src/browser/navigation-store.ts +43 -8
  19. package/src/browser/partial-update.ts +32 -5
  20. package/src/browser/prefetch/cache.ts +16 -6
  21. package/src/browser/prefetch/fetch.ts +52 -6
  22. package/src/browser/prefetch/queue.ts +61 -29
  23. package/src/browser/prefetch/resource-ready.ts +77 -0
  24. package/src/browser/react/Link.tsx +67 -8
  25. package/src/browser/react/NavigationProvider.tsx +13 -4
  26. package/src/browser/react/context.ts +7 -2
  27. package/src/browser/react/use-handle.ts +9 -58
  28. package/src/browser/react/use-router.ts +21 -8
  29. package/src/browser/rsc-router.tsx +26 -3
  30. package/src/browser/scroll-restoration.ts +10 -8
  31. package/src/browser/segment-reconciler.ts +26 -0
  32. package/src/browser/server-action-bridge.ts +8 -6
  33. package/src/browser/types.ts +27 -5
  34. package/src/build/generate-manifest.ts +6 -6
  35. package/src/build/generate-route-types.ts +3 -0
  36. package/src/build/route-types/include-resolution.ts +8 -1
  37. package/src/build/route-types/router-processing.ts +211 -72
  38. package/src/build/route-types/scan-filter.ts +8 -1
  39. package/src/cache/cache-scope.ts +12 -14
  40. package/src/cache/taint.ts +55 -0
  41. package/src/client.tsx +2 -56
  42. package/src/context-var.ts +72 -2
  43. package/src/handle.ts +40 -0
  44. package/src/index.rsc.ts +3 -1
  45. package/src/index.ts +12 -0
  46. package/src/prerender/store.ts +5 -4
  47. package/src/prerender.ts +138 -77
  48. package/src/reverse.ts +22 -1
  49. package/src/route-definition/dsl-helpers.ts +42 -19
  50. package/src/route-definition/helpers-types.ts +10 -6
  51. package/src/route-definition/index.ts +3 -0
  52. package/src/route-definition/redirect.ts +9 -1
  53. package/src/route-definition/resolve-handler-use.ts +149 -0
  54. package/src/route-types.ts +11 -0
  55. package/src/router/content-negotiation.ts +100 -1
  56. package/src/router/handler-context.ts +79 -23
  57. package/src/router/intercept-resolution.ts +9 -4
  58. package/src/router/loader-resolution.ts +156 -21
  59. package/src/router/match-api.ts +124 -189
  60. package/src/router/match-middleware/cache-lookup.ts +26 -7
  61. package/src/router/match-middleware/segment-resolution.ts +53 -0
  62. package/src/router/match-result.ts +82 -4
  63. package/src/router/middleware-types.ts +6 -8
  64. package/src/router/middleware.ts +2 -5
  65. package/src/router/navigation-snapshot.ts +182 -0
  66. package/src/router/prerender-match.ts +110 -10
  67. package/src/router/preview-match.ts +30 -102
  68. package/src/router/request-classification.ts +310 -0
  69. package/src/router/route-snapshot.ts +245 -0
  70. package/src/router/router-interfaces.ts +36 -4
  71. package/src/router/router-options.ts +37 -11
  72. package/src/router/segment-resolution/fresh.ts +80 -9
  73. package/src/router/segment-resolution/helpers.ts +29 -24
  74. package/src/router/segment-resolution/revalidation.ts +91 -8
  75. package/src/router/types.ts +1 -0
  76. package/src/router.ts +54 -5
  77. package/src/rsc/handler.ts +472 -372
  78. package/src/rsc/loader-fetch.ts +23 -3
  79. package/src/rsc/manifest-init.ts +5 -1
  80. package/src/rsc/progressive-enhancement.ts +14 -2
  81. package/src/rsc/rsc-rendering.ts +10 -1
  82. package/src/rsc/server-action.ts +8 -0
  83. package/src/rsc/ssr-setup.ts +2 -2
  84. package/src/rsc/types.ts +9 -1
  85. package/src/server/context.ts +50 -1
  86. package/src/server/handle-store.ts +19 -0
  87. package/src/server/loader-registry.ts +9 -8
  88. package/src/server/request-context.ts +175 -15
  89. package/src/ssr/index.tsx +3 -0
  90. package/src/static-handler.ts +18 -6
  91. package/src/types/cache-types.ts +4 -4
  92. package/src/types/handler-context.ts +37 -19
  93. package/src/types/loader-types.ts +36 -9
  94. package/src/types/route-entry.ts +1 -1
  95. package/src/types/segments.ts +1 -0
  96. package/src/urls/path-helper-types.ts +9 -2
  97. package/src/urls/path-helper.ts +47 -12
  98. package/src/urls/pattern-types.ts +12 -0
  99. package/src/urls/response-types.ts +16 -6
  100. package/src/use-loader.tsx +77 -5
  101. package/src/vite/discovery/bundle-postprocess.ts +30 -33
  102. package/src/vite/discovery/discover-routers.ts +5 -1
  103. package/src/vite/discovery/prerender-collection.ts +128 -74
  104. package/src/vite/discovery/state.ts +13 -4
  105. package/src/vite/index.ts +4 -0
  106. package/src/vite/plugin-types.ts +60 -5
  107. package/src/vite/plugins/expose-id-utils.ts +12 -0
  108. package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
  109. package/src/vite/plugins/expose-internal-ids.ts +257 -40
  110. package/src/vite/plugins/performance-tracks.ts +88 -0
  111. package/src/vite/plugins/refresh-cmd.ts +88 -26
  112. package/src/vite/rango.ts +19 -2
  113. package/src/vite/router-discovery.ts +178 -37
  114. package/src/vite/utils/prerender-utils.ts +18 -0
  115. package/src/vite/utils/shared-utils.ts +3 -2
@@ -12,6 +12,9 @@
12
12
  * interface PaginationData { current: number; total: number }
13
13
  * export const Pagination = createVar<PaginationData>();
14
14
  *
15
+ * // Non-cacheable var — throws if set/get inside cache() or "use cache"
16
+ * export const User = createVar<UserData>({ cache: false });
17
+ *
15
18
  * // handler
16
19
  * ctx.set(Pagination, { current: 1, total: 4 });
17
20
  *
@@ -23,18 +26,36 @@
23
26
  export interface ContextVar<T> {
24
27
  readonly __brand: "context-var";
25
28
  readonly key: symbol;
29
+ /** When false, the var is non-cacheable — throws inside cache() / "use cache" */
30
+ readonly cache: boolean;
26
31
  /** Phantom field to carry the type parameter. Never set at runtime. */
27
32
  readonly __type?: T;
28
33
  }
29
34
 
35
+ export interface ContextVarOptions {
36
+ /**
37
+ * When false, marks this variable as non-cacheable.
38
+ * Setting or getting this var inside a cache() boundary or "use cache"
39
+ * function will throw. Use for inherently request-specific data (user
40
+ * sessions, auth tokens, etc.) that must never be baked into cached segments.
41
+ *
42
+ * @default true
43
+ */
44
+ cache?: boolean;
45
+ }
46
+
30
47
  /**
31
48
  * Create a typed context variable token.
32
49
  *
33
50
  * The returned object is used with ctx.set(token, value) and ctx.get(token)
34
51
  * for compile-time-checked data flow between handlers, layouts, and middleware.
35
52
  */
36
- export function createVar<T>(): ContextVar<T> {
37
- return { __brand: "context-var" as const, key: Symbol() };
53
+ export function createVar<T>(options?: ContextVarOptions): ContextVar<T> {
54
+ return {
55
+ __brand: "context-var" as const,
56
+ key: Symbol(),
57
+ cache: options?.cache !== false,
58
+ };
38
59
  }
39
60
 
40
61
  /**
@@ -49,6 +70,36 @@ export function isContextVar(value: unknown): value is ContextVar<unknown> {
49
70
  );
50
71
  }
51
72
 
73
+ /**
74
+ * Symbol used as a Set stored on the variables object to track
75
+ * which keys hold non-cacheable values (from write-level { cache: false }).
76
+ */
77
+ const NON_CACHEABLE_KEYS: unique symbol = Symbol.for(
78
+ "rango:non-cacheable-keys",
79
+ ) as any;
80
+
81
+ function getNonCacheableKeys(variables: any): Set<string | symbol> {
82
+ if (!variables[NON_CACHEABLE_KEYS]) {
83
+ variables[NON_CACHEABLE_KEYS] = new Set();
84
+ }
85
+ return variables[NON_CACHEABLE_KEYS];
86
+ }
87
+
88
+ /**
89
+ * Check if a variable value is non-cacheable (either var-level or write-level).
90
+ */
91
+ export function isNonCacheable(
92
+ variables: any,
93
+ keyOrVar: string | ContextVar<any>,
94
+ ): boolean {
95
+ if (typeof keyOrVar !== "string" && !keyOrVar.cache) {
96
+ return true; // var-level policy
97
+ }
98
+ const key = typeof keyOrVar === "string" ? keyOrVar : keyOrVar.key;
99
+ const set = variables[NON_CACHEABLE_KEYS] as Set<string | symbol> | undefined;
100
+ return set?.has(key) ?? false; // write-level policy
101
+ }
102
+
52
103
  /**
53
104
  * Read a variable from the variables store.
54
105
  * Accepts either a string key (legacy) or a ContextVar token (typed).
@@ -64,6 +115,17 @@ export function contextGet(
64
115
  /** Keys that must never be used as string variable names */
65
116
  const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
66
117
 
118
+ export interface ContextSetOptions {
119
+ /**
120
+ * When false, marks this specific write as non-cacheable.
121
+ * "Least cacheable wins" — if either the var definition or this option
122
+ * says cache: false, the value is non-cacheable.
123
+ *
124
+ * @default true (inherits from createVar)
125
+ */
126
+ cache?: boolean;
127
+ }
128
+
67
129
  /**
68
130
  * Write a variable to the variables store.
69
131
  * Accepts either a string key (legacy) or a ContextVar token (typed).
@@ -72,6 +134,7 @@ export function contextSet(
72
134
  variables: any,
73
135
  keyOrVar: string | ContextVar<any>,
74
136
  value: any,
137
+ options?: ContextSetOptions,
75
138
  ): void {
76
139
  if (typeof keyOrVar === "string") {
77
140
  if (FORBIDDEN_KEYS.has(keyOrVar)) {
@@ -80,7 +143,14 @@ export function contextSet(
80
143
  );
81
144
  }
82
145
  variables[keyOrVar] = value;
146
+ if (options?.cache === false) {
147
+ getNonCacheableKeys(variables).add(keyOrVar);
148
+ }
83
149
  } else {
84
150
  variables[keyOrVar.key] = value;
151
+ // Track write-level non-cacheable (var-level is checked via keyOrVar.cache)
152
+ if (options?.cache === false) {
153
+ getNonCacheableKeys(variables).add(keyOrVar.key);
154
+ }
85
155
  }
86
156
  }
package/src/handle.ts CHANGED
@@ -133,3 +133,43 @@ export function isHandle(value: unknown): value is Handle<unknown, unknown> {
133
133
  (value as { __brand: unknown }).__brand === "handle"
134
134
  );
135
135
  }
136
+
137
+ /**
138
+ * Collect handle data from a HandleData map, applying the handle's collect
139
+ * function over segments in order. Shared between server-side rendered()
140
+ * reads and client-side useHandle().
141
+ *
142
+ * @param handle - The handle to collect data for
143
+ * @param data - Full handle data map (handleName -> segmentId -> entries[])
144
+ * @param segmentOrder - Segment IDs in parent -> child resolution order
145
+ */
146
+ export function collectHandleData<TData, TAccumulated>(
147
+ handle: Handle<TData, TAccumulated>,
148
+ data: Record<string, Record<string, unknown[]>>,
149
+ segmentOrder: string[],
150
+ ): TAccumulated {
151
+ const collectFn = getCollectFn(handle.$$id);
152
+ if (!collectFn && process.env.NODE_ENV !== "production") {
153
+ console.warn(
154
+ `[rsc-router] Handle "${handle.$$id}" has no registered collect function. ` +
155
+ `Falling back to flat array. Ensure the handle module is imported so ` +
156
+ `createHandle() runs and registers the collect function.`,
157
+ );
158
+ }
159
+ const collect = (collectFn ??
160
+ (defaultCollect as unknown as (segments: unknown[][]) => unknown)) as (
161
+ segments: TData[][],
162
+ ) => TAccumulated;
163
+
164
+ const segmentData = data[handle.$$id];
165
+ if (!segmentData) return collect([]);
166
+
167
+ const segmentArrays: TData[][] = [];
168
+ for (const segmentId of segmentOrder) {
169
+ const entries = segmentData[segmentId];
170
+ if (entries && entries.length > 0) {
171
+ segmentArrays.push(entries as TData[]);
172
+ }
173
+ }
174
+ return collect(segmentArrays);
175
+ }
package/src/index.rsc.ts CHANGED
@@ -100,6 +100,7 @@ export type {
100
100
  LayoutUseItem,
101
101
  AllUseItems,
102
102
  UseItems,
103
+ HandlerUseItem,
103
104
  } from "./route-types.js";
104
105
 
105
106
  // Handle API
@@ -114,8 +115,9 @@ export { nonce } from "./rsc/nonce.js";
114
115
  // Pre-render handler API
115
116
  export {
116
117
  Prerender,
118
+ Passthrough,
117
119
  type PrerenderHandlerDefinition,
118
- type PrerenderPassthroughContext,
120
+ type PassthroughHandlerDefinition,
119
121
  type PrerenderOptions,
120
122
  type BuildContext,
121
123
  type StaticBuildContext,
package/src/index.ts CHANGED
@@ -88,6 +88,7 @@ export type {
88
88
  LayoutUseItem,
89
89
  AllUseItems,
90
90
  UseItems,
91
+ HandlerUseItem,
91
92
  } from "./route-types.js";
92
93
 
93
94
  // Response route types (usable in both server and client contexts)
@@ -152,6 +153,13 @@ export function Prerender(): never {
152
153
  throw serverOnlyStubError("Prerender");
153
154
  }
154
155
 
156
+ /**
157
+ * Error-throwing stub for server-only `Passthrough` function.
158
+ */
159
+ export function Passthrough(): never {
160
+ throw serverOnlyStubError("Passthrough");
161
+ }
162
+
155
163
  /**
156
164
  * Error-throwing stub for server-only `Static` function.
157
165
  */
@@ -235,6 +243,10 @@ export type {
235
243
  ReadonlyHeaders,
236
244
  } from "./server/cookie-store.js";
237
245
 
246
+ // Built-in handles (universal — work on both server and client)
247
+ export { Meta } from "./handles/meta.js";
248
+ export { Breadcrumbs } from "./handles/breadcrumbs.js";
249
+
238
250
  // Meta types
239
251
  export type { MetaDescriptor, MetaDescriptorBase } from "./router/types.js";
240
252
 
@@ -121,10 +121,11 @@ export function createPrerenderStore(): PrerenderStore | null {
121
121
  if (!mod) return null;
122
122
  const specifier = mod.default[key];
123
123
  if (!specifier) return null;
124
- return mod
125
- .loadPrerenderAsset(specifier)
126
- .then((asset) => asset.default)
127
- .catch(() => null);
124
+ // Let asset load errors propagate — a missing/corrupted artifact
125
+ // for a key that exists in the manifest is a build/deploy error
126
+ // and should surface as a 500, not be silently swallowed as null
127
+ // (which the handler stub would misreport as a 404).
128
+ return mod.loadPrerenderAsset(specifier).then((asset) => asset.default);
128
129
  });
129
130
  cache.set(key, promise);
130
131
  return promise;
package/src/prerender.ts CHANGED
@@ -36,6 +36,7 @@ import type { Handle } from "./handle.js";
36
36
  import type { ContextVar } from "./context-var.js";
37
37
  import type { ReverseFunction } from "./reverse.js";
38
38
  import type { DefaultReverseRouteMap } from "./types/global-namespace.js";
39
+ import type { UseItems, HandlerUseItem } from "./route-types.js";
39
40
  import { isCachedFunction } from "./cache/taint.js";
40
41
 
41
42
  // -- Named route resolution types -------------------------------------------
@@ -105,13 +106,6 @@ type ResolvePrerenderParams<
105
106
  // -- Types ------------------------------------------------------------------
106
107
 
107
108
  export interface PrerenderOptions {
108
- /**
109
- * Keep handler in server bundle for live fallback (default: false).
110
- * false: handler replaced with stub, source-only APIs excluded from bundle.
111
- * true: handler stays in bundle, unknown params render live at request time.
112
- */
113
- passthrough?: boolean;
114
-
115
109
  /**
116
110
  * Maximum number of param sets to render in parallel (default: 1).
117
111
  * Only applies to dynamic Prerender handlers with getParams().
@@ -131,8 +125,8 @@ export interface PrerenderOptions {
131
125
 
132
126
  /**
133
127
  * Context passed to Prerender() handlers at build time.
134
- * Has a synthetic URL from getParams, params, and pathname.
135
- * No request, env, headers, cookies.
128
+ * Has a synthetic URL from getParams, params, pathname, and optionally env.
129
+ * No request, headers, cookies.
136
130
  */
137
131
  export interface BuildContext<TParams> {
138
132
  /** Params extracted from the route pattern (populated from getParams). */
@@ -141,6 +135,23 @@ export interface BuildContext<TParams> {
141
135
  /** True during build-time pre-rendering, false during passthrough live render. */
142
136
  build: true;
143
137
 
138
+ /**
139
+ * True when running in Vite dev mode (on-demand prerender), false during
140
+ * production `vite build`. Use this to branch on runtime mode without
141
+ * changing build semantics.
142
+ */
143
+ dev: boolean;
144
+
145
+ /**
146
+ * Build-time environment bindings (KV, D1, etc.) supplied by the Vite plugin.
147
+ * Only available when `buildEnv` is configured in rango() options.
148
+ * Throws with a clear error if not configured.
149
+ *
150
+ * This is NOT the live request env — it is shared across all prerender
151
+ * invocations for the build.
152
+ */
153
+ env: DefaultEnv;
154
+
144
155
  /** Read a variable set by getParams or a parent handler. */
145
156
  get: {
146
157
  <T>(contextVar: ContextVar<T>): T | undefined;
@@ -173,8 +184,8 @@ export interface BuildContext<TParams> {
173
184
 
174
185
  /**
175
186
  * Signal that this param set should not produce a local prerender artifact.
176
- * At runtime the handler runs live instead. Only valid on routes declared
177
- * with `{ passthrough: true }`.
187
+ * At runtime the live handler runs instead. Only valid on routes wrapped
188
+ * with `Passthrough()`.
178
189
  */
179
190
  passthrough: () => PrerenderPassthroughResult;
180
191
  }
@@ -187,6 +198,17 @@ export interface StaticBuildContext {
187
198
  /** Always true for Static handlers at build time. */
188
199
  build: true;
189
200
 
201
+ /**
202
+ * True when running in Vite dev mode, false during production build.
203
+ */
204
+ dev: boolean;
205
+
206
+ /**
207
+ * Build-time environment bindings supplied by the Vite plugin.
208
+ * Only available when `buildEnv` is configured in rango() options.
209
+ */
210
+ env: DefaultEnv;
211
+
190
212
  /** Read a variable (available for type consistency with BuildContext). */
191
213
  get: {
192
214
  <T>(contextVar: ContextVar<T>): T | undefined;
@@ -214,6 +236,17 @@ export interface GetParamsContext {
214
236
  /** Always true during build-time getParams execution. */
215
237
  build: true;
216
238
 
239
+ /**
240
+ * True when running in Vite dev mode, false during production build.
241
+ */
242
+ dev: boolean;
243
+
244
+ /**
245
+ * Build-time environment bindings supplied by the Vite plugin.
246
+ * Only available when `buildEnv` is configured in rango() options.
247
+ */
248
+ env: DefaultEnv;
249
+
217
250
  /** Set a variable that will be available to each handler invocation via ctx.get(). */
218
251
  set: {
219
252
  <T>(contextVar: ContextVar<T>, value: T): void;
@@ -224,23 +257,6 @@ export interface GetParamsContext {
224
257
  reverse: BuildReverseFunction;
225
258
  }
226
259
 
227
- /**
228
- * Context type for passthrough Prerender handlers.
229
- *
230
- * When `passthrough: true`, the handler runs both at build time and at request
231
- * time. The context is a full `HandlerContext` with `build: boolean`:
232
- * - `ctx.build === true`: build-time, env/request/res throw at runtime
233
- * - `ctx.build === false`: live request, full context available
234
- *
235
- * For `passthrough: false` (default), handlers receive `BuildContext` only.
236
- */
237
- export type PrerenderPassthroughContext<
238
- TParams = {},
239
- TEnv = DefaultEnv,
240
- > = HandlerContext<TParams, TEnv> & {
241
- passthrough: () => PrerenderPassthroughResult;
242
- };
243
-
244
260
  export interface PrerenderHandlerDefinition<
245
261
  TParams extends Record<string, any> = any,
246
262
  > {
@@ -253,6 +269,8 @@ export interface PrerenderHandlerDefinition<
253
269
  getParams?: (ctx: GetParamsContext) => Promise<TParams[]> | TParams[];
254
270
  /** Pre-render options. */
255
271
  options?: PrerenderOptions;
272
+ /** Composable default DSL items merged when the handler is mounted. */
273
+ use?: () => UseItems<HandlerUseItem>;
256
274
  }
257
275
 
258
276
  // -- Overloads --------------------------------------------------------------
@@ -263,7 +281,7 @@ export interface PrerenderHandlerDefinition<
263
281
  // Explicit params work as before:
264
282
  // Prerender<{ slug: string }> → params = { slug: string }
265
283
 
266
- // Overload 1: Static handler, no passthrough (build-time only)
284
+ // Overload 1: Static handler (build-time only)
267
285
  export function Prerender<
268
286
  T extends
269
287
  | keyof DefaultPrerenderRouteMap
@@ -273,34 +291,15 @@ export function Prerender<
273
291
  >(
274
292
  handler: (
275
293
  ctx: BuildContext<ResolvePrerenderParams<T, TRouteMap>>,
276
- ) => ReactNode | Promise<ReactNode>,
277
- options?: PrerenderOptions & { passthrough?: false },
278
- __injectedId?: string,
279
- ): PrerenderHandlerDefinition<ResolvePrerenderParams<T, TRouteMap>>;
280
-
281
- // Overload 2: Static handler, passthrough (build + live — full HandlerContext)
282
- export function Prerender<
283
- T extends
284
- | keyof DefaultPrerenderRouteMap
285
- | `.${keyof TRouteMap & string}`
286
- | Record<string, any> = {},
287
- TRouteMap extends {} = DefaultPrerenderRouteMap,
288
- TEnv = DefaultEnv,
289
- >(
290
- handler: (
291
- ctx: PrerenderPassthroughContext<
292
- ResolvePrerenderParams<T, TRouteMap>,
293
- TEnv
294
- >,
295
294
  ) =>
296
295
  | ReactNode
297
296
  | PrerenderPassthroughResult
298
297
  | Promise<ReactNode | PrerenderPassthroughResult>,
299
- options: PrerenderOptions & { passthrough: true },
298
+ options?: PrerenderOptions,
300
299
  __injectedId?: string,
301
300
  ): PrerenderHandlerDefinition<ResolvePrerenderParams<T, TRouteMap>>;
302
301
 
303
- // Overload 3: Dynamic handler, no passthrough (build-time only)
302
+ // Overload 2: Dynamic handler (build-time only)
304
303
  export function Prerender<
305
304
  T extends
306
305
  | keyof DefaultPrerenderRouteMap
@@ -315,35 +314,11 @@ export function Prerender<
315
314
  | ResolvePrerenderParams<T, TRouteMap>[],
316
315
  handler: (
317
316
  ctx: BuildContext<ResolvePrerenderParams<T, TRouteMap>>,
318
- ) => ReactNode | Promise<ReactNode>,
319
- options?: PrerenderOptions & { passthrough?: false },
320
- __injectedId?: string,
321
- ): PrerenderHandlerDefinition<ResolvePrerenderParams<T, TRouteMap>>;
322
-
323
- // Overload 4: Dynamic handler, passthrough (build + live — full HandlerContext)
324
- export function Prerender<
325
- T extends
326
- | keyof DefaultPrerenderRouteMap
327
- | `.${keyof TRouteMap & string}`
328
- | Record<string, any>,
329
- TRouteMap extends {} = DefaultPrerenderRouteMap,
330
- TEnv = DefaultEnv,
331
- >(
332
- getParams: (
333
- ctx: GetParamsContext,
334
- ) =>
335
- | Promise<ResolvePrerenderParams<T, TRouteMap>[]>
336
- | ResolvePrerenderParams<T, TRouteMap>[],
337
- handler: (
338
- ctx: PrerenderPassthroughContext<
339
- ResolvePrerenderParams<T, TRouteMap>,
340
- TEnv
341
- >,
342
317
  ) =>
343
318
  | ReactNode
344
319
  | PrerenderPassthroughResult
345
320
  | Promise<ReactNode | PrerenderPassthroughResult>,
346
- options: PrerenderOptions & { passthrough: true },
321
+ options?: PrerenderOptions,
347
322
  __injectedId?: string,
348
323
  ): PrerenderHandlerDefinition<ResolvePrerenderParams<T, TRouteMap>>;
349
324
 
@@ -422,7 +397,7 @@ export function Prerender<TParams extends Record<string, any>>(
422
397
  /**
423
398
  * Sentinel returned by `ctx.passthrough()` to signal that a specific param set
424
399
  * should not produce a local prerender artifact. The build skips writing the
425
- * entry; at runtime the handler runs live (requires `{ passthrough: true }`).
400
+ * entry; at runtime the Passthrough live handler runs instead.
426
401
  */
427
402
  export const PRERENDER_PASSTHROUGH: Readonly<{
428
403
  __brand: "prerenderPassthrough";
@@ -446,7 +421,7 @@ export function isPrerenderPassthrough(
446
421
  );
447
422
  }
448
423
 
449
- // -- Type guard -------------------------------------------------------------
424
+ // -- Type guards ------------------------------------------------------------
450
425
 
451
426
  /**
452
427
  * Type guard to check if a value is a PrerenderHandlerDefinition.
@@ -461,3 +436,89 @@ export function isPrerenderHandler(
461
436
  (value as { __brand: unknown }).__brand === "prerenderHandler"
462
437
  );
463
438
  }
439
+
440
+ // -- Passthrough wrapper ----------------------------------------------------
441
+
442
+ /**
443
+ * A prerender route with a live fallback handler for unknown params at runtime.
444
+ *
445
+ * Wraps a `Prerender(...)` definition with a separate handler that runs at
446
+ * request time for params not covered by `getParams()`.
447
+ *
448
+ * - Build time: `prerenderDef` provides getParams + build handler.
449
+ * - Runtime: `liveHandler` runs for unknown params with full HandlerContext.
450
+ *
451
+ * @example
452
+ * ```ts
453
+ * const BlogPrerender = Prerender(
454
+ * async () => [{ slug: "getting-started" }, { slug: "api-reference" }],
455
+ * async (ctx) => <BlogPost slug={ctx.params.slug} />,
456
+ * );
457
+ *
458
+ * // In route definition:
459
+ * path("/blog/:slug", Passthrough(BlogPrerender, async (ctx) => {
460
+ * const post = await ctx.env.DB.get(ctx.params.slug);
461
+ * return <BlogPost slug={ctx.params.slug} post={post} />;
462
+ * }))
463
+ * ```
464
+ */
465
+ export interface PassthroughHandlerDefinition<
466
+ TParams extends Record<string, any> = any,
467
+ TEnv = DefaultEnv,
468
+ > {
469
+ readonly __brand: "passthroughHandler";
470
+ /** The underlying prerender definition (build-time rendering). */
471
+ prerenderDef: PrerenderHandlerDefinition<TParams>;
472
+ /** Live handler for runtime fallback on unknown params. */
473
+ liveHandler: (
474
+ ctx: HandlerContext<TParams, TEnv>,
475
+ ) => ReactNode | Promise<ReactNode> | Response | Promise<Response>;
476
+ /** Composable default DSL items merged when the handler is mounted. */
477
+ use?: () => UseItems<HandlerUseItem>;
478
+ }
479
+
480
+ export function Passthrough<
481
+ TParams extends Record<string, any>,
482
+ TEnv = DefaultEnv,
483
+ >(
484
+ prerenderDef: PrerenderHandlerDefinition<TParams>,
485
+ liveHandler: (
486
+ ctx: HandlerContext<TParams, TEnv>,
487
+ ) => ReactNode | Promise<ReactNode> | Response | Promise<Response>,
488
+ ): PassthroughHandlerDefinition<TParams, TEnv>;
489
+
490
+ // Implementation
491
+ export function Passthrough<
492
+ TParams extends Record<string, any>,
493
+ TEnv = DefaultEnv,
494
+ >(
495
+ prerenderDef: PrerenderHandlerDefinition<TParams>,
496
+ liveHandler: (
497
+ ctx: HandlerContext<TParams, TEnv>,
498
+ ) => ReactNode | Promise<ReactNode> | Response | Promise<Response>,
499
+ ): PassthroughHandlerDefinition<TParams, TEnv> {
500
+ if (!isPrerenderHandler(prerenderDef)) {
501
+ throw new Error(
502
+ "[rsc-router] Passthrough: first argument must be a Prerender() definition.",
503
+ );
504
+ }
505
+ return {
506
+ __brand: "passthroughHandler" as const,
507
+ prerenderDef,
508
+ liveHandler,
509
+ };
510
+ }
511
+
512
+ /**
513
+ * Type guard to check if a value is a PassthroughHandlerDefinition.
514
+ */
515
+ export function isPassthroughHandler(
516
+ value: unknown,
517
+ ): value is PassthroughHandlerDefinition {
518
+ return (
519
+ typeof value === "object" &&
520
+ value !== null &&
521
+ "__brand" in value &&
522
+ (value as { __brand: unknown }).__brand === "passthroughHandler"
523
+ );
524
+ }
package/src/reverse.ts CHANGED
@@ -305,8 +305,22 @@ export function createReverse<TRoutes extends Record<string, string>>(
305
305
  if (params) {
306
306
  // Replace :param placeholders with actual values
307
307
  // Strip constraint syntax: :param(a|b) -> use "param" as key
308
+ // Optional params (:param?) are omitted when not provided
309
+ let hadOmittedOptional = false;
308
310
  result = result.replace(
309
- /:([a-zA-Z_][a-zA-Z0-9_]*)(\([^)]*\))?\??/g,
311
+ /:([a-zA-Z_][a-zA-Z0-9_]*)(\([^)]*\))?(\?)/g,
312
+ (_, key, _constraint, optional) => {
313
+ const value = params[key];
314
+ if (value === undefined) {
315
+ hadOmittedOptional = true;
316
+ return "";
317
+ }
318
+ return encodeURIComponent(value);
319
+ },
320
+ );
321
+ // Second pass: required params (no trailing ?)
322
+ result = result.replace(
323
+ /:([a-zA-Z_][a-zA-Z0-9_]*)(\([^)]*\))?(?!\?)/g,
310
324
  (_, key) => {
311
325
  const value = params[key];
312
326
  if (value === undefined) {
@@ -315,6 +329,13 @@ export function createReverse<TRoutes extends Record<string, string>>(
315
329
  return encodeURIComponent(value);
316
330
  },
317
331
  );
332
+ // Clean up slashes only when an optional param was actually omitted,
333
+ // so intentional trailing-slash patterns like "/blog/" are preserved.
334
+ if (hadOmittedOptional) {
335
+ const hadTrailingSlash = pattern.length > 1 && pattern.endsWith("/");
336
+ result = result.replace(/\/\/+/g, "/").replace(/\/+$/, "") || "/";
337
+ if (hadTrailingSlash && !result.endsWith("/")) result += "/";
338
+ }
318
339
  }
319
340
 
320
341
  // Append search params as query string