@rangojs/router 0.18.0 → 0.19.0

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 (244) hide show
  1. package/dist/types/browser/event-controller.d.ts +3 -3
  2. package/dist/types/browser/history-state.d.ts +2 -0
  3. package/dist/types/browser/navigation-transaction.d.ts +20 -2
  4. package/dist/types/browser/partial-update.d.ts +16 -1
  5. package/dist/types/browser/prefetch/cache.d.ts +6 -6
  6. package/dist/types/browser/react/Link.d.ts +19 -9
  7. package/dist/types/browser/react/context.d.ts +2 -2
  8. package/dist/types/browser/react/location-state-shared.d.ts +95 -56
  9. package/dist/types/browser/react/location-state.d.ts +1 -1
  10. package/dist/types/browser/transition-when.d.ts +80 -0
  11. package/dist/types/browser/types.d.ts +104 -9
  12. package/dist/types/build/generate-manifest.d.ts +8 -0
  13. package/dist/types/cache/background-task.d.ts +24 -2
  14. package/dist/types/cache/cache-exec-scope.d.ts +31 -0
  15. package/dist/types/cache/cache-key-utils.d.ts +44 -13
  16. package/dist/types/cache/cache-policy.d.ts +1 -1
  17. package/dist/types/cache/cache-runtime.d.ts +7 -0
  18. package/dist/types/cache/cache-scope.d.ts +117 -35
  19. package/dist/types/cache/cache-tag.d.ts +24 -4
  20. package/dist/types/cache/cf/cf-cache-store.d.ts +55 -44
  21. package/dist/types/cache/cf/cf-shell-frame.d.ts +1 -1
  22. package/dist/types/cache/cf/cf-tag-marker-memo.d.ts +0 -15
  23. package/dist/types/cache/document-cache.d.ts +10 -0
  24. package/dist/types/cache/handle-snapshot.d.ts +40 -8
  25. package/dist/types/cache/invalidation-order.d.ts +23 -0
  26. package/dist/types/cache/request-tag-mask.d.ts +54 -0
  27. package/dist/types/cache/shell-snapshot.d.ts +88 -141
  28. package/dist/types/cache/tag-invalidation.d.ts +38 -14
  29. package/dist/types/cache/types.d.ts +68 -61
  30. package/dist/types/cache/vercel/vercel-cache-store.d.ts +23 -16
  31. package/dist/types/client-urls/navigation.d.ts +28 -2
  32. package/dist/types/client-urls/server-projection.d.ts +5 -2
  33. package/dist/types/client-urls/types.d.ts +5 -5
  34. package/dist/types/client.d.ts +1 -1
  35. package/dist/types/index.d.ts +1 -1
  36. package/dist/types/index.rsc.d.ts +1 -1
  37. package/dist/types/route-definition/helpers-types.d.ts +11 -11
  38. package/dist/types/route-name.d.ts +7 -0
  39. package/dist/types/router/error-handling.d.ts +1 -1
  40. package/dist/types/router/intercept-resolution.d.ts +2 -0
  41. package/dist/types/router/match-context.d.ts +5 -0
  42. package/dist/types/router/match-middleware/background-revalidation.d.ts +0 -4
  43. package/dist/types/router/router-options.d.ts +4 -1
  44. package/dist/types/router/segment-resolution/loader-cache.d.ts +18 -1
  45. package/dist/types/router/segment-resolution/loader-mask.d.ts +3 -4
  46. package/dist/types/router/segment-resolution/loader-snapshot.d.ts +14 -40
  47. package/dist/types/router/segment-resolution/mask-nested.d.ts +11 -3
  48. package/dist/types/router/segment-resolution/view-transition-default.d.ts +7 -5
  49. package/dist/types/router/transition-when.d.ts +24 -10
  50. package/dist/types/rsc/attach-transition-when.d.ts +18 -0
  51. package/dist/types/rsc/full-payload.d.ts +14 -7
  52. package/dist/types/rsc/response-cache-serve.d.ts +15 -12
  53. package/dist/types/rsc/shell-build-manifest.d.ts +4 -3
  54. package/dist/types/rsc/shell-capture-constants.d.ts +77 -20
  55. package/dist/types/rsc/shell-capture.d.ts +78 -81
  56. package/dist/types/rsc/shell-serve.d.ts +19 -48
  57. package/dist/types/rsc/types.d.ts +2 -0
  58. package/dist/types/segment-system.d.ts +7 -0
  59. package/dist/types/server/context.d.ts +89 -61
  60. package/dist/types/server/cookie-store.d.ts +30 -18
  61. package/dist/types/server/handle-store.d.ts +52 -1
  62. package/dist/types/server/request-context.d.ts +66 -45
  63. package/dist/types/server/request-headers.d.ts +44 -0
  64. package/dist/types/server.d.ts +1 -0
  65. package/dist/types/testing/e2e/index.d.ts +1 -1
  66. package/dist/types/testing/index.d.ts +3 -2
  67. package/dist/types/testing/internal/action-id.d.ts +7 -0
  68. package/dist/types/testing/location-state-key.d.ts +24 -0
  69. package/dist/types/testing/render-route.d.ts +17 -1
  70. package/dist/types/testing/run-transition-when.d.ts +44 -69
  71. package/dist/types/testing/serve-shell-request.d.ts +7 -6
  72. package/dist/types/testing/shell-status.d.ts +34 -22
  73. package/dist/types/transition-when-ref.d.ts +79 -0
  74. package/dist/types/types/cache-types.d.ts +15 -3
  75. package/dist/types/types/index.d.ts +1 -1
  76. package/dist/types/types/segments.d.ts +86 -71
  77. package/dist/types/urls/path-helper-types.d.ts +3 -4
  78. package/dist/types/urls/pattern-types.d.ts +3 -4
  79. package/dist/types/vite/plugins/transition-when-hoist.d.ts +45 -0
  80. package/dist/vite/index.js +960 -97
  81. package/package.json +1 -1
  82. package/skills/cache-guide/SKILL.md +76 -49
  83. package/skills/caching/SKILL.md +167 -69
  84. package/skills/client-urls/SKILL.md +1 -1
  85. package/skills/comparison/references/framework-comparison.md +8 -5
  86. package/skills/document-cache/SKILL.md +24 -0
  87. package/skills/hooks/SKILL.md +3 -1
  88. package/skills/hooks/navigation.md +23 -2
  89. package/skills/hooks/state.md +98 -6
  90. package/skills/intercept/SKILL.md +29 -12
  91. package/skills/loader/SKILL.md +52 -21
  92. package/skills/middleware/SKILL.md +18 -0
  93. package/skills/migrate-nextjs/SKILL.md +3 -3
  94. package/skills/observability/SKILL.md +6 -5
  95. package/skills/parallel/SKILL.md +1 -1
  96. package/skills/ppr/SKILL.md +129 -77
  97. package/skills/prerender/SKILL.md +3 -3
  98. package/skills/rango/SKILL.md +25 -6
  99. package/skills/route/SKILL.md +2 -0
  100. package/skills/testing/SKILL.md +27 -25
  101. package/skills/testing/cache-prerender.md +9 -9
  102. package/skills/testing/client-components.md +45 -3
  103. package/skills/testing/loader.md +3 -2
  104. package/skills/testing/middleware.md +1 -0
  105. package/skills/testing/predicates.md +49 -49
  106. package/skills/testing/render-handler.md +1 -0
  107. package/skills/testing/serve-shell-request.md +14 -0
  108. package/skills/testing/server-actions.md +9 -3
  109. package/skills/theme/SKILL.md +8 -4
  110. package/skills/typesafety/env-and-bindings.md +8 -0
  111. package/skills/use-cache/SKILL.md +64 -19
  112. package/skills/view-transitions/SKILL.md +150 -29
  113. package/src/__augment-tests__/augmented.check.ts +23 -0
  114. package/src/browser/event-controller.ts +4 -4
  115. package/src/browser/history-state.ts +52 -1
  116. package/src/browser/link-interceptor.ts +4 -0
  117. package/src/browser/navigation-bridge.ts +77 -18
  118. package/src/browser/navigation-client.ts +4 -3
  119. package/src/browser/navigation-store.ts +43 -1
  120. package/src/browser/navigation-transaction.ts +31 -11
  121. package/src/browser/partial-update.ts +146 -35
  122. package/src/browser/prefetch/cache.ts +6 -6
  123. package/src/browser/prefetch/fetch.ts +2 -2
  124. package/src/browser/react/Link.tsx +38 -33
  125. package/src/browser/react/NavigationProvider.tsx +2 -2
  126. package/src/browser/react/context.ts +2 -2
  127. package/src/browser/react/location-state-shared.ts +241 -49
  128. package/src/browser/react/location-state.ts +5 -2
  129. package/src/browser/rsc-router.tsx +4 -0
  130. package/src/browser/server-action-bridge.ts +84 -15
  131. package/src/browser/transition-when.ts +205 -0
  132. package/src/browser/types.ts +124 -10
  133. package/src/build/generate-manifest.ts +77 -1
  134. package/src/cache/background-task.ts +55 -2
  135. package/src/cache/cache-exec-scope.ts +48 -1
  136. package/src/cache/cache-key-utils.ts +56 -16
  137. package/src/cache/cache-policy.ts +9 -4
  138. package/src/cache/cache-runtime.ts +197 -144
  139. package/src/cache/cache-scope.ts +304 -112
  140. package/src/cache/cache-tag.ts +105 -13
  141. package/src/cache/cf/cf-cache-store.ts +152 -76
  142. package/src/cache/cf/cf-shell-frame.ts +2 -2
  143. package/src/cache/cf/cf-tag-marker-memo.ts +11 -100
  144. package/src/cache/document-cache.ts +53 -7
  145. package/src/cache/handle-snapshot.ts +52 -9
  146. package/src/cache/invalidation-order.ts +84 -0
  147. package/src/cache/request-tag-mask.ts +147 -0
  148. package/src/cache/shell-snapshot.ts +130 -348
  149. package/src/cache/tag-invalidation.ts +57 -51
  150. package/src/cache/types.ts +71 -67
  151. package/src/cache/vercel/vercel-cache-store.ts +61 -58
  152. package/src/client-urls/client-root.tsx +8 -4
  153. package/src/client-urls/client-urls.ts +8 -6
  154. package/src/client-urls/navigation.ts +55 -4
  155. package/src/client-urls/server-projection.ts +31 -10
  156. package/src/client-urls/types.ts +12 -5
  157. package/src/client.tsx +2 -0
  158. package/src/host/cookie-handler.ts +2 -1
  159. package/src/index.rsc.ts +3 -0
  160. package/src/index.ts +3 -0
  161. package/src/loader-redirect.tsx +7 -3
  162. package/src/prerender/build-shell-capture.ts +155 -146
  163. package/src/route-definition/dsl-helpers.ts +2 -0
  164. package/src/route-definition/helpers-types.ts +11 -11
  165. package/src/route-name.ts +12 -0
  166. package/src/router/content-negotiation.ts +4 -1
  167. package/src/router/error-handling.ts +5 -2
  168. package/src/router/handler-context.ts +10 -7
  169. package/src/router/intercept-resolution.ts +11 -1
  170. package/src/router/loader-resolution.ts +28 -3
  171. package/src/router/logging.ts +5 -3
  172. package/src/router/match-api.ts +62 -34
  173. package/src/router/match-context.ts +5 -0
  174. package/src/router/match-handlers.ts +9 -29
  175. package/src/router/match-middleware/background-revalidation.ts +3 -5
  176. package/src/router/match-middleware/cache-lookup.ts +35 -19
  177. package/src/router/match-middleware/cache-store.ts +15 -9
  178. package/src/router/match-result.ts +1 -0
  179. package/src/router/middleware.ts +2 -5
  180. package/src/router/navigation-snapshot.ts +6 -5
  181. package/src/router/prerender-match.ts +4 -0
  182. package/src/router/request-classification.ts +7 -4
  183. package/src/router/router-options.ts +4 -1
  184. package/src/router/segment-resolution/fresh.ts +0 -4
  185. package/src/router/segment-resolution/loader-cache.ts +150 -25
  186. package/src/router/segment-resolution/loader-mask.ts +3 -4
  187. package/src/router/segment-resolution/loader-snapshot.ts +15 -78
  188. package/src/router/segment-resolution/mask-nested.ts +47 -22
  189. package/src/router/segment-resolution/revalidation.ts +0 -3
  190. package/src/router/segment-resolution/view-transition-default.ts +6 -21
  191. package/src/router/telemetry.ts +6 -3
  192. package/src/router/transition-when.ts +34 -52
  193. package/src/router.ts +2 -1
  194. package/src/rsc/attach-transition-when.ts +47 -0
  195. package/src/rsc/full-payload.ts +30 -10
  196. package/src/rsc/handler.ts +12 -10
  197. package/src/rsc/loader-fetch.ts +2 -1
  198. package/src/rsc/manifest-init.ts +4 -0
  199. package/src/rsc/origin-guard.ts +8 -5
  200. package/src/rsc/progressive-enhancement.ts +7 -30
  201. package/src/rsc/response-cache-serve.ts +68 -80
  202. package/src/rsc/response-route-handler.ts +2 -2
  203. package/src/rsc/rsc-rendering.ts +206 -252
  204. package/src/rsc/server-action.ts +8 -20
  205. package/src/rsc/shell-build-manifest.ts +22 -20
  206. package/src/rsc/shell-capture-constants.ts +136 -20
  207. package/src/rsc/shell-capture.ts +352 -589
  208. package/src/rsc/shell-serve.ts +73 -109
  209. package/src/rsc/ssr-setup.ts +3 -2
  210. package/src/rsc/types.ts +2 -0
  211. package/src/segment-system.tsx +40 -7
  212. package/src/server/context.ts +189 -124
  213. package/src/server/cookie-store.ts +153 -127
  214. package/src/server/handle-store.ts +245 -27
  215. package/src/server/request-context.ts +123 -84
  216. package/src/server/request-headers.ts +134 -0
  217. package/src/server.ts +4 -0
  218. package/src/testing/dispatch.ts +4 -7
  219. package/src/testing/e2e/index.ts +1 -0
  220. package/src/testing/index.ts +5 -0
  221. package/src/testing/internal/action-id.ts +25 -0
  222. package/src/testing/internal/context.ts +1 -1
  223. package/src/testing/location-state-key.ts +45 -0
  224. package/src/testing/render-handler.ts +1 -1
  225. package/src/testing/render-route.tsx +109 -16
  226. package/src/testing/run-client-revalidate.ts +3 -19
  227. package/src/testing/run-loader.ts +5 -1
  228. package/src/testing/run-transition-when.ts +109 -172
  229. package/src/testing/serve-shell-request.ts +10 -7
  230. package/src/testing/shell-status.ts +60 -56
  231. package/src/transition-when-ref.ts +220 -0
  232. package/src/types/cache-types.ts +15 -3
  233. package/src/types/index.ts +3 -0
  234. package/src/types/segments.ts +94 -91
  235. package/src/urls/path-helper-types.ts +3 -4
  236. package/src/urls/pattern-types.ts +3 -4
  237. package/src/vite/discovery/discover-routers.ts +3 -0
  238. package/src/vite/discovery/shell-prerender-phase.ts +0 -2
  239. package/src/vite/discovery/virtual-module-codegen.ts +16 -6
  240. package/src/vite/plugins/transition-when-hoist.ts +1064 -0
  241. package/src/vite/rango.ts +2 -0
  242. package/src/vite/router-discovery.ts +75 -5
  243. package/dist/types/rsc/transition-gate.d.ts +0 -23
  244. package/src/rsc/transition-gate.ts +0 -86
