@rangojs/router 0.2.0 → 0.4.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 (105) hide show
  1. package/README.md +19 -1
  2. package/dist/types/browser/event-controller.d.ts +4 -0
  3. package/dist/types/browser/link-interceptor.d.ts +17 -7
  4. package/dist/types/browser/navigation-bridge.d.ts +13 -1
  5. package/dist/types/browser/notify-listeners.d.ts +2 -0
  6. package/dist/types/browser/prefetch/cache.d.ts +1 -1
  7. package/dist/types/browser/prefetch/default-strategy.d.ts +31 -0
  8. package/dist/types/browser/prefetch/invalidation.d.ts +6 -0
  9. package/dist/types/browser/prefetch/loader.d.ts +3 -1
  10. package/dist/types/browser/prefetch/observer.d.ts +3 -6
  11. package/dist/types/browser/prefetch/runtime.d.ts +0 -1
  12. package/dist/types/browser/rango-state.d.ts +4 -0
  13. package/dist/types/browser/react/Link.d.ts +11 -19
  14. package/dist/types/browser/react/context.d.ts +3 -0
  15. package/dist/types/browser/rsc-router.d.ts +7 -2
  16. package/dist/types/browser/types.d.ts +6 -0
  17. package/dist/types/cache/cache-key-utils.d.ts +11 -3
  18. package/dist/types/cache/cache-scope.d.ts +82 -3
  19. package/dist/types/cache/cf/cf-cache-store.d.ts +2 -2
  20. package/dist/types/cache/index.d.ts +3 -1
  21. package/dist/types/cache/search-params-filter.d.ts +64 -0
  22. package/dist/types/cache/shell-snapshot.d.ts +4 -4
  23. package/dist/types/cache/types.d.ts +36 -2
  24. package/dist/types/cache/vercel/vercel-cache-store.d.ts +2 -2
  25. package/dist/types/index.d.ts +1 -0
  26. package/dist/types/index.rsc.d.ts +1 -0
  27. package/dist/types/router/match-middleware/cache-lookup.d.ts +13 -0
  28. package/dist/types/router/navigation-snapshot.d.ts +29 -0
  29. package/dist/types/router/prefetch-default.d.ts +28 -0
  30. package/dist/types/router/router-interfaces.d.ts +7 -0
  31. package/dist/types/router/router-options.d.ts +54 -0
  32. package/dist/types/rsc/capture-queue.d.ts +6 -0
  33. package/dist/types/rsc/shell-build-manifest.d.ts +7 -1
  34. package/dist/types/rsc/shell-capture.d.ts +15 -7
  35. package/dist/types/rsc/shell-serve.d.ts +11 -4
  36. package/dist/types/rsc/types.d.ts +19 -0
  37. package/dist/types/server/request-context.d.ts +57 -4
  38. package/dist/types/testing/e2e/index.d.ts +2 -2
  39. package/dist/types/testing/e2e/page-helpers.d.ts +24 -0
  40. package/dist/types/testing/render-route.d.ts +10 -1
  41. package/dist/types/testing/shell-status.d.ts +6 -3
  42. package/dist/types/vite/plugin-types.d.ts +1 -1
  43. package/dist/vite/index.js +9 -6
  44. package/package.json +23 -22
  45. package/skills/caching/SKILL.md +39 -0
  46. package/skills/comparison/references/framework-comparison.md +9 -2
  47. package/skills/links/SKILL.md +24 -0
  48. package/skills/ppr/SKILL.md +80 -16
  49. package/skills/router-setup/SKILL.md +9 -0
  50. package/skills/testing/client-components.md +15 -14
  51. package/skills/vercel/SKILL.md +1 -1
  52. package/src/browser/event-controller.ts +110 -11
  53. package/src/browser/link-interceptor.ts +469 -20
  54. package/src/browser/navigation-bridge.ts +71 -2
  55. package/src/browser/navigation-store.ts +24 -1
  56. package/src/browser/notify-listeners.ts +22 -0
  57. package/src/browser/prefetch/cache.ts +4 -2
  58. package/src/browser/prefetch/default-strategy.ts +74 -0
  59. package/src/browser/prefetch/invalidation.ts +30 -0
  60. package/src/browser/prefetch/loader.ts +18 -17
  61. package/src/browser/prefetch/observer.ts +50 -22
  62. package/src/browser/prefetch/runtime.ts +0 -1
  63. package/src/browser/rango-state.ts +21 -0
  64. package/src/browser/react/Link.tsx +111 -101
  65. package/src/browser/react/NavigationProvider.tsx +1 -0
  66. package/src/browser/react/context.ts +4 -0
  67. package/src/browser/rsc-router.tsx +30 -9
  68. package/src/browser/types.ts +6 -0
  69. package/src/cache/cache-key-utils.ts +18 -4
  70. package/src/cache/cache-runtime.ts +7 -2
  71. package/src/cache/cache-scope.ts +152 -23
  72. package/src/cache/cf/cf-cache-store.ts +55 -16
  73. package/src/cache/document-cache.ts +7 -1
  74. package/src/cache/index.ts +7 -0
  75. package/src/cache/search-params-filter.ts +118 -0
  76. package/src/cache/shell-snapshot.ts +8 -4
  77. package/src/cache/types.ts +39 -2
  78. package/src/cache/vercel/vercel-cache-store.ts +22 -3
  79. package/src/index.rsc.ts +4 -0
  80. package/src/index.ts +6 -0
  81. package/src/router/match-middleware/cache-lookup.ts +146 -33
  82. package/src/router/match-middleware/cache-store.ts +70 -0
  83. package/src/router/navigation-snapshot.ts +46 -6
  84. package/src/router/prefetch-default.ts +59 -0
  85. package/src/router/router-interfaces.ts +8 -0
  86. package/src/router/router-options.ts +59 -1
  87. package/src/router.ts +7 -0
  88. package/src/rsc/capture-queue.ts +24 -1
  89. package/src/rsc/full-payload.ts +1 -0
  90. package/src/rsc/handler.ts +10 -0
  91. package/src/rsc/response-cache-serve.ts +1 -1
  92. package/src/rsc/rsc-rendering.ts +367 -40
  93. package/src/rsc/shell-build-manifest.ts +8 -1
  94. package/src/rsc/shell-capture.ts +99 -50
  95. package/src/rsc/shell-serve.ts +14 -6
  96. package/src/rsc/types.ts +19 -0
  97. package/src/server/request-context.ts +62 -3
  98. package/src/testing/dispatch.ts +21 -3
  99. package/src/testing/e2e/index.ts +6 -0
  100. package/src/testing/e2e/page-helpers.ts +47 -0
  101. package/src/testing/e2e/parity.ts +13 -0
  102. package/src/testing/render-route.tsx +86 -17
  103. package/src/testing/shell-status.ts +20 -3
  104. package/src/vite/plugin-types.ts +1 -1
  105. package/src/vite/plugins/vercel-output.ts +2 -2
@@ -20,7 +20,10 @@ import React from "react";
20
20
  import { bufferToBase64 } from "../cache/cf/cf-base64.js";
21
21
  import { reportCacheError } from "../cache/cache-error.js";
22
22
  import { runBackground } from "../cache/background-task.js";
23
- import { enqueueSerializedCapture } from "./capture-queue.js";
23
+ import {
24
+ CaptureQueueFullError,
25
+ enqueueSerializedCapture,
26
+ } from "./capture-queue.js";
24
27
  import { SHELL_CAPTURE_MAX_WAIT_MS } from "./shell-capture-constants.js";
25
28
  import { INTERNAL_RANGO_DEBUG } from "../internal-debug.js";
26
29
  import { observePhase, PHASES } from "../router/instrument.js";
@@ -57,6 +60,7 @@ import type { SSRModule } from "./types.js";
57
60
  import { buildFullPayload } from "./full-payload.js";
58
61
  import { resolveDeferredHandleValues } from "../handles/deferred-resolution.js";
59
62
  import { renderRscFlightStage } from "./render-pipeline.js";
63
+ import { stripInternalParams } from "../router/handler-context.js";
60
64
 
61
65
  /**
62
66
  * Task-quantized quiesce: the number of consecutive macrotask hops with zero new
@@ -344,39 +348,6 @@ function warnCaptureRefusedOnce(key: string, reason: string): void {
344
348
  );
345
349
  }
346
350
 
347
- /** Keys already warned about untagged bake-lane data baked into the shell. */
348
- const warnedUntaggedShellBakes = new Set<string>();
349
-
350
- /**
351
- * Warn once per shell key that a bake-lane loader baked material into the shell
352
- * but the capture recorded ZERO tags (no render-collected _requestTags, no
353
- * static ppr.tags). Such data is frozen in the shared shell until TTL and is
354
- * un-evictable by tag: a server action refreshes the CLIENT only (rotates Rango
355
- * state, busts the browser HTTP cache) and never touches the server shell store,
356
- * and updateTag()/revalidateTag() cannot drop data that was baked WITHOUT a tag.
357
- *
358
- * Coarse per-shell-key signal, not per-loader attribution — the tag set is
359
- * unioned globally at the write barrier, not tracked per loader, so we cannot
360
- * name the offending loader without adding attribution plumbing (deliberately
361
- * not done). Dev-only + once-per-key so it never spams production or fires on
362
- * every capture.
363
- */
364
- function warnUntaggedShellBakeOnce(key: string): void {
365
- if (warnedUntaggedShellBakes.has(key)) return;
366
- warnedUntaggedShellBakes.add(key);
367
- console.warn(
368
- `[rango] Shell capture for "${key}" baked bake-lane loader data into the ` +
369
- "shell with NO cache tag. That data is frozen in the shared shell until " +
370
- "TTL and cannot be tag-invalidated: a server action refresh touches the " +
371
- "client only (not the server shell store), and updateTag() cannot evict " +
372
- "data that was baked without a tag.\n" +
373
- 'Fix: tag the data (cacheTag() / "use cache" / cache({ tags })) so ' +
374
- "updateTag() drops the shell, or move the volatile read under a loading() " +
375
- "hole so it stays on the live lane and is never baked. See the /ppr skill " +
376
- "(node_modules/@rangojs/router/skills/ppr/SKILL.md).",
377
- );
378
- }
379
-
380
351
  /**
381
352
  * Default cap (serialized UTF-8 bytes) on the capture data snapshot riding
382
353
  * inside a shell entry, when the route's `ppr` option does not set
@@ -444,6 +415,7 @@ export interface ShellCaptureDebugEvent {
444
415
  * the key (stampede guard) and scheduled nothing
445
416
  * - skip-backoff: the key is inside its refused-capture backoff window and
446
417
  * the capture was not attempted
418
+ * - skip-capacity: the isolate capture queue is full; a later request may retry
447
419
  * - backoff: the key entered (or escalated) backoff after a terminal
448
420
  * no-shell — carries the new backoff state
449
421
  */