@@ -48,6 +48,7 @@ import { runBackground } from "./background-task.js";
48
48
  import { observePhase, PHASES } from "../router/instrument.js";
49
49
  import {
50
50
  normalizeTags,
51
+ outsideCacheTagScope,
51
52
  recordRequestTags,
52
53
  runWithCacheTagScope,
53
54
  } from "./cache-tag.js";
@@ -58,7 +59,12 @@ import {
58
59
  type CacheExecScope,
59
60
  } from "./cache-exec-scope.js";
60
61
  import { reportCacheError } from "./cache-error.js";
61
- import { currentCacheSeq, invalidatedSince } from "./tag-invalidation.js";
62
+ import {
63
+ executionStart,
64
+ invalidatedSince,
65
+ predatesInvalidation,
66
+ type ExecutionStart,
67
+ } from "./tag-invalidation.js";
62
68
  import type { CacheItemResult } from "./types.js";
63
69
  import type { InternalHandlerContext } from "../types.js";
64
70
 
@@ -267,6 +273,12 @@ interface CacheEnvelope {
267
273
  tags: string[];
268
274
  /** RSC-encoded handle blob captured during execution, if any. */
269
275
  handles?: string;
276
+ /**
277
+ * One of `tags` was invalidated after the leader started, as the store
278
+ * tells it (another isolate, #977): the leader does not write it, and a
279
+ * follower does not serve it.
280
+ */
281
+ predates?: boolean;
270
282
  }