@@ -455,6 +427,7 @@ export interface ShellCaptureDebugEvent {
455
427
  | "error"
456
428
  | "skip-in-flight"
457
429
  | "skip-backoff"
430
+ | "skip-capacity"
458
431
  | "backoff";
459
432
  /** Attempt number (1 = first, 2 = in-place retry). Absent on skips. */
460
433
  attempt?: number;
@@ -476,6 +449,8 @@ export interface ShellCaptureDebugEvent {
476
449
  snapshotBytes?: number;
477
450
  /** True when the snapshot exceeded maxSnapshotBytes and was dropped. */
478
451
  snapshotSkipped?: boolean;
452
+ /** A bake-lane loader settled into a shell that uses TTL/SWR-only invalidation. */
453
+ untaggedBake?: true;
479
454
  /** Outcome reported by a store that supports shell-write acknowledgements. */
480
455
  storeWrite?: "stored" | "invalidated";
481
456
  /** Consecutive failure count in the key's backoff entry, when one exists. */
@@ -518,6 +493,7 @@ export function describeShellCaptureEvent(
518
493
  `snapshot=${event.snapshotBytes}b${event.snapshotSkipped ? " (over cap, skipped)" : ""}`,
519
494
  );
520
495
  }
496
+ if (event.untaggedBake) parts.push("untagged-bake");
521
497
  if (event.storeWrite !== undefined) {
522
498
  parts.push(`store-write=${event.storeWrite}`);
523
499
  }
@@ -835,6 +811,8 @@ export interface ShellCaptureDescriptor {
835
811
  * {@link ShellCaptureDebugEvent} per attempt/skip.
836
812
  */
837
813
  debugSink?: (event: ShellCaptureDebugEvent) => void;
814
+ /** Store the snapshot for navigation replay, never the captured HTML prelude. */
815
+ navigationOnly?: true;
838
816
  }
839
817
 
840
818
  /**
@@ -844,9 +822,9 @@ export interface ShellCaptureDescriptor {
844
822
  * error is routed through reportCacheError — capture is best-effort; a failure just
845
823
  * means the next request recaptures.
846
824
  *
847
- * Eligibility (nonce/allReady/partial/status/strategy) is decided by the caller
848
- * (rsc-rendering.ts maybeScheduleShellCapture); this function only owns the
849
- * stampede guard and the background dispatch.
825
+ * Eligibility (nonce/partial/status/strategy) is decided by the caller. An SSR
826
+ * module loader may be passed for cold partial requests; it runs only after the
827
+ * capture enters the guarded background queue, never on response latency.
850
828
  */
851
829
  export function scheduleShellCapture(
852
830
  ctx: HandlerContext<any>,
@@ -854,7 +832,9 @@ export function scheduleShellCapture(
854
832
  env: any,
855
833
  url: URL,
856
834
  reqCtx: RequestContext<any>,
857
- ssrModule: SSRModule,
835
+ ssrModule:
836
+ | SSRModule
837
+ | ((request: Request, url: URL) => Promise<SSRModule | null>),
858
838
  descriptor: ShellCaptureDescriptor,
859
839
  ): void {
860
840
  const key = descriptor.key;
@@ -875,13 +855,30 @@ export function scheduleShellCapture(
875
855
  inFlightCaptures.add(key);
876
856
  const captureTask = async () => {
877
857
  try {
858
+ const setupUrl = descriptor.navigationOnly
859
+ ? stripInternalParams(url)
860
+ : url;
861
+ const setupRequest = descriptor.navigationOnly
862
+ ? createNavigationCaptureRequest(request, setupUrl)
863
+ : request;
864
+ const resolvedSsrModule =
865
+ typeof ssrModule === "function"
866
+ ? await ssrModule(setupRequest, setupUrl)
867
+ : ssrModule;
868
+ if (
869
+ !resolvedSsrModule ||
870
+ !resolvedSsrModule.resumeShellHTML ||
871
+ !resolvedSsrModule.captureShellHTML
872
+ ) {
873
+ return;
874
+ }
878
875
  const outcome = await runShellCapture(
879
876
  ctx,
880
877
  request,
881
878
  env,
882
879
  url,
883
880
  reqCtx,
884
- ssrModule,
881
+ resolvedSsrModule,
885
882
  descriptor,
886
883
  );
887
884
  // Update the negative cache off the terminal outcome. A stored shell clears
@@ -917,7 +914,21 @@ export function scheduleShellCapture(
917
914
  // capture makes the sibling freeze a trivial prelude and store nothing
918
915
  // (rotating eternal-MISS victims on GH runners). The stampede guard above
919
916
  // stays per-key (dedupe while queued); the queue is cross-key.
920
- const serializedTask = () => enqueueSerializedCapture(captureTask);
917
+ const serializedTask = async () => {
918
+ try {
919
+ await enqueueSerializedCapture(captureTask);
920
+ } catch (error) {
921
+ if (error instanceof CaptureQueueFullError) {
922
+ inFlightCaptures.delete(key);
923
+ publishCaptureDebugEvent(descriptor, {
924
+ key,
925
+ outcome: "skip-capacity",
926
+ });
927
+ return;
928
+ }
929
+ throw error;
930
+ }
931
+ };
921
932
  // The capture's own task must NOT enter reqCtx._pendingBackgroundTasks: the
922
933
  // capture drains that list before rendering (the write-barrier ordering edge),
923
934
  // and awaiting its own still-running promise would burn the whole barrier
@@ -939,6 +950,22 @@ export function scheduleShellCapture(
939
950
  */
940
951
  type CaptureAttemptOutcome = "stored" | "redirect" | "no-shell" | "refused";
941
952
 
953
+ function createNavigationCaptureRequest(request: Request, url: URL): Request {
954
+ const headers = new Headers(request.headers);
955
+ headers.set("accept", "text/html");
956
+ for (const name of [
957
+ "rsc-action",
958
+ "x-rango-prefetch",
959
+ "x-rango-state",
960
+ "x-rsc-hmr",
961
+ "x-rsc-router-client-path",
962
+ "x-rsc-router-intercept-source",
963
+ ]) {
964
+ headers.delete(name);
965
+ }
966
+ return new Request(url, { method: request.method, headers });
967
+ }
968
+
942
969
  /**
943
970
  * Per-attempt observability fields, filled along the capture path (barrier in
944
971
  * attemptCapture, the rest in captureAndStoreShell) and folded into the
@@ -953,6 +980,7 @@ type CaptureAttemptStats = Pick<
953
980
  | "preludeBytes"
954
981
  | "snapshotBytes"
955
982
  | "snapshotSkipped"
983
+ | "untaggedBake"
956
984
  | "storeWrite"
957
985
  >;
958
986
 
@@ -984,6 +1012,10 @@ async function runShellCapture(
984
1012
  descriptor: ShellCaptureDescriptor,
985
1013
  retryDelayMs: number = SHELL_CAPTURE_RETRY_DELAY_MS,
986
1014
  ): Promise<CaptureAttemptOutcome> {
1015
+ const captureUrl = descriptor.navigationOnly ? stripInternalParams(url) : url;
1016
+ const captureRequest = descriptor.navigationOnly
1017
+ ? createNavigationCaptureRequest(request, captureUrl)
1018
+ : request;
987
1019
  const log = descriptor.debug
988
1020
  ? (message: string) => console.log(message)
989
1021
  : () => {};
@@ -1000,9 +1032,9 @@ async function runShellCapture(
1000
1032
  const start = performance.now();
1001
1033
  const outcome = await attemptCapture(
1002
1034
  ctx,
1003
- request,
1035
+ captureRequest,
1004
1036
  env,
1005
- url,
1037
+ captureUrl,
1006
1038
  reqCtx,
1007
1039
  ssrModule,
1008
1040
  descriptor,
@@ -1122,6 +1154,7 @@ async function attemptCapture(
1122
1154
  const { derivedCtx, freshHandleStore } = deriveShellCaptureContext(
1123
1155
  reqCtx,
1124
1156
  descriptor,
1157
+ descriptor.navigationOnly ? { request, url } : undefined,
1125
1158
  );
1126
1159
  const captureStartedAt = Date.now();
1127
1160
 
@@ -1195,6 +1228,7 @@ export interface CaptureContextDerivation {
1195
1228
  export function deriveShellCaptureContext(
1196
1229
  reqCtx: RequestContext<any>,
1197
1230
  descriptor: Pick<ShellCaptureDescriptor, "ttl" | "swr">,
1231
+ identity?: { request: Request; url: URL },
1198
1232
  ): CaptureContextDerivation {
1199
1233
  const freshHandleStore = createHandleStore();
1200
1234
  freshHandleStore.onError = reqCtx._handleStore.onError;
@@ -1266,6 +1300,13 @@ export function deriveShellCaptureContext(
1266
1300
  };
1267
1301
 
1268
1302
  const derivedCtx: RequestContext = Object.create(reqCtx);
1303
+ if (identity) {
1304
+ derivedCtx.request = identity.request;
1305
+ derivedCtx.url = identity.url;
1306
+ derivedCtx.originalUrl = new URL(identity.url);
1307
+ derivedCtx.pathname = identity.url.pathname;
1308
+ derivedCtx.searchParams = identity.url.searchParams;
1309
+ }
1269
1310
  derivedCtx._handleStore = freshHandleStore;
1270
1311
  // Own render barrier, closure-bound to the derived ctx and the fresh store
1271
1312
  // (issue #684, plan 009). Without this every _renderBarrier* read fell
@@ -1553,7 +1594,7 @@ async function captureAndStoreShell(
1553
1594
  const loaderRecords = reqCtx._shellCaptureLoaderRecords;
1554
1595
  // Set once a bake-lane loader settles with real (non-hole) material: its data
1555
1596
  // is frozen into the shell prelude regardless of whether snapshot
1556
- // serialization succeeds. Drives the untagged-bake dev warning below.
1597
+ // serialization succeeds. Drives the opt-in debug metadata below.
1557
1598
  let bakedLoaderMaterial = false;
1558
1599
  if (loaderRecords && loaderRecords.size > 0) {
1559
1600
  // The codec import is deferred past the elide probes: a rejected record
@@ -1638,13 +1679,15 @@ async function captureAndStoreShell(
1638
1679
  const union = new Set<string>([...(capture.tags ?? []), ...collected]);
1639
1680
  const shellTags = union.size > 0 ? [...union] : undefined;
1640
1681
 
1641
- // Untagged-bake diagnostic: a bake-lane loader froze mutable data into the
1642
- // shell but nothing tags the entry, so it is un-invalidatable except by TTL —
1643
- // a read-your-own-writes gap on the document channel (an action refresh skips
1644
- // the server shell; updateTag cannot drop untagged data). Coarse per-shell-key
1645
- // signal; dev-only and once-per-key so it never spams production.
1646
- if (isDevMode() && bakedLoaderMaterial && shellTags === undefined) {
1647
- warnUntaggedShellBakeOnce(capture.key);
1682
+ // Missing tags are valid: the shell follows TTL/SWR-only invalidation. Expose
1683
+ // that choice only to operators who enabled structured capture diagnostics.
1684
+ if (
1685
+ capture.debugSink &&
1686
+ stats &&
1687
+ bakedLoaderMaterial &&
1688
+ shellTags === undefined
1689
+ ) {
1690
+ stats.untaggedBake = true;
1648
1691
  }
1649
1692
 
1650
1693
  const store = capture.store ?? reqCtx._cacheStore;
@@ -1664,6 +1707,12 @@ async function captureAndStoreShell(
1664
1707
  // ShellCacheEntry.initialTheme.
1665
1708
  initialTheme: reqCtx.theme,
1666
1709
  snapshot,
1710
+ // The canonical doc segment record's key, published by the doc
1711
+ // scope's cacheRoute during this capture's match (undefined when no
1712
+ // doc record was recorded — the entry then never claims navigation
1713
+ // replayability). Only meaningful alongside a snapshot.
1714
+ docKey: snapshot ? reqCtx._shellImplicitCache?.docKey : undefined,
1715
+ navigationOnly: capture.navigationOnly,
1667
1716
  // Handler-layer liveness folded at the barrier: nested thenables in
1668
1717
  // handler-scoped pushes, handler pushes still pending (liveness
1669
1718
  // unknowable), or a handler-invoked loader execution — any of them
@@ -19,7 +19,9 @@
19
19
  import React from "react";
20
20
  import { isPprEntry, type EntryData } from "../server/context.js";
21
21
  import { sortedSearchString } from "../cache/cache-key-utils.js";
22
+ import type { SearchParamsFilter } from "../cache/search-params-filter.js";
22
23
  import type { ShellCacheEntry, SegmentCacheStore } from "../cache/types.js";
24
+ import { SHELL_CAPTURE_MAX_WAIT_MS } from "./shell-capture-constants.js";
23
25
 
24
26
  /** Debug/status header the browser (and e2e assertions) can read: HIT | MISS. */
25
27
  export const SHELL_STATUS_HEADER = "x-rango-shell";
@@ -62,9 +64,10 @@ export interface ResolvedPprConfig {
62
64
  }
63
65
 
64
66
  /**
65
- * Validate the raw `ppr.captureTimeout` option: a finite number >= 1ms passes
66
- * through; anything else (including 0/negative/NaN/Infinity/non-number)
67
- * resolves to undefined, which means "use the capture default" downstream.
67
+ * Validate the raw `ppr.captureTimeout` option: a finite number >= 1ms is
68
+ * clamped to the default ceiling; anything else (including
69
+ * 0/negative/NaN/Infinity/non-number) resolves to undefined, which means "use
70
+ * the capture default" downstream.
68
71
  * Mirrors the prefetch-limit option policy: invalid values silently fall back
69
72
  * to the default rather than throwing at request time. Also the boundary
70
73
  * re-normalizer for the dev /__rsc_shell endpoint (vite/router-discovery.ts),
@@ -72,7 +75,7 @@ export interface ResolvedPprConfig {
72
75
  */
73
76
  export function normalizeCaptureTimeout(value: unknown): number | undefined {
74
77
  return typeof value === "number" && Number.isFinite(value) && value >= 1
75
- ? value
78
+ ? Math.min(value, SHELL_CAPTURE_MAX_WAIT_MS)
76
79
  : undefined;
77
80
  }
78
81
 
@@ -115,9 +118,14 @@ export function resolvePprConfig(
115
118
  * The key includes the request HOST: in a multi-tenant host-router deployment
116
119
  * (one worker, one shared KV/runtime-cache store) a host-less key would serve
117
120
  * tenant A's captured shell to tenant B's users.
121
+ *
122
+ * `filter` is the request's compiled `cache.searchParams` config
123
+ * (ctx._searchParamsFilter): excluded params collapse onto one shell slot.
124
+ * Callers on the serve/capture path MUST pass it -- key drift between capture
125
+ * and lookup makes every shell request a permanent miss.
118
126
  */
119
- export function buildShellKey(url: URL): string {
120
- const sorted = sortedSearchString(url.searchParams);
127
+ export function buildShellKey(url: URL, filter?: SearchParamsFilter): string {
128
+ const sorted = sortedSearchString(url.searchParams, filter);
121
129
  const searchSuffix = sorted ? `?${sorted}` : "";
122
130
  return `${url.host}${url.pathname}${searchSuffix}:shell`;
123
131
  }
package/src/rsc/types.ts CHANGED
@@ -49,6 +49,8 @@ export interface RscPayload {
49
49
  prefetchCacheSize?: number;
50
50
  /** Max concurrent speculative prefetch requests on the client */
51
51
  prefetchConcurrency?: number;
52
+ /** Router-wide default prefetch strategy for Links without a `prefetch` prop */
53
+ defaultPrefetch?: import("../router/prefetch-default.js").PrefetchStrategy;
52
54
  /** Server-resolved rango state cookie name; the client reads it verbatim. */
53
55
  stateCookieName?: string;
54
56
  /** Theme configuration for FOUC prevention */
@@ -208,6 +210,23 @@ export interface HandlerCacheConfig {
208
210
  store: import("../cache/types.js").SegmentCacheStore;
209
211
  /** Enable/disable caching (default: true) */
210
212
  enabled?: boolean;
213
+ /**
214
+ * Which query params key the cache (default: `"all"`). Affects cache keys
215
+ * ONLY -- handlers and loaders still see the full query string. Global by
216
+ * design: the per-route case is already reachable through `cache({ key })`.
217
+ *
218
+ * Excluding a param is a promise that rendered output does not depend on
219
+ * it; if it does, the first variant is cached and served to everyone.
220
+ *
221
+ * @example
222
+ * ```typescript
223
+ * cache: {
224
+ * store: cacheStore,
225
+ * searchParams: { exclude: TRACKING_SEARCH_PARAMS },
226
+ * }
227
+ * ```
228
+ */
229
+ searchParams?: import("../cache/search-params-filter.js").CacheSearchParams;
211
230
  }
212
231
 
213
232
  /**
@@ -211,9 +211,27 @@ export interface RequestContext<
211
211
  /** @internal PPR transition decisions evaluated before cache lookup/handlers. */
212
212
  _pprTransitionDecisions?: Map<string, boolean>;
213
213
 
214
+ /**
215
+ * @internal Post-match serve-source truth for the PPR replay reporter.
216
+ * Stamped from the match context as `intercept`, then overwritten as
217
+ * `prerender-store` if that lookup actually serves. The latter wins because
218
+ * it identifies the response source. matchPartialWithPprReplay reads this
219
+ * AFTER matching to reclassify its pre-match guess and suppress pointless
220
+ * heal captures.
221
+ */
222
+ _pprReplayPostMatchReason?: "prerender-store" | "intercept";
223
+
214
224
  /** @internal Cache store for segment caching (optional, used by CacheScope) */
215
225
  _cacheStore?: SegmentCacheStore;
216
226
 
227
+ /**
228
+ * @internal Compiled `cache.searchParams` filter for default cache-key
229
+ * generation (undefined = "all", the byte-stable unfiltered format). Set
230
+ * once per request by handler.ts; every URL-keyed tier (segment, document,
231
+ * response, shell, "use cache") reads it so the tiers cannot drift.
232
+ */
233
+ _searchParamsFilter?: import("../cache/search-params-filter.js").SearchParamsFilter;
234
+
217
235
  /**
218
236
  * @internal PPR shell-capture ACTIVE marker. True ONLY inside the background
219
237
  * capture task's derived request context (built by shell-capture.ts). This is
@@ -265,9 +283,13 @@ export interface RequestContext<
265
283
  * (b) a HIT tail's seeded context, and (c) an eligible normal-route partial
266
284
  * replay, where `store` is a request-local segment overlay. Handler-live holes
267
285
  * and conditional transitions decline replay.
268
- * Routes with their own cache() config (including cache(false)) are never
269
- * overridden: the marker only applies when the route tree derived NO cache
270
- * scope.
286
+ * Routes with their own cache() config are never overridden — their scope's
287
+ * store/key/ttl/swr/condition semantics stay authoritative. On the
288
+ * navigation-replay serve path (`onExplicitHit` set) the marker COMPOSES with
289
+ * such a scope instead of being ignored: the seeded doc record supplies the match
290
+ * only when the explicit tier misses (withCacheLookup). cache(false) and a
291
+ * false condition() stay absolute opt-outs — replay bypasses before any
292
+ * shell read (`cache-disabled`).
271
293
  */
272
294
  _shellImplicitCache?: {
273
295
  ttl?: number;
@@ -281,6 +303,34 @@ export interface RequestContext<
281
303
  keyPrefix?: "doc";
282
304
  /** @internal Called only after the implicit cache hit decodes successfully. */
283
305
  onHit?: () => void;
306
+ /**
307
+ * @internal The resolved key of the canonical document segment record.
308
+ * Written during a CAPTURE render by CacheScope.cacheRoute when a
309
+ * doc-namespaced scope records the matched segments; captureAndStoreShell
310
+ * stamps it onto the ShellCacheEntry (`docKey`) so replay eligibility can
311
+ * require the exact consumable record instead of "any segment record".
312
+ */
313
+ docKey?: string;
314
+ /**
315
+ * @internal Set ONLY by matchPartialWithPprReplay on the navigation-replay
316
+ * serve path. Its presence arms the explicit-scope composition in
317
+ * withCacheLookup: a route-derived cache() scope stays authoritative, and
318
+ * only when its lookup MISSes does the seeded doc record supply the match.
319
+ * A capture render must never set this (its match must re-run handlers so
320
+ * SWR recapture stays fresh), which is why the fallback keys off this
321
+ * field and not off the marker itself. Fired when the route-derived
322
+ * scope's own lookup supplied the match — the header then reports
323
+ * `BYPASS; reason=explicit-cache-hit`, never a false replay HIT.
324
+ */
325
+ onExplicitHit?: () => void;
326
+ /**
327
+ * @internal Companion to onExplicitHit, same lifecycle: fired when the
328
+ * route-derived scope's lookup REFUSED the read (`bypass` outcome — a
329
+ * false condition() or no store). The gate only pre-decides the static
330
+ * cache(false) case; a predicate refusal is known only at lookup time and
331
+ * reports `BYPASS; reason=cache-disabled` post-match.
332
+ */
333
+ onExplicitBypass?: () => void;
284
334
  };
285
335
 
286
336
  /**
@@ -656,7 +706,9 @@ export type PublicRequestContext<
656
706
  | "_handleStore"
657
707
  | "_transitionWhen"
658
708
  | "_pprTransitionDecisions"
709
+ | "_pprReplayPostMatchReason"
659
710
  | "_cacheStore"
711
+ | "_searchParamsFilter"
660
712
  | "_shellCaptureRun"
661
713
  | "_shellImplicitCache"
662
714
  | "_shellLoaderSeed"
@@ -842,6 +894,11 @@ export interface CreateRequestContextOptions<TEnv> {
842
894
  initialResponse?: Response;
843
895
  /** Optional cache store for segment caching (used by CacheScope) */
844
896
  cacheStore?: SegmentCacheStore;
897
+ /**
898
+ * Compiled `cache.searchParams` filter from the resolved handler cache
899
+ * config (handler.ts). Stored as _searchParamsFilter.
900
+ */
901
+ searchParamsFilter?: import("../cache/search-params-filter.js").SearchParamsFilter;
845
902
  /**
846
903
  * Handler-owned registry of explicit per-scope stores for cross-store tag
847
904
  * invalidation. Created once per handler, reused across requests.
@@ -882,6 +939,7 @@ export function createRequestContext<TEnv>(
882
939
  variables,
883
940
  initialResponse,
884
941
  cacheStore,
942
+ searchParamsFilter,
885
943
  explicitTaggedStores,
886
944
  cacheProfiles,
887
945
  executionContext,
@@ -1176,6 +1234,7 @@ export function createRequestContext<TEnv>(
1176
1234
  _handleStore: handleStore,
1177
1235
  _transitionWhen: [],
1178
1236
  _cacheStore: cacheStore,
1237
+ _searchParamsFilter: searchParamsFilter,
1179
1238
  _explicitTaggedStores: explicitTaggedStores,
1180
1239
  _requestTags: new Set<string>(),
1181
1240
  _cacheProfiles: cacheProfiles,
@@ -116,6 +116,11 @@ import {
116
116
  stripInternalParams,
117
117
  } from "../router/handler-context.js";
118
118
  import { NOCACHE_SYMBOL } from "../cache/taint.js";
119
+ import {
120
+ compileSearchParamsFilter,
121
+ type CacheSearchParams,
122
+ type SearchParamsFilter,
123
+ } from "../cache/search-params-filter.js";
119
124
  import type { SegmentCacheStore } from "../cache/types.js";
120
125
  import type { CacheProfile } from "../cache/profile-registry.js";
121
126
  // cache-scope is loaded LAZILY inside the response-route cache path (below):
@@ -193,11 +198,19 @@ interface DispatchableRouter<TEnv> {
193
198
  } | null>;
194
199
  basename?: string;
195
200
  cache?:
196
- | { enabled?: boolean; store?: SegmentCacheStore }
201
+ | {
202
+ enabled?: boolean;
203
+ store?: SegmentCacheStore;
204
+ searchParams?: CacheSearchParams;
205
+ }
197
206
  | ((
198
207
  env: TEnv,
199
208
  executionContext: unknown,
200
- ) => { enabled?: boolean; store?: SegmentCacheStore });
209
+ ) => {
210
+ enabled?: boolean;
211
+ store?: SegmentCacheStore;
212
+ searchParams?: CacheSearchParams;
213
+ });
201
214
  cacheProfiles?: Record<string, CacheProfile>;
202
215
  }
203
216
 
@@ -375,13 +388,17 @@ export async function dispatch<TEnv = any>(
375
388
  // "use cache" inside a response-route handler reaches the request-scope
376
389
  // (NOCACHE) detection below instead of bypassing on a missing store.
377
390
  let cacheStore: SegmentCacheStore | undefined;
391
+ let searchParamsFilter: SearchParamsFilter | undefined;
378
392
  const cacheOption = router.cache;
379
393
  if (cacheOption && !url.searchParams.has("__no_cache")) {
380
394
  const cacheConfig =
381
395
  typeof cacheOption === "function"
382
396
  ? cacheOption(env, undefined)
383
397
  : cacheOption;
384
- if (cacheConfig.enabled !== false) cacheStore = cacheConfig.store;
398
+ if (cacheConfig.enabled !== false) {
399
+ cacheStore = cacheConfig.store;
400
+ searchParamsFilter = compileSearchParamsFilter(cacheConfig.searchParams);
401
+ }
385
402
  }
386
403
 
387
404
  const requestContext = createRequestContext<TEnv>({
@@ -390,6 +407,7 @@ export async function dispatch<TEnv = any>(
390
407
  url,
391
408
  variables,
392
409
  cacheStore,
410
+ searchParamsFilter,
393
411
  cacheProfiles: router.cacheProfiles,
394
412
  });
395
413
  // Wire background error reporting so cache degradation (reportCacheError ->
@@ -5,12 +5,15 @@ import {
5
5
  type FixtureOptions,
6
6
  } from "./fixture.js";
7
7
  import {
8
+ blockPrefetch,
9
+ unblockPrefetch,
8
10
  createPageHelpers,
9
11
  createStopwatch,
10
12
  getHistoryState,
11
13
  getNumericContent,
12
14
  goBack,
13
15
  goForward,
16
+ isPrefetchRequest,
14
17
  isVisibleInViewport,
15
18
  measureTime,
16
19
  type PageHelpers,
@@ -62,6 +65,9 @@ export {
62
65
  getHistoryState,
63
66
  waitForElement,
64
67
  isVisibleInViewport,
68
+ isPrefetchRequest,
69
+ blockPrefetch,
70
+ unblockPrefetch,
65
71
  parseNumber,
66
72
  getNumericContent,
67
73
  createStopwatch,
@@ -159,6 +159,53 @@ export async function measureTime<T>(
159
159
  return { elapsed, result };
160
160
  }
161
161
 
162
+ /**
163
+ * True when the request is a speculative prefetch (Link viewport/hover/render
164
+ * strategies or `useRouter().prefetch()`). Every prefetch fetch carries the
165
+ * `X-Rango-Prefetch` header. Links prefetch by default in production unless
166
+ * the router opts out, so tests that track `_rsc_partial` requests to pin
167
+ * NAVIGATION behavior must skip these — a request-count or first-request
168
+ * assertion otherwise races background prefetch traffic.
169
+ */
170
+ export function isPrefetchRequest(req: {
171
+ headers: () => Record<string, string>;
172
+ }): boolean {
173
+ return !!req.headers()["x-rango-prefetch"];
174
+ }
175
+
176
+ // Module-level matcher + handler so blockPrefetch/unblockPrefetch share
177
+ // stable references — Playwright's unroute matches by identity.
178
+ const rscPartialUrl = (url: URL): boolean =>
179
+ url.searchParams.has("_rsc_partial");
180
+ async function abortPrefetchRoute(
181
+ route: import("@playwright/test").Route,
182
+ ): Promise<void> {
183
+ if (isPrefetchRequest(route.request())) {
184
+ await route.abort("aborted");
185
+ } else {
186
+ await route.fallback();
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Abort every speculative prefetch request on this page. Install BEFORE
192
+ * `page.goto` so no prefetch can complete first. For tests whose semantics
193
+ * need a virgin prefetch cache: a click on a Link whose target was already
194
+ * prefetched ADOPTS the warmed entry and issues no navigation fetch at all —
195
+ * a `page.route` override, a request waiter, or a Set-Cookie assertion aimed
196
+ * at the navigation request then sees nothing (or sees the prefetch's side
197
+ * effects instead). Aborted prefetches are benign by design (evicted, never
198
+ * adopted, no page error), so the click's real fetch is guaranteed live.
199
+ */
200
+ export async function blockPrefetch(page: Page): Promise<void> {
201
+ await page.route(rscPartialUrl, abortPrefetchRoute);
202
+ }
203
+
204
+ /** Remove a `blockPrefetch` guard, restoring normal prefetch traffic. */
205
+ export async function unblockPrefetch(page: Page): Promise<void> {
206
+ await page.unroute(rscPartialUrl, abortPrefetchRoute);
207
+ }
208
+
162
209
  // ============================================================================
163
210
  // Factory-bound helpers (need the injected `expect`)
164
211
  // ============================================================================
@@ -7,6 +7,7 @@
7
7
  import type { Expect, Page, TestType } from "@playwright/test";
8
8
  import type { Fixture, FixtureOptions } from "./fixture.js";
9
9
  import { DEFAULT_STATE_COOKIE_PREFIX } from "../../browser/cookie-name.js";
10
+ import { blockPrefetch, unblockPrefetch } from "./page-helpers.js";
10
11
 
11
12
  export interface ParityDescribeOptions extends Partial<
12
13
  Omit<FixtureOptions, "mode">
@@ -318,6 +319,15 @@ export function createParity({
318
319
  // navigation away from it.
319
320
  const originUrl = page.url();
320
321
 
322
+ // Exclude speculative prefetch traffic from the parity window. Links
323
+ // prefetch by default in production unless the router opts out, and a
324
+ // prefetched route's middleware/loader side effects
325
+ // (Set-Cookie, session state) land in the JS jar only — a no-JS context
326
+ // cannot prefetch, so that traffic would diverge the jars on requests the
327
+ // intent never caused. Aborted prefetches are benign by design (evicted,
328
+ // never adopted), so the intent's real navigation always fetches live.
329
+ await blockPrefetch(page);
330
+
321
331
  // Settle the intent's observable effect before snapshotting. A `navigate`
322
332
  // intent already awaited its navigation in applyIntent (page.goto), so only
323
333
  // `submit` needs the DOM-driven settle, and only when no `waitFor` override
@@ -380,6 +390,9 @@ export function createParity({
380
390
  );
381
391
  } finally {
382
392
  await noJsContext.close();
393
+ // Restore the caller's page: the prefetch guard is scoped to the parity
394
+ // window, not the rest of the test.
395
+ await unblockPrefetch(page);
383
396
  }
384
397
  }
385
398