271
283
 
272
284
  /**
@@ -295,8 +307,8 @@ interface InFlightExecution {
295
307
  promise: Promise<CacheEnvelope>;
296
308
  /** Date.now() at registration, for IN_FLIGHT_LEADER_MAX_WAIT_MS. */
297
309
  registeredAt: number;
298
- /** currentCacheSeq() at registration, for invalidatedSince (#973). */
299
- startSeq: number;
310
+ /** Where the leader started, for invalidatedSince (#973, #977). */
311
+ start: ExecutionStart;
300
312
  }
301
313
 
302
314
  const inFlightExecutions = new Map<string, InFlightExecution>();
@@ -313,6 +325,18 @@ const IN_FLIGHT_LEADER_MAX_WAIT_MS = 15_000;
313
325
  /** Distinguishes a leader timeout from a leader rejection in raceLeader. */
314
326
  const LEADER_TIMED_OUT = Symbol("leader-timed-out");
315
327
 
328
+ /**
329
+ * @internal Reset this module's per-isolate state: the in-flight leaders a
330
+ * follower would join for up to IN_FLIGHT_LEADER_MAX_WAIT_MS, and the
331
+ * once-per-function warnings. Tests only (testing/serve-shell-request.ts
332
+ * resetShellTestState), never while a request is in flight.
333
+ */
334
+ export function resetCacheRuntimeForTests(): void {
335
+ inFlightExecutions.clear();
336
+ warnedUncachedUnderTest.clear();
337
+ warnedUnkeyableArgs.clear();
338
+ }
339
+
316
340
  /**
317
341
  * Await a leader's envelope for at most `remainingMs`. Resolves with the
318
342
  * envelope, `undefined` on leader rejection (the leader already cleared its
@@ -431,6 +455,20 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
431
455
  );
432
456
  }
433
457
 
458
+ // An entry's tags: the profile/DSL tags plus what its execution
459
+ // recorded, normalized (drops empty profile tags, matching the
460
+ // invalidate path) and deduped.
461
+ const entryTags = (recorded: Set<string>): string[] => [
462
+ ...new Set(normalizeTags([...(profile.tags ?? []), ...recorded])),
463
+ ];
464
+ // The value's Flight encode runs back inside its execution's tag scope:
465
+ // it renders the server components in the value, and a "use cache" call
466
+ // or cacheTag() among them belongs to this entry (#980).
467
+ const inTagScope = <T>(
468
+ recorded: Set<string>,
469
+ encode: () => Promise<T>,
470
+ ): Promise<T> => runWithCacheTagScope(encode, recorded).result;
471
+
434
472
  // Separate request-scoped args (ctx, a Request, the request's env) from
435
473
  // key-generating args. For those that carry route context (ctx params,
436
474
  // pathname, searchParams; a Request's URL), extract serializable values
@@ -631,124 +669,121 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
631
669
  const liveStore = hasTaintedArgs ? requestCtx?._handleStore : undefined;
632
670
  const recordKey = ownerKeyed ? useCacheRecordKey() : undefined;
633
671
  // Background revalidation — must capture handles if tainted args present.
634
- runBackground(requestCtx, async () => {
635
- // The background body's handle pushes belong to the refreshed entry
636
- // only: the foreground already replayed the stale entry's. They
637
- // reach the REQUEST's store (a handler ctx.use(Handle) binds it at
638
- // setupLoaderAccess, so a derived context with its own store never
639
- // sees them), so the capture accepts only this body's chain and
640
- // diverts what it records away from the live store. The foreground
641
- // is still rendering here (runBackground starts on the next
642
- // microtask), and its concurrent pushes are neither recorded nor
643
- // diverted (issue #684, plan 010). A root scope: the task is
644
- // detached, so an outer "use cache" body that scheduled it must not
645
- // record the refresh's pushes.
646
- const bgScope: CacheExecScope = {};
647
- const bgCapture = liveStore
648
- ? startHandleCapture(liveStore, {
649
- accept: () => isInCacheExecChain(bgScope),
650
- divert: true,
651
- key: recordKey,
652
- })
653
- : undefined;
654
-
655
- // Tainted args are NOT stamped here, in contrast to the foreground
656
- // miss path below. The args include the live HandlerContext the
657
- // still-rendering foreground holds, and INSIDE_CACHE_EXEC is a
658
- // property stamped onto that SHARED object — so for the whole
659
- // revalidation window a concurrent foreground ctx.set() /
660
- // ctx.headers.*() would throw (issue #684, plan 010). requestCtx is
661
- // never stamped anywhere for the same reason. In-body misuse IS
662
- // still guarded here: runWithCacheExecScope below follows only this
663
- // body's async chain, so a conditional cookies()/headers() read
664
- // that fires only during revalidation throws instead of baking one
665
- // user's value into the shared entry — with zero visibility to the
666
- // concurrent foreground.
667
-
668
- try {
669
- // Re-establish the request-context ALS so a "use cache" body that
670
- // reads the ambient getRequestContext() (e.g.
671
- // getRequestContext().env.ApiKey) resolves during the background
672
- // revalidation instead of throwing "called outside of a request
673
- // context". runWithRequestContext sets the store for fn's
674
- // synchronous kickoff; its async continuations inherit it.
675
- //
676
- // The span opens inside the request ALS and wraps the WHOLE task —
677
- // fn kickoff through the store write — so its platform spans nest
678
- // under rango.background and a slow or failing setItem is part of
679
- // the traced revalidation, not an untraced tail.
680
- await runWithRequestContext(requestCtx, () =>
681
- observePhase(
682
- PHASES.background("use-cache-revalidation"),
683
- async () => {
684
- const refreshArgs = args.map(refreshView);
685
- // The refresh reads its data from here on (#973).
686
- const startSeq = currentCacheSeq();
687
- const scoped = runWithCacheTagScope(() =>
688
- runWithCacheExecScope(
689
- () => fn.apply(this, refreshArgs),
690
- bgScope,
691
- ),
692
- );
693
- const freshResult = await scoped.result;
694
- bgCapture?.stop();
695
- // Merge profile/DSL tags with runtime cacheTag() tags, read
696
- // after awaiting so post-await cacheTag() calls are included.
697
- // Normalize (drops empty profile tags, matching the
698
- // invalidate path) + dedupe.
699
- const freshTags = [
700
- ...new Set(
701
- normalizeTags([...(profile.tags ?? []), ...scoped.tags]),
702
- ),
703
- ];
704
- recordRequestTags(freshTags, requestCtx);
705
- const flightErrors: unknown[] = [];
706
- const onFlightError = (error: unknown): void => {
707
- flightErrors.push(error);
708
- };
709
- const serialized = await serializeResult(
710
- freshResult,
711
- onFlightError,
712
- );
713
- if (serialized !== null) {
714
- const encodedHandles = bgCapture
715
- ? await encodeHandles(
716
- bgCapture.capture.data,
717
- onFlightError,
718
- )
719
- : undefined;
720
- // An error row would replace the stale entry; the catch
721
- // below reports it and the stale entry keeps serving.
722
- if (flightErrors.length > 0) throw flightErrors[0];
723
- // The request invalidated one of the refreshed value's
724
- // tags after the refresh started: the value may predate
725
- // it, and written now it would outlive it.
726
- if (invalidatedSince(requestCtx, freshTags, startSeq)) {
727
- return;
672
+ // Scheduled outside the caller's tag scope: an enclosing "use cache"
673
+ // entry bakes the stale value, not the refreshed one (#980).
674
+ outsideCacheTagScope(() =>
675
+ runBackground(requestCtx, async () => {
676
+ // The background body's handle pushes belong to the refreshed entry
677
+ // only: the foreground already replayed the stale entry's. They
678
+ // reach the REQUEST's store (a handler ctx.use(Handle) binds it at
679
+ // setupLoaderAccess, so a derived context with its own store never
680
+ // sees them), so the capture accepts only this body's chain and
681
+ // diverts what it records away from the live store. The foreground
682
+ // is still rendering here (runBackground starts on the next
683
+ // microtask), and its concurrent pushes are neither recorded nor
684
+ // diverted (issue #684, plan 010). A root scope: the task is
685
+ // detached, so an outer "use cache" body that scheduled it must not
686
+ // record the refresh's pushes.
687
+ const bgScope: CacheExecScope = {};
688
+ const bgCapture = liveStore
689
+ ? startHandleCapture(liveStore, {
690
+ accept: () => isInCacheExecChain(bgScope),
691
+ divert: true,
692
+ key: recordKey,
693
+ })
694
+ : undefined;
695
+
696
+ // Tainted args are NOT stamped here, in contrast to the foreground
697
+ // miss path below. The args include the live HandlerContext the
698
+ // still-rendering foreground holds, and INSIDE_CACHE_EXEC is a
699
+ // property stamped onto that SHARED object — so for the whole
700
+ // revalidation window a concurrent foreground ctx.set() /
701
+ // ctx.headers.*() would throw (issue #684, plan 010). requestCtx is
702
+ // never stamped anywhere for the same reason. In-body misuse IS
703
+ // still guarded here: runWithCacheExecScope below follows only this
704
+ // body's async chain, so a conditional cookies()/headers() read
705
+ // that fires only during revalidation throws instead of baking one
706
+ // user's value into the shared entry — with zero visibility to the
707
+ // concurrent foreground.
708
+
709
+ try {
710
+ // Re-establish the request-context ALS so a "use cache" body that
711
+ // reads the ambient getRequestContext() (e.g.
712
+ // getRequestContext().env.ApiKey) resolves during the background
713
+ // revalidation instead of throwing "called outside of a request
714
+ // context". runWithRequestContext sets the store for fn's
715
+ // synchronous kickoff; its async continuations inherit it.
716
+ //
717
+ // The span opens inside the request ALS and wraps the WHOLE task —
718
+ // fn kickoff through the store write — so its platform spans nest
719
+ // under rango.background and a slow or failing setItem is part of
720
+ // the traced revalidation, not an untraced tail.
721
+ await runWithRequestContext(requestCtx, () =>
722
+ observePhase(
723
+ PHASES.background("use-cache-revalidation"),
724
+ async () => {
725
+ const refreshArgs = args.map(refreshView);
726
+ // The refresh reads its data from here on (#973, #977).
727
+ const start = executionStart();
728
+ const scoped = runWithCacheTagScope(() =>
729
+ runWithCacheExecScope(
730
+ () => fn.apply(this, refreshArgs),
731
+ bgScope,
732
+ ),
733
+ );
734
+ const freshResult = await scoped.result;
735
+ bgCapture?.stop();
736
+ recordRequestTags(entryTags(scoped.tags), requestCtx);
737
+ const flightErrors: unknown[] = [];
738
+ const onFlightError = (error: unknown): void => {
739
+ flightErrors.push(error);
740
+ };
741
+ const serialized = await inTagScope(scoped.tags, () =>
742
+ serializeResult(freshResult, onFlightError),
743
+ );
744
+ if (serialized !== null) {
745
+ const encodedHandles = bgCapture
746
+ ? await inTagScope(scoped.tags, () =>
747
+ encodeHandles(
748
+ bgCapture.capture.data,
749
+ onFlightError,
750
+ ),
751
+ )
752
+ : undefined;
753
+ // An error row would replace the stale entry; the catch
754
+ // below reports it and the stale entry keeps serving.
755
+ if (flightErrors.length > 0) throw flightErrors[0];
756
+ const freshTags = entryTags(scoped.tags);
757
+ // One of the refreshed value's tags was invalidated after
758
+ // the refresh started: written now, a value that may
759
+ // predate it would outlive it.
760
+ if (await predatesInvalidation(store, freshTags, start)) {
761
+ return;
762
+ }
763
+ await store.setItem!(cacheKey, serialized, {
764
+ handles: encodedHandles,
765
+ ttl: profile.ttl,
766
+ swr: profile.swr,
767
+ tags: freshTags.length > 0 ? freshTags : undefined,
768
+ });
728
769
  }
729
- await store.setItem!(cacheKey, serialized, {
730
- handles: encodedHandles,
731
- ttl: profile.ttl,
732
- swr: profile.swr,
733
- tags: freshTags.length > 0 ? freshTags : undefined,
734
- });
735
- }
736
- },
737
- ),
738
- );
739
- } catch (bgError) {
740
- bgCapture?.stop();
741
- // Pass requestCtx explicitly: this runs in a detached background
742
- // task where the ALS context is gone, so onError can only fire if
743
- // we hand it the context captured up front.
744
- reportCacheError(
745
- bgError,
746
- "stale-revalidation",
747
- "[use cache] background revalidation failed",
748
- requestCtx,
749
- );
750
- }
751
- });
770
+ },
771
+ ),
772
+ );
773
+ } catch (bgError) {
774
+ bgCapture?.stop();
775
+ // Pass requestCtx explicitly: this runs in a detached background
776
+ // task where the ALS context is gone, so onError can only fire if
777
+ // we hand it the context captured up front.
778
+ reportCacheError(
779
+ bgError,
780
+ "stale-revalidation",
781
+ "[use cache] background revalidation failed",
782
+ requestCtx,
783
+ );
784
+ }
785
+ }),
786
+ );
752
787
  return result;
753
788
  } catch (error) {
754
789
  // Stale value is corrupt/partial; report and fall through to a fresh
@@ -797,7 +832,10 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
797
832
  // Leader rejected: its map entry is already cleared; run fresh.
798
833
  if (!raced) break;
799
834
  // Checked after the wait, so an invalidation made meanwhile counts too.
800
- if (!invalidatedSince(requestCtx, raced.tags, existing.startSeq)) {
835
+ if (
836
+ !raced.predates &&
837
+ !invalidatedSince(raced.tags, existing.start.seq)
838
+ ) {
801
839
  try {
802
840
  return await serveCached({
803
841
  value: raced.serialized,
@@ -814,11 +852,12 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
814
852
  break; // Run fresh below.
815
853
  }
816
854
  }
817
- // This request invalidated one of the leader's tags after it started
818
- // (#973): its value may predate the invalidation. The leader cleared
819
- // its entry before resolving, so an entry now is a newer execution
820
- // (another caller that made this same decision): join it rather than
821
- // start one more.
855
+ // One of the leader's tags was invalidated after it started, in any
856
+ // request or, as the store tells it, another isolate (#973, #977): its
857
+ // value may predate the invalidation. The leader cleared its entry
858
+ // before resolving, so an entry now is a newer execution (another
859
+ // caller that made this same decision): join it rather than start one
860
+ // more.
822
861
  const next = inFlightExecutions.get(cacheKey);
823
862
  existing = next !== existing ? next : undefined;
824
863
  }
@@ -837,11 +876,11 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
837
876
  // Followers attach their own catch; guard the map's own reference so a
838
877
  // rejected envelope with no waiter is not an unhandled rejection.
839
878
  envelopePromise.catch(() => {});
840
- const startSeq = currentCacheSeq();
879
+ const start = executionStart();
841
880
  inFlightExecutions.set(cacheKey, {
842
881
  promise: envelopePromise,
843
882
  registeredAt: Date.now(),
844
- startSeq,
883
+ start,
845
884
  });
846
885
  const clearSelf = (): void => {
847
886
  if (inFlightExecutions.get(cacheKey)?.promise === envelopePromise) {
@@ -904,13 +943,10 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
904
943
  capture?.stop();
905
944
  }
906
945
 
907
- // Merge profile/DSL tags with runtime cacheTag() tags. Read scoped.tags
908
- // after awaiting result so post-await cacheTag() calls are included.
909
- // Normalize (drops empty profile tags, matching the invalidate path) + dedupe.
910
- const allTags = [
911
- ...new Set(normalizeTags([...(profile.tags ?? []), ...scoped!.tags])),
912
- ];
913
- recordRequestTags(allTags, requestCtx);
946
+ // Read scoped.tags after awaiting result so post-await cacheTag() calls
947
+ // are included.
948
+ const recorded = scoped!.tags;
949
+ recordRequestTags(entryTags(recorded), requestCtx);
914
950
 
915
951
  // Serialize + encode handles ONCE, resolve the in-flight envelope so any
916
952
  // concurrent followers can serve a synthetic hit, then persist to the store.
@@ -924,9 +960,13 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
924
960
  flightErrors.push(error);
925
961
  };
926
962
  try {
927
- serialized = await serializeResult(result, onFlightError);
963
+ serialized = await inTagScope(recorded, () =>
964
+ serializeResult(result, onFlightError),
965
+ );
928
966
  encodedHandles = capture
929
- ? await encodeHandles(capture.capture.data, onFlightError)
967
+ ? await inTagScope(recorded, () =>
968
+ encodeHandles(capture.capture.data, onFlightError),
969
+ )
930
970
  : undefined;
931
971
  // Flight encodes an async component that throws, or a rejected
932
972
  // promise in the result or a handle value, as an error row and
@@ -940,8 +980,8 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
940
980
  requestCtx?._reportBackgroundError?.(buildError, "cache-write");
941
981
  return;
942
982
  }
943
- clearSelf();
944
983
  if (serialized === null) {
984
+ clearSelf();
945
985
  // Non-serializable result: no store write (matches the prior silent
946
986
  // skip); reject so any waiter falls through to a fresh execution.
947
987
  rejectEnvelope(
@@ -951,19 +991,32 @@ export function registerCachedFunction<T extends (...args: any[]) => any>(
951
991
  );
952
992
  return;
953
993
  }
994
+ const tags = entryTags(recorded);
995
+ // One of the value's tags was invalidated after the execution started
996
+ // (#973, #977): written now, a value that may predate it would outlive
997
+ // it. Asked before the followers get the value: another isolate's
998
+ // invalidation is only in the store's answer, and a follower serving
999
+ // the value would bake it into its own entries. Yes also when the store
1000
+ // cannot read a marker (predatesInvalidation asks it fail-closed) or
1001
+ // throws: the cost is a later miss.
1002
+ let predates = true;
1003
+ try {
1004
+ predates = await predatesInvalidation(store, tags, start);
1005
+ } catch (gateError) {
1006
+ requestCtx?._reportBackgroundError?.(gateError, "cache-write");
1007
+ }
1008
+ clearSelf();
954
1009
  // Hand followers the envelope before the store write so a slow/failed
955
1010
  // write never stalls them.
956
- resolveEnvelope({ serialized, tags: allTags, handles: encodedHandles });
957
- // This request invalidated one of the value's tags after the execution
958
- // started (#973): the value may predate the invalidation, and written
959
- // now it would outlive it. Skip the write; the next read runs fresh.
960
- if (invalidatedSince(requestCtx, allTags, startSeq)) return;
1011
+ resolveEnvelope({ serialized, tags, handles: encodedHandles, predates });
1012
+ // Skipped, the next read runs fresh.
1013
+ if (predates) return;
961
1014
  try {
962
1015
  await store.setItem!(cacheKey, serialized, {
963
1016
  handles: encodedHandles,
964
1017
  ttl: profile.ttl,
965
1018
  swr: profile.swr,
966
- tags: allTags.length > 0 ? allTags : undefined,
1019
+ tags: tags.length > 0 ? tags : undefined,
967
1020
  });
968
1021
  } catch (writeError) {
969
1022
  requestCtx?._reportBackgroundError?.(writeError, "cache-write");