{"version":3,"sources":["../../../../src/client/components/segment-cache/cache.ts"],"sourcesContent":["import type {\n  TreePrefetch,\n  RootTreePrefetch,\n  SegmentPrefetchResponse,\n} from '../../../server/app-render/collect-segment-data'\nimport type {\n  CacheNodeSeedData,\n  FlightData,\n  Segment as FlightRouterStateSegment,\n} from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport {\n  readVaryParams,\n  type VaryParams,\n  type VaryParamsIterable,\n} from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport {\n  NEXT_DID_POSTPONE_HEADER,\n  NEXT_ROUTER_PREFETCH_HEADER,\n  NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n  NEXT_ROUTER_STALE_TIME_HEADER,\n  NEXT_ROUTER_STATE_TREE_HEADER,\n  NEXT_URL,\n  RSC_CONTENT_TYPE_HEADER,\n  RSC_HEADER,\n} from '../app-router-headers'\nimport {\n  createFetch,\n  createFromNextReadableStream,\n  decodeBufferedStage,\n  resolveShellStageData,\n  type RSCResponse,\n  type RequestHeaders,\n} from '../router-reducer/fetch-server-response'\nimport { fetch } from './fetch'\nimport {\n  pingPrefetchTask,\n  isPrefetchTaskDirty,\n  type PrefetchTask,\n  type PrefetchSubtaskResult,\n} from './scheduler'\nimport {\n  type RouteVaryPath,\n  type SegmentVaryPath,\n  type PartialSegmentVaryPath,\n  getRouteVaryPath,\n  getFulfilledRouteVaryPath,\n  getFulfilledSegmentVaryPath,\n  getSegmentVaryPathForRequest,\n  getShellSegmentVaryPath,\n  appendLayoutVaryPath,\n  finalizeLayoutVaryPath,\n  finalizePageVaryPath,\n  clonePageVaryPathWithNewSearchParams,\n  type PageVaryPath,\n  type LayoutVaryPath,\n  finalizeMetadataVaryPath,\n  getPartialPageVaryPath,\n  getPartialLayoutVaryPath,\n  getRenderedSearchFromVaryPath,\n} from './vary-path'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport type {\n  NormalizedPathname,\n  NormalizedSearch,\n  NormalizedNextUrl,\n  RouteCacheKey,\n} from './cache-key'\nimport { createCacheKey as createPrefetchRequestKey } from './cache-key'\nimport { splitPathnameIntoParts } from './cache-key'\nimport {\n  doesStaticSegmentAppearInURL,\n  getCacheKeyForDynamicParam,\n  getRenderedPathname,\n  getRenderedSearch,\n  parseDynamicParamFromURLPart,\n} from '../../route-params'\nimport {\n  createCacheMap,\n  getFromCacheMap,\n  setInCacheMap,\n  setSizeInCacheMap,\n  deleteFromCacheMap,\n  isValueExpired,\n  EntryStatus,\n  type CacheMap,\n  type UnknownMapEntry,\n} from './cache-map'\nexport { EntryStatus } from './cache-map'\nimport {\n  appendSegmentRequestKeyPart,\n  convertSegmentPathToStaticExportFilename,\n  createSegmentRequestKeyPart,\n  HEAD_REQUEST_KEY,\n  ROOT_SEGMENT_REQUEST_KEY,\n  type SegmentRequestKey,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport type {\n  FlightRouterState,\n  NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\nimport {\n  type NormalizedFlightData,\n  normalizeFlightData,\n  prepareFlightRouterStateForRequest,\n} from '../../flight-data-helpers'\nimport { STATIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'\nimport { pingVisibleLinks } from '../links'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport { FetchStrategy } from './types'\nimport { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'\nimport { readFromBFCache, UnknownDynamicStaleTime } from './bfcache'\nimport { discoverKnownRoute, matchKnownRoute } from './optimistic-routes'\nimport { convertServerPatchToFullTree, type NavigationSeed } from './navigation'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\n\n/**\n * Ensures a minimum stale time of 30s to avoid issues where the server sends a too\n * short-lived stale time, which would prevent anything from being prefetched.\n */\nexport function getStaleTimeMs(staleTimeSeconds: number): number {\n  return Math.max(staleTimeSeconds, 30) * 1000\n}\n\n// A note on async/await when working in the prefetch cache:\n//\n// Most async operations in the prefetch cache should *not* use async/await,\n// Instead, spawn a subtask that writes the results to a cache entry, and attach\n// a \"ping\" listener to notify the prefetch queue to try again.\n//\n// The reason is we need to be able to access the segment cache and traverse its\n// data structures synchronously. For example, if there's a synchronous update\n// we can take an immediate snapshot of the cache to produce something we can\n// render. Limiting the use of async/await also makes it easier to avoid race\n// conditions, which is especially important because is cache is mutable.\n//\n// Another reason is that while we're performing async work, it's possible for\n// existing entries to become stale, or for Link prefetches to be removed from\n// the queue. For optimal scheduling, we need to be able to \"cancel\" subtasks\n// that are no longer needed. So, when a segment is received from the server, we\n// restart from the root of the tree that's being prefetched, to confirm all the\n// parent segments are still cached. If the segment is no longer reachable from\n// the root, then it's effectively canceled. This is similar to the design of\n// Rust Futures, or React Suspense.\n\ntype RouteTreeShared = {\n  requestKey: SegmentRequestKey\n  // TODO: Remove the `segment` field, now that it can be reconstructed\n  // from `param`.\n  segment: FlightRouterStateSegment\n  // The vary path used to key this segment's App Shell entry: the segment's\n  // vary path with every non-root param replaced with Fallback (see\n  // getShellSegmentVaryPath). Precomputed once during tree construction so we\n  // don't have to recompute it on every shell request.\n  shellVaryPath: SegmentVaryPath\n  refreshState: RefreshState | null\n  // Keyed by parallel route slot name. Stored as a Map rather than a plain\n  // object because slot names are app-defined; with a plain object, every\n  // distinct combination of slot names creates a different hidden class,\n  // making keyed access to the slots megamorphic.\n  slots: null | Map<string, RouteTree>\n  // Bitmask of PrefetchHint flags. Encodes route structure metadata:\n  // root layout, loading boundaries, instant configs, and runtime prefetch\n  // hints.\n  prefetchHints: number\n}\n\nexport type RefreshState = {\n  canonicalUrl: string\n  renderedSearch: NormalizedSearch\n}\n\ntype LayoutRouteTree = RouteTreeShared & {\n  isPage: false\n  varyPath: LayoutVaryPath\n}\n\ntype PageRouteTree = RouteTreeShared & {\n  isPage: true\n  varyPath: PageVaryPath\n}\n\nexport type RouteTree = LayoutRouteTree | PageRouteTree\n\ntype RouteCacheEntryShared = {\n  // This is false only if we're certain the route cannot be intercepted. It's\n  // true in all other cases, including on initialization when we haven't yet\n  // received a response from the server.\n  couldBeIntercepted: boolean\n\n  // When true, this entry should not be used as a template for route\n  // prediction. Set when we discover that the URL was rewritten by middleware\n  // to a different route structure (e.g., /foo was rewritten to /bar). Since\n  // rewrite behavior can vary by param value, we can't safely predict the\n  // route structure for other URLs matching this pattern.\n  //\n  // This is declared on every entry variant (not just fulfilled entries) so\n  // that all RouteCacheEntry objects share a single hidden class; it is\n  // pre-initialized to `false` when the entry is created and only meaningful\n  // once the entry is fulfilled.\n  hasDynamicRewrite: boolean\n\n  // Map-related fields.\n  ref: UnknownMapEntry | null\n  size: number\n  staleAt: number\n  version: number\n}\n\nexport type PendingRouteCacheEntry = RouteCacheEntryShared & {\n  status: EntryStatus.Empty | EntryStatus.Pending\n  blockedTasks: Set<PrefetchTask> | null\n  canonicalUrl: null\n  renderedSearch: null\n  tree: null\n  metadata: null\n  supportsPerSegmentPrefetching: false\n}\n\ntype RejectedRouteCacheEntry = RouteCacheEntryShared & {\n  status: EntryStatus.Rejected\n  blockedTasks: Set<PrefetchTask> | null\n  canonicalUrl: null\n  renderedSearch: null\n  tree: null\n  metadata: null\n  supportsPerSegmentPrefetching: boolean\n}\n\nexport type FulfilledRouteCacheEntry = RouteCacheEntryShared & {\n  status: EntryStatus.Fulfilled\n  blockedTasks: null\n  canonicalUrl: string\n  renderedSearch: NormalizedSearch\n  tree: RouteTree\n  metadata: RouteTree\n  supportsPerSegmentPrefetching: boolean\n}\n\nexport type RouteCacheEntry =\n  | PendingRouteCacheEntry\n  | FulfilledRouteCacheEntry\n  | RejectedRouteCacheEntry\n\ntype SegmentCacheEntryShared = {\n  /**\n   * The fetch strategy this entry's content EFFECTIVELY corresponds to,\n   * which may be deeper than the strategy that requested it: an entry is\n   * recorded at the tier of the payload that fully satisfied it (e.g. a\n   * shell-spawned entry fulfilled by a response whose shell IS the full\n   * response is recorded at the full tier, while still keyed at the shell\n   * vary path — valid precisely because the variants coincide). Compared\n   * via `canNewFetchStrategyProvideMoreContent` to decide whether a new\n   * request could yield more content than what's already cached.\n   *\n   * \"Effectively\" spans both of the tier axes, static-vs-runtime included: a\n   * static response that accessed no runtime data is as complete as a runtime\n   * response of the same variant, so it records the RUNTIME tier (see\n   * `recordedFetchStrategy` in writeSegmentBundleResponse). That is what lets\n   * \"would a runtime request return more?\" be answered by comparing tiers,\n   * with no separate per-entry signal — the question the scheduler asks in\n   * `wouldRuntimeRequestProvideMore`.\n   */\n  fetchStrategy: FetchStrategy\n\n  /**\n   * True if this entry was fulfilled from a fallback shell response (the page\n   * had not yet been prerendered with concrete params). The scheduler uses\n   * this to retry the static prefetch, since a more complete version may\n   * become available once the server's background regeneration finishes.\n   *\n   * Distinct from `isPartial`: a fully-prerendered PPR page can have partial\n   * segments that should NOT be retried. See `SegmentPrefetchResponse`.\n   */\n  isUpgradeableISRFallback: boolean\n\n  // Map-related fields.\n  ref: UnknownMapEntry | null\n  size: number\n  staleAt: number\n  version: number\n}\n\nexport type EmptySegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Empty\n  blockedTasks: Set<PrefetchTask> | null\n  rsc: null\n  isPartial: true\n  promise: null\n}\n\nexport type PendingSegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Pending\n  blockedTasks: Set<PrefetchTask> | null\n  rsc: null\n  isPartial: boolean\n  promise: null | PromiseWithResolvers<FulfilledSegmentCacheEntry | null>\n}\n\ntype RejectedSegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Rejected\n  blockedTasks: Set<PrefetchTask> | null\n  rsc: null\n  isPartial: true\n  promise: null\n}\n\nexport type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Fulfilled\n  blockedTasks: null\n  rsc: React.ReactNode | null\n  isPartial: boolean\n  promise: null\n}\n\nexport type SegmentCacheEntry =\n  | EmptySegmentCacheEntry\n  | PendingSegmentCacheEntry\n  | RejectedSegmentCacheEntry\n  | FulfilledSegmentCacheEntry\n\nexport type NonEmptySegmentCacheEntry = Exclude<\n  SegmentCacheEntry,\n  EmptySegmentCacheEntry\n>\n\n/**\n * A linked list of segment cache entries to fulfill from a single prefetch\n * response. The head is the requested segment; subsequent nodes are parent\n * segments whose data is bundled into the same response by the server.\n *\n * When segments are not bundled, the list has a single node. The list\n * maps 1:1 to the data array in the SegmentPrefetchResponse the server returns.\n */\nexport type SegmentBundle = {\n  // Null when the segment has prefetching disabled entirely\n  // (prefetch: 'force-disabled' / instant = false; Partial Prefetching\n  // segments have static data and occupy a real node). The bundle chain\n  // passes through it but no cache entry is created.\n  tree: RouteTree | null\n  entry: SegmentCacheEntry | null\n  parent: SegmentBundle | null\n}\n\nconst isOutputExportMode =\n  process.env.NODE_ENV === 'production' &&\n  process.env.__NEXT_CONFIG_OUTPUT === 'export'\n\nexport const MetadataOnlyRequestTree: FlightRouterState = [\n  '',\n  {},\n  null,\n  'metadata-only',\n]\n\nconst routeCacheMap: CacheMap<RouteCacheEntry> = createCacheMap()\n\n/**\n * The shared segment cache map. Segment cache functions do not access this\n * ambiently — every unit of work is bound to a map when it is created, and\n * reads and writes receive that map explicitly:\n *\n * - A prefetch task captures its map when it is scheduled\n *   (`PrefetchTask.segmentCacheMap` in scheduler.ts). Almost always this one;\n *   a task scheduled while the Instant Navigation Testing lock is held gets\n *   the lock scope's private map instead (which starts empty and is discarded\n *   at release), so a locked navigation observes only data fetched under the\n *   lock — never a stale entry left in the shared cache by an earlier\n *   navigation, prefetch, or scope.\n * - A locked navigation inherits the map of the prefetch task that drives it\n *   (see `ensurePrefetchThenNavigate` in navigation.ts).\n * - Everything else — unlocked navigations, hydration, and router work that\n *   is not a captured navigation (refreshes, history-traversal restores,\n *   server-action redirects, server patches) — uses this shared map\n *   directly, even while a lock is held.\n *\n * Binding at creation means a task queued before a lock scope begins never\n * leaks entries into the scope's map (or reads out of it), and a scope task's\n * late responses never leak into the shared map.\n */\nexport const segmentCacheMap: CacheMap<SegmentCacheEntry> = createCacheMap()\n\n// All invalidation listeners for the whole cache are tracked in single set.\n// Since we don't yet support tag or path-based invalidation, there's no point\n// tracking them any more granularly than this. Once we add granular\n// invalidation, that may change, though generally the model is to just notify\n// the listeners and allow the caller to poll the prefetch cache with a new\n// prefetch task if desired.\nlet invalidationListeners: Set<PrefetchTask> | null = null\n\n// Incrementing counters used to track cache invalidations. Route and segment\n// caches have separate versions so they can be invalidated independently.\n// Invalidation does not eagerly evict anything from the cache; entries are\n// lazily evicted when read.\nlet currentRouteCacheVersion = 0\nlet currentSegmentCacheVersion = 0\n\nexport function getCurrentRouteCacheVersion(): number {\n  return currentRouteCacheVersion\n}\n\nexport function getCurrentSegmentCacheVersion(): number {\n  return currentSegmentCacheVersion\n}\n\n/**\n * Invalidates all prefetch cache entries (both route and segment caches).\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */\nexport function invalidateEntirePrefetchCache(\n  nextUrl: string | null,\n  tree: FlightRouterState\n): void {\n  currentRouteCacheVersion++\n  currentSegmentCacheVersion++\n\n  pingVisibleLinks(nextUrl, tree)\n  pingInvalidationListeners(nextUrl, tree)\n}\n\n/**\n * Invalidates all route cache entries. Route entries contain the tree structure\n * (which segments exist at a given URL) but not the segment data itself.\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */\nexport function invalidateRouteCacheEntries(\n  nextUrl: string | null,\n  tree: FlightRouterState\n): void {\n  currentRouteCacheVersion++\n\n  pingVisibleLinks(nextUrl, tree)\n  pingInvalidationListeners(nextUrl, tree)\n}\n\n/**\n * Invalidates all segment cache entries. Segment entries contain the actual\n * RSC data for each segment.\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */\nexport function invalidateSegmentCacheEntries(\n  nextUrl: string | null,\n  tree: FlightRouterState\n): void {\n  currentSegmentCacheVersion++\n\n  pingVisibleLinks(nextUrl, tree)\n  pingInvalidationListeners(nextUrl, tree)\n}\n\nfunction attachInvalidationListener(task: PrefetchTask): void {\n  // This function is called whenever a prefetch task reads a cache entry. If\n  // the task has an onInvalidate function associated with it — i.e. the one\n  // optionally passed to router.prefetch(onInvalidate) — then we attach that\n  // listener to the every cache entry that the task reads. Then, if an entry\n  // is invalidated, we call the function.\n  if (task.onInvalidate !== null) {\n    if (invalidationListeners === null) {\n      invalidationListeners = new Set([task])\n    } else {\n      invalidationListeners.add(task)\n    }\n  }\n}\n\nfunction notifyInvalidationListener(task: PrefetchTask): void {\n  const onInvalidate = task.onInvalidate\n  if (onInvalidate !== null) {\n    // Clear the callback from the task object to guarantee it's not called more\n    // than once.\n    task.onInvalidate = null\n\n    // This is a user-space function, so we must wrap in try/catch.\n    try {\n      onInvalidate()\n    } catch (error) {\n      if (typeof reportError === 'function') {\n        reportError(error)\n      } else {\n        console.error(error)\n      }\n    }\n  }\n}\n\nexport function pingInvalidationListeners(\n  nextUrl: string | null,\n  tree: FlightRouterState\n): void {\n  // The rough equivalent of pingVisibleLinks, but for onInvalidate callbacks.\n  // This is called when the Next-Url or the base tree changes, since those\n  // may affect the result of a prefetch task. It's also called after a\n  // cache invalidation.\n  if (invalidationListeners !== null) {\n    const tasks = invalidationListeners\n    invalidationListeners = null\n    for (const task of tasks) {\n      if (isPrefetchTaskDirty(task, nextUrl, tree)) {\n        notifyInvalidationListener(task)\n      }\n    }\n  }\n}\n\nexport function readRouteCacheEntry(\n  now: number,\n  key: RouteCacheKey\n): RouteCacheEntry | null {\n  const varyPath: RouteVaryPath = getRouteVaryPath(\n    key.pathname,\n    key.search,\n    key.nextUrl\n  )\n  const isRevalidation = false\n  const existingEntry = getFromCacheMap(\n    now,\n    getCurrentRouteCacheVersion(),\n    routeCacheMap,\n    varyPath,\n    isRevalidation,\n    false\n  )\n  if (existingEntry !== null) {\n    return existingEntry\n  }\n\n  // No cache hit. Attempt to construct from template using the new\n  // optimistic routing mechanism (pattern-based matching).\n  if (process.env.__NEXT_OPTIMISTIC_ROUTING) {\n    return matchKnownRoute(now, key.pathname, key.search)\n  }\n\n  return null\n}\n\n/**\n * Reads the cache entry for a segment during a navigation. Unlike a plain\n * lookup, prefers a Fulfilled entry over a more-specific Pending or Rejected\n * entry: during a navigation, a less-specific shell entry (e.g. params ->\n * Fallback) should be rendered immediately rather than blocking on a\n * more-specific Pending entry that may still be in-flight.\n *\n * Performs up to two lookups:\n *  1. An `onlyMatchFulfilled` lookup that walks past Pending/Rejected entries\n *     at more-specific keypaths to find a Fulfilled fallback (e.g. a cached\n *     shell).\n *  2. If no Fulfilled entry is found, a regular lookup that returns the most\n *     specific match regardless of status.\n */\nexport function readSegmentCacheEntryForNavigation(\n  now: number,\n  // The map the navigation is bound to: a locked navigation's driving-task\n  // map, or the shared map otherwise.\n  map: CacheMap<SegmentCacheEntry>,\n  varyPath: SegmentVaryPath,\n  restrictToShell: boolean = false\n): SegmentCacheEntry | null {\n  const isRevalidation = false\n\n  let lookupVaryPath = varyPath\n  if (process.env.__NEXT_EXPOSE_TESTING_API && restrictToShell) {\n    // Instant Navigation Testing API: we're navigating to a link that 1) has\n    // Partial Prefetching enabled, and 2) does not have a prefetch prop set.\n    // Only the shell may render, not anything that varies on concrete route\n    // params.\n    lookupVaryPath = getShellSegmentVaryPath(varyPath)\n  }\n\n  // Prefer a Fulfilled entry (e.g. a cached shell) over a more-specific\n  // Pending/Rejected one so it renders immediately instead of blocking on an\n  // in-flight entry.\n  const fulfilled = getFromCacheMap(\n    now,\n    getCurrentSegmentCacheVersion(),\n    map,\n    lookupVaryPath,\n    isRevalidation,\n    true\n  )\n  if (fulfilled !== null) {\n    return fulfilled\n  }\n  return getFromCacheMap(\n    now,\n    getCurrentSegmentCacheVersion(),\n    map,\n    lookupVaryPath,\n    isRevalidation,\n    false\n  )\n}\n\nfunction readRevalidatingSegmentCacheEntry(\n  now: number,\n  map: CacheMap<SegmentCacheEntry>,\n  varyPath: SegmentVaryPath\n): SegmentCacheEntry | null {\n  const isRevalidation = true\n  return getFromCacheMap(\n    now,\n    getCurrentSegmentCacheVersion(),\n    map,\n    varyPath,\n    isRevalidation,\n    false\n  )\n}\n\nexport function waitForSegmentCacheEntry(\n  pendingEntry: PendingSegmentCacheEntry\n): Promise<FulfilledSegmentCacheEntry | null> {\n  // Because the entry is pending, there's already a in-progress request.\n  // Attach a promise to the entry that will resolve when the server responds.\n  let promiseWithResolvers = pendingEntry.promise\n  if (promiseWithResolvers === null) {\n    promiseWithResolvers = pendingEntry.promise =\n      createPromiseWithResolvers<FulfilledSegmentCacheEntry | null>()\n  } else {\n    // There's already a promise we can use\n  }\n  return promiseWithResolvers.promise\n}\n\nfunction createDetachedRouteCacheEntry(): PendingRouteCacheEntry {\n  return {\n    canonicalUrl: null,\n    status: EntryStatus.Empty,\n    blockedTasks: null,\n    tree: null,\n    metadata: null,\n    // This is initialized to true because we don't know yet whether the route\n    // could be intercepted. It's only set to false once we receive a response\n    // from the server.\n    couldBeIntercepted: true,\n    // Similarly, we don't yet know if the route supports PPR.\n    supportsPerSegmentPrefetching: false,\n    hasDynamicRewrite: false,\n    renderedSearch: null,\n\n    // Map-related fields\n    ref: null,\n    size: 0,\n    // Since this is an empty entry, there's no reason to ever evict it. It will\n    // be updated when the data is populated.\n    staleAt: Infinity,\n    version: getCurrentRouteCacheVersion(),\n  }\n}\n\n/**\n * Checks if an entry for a route exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */\nexport function readOrCreateRouteCacheEntry(\n  now: number,\n  task: PrefetchTask,\n  key: RouteCacheKey\n): RouteCacheEntry {\n  attachInvalidationListener(task)\n\n  const existingEntry = readRouteCacheEntry(now, key)\n  if (existingEntry !== null) {\n    return existingEntry\n  }\n  // Create a pending entry and add it to the cache.\n  const pendingEntry = createDetachedRouteCacheEntry()\n  const varyPath: RouteVaryPath = getRouteVaryPath(\n    key.pathname,\n    key.search,\n    key.nextUrl\n  )\n  const isRevalidation = false\n  setInCacheMap(routeCacheMap, varyPath, pendingEntry, isRevalidation)\n  return pendingEntry\n}\n\n// TODO: This function predates the new optimisticRouting feature and will be\n// removed once optimisticRouting is stable. The new mechanism (matchKnownRoute)\n// handles search param variations more robustly as part of the general route\n// prediction system. This fallback remains for when optimisticRouting is\n// disabled (staticChildren is null).\nexport function deprecated_requestOptimisticRouteCacheEntry(\n  now: number,\n  requestedUrl: URL,\n  nextUrl: string | null\n): FulfilledRouteCacheEntry | null {\n  // This function is called during a navigation when there was no matching\n  // route tree in the prefetch cache. Before de-opting to a blocking,\n  // unprefetched navigation, we will first attempt to construct an \"optimistic\"\n  // route tree by checking the cache for similar routes.\n  //\n  // Check if there's a route with the same pathname, but with different\n  // search params. We can then base our optimistic route tree on this entry.\n  //\n  // Conceptually, we are simulating what would happen if we did perform a\n  // prefetch the requested URL, under the assumption that the server will\n  // not redirect or rewrite the request in a different manner than the\n  // base route tree. This assumption might not hold, in which case we'll have\n  // to recover when we perform the dynamic navigation request. However, this\n  // is what would happen if a route were dynamically rewritten/redirected\n  // in between the prefetch and the navigation. So the logic needs to exist\n  // to handle this case regardless.\n\n  // Look for a route with the same pathname, but with an empty search string.\n  // TODO: There's nothing inherently special about the empty search string;\n  // it's chosen somewhat arbitrarily, with the rationale that it's the most\n  // likely one to exist. But we should update this to match _any_ search\n  // string. The plan is to generalize this logic alongside other improvements\n  // related to \"fallback\" cache entries.\n  const requestedSearch = requestedUrl.search as NormalizedSearch\n  if (requestedSearch === '') {\n    // The caller would have already checked if a route with an empty search\n    // string is in the cache. So we can bail out here.\n    return null\n  }\n  const urlWithoutSearchParams = new URL(requestedUrl)\n  urlWithoutSearchParams.search = ''\n  const routeWithNoSearchParams = readRouteCacheEntry(\n    now,\n    createPrefetchRequestKey(urlWithoutSearchParams.href, nextUrl)\n  )\n\n  if (\n    routeWithNoSearchParams === null ||\n    routeWithNoSearchParams.status !== EntryStatus.Fulfilled\n  ) {\n    // Bail out of constructing an optimistic route tree. This will result in\n    // a blocking, unprefetched navigation.\n    return null\n  }\n\n  // Now we have a base route tree we can \"patch\" with our optimistic values.\n\n  // Optimistically assume that redirects for the requested pathname do\n  // not vary on the search string. Therefore, if the base route was\n  // redirected to a different search string, then the optimistic route\n  // should be redirected to the same search string. Otherwise, we use\n  // the requested search string.\n  const canonicalUrlForRouteWithNoSearchParams = new URL(\n    routeWithNoSearchParams.canonicalUrl,\n    requestedUrl.origin\n  )\n  const optimisticCanonicalSearch =\n    canonicalUrlForRouteWithNoSearchParams.search !== ''\n      ? // Base route was redirected. Reuse the same redirected search string.\n        canonicalUrlForRouteWithNoSearchParams.search\n      : requestedSearch\n\n  // Similarly, optimistically assume that rewrites for the requested\n  // pathname do not vary on the search string. Therefore, if the base\n  // route was rewritten to a different search string, then the optimistic\n  // route should be rewritten to the same search string. Otherwise, we use\n  // the requested search string.\n  const optimisticRenderedSearch =\n    routeWithNoSearchParams.renderedSearch !== ''\n      ? // Base route was rewritten. Reuse the same rewritten search string.\n        routeWithNoSearchParams.renderedSearch\n      : requestedSearch\n\n  const optimisticUrl = new URL(\n    routeWithNoSearchParams.canonicalUrl,\n    location.origin\n  )\n  optimisticUrl.search = optimisticCanonicalSearch\n  const optimisticCanonicalUrl = createHrefFromUrl(optimisticUrl)\n\n  const optimisticRouteTree = deprecated_createOptimisticRouteTree(\n    routeWithNoSearchParams.tree,\n    optimisticRenderedSearch\n  )\n  const optimisticMetadataTree = deprecated_createOptimisticRouteTree(\n    routeWithNoSearchParams.metadata,\n    optimisticRenderedSearch\n  )\n\n  // Clone the base route tree, and override the relevant fields with our\n  // optimistic values.\n  const optimisticEntry: FulfilledRouteCacheEntry = {\n    canonicalUrl: optimisticCanonicalUrl,\n\n    status: EntryStatus.Fulfilled,\n    // This isn't cloned because it's instance-specific\n    blockedTasks: null,\n    tree: optimisticRouteTree,\n    metadata: optimisticMetadataTree,\n    couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted,\n    supportsPerSegmentPrefetching:\n      routeWithNoSearchParams.supportsPerSegmentPrefetching,\n    hasDynamicRewrite: routeWithNoSearchParams.hasDynamicRewrite,\n\n    // Override the rendered search with the optimistic value.\n    renderedSearch: optimisticRenderedSearch,\n\n    // Map-related fields\n    ref: null,\n    size: 0,\n    staleAt: routeWithNoSearchParams.staleAt,\n    version: routeWithNoSearchParams.version,\n  }\n\n  // Do not insert this entry into the cache. It only exists so we can\n  // perform the current navigation. Just return it to the caller.\n  return optimisticEntry\n}\n\nfunction deprecated_createOptimisticRouteTree(\n  tree: RouteTree,\n  newRenderedSearch: NormalizedSearch\n): RouteTree {\n  // Create a new route tree that identical to the original one except for\n  // the rendered search string, which is contained in the vary path.\n\n  let clonedSlots: Map<string, RouteTree> | null = null\n  const originalSlots = tree.slots\n  if (originalSlots !== null) {\n    clonedSlots = new Map()\n    for (const [parallelRouteKey, childTree] of originalSlots) {\n      clonedSlots.set(\n        parallelRouteKey,\n        deprecated_createOptimisticRouteTree(childTree, newRenderedSearch)\n      )\n    }\n  }\n\n  // We only need to clone the vary path if the route is a page.\n  if (tree.isPage) {\n    // The shell vary path Fallbacks search params, so it's unaffected by the\n    // new rendered search and can be reused as-is.\n    return {\n      requestKey: tree.requestKey,\n      segment: tree.segment,\n      shellVaryPath: tree.shellVaryPath,\n      refreshState: tree.refreshState,\n      varyPath: clonePageVaryPathWithNewSearchParams(\n        tree.varyPath,\n        newRenderedSearch\n      ),\n      isPage: true,\n      slots: clonedSlots,\n\n      prefetchHints: tree.prefetchHints,\n    }\n  }\n\n  return {\n    requestKey: tree.requestKey,\n    segment: tree.segment,\n    shellVaryPath: tree.shellVaryPath,\n    refreshState: tree.refreshState,\n    varyPath: tree.varyPath,\n    isPage: false,\n    slots: clonedSlots,\n    prefetchHints: tree.prefetchHints,\n  }\n}\n\n/**\n * Checks if an entry for a segment exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */\nexport function readOrCreateSegmentCacheEntry(\n  now: number,\n  // The map the calling task operates in (`PrefetchTask.segmentCacheMap`,\n  // captured when the task was scheduled).\n  map: CacheMap<SegmentCacheEntry>,\n  fetchStrategy: FetchStrategy,\n  tree: RouteTree\n): SegmentCacheEntry {\n  const existingEntry = getFromCacheMap(\n    now,\n    getCurrentSegmentCacheVersion(),\n    map,\n    tree.varyPath,\n    false,\n    false\n  )\n  if (existingEntry !== null) {\n    return existingEntry\n  }\n  return insertEmptySegmentCacheEntry(now, map, fetchStrategy, tree)\n}\n\n/**\n * Creates an empty segment cache entry and inserts it into the cache, keyed\n * at the vary path a request made with the given fetch strategy is stored\n * under. The stale time is set to a default value; the actual stale time will\n * be set when the entry is fulfilled with data from the server response.\n */\nfunction insertEmptySegmentCacheEntry(\n  now: number,\n  map: CacheMap<SegmentCacheEntry>,\n  fetchStrategy: FetchStrategy,\n  tree: RouteTree\n): EmptySegmentCacheEntry {\n  const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n  const emptyEntry = createDetachedSegmentCacheEntry(now)\n  const isRevalidation = false\n  setInCacheMap(map, varyPathForRequest, emptyEntry, isRevalidation)\n  return emptyEntry\n}\n\nexport function readOrCreateRevalidatingSegmentEntry(\n  now: number,\n  // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).\n  map: CacheMap<SegmentCacheEntry>,\n  fetchStrategy: FetchStrategy,\n  tree: RouteTree\n): SegmentCacheEntry {\n  // This function is called when we've already confirmed that a particular\n  // segment is cached, but we want to perform another request anyway in case it\n  // returns more complete and/or fresher data than we already have. The logic\n  // for deciding whether to replace the existing entry is handled elsewhere;\n  // this function just handles retrieving a cache entry that we can use to\n  // track the revalidation.\n  //\n  // The reason revalidations are stored in the cache is because we need to be\n  // able to dedupe multiple revalidation requests. The reason they have to be\n  // handled specially is because we shouldn't overwrite a \"normal\" entry if\n  // one exists at the same keypath. So, for each internal cache location, there\n  // is a special \"revalidation\" slot that is used solely for this purpose.\n  //\n  // You can think of it as if all the revalidation entries were stored in a\n  // separate cache map from the canonical entries, and then transfered to the\n  // canonical cache map once the request is complete — this isn't how it's\n  // actually implemented, since it's more efficient to store them in the same\n  // data structure as the normal entries, but that's how it's modeled\n  // conceptually.\n\n  // TODO: Once we implement Fallback behavior for params, where an entry is\n  // re-keyed based on response information, we'll need to account for the\n  // possibility that the keypath of the previous entry is more generic than\n  // the keypath of the revalidating entry. In other words, the server could\n  // return a less generic entry upon revalidation. For now, though, this isn't\n  // a concern because the keypath is based solely on the prefetch strategy,\n  // not on data contained in the response.\n  const existingEntry = readRevalidatingSegmentCacheEntry(\n    now,\n    map,\n    tree.varyPath\n  )\n  if (existingEntry !== null) {\n    return existingEntry\n  }\n  // Create a pending entry and add it to the cache. The stale time is set to a\n  // default value; the actual stale time will be set when the entry is\n  // fulfilled with data from the server response.\n  const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n  const pendingEntry = createDetachedSegmentCacheEntry(now)\n  const isRevalidation = true\n  setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)\n  return pendingEntry\n}\n\nexport function overwriteRevalidatingSegmentCacheEntry(\n  now: number,\n  // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).\n  map: CacheMap<SegmentCacheEntry>,\n  fetchStrategy: FetchStrategy,\n  tree: RouteTree\n) {\n  // This function is called when we've already decided to replace an existing\n  // revalidation entry. Create a new entry and write it into the cache,\n  // overwriting the previous value. The stale time is set to a default value;\n  // the actual stale time will be set when the entry is fulfilled with data\n  // from the server response.\n  const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n  const pendingEntry = createDetachedSegmentCacheEntry(now)\n  const isRevalidation = true\n  setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)\n  return pendingEntry\n}\n\n/**\n * Whether an existing cache entry is preferred over an incoming candidate —\n * i.e. the candidate does NOT supersede it. (On an exact tie — same fetch\n * strategy, same partialness — this returns false, so the candidate replaces\n * the existing entry.) This is the precedence rule used both when deciding\n * whether an upsert may replace the entry at its own keypath, and when\n * deciding whether an entry at a more specific keypath may be evicted because\n * it shadows a just-inserted candidate (see `evictShadowingSegmentEntries`).\n *\n * Note that \"less/more specific\" in the comments below refers to fetch\n * strategy content tiers (how much content a strategy can produce), not the\n * vary-path specificity the eviction docs are concerned with.\n */\nfunction isExistingSegmentEntryPreferred(\n  existingEntry: SegmentCacheEntry,\n  candidateEntry: SegmentCacheEntry\n): boolean {\n  return (\n    // We fetched the new segment using a different, less specific fetch\n    // strategy than the segment we already have in the cache, so it can't\n    // have more content.\n    (candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&\n      !canNewFetchStrategyProvideMoreContent(\n        existingEntry.fetchStrategy,\n        candidateEntry.fetchStrategy\n      )) ||\n    // The existing entry isn't partial, but the new one is.\n    // (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)\n    (!existingEntry.isPartial && candidateEntry.isPartial)\n  )\n}\n\nexport function upsertSegmentEntry(\n  now: number,\n  // The map the whole upsert (existing-entry read, insert, shadow eviction)\n  // operates in. Prefetch response-write paths pass the spawning task's map\n  // (`PrefetchTask.segmentCacheMap`), so a response that lands after a\n  // testing-lock scope boundary still writes into the map its entries\n  // live in.\n  map: CacheMap<SegmentCacheEntry>,\n  varyPath: SegmentVaryPath,\n  candidateEntry: SegmentCacheEntry,\n  // The fully concrete vary path a read for this segment position resolves\n  // against (all concrete param values, i.e. `tree.varyPath`) — the most\n  // specific path a read would use. Note this is the opposite of the\n  // generalized keying path that `getSegmentVaryPathForRequest` computes.\n  // Used to detect and evict stale entries at more specific keypaths that\n  // would otherwise shadow the candidate. Pass null when there's no request\n  // context; the shadow check is skipped.\n  lookupVaryPath: SegmentVaryPath | null\n): SegmentCacheEntry | null {\n  // We have a new entry that has not yet been inserted into the cache. Before\n  // we do so, we need to confirm whether it takes precedence over the existing\n  // entry (if one exists).\n  // TODO: We should not upsert an entry if its key was invalidated in the time\n  // since the request was made. We can do that by passing the \"owner\" entry to\n  // this function and confirming it's the same as `existingEntry`.\n\n  if (isValueExpired(now, getCurrentSegmentCacheVersion(), candidateEntry)) {\n    // The entry is expired. We cannot upsert it.\n    return null\n  }\n\n  const existingEntry = getFromCacheMap(\n    now,\n    getCurrentSegmentCacheVersion(),\n    map,\n    varyPath,\n    false,\n    false\n  )\n  if (existingEntry !== null) {\n    // Don't replace a more specific segment with a less-specific one. A case where this\n    // might happen is if the existing segment was fetched via\n    // `<Link prefetch={true}>`.\n    if (isExistingSegmentEntryPreferred(existingEntry, candidateEntry)) {\n      // The candidate does not supersede the existing entry. Leave the\n      // existing entry in place and discard the candidate by not inserting it.\n      //\n      // We must not mutate the candidate here (e.g. downgrade it to Rejected or\n      // null out its `rsc`). The caller does not transfer exclusive ownership\n      // of it: it may already have been fulfilled, resolving its promise to a\n      // waiter that holds the entry and reads `rsc` off it later. A navigation\n      // seed is such a waiter, via `waitForSegmentCacheEntry`. Nulling `rsc`\n      // after the fact resolves that read to `null`, so the waiter loses the\n      // data it was about to render. Declining to insert it is enough: the\n      // existing entry stays canonical, and the candidate keeps its valid (if\n      // less complete) data for any waiter that already took it.\n      return null\n    }\n\n    // Ping any tasks blocked on the existing entry before replacing it so they\n    // re-run and pick up the new entry. Without this, tasks waiting on the\n    // existing Empty/Pending entry would be stranded — the new fulfilled\n    // candidate has no blockedTasks of its own.\n    if (\n      existingEntry.status === EntryStatus.Empty ||\n      existingEntry.status === EntryStatus.Pending\n    ) {\n      pingBlockedTasks(existingEntry)\n    }\n\n    // Replace the existing entry by writing the candidate over its keypath\n    // below (the same mechanism `overwriteRevalidatingSegmentCacheEntry`\n    // uses). We intentionally do NOT call `deleteFromCacheMap` first: deleting\n    // vacates the canonical slot, and `deleteMapEntry` promotes a pending\n    // Revalidation-slot entry into the vacated slot — which the immediate\n    // insert below would then silently overwrite. The in-flight revalidation\n    // would vanish from the map, so the next scheduler pass would find an\n    // empty revalidation slot and spawn a duplicate request instead of\n    // deduping against it. Replacing in place never vacates the slot, so\n    // promotion never runs and the pending revalidating entry stays in its\n    // Revalidation slot where `readOrCreateRevalidatingSegmentEntry`'s dedupe\n    // finds it.\n    //\n    // The displaced entry's map/LRU accounting is handled by the replacement\n    // itself: `setMapEntryValue` drops the displaced value's `ref` and\n    // `updateLruSize` swaps its size for the candidate's, which is exactly\n    // what delete-then-insert did.\n  }\n\n  const isRevalidation = false\n  setInCacheMap(map, varyPath, candidateEntry, isRevalidation)\n\n  if (lookupVaryPath !== null) {\n    evictShadowingSegmentEntries(now, map, lookupVaryPath, candidateEntry)\n  }\n\n  return candidateEntry\n}\n\n/**\n * Evicts stale entries at more specific keypaths that shadow a just-inserted\n * candidate entry.\n *\n * A response can be written to the cache at a MORE GENERIC vary path than the\n * path the request was issued against — for example, the server may report\n * that a segment doesn't vary on a param, so the entry is re-keyed with that\n * param as Fallback. Meanwhile, an older, less useful entry can exist at a\n * more specific path within the same fallback chain — for example, a partial\n * shell entry keyed with root params concrete (see\n * `getShellSegmentVaryPath`). Because segment lookup is\n * most-specific-match-wins, every subsequent read at the concrete request\n * path keeps returning the stale specific entry, and the more complete\n * generic entry is unreachable from that URL. That both wastes the completed\n * request and can loop: a prefetch task that revalidated the segment reads\n * back the same stale entry, decides it needs to revalidate again, and\n * repeats forever.\n *\n * The upsert is the one moment we know the ordering between the two entries:\n * the candidate was produced by a request for this segment position, and\n * `lookupVaryPath` is the fully concrete path a read for that position\n * resolves against, so any entry that a read at that path would return in the\n * candidate's stead is directly comparable to it. If such an entry is settled\n * and the candidate supersedes it — under the same precedence rules the\n * upsert applies at its own keypath — we know we never want to match against\n * it again, so delete it, making the candidate reachable.\n *\n * Non-settled entries are never evicted here: a Pending entry is owned by an\n * in-flight request that will settle it, and an Empty entry is a placeholder\n * that a scheduler pass may still claim and upgrade.\n */\nfunction evictShadowingSegmentEntries(\n  now: number,\n  map: CacheMap<SegmentCacheEntry>,\n  lookupVaryPath: SegmentVaryPath,\n  candidateEntry: SegmentCacheEntry\n): void {\n  // There can in principle be multiple shadowing entries at successively less\n  // specific keypaths, so loop until the read returns the candidate (or an\n  // entry we don't supersede). Each iteration re-reads and re-checks from\n  // scratch (in part because `deleteFromCacheMap` can promote a settled\n  // Revalidation-slot value into the just-vacated slot, surfacing a new entry\n  // at the same keypath). Each iteration deletes an entry from the map, so\n  // the loop terminates naturally; the bound is defensive, and 32 is far\n  // beyond any real fallback chain, which is bounded by the vary\n  // path's length.\n  for (let i = 0; i < 32; i++) {\n    const shadowEntry = getFromCacheMap(\n      now,\n      getCurrentSegmentCacheVersion(),\n      map,\n      lookupVaryPath,\n      false,\n      false\n    )\n    if (shadowEntry === null || shadowEntry === candidateEntry) {\n      // The candidate is reachable from the lookup path (or the read missed\n      // entirely, e.g. because the candidate expired). Done.\n      return\n    }\n    if (\n      shadowEntry.status !== EntryStatus.Fulfilled &&\n      shadowEntry.status !== EntryStatus.Rejected\n    ) {\n      // Only settled entries may be evicted. A Pending entry is held by an\n      // in-flight request and will settle on its own.\n      return\n    }\n    if (isExistingSegmentEntryPreferred(shadowEntry, candidateEntry)) {\n      // The shadowing entry is preferred over the candidate (e.g. it's a\n      // complete entry fetched with a more specific strategy). Leave it —\n      // reads at this path should keep matching it.\n      return\n    }\n    // The candidate supersedes the shadowing entry. Evict it. Settled entries\n    // shouldn't have blocked tasks (Fulfilled always has `blockedTasks:\n    // null`, and Rejected entries were pinged at rejection), but ping\n    // defensively before deleting, matching the upsert-evict pattern above.\n    pingBlockedTasks(shadowEntry)\n    deleteFromCacheMap(shadowEntry)\n  }\n}\n\nexport function createDetachedSegmentCacheEntry(\n  now: number\n): EmptySegmentCacheEntry {\n  // Default stale time for pending segment cache entries. The actual stale time\n  // is set when the entry is fulfilled with data from the server response.\n  const staleAt = now + 30 * 1000\n  const emptyEntry: EmptySegmentCacheEntry = {\n    status: EntryStatus.Empty,\n    blockedTasks: null,\n    // Default to assuming the fetch strategy will be PPR. This will be updated\n    // when a fetch is actually initiated.\n    fetchStrategy: FetchStrategy.PPR,\n    rsc: null,\n    isPartial: true,\n    isUpgradeableISRFallback: false,\n    promise: null,\n\n    // Map-related fields\n    ref: null,\n    size: 0,\n    staleAt,\n    version: 0,\n  }\n  return emptyEntry\n}\n\nexport function upgradeToPendingSegment(\n  emptyEntry: EmptySegmentCacheEntry,\n  fetchStrategy: FetchStrategy\n): PendingSegmentCacheEntry {\n  const pendingEntry: PendingSegmentCacheEntry = emptyEntry as any\n  pendingEntry.status = EntryStatus.Pending\n  pendingEntry.fetchStrategy = fetchStrategy\n\n  if (fetchStrategy === FetchStrategy.Full) {\n    // We can assume the response will contain the full segment data. Set this\n    // to false so we know it's OK to omit this segment from any navigation\n    // requests that may happen while the data is still pending.\n    pendingEntry.isPartial = false\n  }\n\n  // Set the version here, since this is right before the request is initiated.\n  // The next time the segment cache version is incremented, the entry will\n  // effectively be evicted. This happens before initiating the request, rather\n  // than when receiving the response, because it's guaranteed to happen\n  // before the data is read on the server.\n  pendingEntry.version = getCurrentSegmentCacheVersion()\n\n  return pendingEntry\n}\n\nexport function attemptToFulfillDynamicSegmentFromBFCache(\n  now: number,\n  segment: EmptySegmentCacheEntry,\n  tree: RouteTree\n): FulfilledSegmentCacheEntry | null {\n  // Attempts to fulfill an empty segment cache entry using data from the\n  // bfcache. This is only valid during a Full prefetch (i.e. one that includes\n  // dynamic data), because the bfcache stores data from navigations which\n  // always include dynamic data.\n\n  // We always use the canonical vary path when checking the bfcache. This is\n  // the same operation we'd use to access the cache during a\n  // regular navigation.\n  const varyPath = tree.varyPath\n\n  // Read from the BFCache without expiring it (pass -1). We check freshness\n  // ourselves using navigatedAt, because the BFCache's staleAt may have been\n  // overridden by a per-page unstable_dynamicStaleTime and can't be used to\n  // derive the original request time.\n  const bfcacheEntry = readFromBFCache(varyPath)\n  if (bfcacheEntry !== null) {\n    // The stale time for dynamic prefetches (default: 5 mins) is different\n    // from the stale time for regular navigations (default: 0 secs). Use\n    // navigatedAt to compute the correct expiry for prefetch purposes.\n    const dynamicPrefetchStaleAt =\n      bfcacheEntry.navigatedAt + STATIC_STALETIME_MS\n    if (now > dynamicPrefetchStaleAt) {\n      return null\n    }\n\n    const pendingSegment = upgradeToPendingSegment(segment, FetchStrategy.Full)\n    const isPartial = false\n    return fulfillSegmentCacheEntry(\n      pendingSegment,\n      bfcacheEntry.rsc,\n      dynamicPrefetchStaleAt,\n      isPartial,\n      // bfcache data is concrete, never an ISR fallback.\n      false,\n      FetchStrategy.Full\n    )\n  }\n  return null\n}\n\n/**\n * Attempts to replace an existing segment cache entry with data from the\n * bfcache. Unlike `attemptToFulfillDynamicSegmentFromBFCache` (which fills an\n * empty entry), this creates a new entry and upserts it, so it works even when\n * the segment is already fulfilled.\n */\nexport function attemptToUpgradeSegmentFromBFCache(\n  now: number,\n  // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).\n  map: CacheMap<SegmentCacheEntry>,\n  tree: RouteTree\n): FulfilledSegmentCacheEntry | null {\n  const varyPath = tree.varyPath\n  const bfcacheEntry = readFromBFCache(varyPath)\n  if (bfcacheEntry !== null) {\n    const dynamicPrefetchStaleAt =\n      bfcacheEntry.navigatedAt + STATIC_STALETIME_MS\n    if (now > dynamicPrefetchStaleAt) {\n      return null\n    }\n    const pendingSegment = upgradeToPendingSegment(\n      createDetachedSegmentCacheEntry(now),\n      FetchStrategy.Full\n    )\n    const isPartial = false\n    const newEntry = fulfillSegmentCacheEntry(\n      pendingSegment,\n      bfcacheEntry.rsc,\n      dynamicPrefetchStaleAt,\n      isPartial,\n      // bfcache data is concrete, never an ISR fallback.\n      false,\n      FetchStrategy.Full\n    )\n    const segmentVaryPath = getSegmentVaryPathForRequest(\n      FetchStrategy.Full,\n      tree\n    )\n    const upserted = upsertSegmentEntry(\n      now,\n      map,\n      segmentVaryPath,\n      newEntry,\n      // The concrete lookup path this BFCache upgrade applies to. (In\n      // practice a Full request path is already fully concrete, so nothing\n      // can shadow the new entry and the shadow check is a no-op.)\n      tree.varyPath\n    )\n    if (upserted !== null && upserted.status === EntryStatus.Fulfilled) {\n      return upserted\n    }\n  }\n  return null\n}\n\nfunction pingBlockedTasks(entry: {\n  blockedTasks: Set<PrefetchTask> | null\n}): void {\n  const blockedTasks = entry.blockedTasks\n  if (blockedTasks !== null) {\n    for (const task of blockedTasks) {\n      pingPrefetchTask(task)\n    }\n    entry.blockedTasks = null\n  }\n}\n\nexport function createMetadataRouteTree(\n  metadataVaryPath: PageVaryPath\n): RouteTree {\n  // The Head is not actually part of the route tree, but other than that, it's\n  // fetched and cached like a segment. Some functions expect a RouteTree\n  // object, so rather than fork the logic in all those places, we use this\n  // \"fake\" one.\n  const metadata: RouteTree = {\n    requestKey: HEAD_REQUEST_KEY,\n    segment: HEAD_REQUEST_KEY,\n    shellVaryPath: getShellSegmentVaryPath(metadataVaryPath),\n    refreshState: null,\n    varyPath: metadataVaryPath,\n    // The metadata isn't really a \"page\" (though it isn't really a \"segment\"\n    // either) but for the purposes of how this field is used, it behaves like\n    // one. If this logic ever gets more complex we can change this to an enum.\n    isPage: true,\n    slots: null,\n    prefetchHints: 0,\n  }\n  return metadata\n}\n\nexport function fulfillRouteCacheEntry(\n  now: number,\n  entry: PendingRouteCacheEntry,\n  tree: RouteTree,\n  metadataVaryPath: PageVaryPath,\n  couldBeIntercepted: boolean,\n  canonicalUrl: string,\n  supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n  // Get the rendered search from the vary path\n  const renderedSearch =\n    getRenderedSearchFromVaryPath(metadataVaryPath) ?? ('' as NormalizedSearch)\n  const fulfilledEntry: FulfilledRouteCacheEntry = entry as any\n  fulfilledEntry.status = EntryStatus.Fulfilled\n  fulfilledEntry.tree = tree\n  fulfilledEntry.metadata = createMetadataRouteTree(metadataVaryPath)\n  // Route structure is essentially static — it only changes on deploy.\n  // Always use the static stale time.\n  // NOTE: An exception is rewrites/redirects in middleware or proxy, which can\n  // change routes dynamically. We have other strategies for handling those.\n  //\n  // If the route tree has stale inlining hints (e.g. the initial RSC payload\n  // for a build-time static page, generated before collectPrefetchHints ran),\n  // immediately expire the entry so it gets re-fetched with correct hints.\n  // The segment data itself is still valid — only the route tree (which\n  // contains the hint bits) needs to be re-fetched.\n  if (tree.prefetchHints & PrefetchHint.InliningHintsStale) {\n    fulfilledEntry.staleAt = -1\n  } else {\n    fulfilledEntry.staleAt = now + STATIC_STALETIME_MS\n  }\n  fulfilledEntry.couldBeIntercepted = couldBeIntercepted\n  fulfilledEntry.canonicalUrl = canonicalUrl\n  fulfilledEntry.renderedSearch = renderedSearch\n  fulfilledEntry.supportsPerSegmentPrefetching = supportsPerSegmentPrefetching\n  fulfilledEntry.hasDynamicRewrite = false\n  pingBlockedTasks(entry)\n  return fulfilledEntry\n}\n\nexport function writeRouteIntoCache(\n  now: number,\n  pathname: NormalizedPathname,\n  search: NormalizedSearch,\n  nextUrl: string | null,\n  tree: RouteTree,\n  metadataVaryPath: PageVaryPath,\n  couldBeIntercepted: boolean,\n  canonicalUrl: string,\n  supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n  const pendingEntry = createDetachedRouteCacheEntry()\n  const fulfilledEntry = fulfillRouteCacheEntry(\n    now,\n    pendingEntry,\n    tree,\n    metadataVaryPath,\n    couldBeIntercepted,\n    canonicalUrl,\n    supportsPerSegmentPrefetching\n  )\n  const varyPath = getFulfilledRouteVaryPath(\n    pathname,\n    search,\n    nextUrl as NormalizedNextUrl | null,\n    couldBeIntercepted\n  )\n  const isRevalidation = false\n  setInCacheMap(routeCacheMap, varyPath, fulfilledEntry, isRevalidation)\n  return fulfilledEntry\n}\n\n/**\n * Marks a route cache entry as having a dynamic rewrite. Called when we\n * discover that a route pattern has dynamic rewrite behavior - i.e., we used\n * an optimistic route tree for prediction, but the server responded with a\n * different rendered pathname.\n *\n * Once marked, attempts to use this entry as a template for prediction will\n * bail out to server resolution.\n */\nexport function markRouteEntryAsDynamicRewrite(\n  entry: FulfilledRouteCacheEntry\n): void {\n  entry.hasDynamicRewrite = true\n  // Note: The caller is responsible for also calling invalidateRouteCacheEntries\n  // to invalidate other entries that may have been derived from this template\n  // before we knew it had a dynamic rewrite.\n}\n\nfunction fulfillSegmentCacheEntry(\n  segmentCacheEntry: PendingSegmentCacheEntry,\n  rsc: React.ReactNode,\n  staleAt: number,\n  isPartial: boolean,\n  // Only static (per-segment PPR) responses can be ISR fallbacks; all other\n  // callers pass false. Always assigned (even when false) so that re-fulfilling\n  // a previously-fallback entry with a concrete response clears the flag and\n  // ends the retry loop.\n  isUpgradeableISRFallback: boolean,\n  // The strategy tier describing the CONTENT this entry is fulfilled with —\n  // which comes from the response, not the tier the entry was requested at.\n  // Usually the two agree, but when a response's shell payload IS the full\n  // response (no shell/full split), shell-spawned entries are fulfilled with\n  // full-tier content and recorded as such (see the promotion in\n  // writeSegmentBundleResponse). Always assigned, replacing\n  // the spawn-time strategy set by upgradeToPendingSegment; the write walks'\n  // matching and keying decisions all happen against the spawn-time\n  // strategy, before fulfillment, so they are unaffected. See\n  // SegmentCacheEntryShared['fetchStrategy'].\n  fetchStrategy: FetchStrategy\n): FulfilledSegmentCacheEntry {\n  const fulfilledEntry: FulfilledSegmentCacheEntry = segmentCacheEntry as any\n  fulfilledEntry.status = EntryStatus.Fulfilled\n  fulfilledEntry.rsc = rsc\n  fulfilledEntry.staleAt = staleAt\n  fulfilledEntry.isPartial = isPartial\n  fulfilledEntry.isUpgradeableISRFallback = isUpgradeableISRFallback\n  fulfilledEntry.fetchStrategy = fetchStrategy\n  // Resolve any listeners that were waiting for this data.\n  if (segmentCacheEntry.promise !== null) {\n    segmentCacheEntry.promise.resolve(fulfilledEntry)\n    // Free the promise for garbage collection.\n    fulfilledEntry.promise = null\n  }\n  pingBlockedTasks(segmentCacheEntry)\n  return fulfilledEntry\n}\n\nfunction rejectRouteCacheEntry(\n  entry: PendingRouteCacheEntry,\n  staleAt: number\n): void {\n  const rejectedEntry: RejectedRouteCacheEntry = entry as any\n  rejectedEntry.status = EntryStatus.Rejected\n  rejectedEntry.staleAt = staleAt\n  pingBlockedTasks(entry)\n}\n\nfunction rejectSegmentCacheEntry(\n  entry: PendingSegmentCacheEntry,\n  staleAt: number\n): void {\n  const rejectedEntry: RejectedSegmentCacheEntry = entry as any\n  rejectedEntry.status = EntryStatus.Rejected\n  rejectedEntry.staleAt = staleAt\n  if (entry.promise !== null) {\n    // NOTE: We don't currently propagate the reason the prefetch was canceled\n    // but we could by accepting a `reason` argument.\n    entry.promise.resolve(null)\n    entry.promise = null\n  }\n  pingBlockedTasks(entry)\n}\n\ntype RouteTreeAccumulator = {\n  metadataVaryPath: PageVaryPath | null\n  // Whether the decoded tree's segment identities diverged from the base\n  // tree it was overlaid onto. See NavigationSeed.treeDivergedFromBase.\n  treeDivergedFromBase: boolean\n}\n\nfunction convertRootTreePrefetchToRouteTree(\n  rootTree: RootTreePrefetch,\n  renderedPathname: string,\n  renderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n) {\n  // Remove trailing and leading slashes\n  const pathnameParts = splitPathnameIntoParts(renderedPathname)\n  const index = 0\n  const rootSegment = ROOT_SEGMENT_REQUEST_KEY\n  return convertTreePrefetchToRouteTree(\n    rootTree.tree,\n    rootSegment,\n    null,\n    ROOT_SEGMENT_REQUEST_KEY,\n    pathnameParts,\n    index,\n    renderedSearch,\n    acc\n  )\n}\n\nfunction convertTreePrefetchToRouteTree(\n  prefetch: TreePrefetch,\n  segment: FlightRouterStateSegment,\n  partialVaryPath: PartialSegmentVaryPath | null,\n  requestKey: SegmentRequestKey,\n  pathnameParts: Array<string>,\n  pathnamePartsIndex: number,\n  renderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n): RouteTree {\n  // Converts the route tree sent by the server into the format used by the\n  // cache. The cached version of the tree includes additional fields, such as a\n  // cache key for each segment. Since this is frequently accessed, we compute\n  // it once instead of on every access. This same cache key is also used to\n  // request the segment from the server.\n\n  let slots: Map<string, RouteTree> | null = null\n  let isPage: boolean\n  let varyPath: SegmentVaryPath\n  const prefetchSlots = prefetch.slots\n  if (prefetchSlots !== null) {\n    isPage = false\n    varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n\n    slots = new Map()\n    for (let parallelRouteKey in prefetchSlots) {\n      const childPrefetch = prefetchSlots[parallelRouteKey]\n      const childSegmentName = childPrefetch.name\n      const childParam = childPrefetch.param\n\n      let childDoesAppearInURL: boolean\n      let childSegment: FlightRouterStateSegment\n      let childPartialVaryPath: PartialSegmentVaryPath | null\n      if (childParam !== null) {\n        // This segment is parameterized. Get the param from the pathname.\n        const childParamValue = parseDynamicParamFromURLPart(\n          childParam.type,\n          pathnameParts,\n          pathnamePartsIndex\n        )\n\n        // Assign a cache key to the segment, based on the param value. In the\n        // pre-Segment Cache implementation, the server computes this and sends\n        // it in the body of the response. In the Segment Cache implementation,\n        // the server sends an empty string and we fill it in here.\n\n        // TODO: We're intentionally not adding the search param to page\n        // segments here; it's tracked separately and added back during a read.\n        // This would clearer if we waited to construct the segment until it's\n        // read from the cache, since that's effectively what we're\n        // doing anyway.\n        const childParamKey =\n          // The server omits this field from the prefetch response when\n          // cacheComponents is enabled.\n          childParam.key !== null\n            ? childParam.key\n            : // If no param key was sent, use the value parsed on the client.\n              getCacheKeyForDynamicParam(\n                childParamValue,\n                '' as NormalizedSearch\n              )\n\n        childPartialVaryPath = appendLayoutVaryPath(\n          partialVaryPath,\n          childParamKey,\n          childSegmentName,\n          // The child's param is a root param iff the child segment is at or\n          // above the root layout, which the server marks directly.\n          (childPrefetch.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n        )\n        childSegment = [\n          childSegmentName,\n          childParamKey,\n          childParam.type,\n          childParam.siblings,\n        ]\n        childDoesAppearInURL = true\n      } else {\n        // This segment does not have a param. Inherit the partial vary path of\n        // the parent.\n        childPartialVaryPath = partialVaryPath\n        childSegment = childSegmentName\n        childDoesAppearInURL = doesStaticSegmentAppearInURL(childSegmentName)\n      }\n\n      // Only increment the index if the segment appears in the URL. If it's a\n      // \"virtual\" segment, like a route group, it remains the same.\n      const childPathnamePartsIndex = childDoesAppearInURL\n        ? pathnamePartsIndex + 1\n        : pathnamePartsIndex\n\n      const childRequestKeyPart = createSegmentRequestKeyPart(childSegment)\n      const childRequestKey = appendSegmentRequestKeyPart(\n        requestKey,\n        parallelRouteKey,\n        childRequestKeyPart\n      )\n      slots.set(\n        parallelRouteKey,\n        convertTreePrefetchToRouteTree(\n          childPrefetch,\n          childSegment,\n          childPartialVaryPath,\n          childRequestKey,\n          pathnameParts,\n          childPathnamePartsIndex,\n          renderedSearch,\n          acc\n        )\n      )\n    }\n  } else {\n    if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n      // This is a page segment.\n      isPage = true\n      varyPath = finalizePageVaryPath(\n        requestKey,\n        renderedSearch,\n        partialVaryPath\n      )\n      // The metadata \"segment\" is not part the route tree, but it has the same\n      // conceptual params as a page segment. Write the vary path into the\n      // accumulator object. If there are multiple parallel pages, we use the\n      // first one. Which page we choose is arbitrary as long as it's\n      // consistently the same one every time every time. See\n      // finalizeMetadataVaryPath for more details.\n      if (acc.metadataVaryPath === null) {\n        acc.metadataVaryPath = finalizeMetadataVaryPath(\n          requestKey,\n          renderedSearch,\n          partialVaryPath\n        )\n      }\n    } else {\n      // This is a layout segment.\n      isPage = false\n      varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n    }\n  }\n\n  return {\n    requestKey,\n    segment,\n    shellVaryPath: getShellSegmentVaryPath(varyPath),\n    refreshState: null,\n    // TODO: Cheating the type system here a bit because TypeScript can't tell\n    // that the type of isPage and varyPath are consistent. The fix would be to\n    // create separate constructors and call the appropriate one from each of\n    // the branches above. Just seems a bit overkill only for one field so I'll\n    // leave it as-is for now. If isPage were wrong it would break the behavior\n    // and we'd catch it quickly, anyway.\n    varyPath: varyPath as any,\n    isPage: isPage as boolean as any,\n    slots,\n    prefetchHints: prefetch.prefetchHints,\n  }\n}\n\nexport function convertRootFlightRouterStateToRouteTree(\n  flightRouterState: FlightRouterState,\n  renderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n): RouteTree {\n  return convertFlightRouterStateToRouteTree(\n    flightRouterState,\n    ROOT_SEGMENT_REQUEST_KEY,\n    null,\n    renderedSearch,\n    acc\n  )\n}\n\nexport function convertReusedFlightRouterStateToRouteTree(\n  parentRouteTree: RouteTree,\n  parallelRouteKey: string,\n  flightRouterState: FlightRouterState,\n  renderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n) {\n  // Create a RouteTree for a FlightRouterState that was reused from an older\n  // route. This happens during a navigation when a parallel route slot does not\n  // match the target route; we reuse whatever slot was already active.\n\n  // Unlike a FlightRouterState, the RouteTree type contains backreferences to\n  // the parent segments. Append the vary path to the parent's vary path.\n  const parentPartialVaryPath = parentRouteTree.isPage\n    ? getPartialPageVaryPath(parentRouteTree.varyPath)\n    : getPartialLayoutVaryPath(parentRouteTree.varyPath)\n  const segment = flightRouterState[0]\n  // And the request key.\n  const parentRequestKey = parentRouteTree.requestKey\n  const requestKeyPart = createSegmentRequestKeyPart(segment)\n  const requestKey = appendSegmentRequestKeyPart(\n    parentRequestKey,\n    parallelRouteKey,\n    requestKeyPart\n  )\n  return convertFlightRouterStateToRouteTree(\n    flightRouterState,\n    requestKey,\n    parentPartialVaryPath,\n    renderedSearch,\n    acc\n  )\n}\n\nfunction convertFlightRouterStateToRouteTree(\n  flightRouterState: FlightRouterState,\n  requestKey: SegmentRequestKey,\n  parentPartialVaryPath: PartialSegmentVaryPath | null,\n  parentRenderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n): RouteTree {\n  const originalSegment = flightRouterState[0]\n\n  // This segment's param (if any) is a root param iff the segment is at or\n  // above the root layout, which the server marks directly.\n  const isRootParam =\n    ((flightRouterState[4] ?? 0) & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n  // If the FlightRouterState has a refresh state, then this segment is part of\n  // an inactive parallel route. It has a different rendered search query than\n  // the outer parent route. In order to construct the inactive route correctly,\n  // we must restore the query that was originally used to render it.\n  const compressedRefreshState = flightRouterState[2] ?? null\n  const refreshState =\n    compressedRefreshState !== null\n      ? {\n          canonicalUrl: compressedRefreshState[0] as string,\n          renderedSearch: compressedRefreshState[1] as NormalizedSearch,\n        }\n      : null\n  const renderedSearch =\n    refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch\n\n  let segment: FlightRouterStateSegment\n  let partialVaryPath: PartialSegmentVaryPath | null\n  let isPage: boolean\n  let varyPath: SegmentVaryPath\n  if (Array.isArray(originalSegment)) {\n    isPage = false\n    const paramCacheKey = originalSegment[1]\n    const paramName = originalSegment[0]\n    partialVaryPath = appendLayoutVaryPath(\n      parentPartialVaryPath,\n      paramCacheKey,\n      paramName,\n      isRootParam\n    )\n    varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n    segment = originalSegment\n  } else {\n    // This segment does not have a param. Inherit the partial vary path of\n    // the parent.\n    partialVaryPath = parentPartialVaryPath\n    if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n      // This is a page segment.\n      isPage = true\n\n      // The navigation implementation expects the search params to be included\n      // in the segment. However, in the case of a static response, the search\n      // params are omitted. So the client needs to add them back in when reading\n      // from the Segment Cache.\n      //\n      // For consistency, we'll do this for dynamic responses, too.\n      //\n      // TODO: We should move search params out of FlightRouterState and handle\n      // them entirely on the client, similar to our plan for dynamic params.\n      segment = PAGE_SEGMENT_KEY\n      varyPath = finalizePageVaryPath(\n        requestKey,\n        renderedSearch,\n        partialVaryPath\n      )\n      // The metadata \"segment\" is not part the route tree, but it has the same\n      // conceptual params as a page segment. Write the vary path into the\n      // accumulator object. If there are multiple parallel pages, we use the\n      // first one. Which page we choose is arbitrary as long as it's\n      // consistently the same one every time every time. See\n      // finalizeMetadataVaryPath for more details.\n      if (acc.metadataVaryPath === null) {\n        acc.metadataVaryPath = finalizeMetadataVaryPath(\n          requestKey,\n          renderedSearch,\n          partialVaryPath\n        )\n      }\n    } else {\n      // This is a layout segment.\n      isPage = false\n      segment = originalSegment\n      varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n    }\n  }\n\n  let slots: Map<string, RouteTree> | null = null\n\n  const parallelRoutes = flightRouterState[1]\n  for (let parallelRouteKey in parallelRoutes) {\n    const childRouterState = parallelRoutes[parallelRouteKey]\n    const childSegment = childRouterState[0]\n    // TODO: Eventually, the param values will not be included in the response\n    // from the server. We'll instead fill them in on the client by parsing\n    // the URL. This is where we'll do that.\n    const childRequestKeyPart = createSegmentRequestKeyPart(childSegment)\n    const childRequestKey = appendSegmentRequestKeyPart(\n      requestKey,\n      parallelRouteKey,\n      childRequestKeyPart\n    )\n    const childTree = convertFlightRouterStateToRouteTree(\n      childRouterState,\n      childRequestKey,\n      partialVaryPath,\n      renderedSearch,\n      acc\n    )\n    if (slots === null) {\n      slots = new Map()\n    }\n    slots.set(parallelRouteKey, childTree)\n  }\n\n  return {\n    requestKey,\n    segment,\n    shellVaryPath: getShellSegmentVaryPath(varyPath),\n    refreshState,\n    // TODO: Cheating the type system here a bit because TypeScript can't tell\n    // that the type of isPage and varyPath are consistent. The fix would be to\n    // create separate constructors and call the appropriate one from each of\n    // the branches above. Just seems a bit overkill only for one field so I'll\n    // leave it as-is for now. If isPage were wrong it would break the behavior\n    // and we'd catch it quickly, anyway.\n    varyPath: varyPath as any,\n    isPage: isPage as boolean as any,\n    slots,\n    prefetchHints: flightRouterState[4] ?? 0,\n  }\n}\n\nexport function convertRouteTreeToFlightRouterState(\n  routeTree: RouteTree\n): FlightRouterState {\n  const parallelRoutes: Record<string, FlightRouterState> = {}\n  const slots = routeTree.slots\n  if (slots !== null) {\n    for (const [parallelRouteKey, childTree] of slots) {\n      parallelRoutes[parallelRouteKey] =\n        convertRouteTreeToFlightRouterState(childTree)\n    }\n  }\n  const flightRouterState: FlightRouterState = [\n    routeTree.segment,\n    parallelRoutes,\n    null,\n    null,\n  ]\n  if (routeTree.prefetchHints !== 0) {\n    flightRouterState[4] = routeTree.prefetchHints\n  }\n  return flightRouterState\n}\n\nexport async function fetchRouteOnCacheMiss(\n  entry: PendingRouteCacheEntry,\n  key: RouteCacheKey,\n  // The spawning task's `PrefetchTask.segmentCacheMap`, for the legacy\n  // branch that writes segment data included in the tree response.\n  map: CacheMap<SegmentCacheEntry>\n): Promise<PrefetchSubtaskResult<null> | null> {\n  // This function is allowed to use async/await because it contains the actual\n  // fetch that gets issued on a cache miss. Notice it writes the result to the\n  // cache entry directly, rather than return data that is then written by\n  // the caller.\n  const pathname = key.pathname\n  const search = key.search\n  const nextUrl = key.nextUrl\n  const segmentPath = '/_tree' as SegmentRequestKey\n\n  const headers: RequestHeaders = {\n    [RSC_HEADER]: '1',\n    [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n    [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: segmentPath,\n  }\n  if (nextUrl !== null) {\n    headers[NEXT_URL] = nextUrl\n  }\n\n  try {\n    const url = new URL(pathname + search, location.origin)\n    let response\n    let urlAfterRedirects\n    if (isOutputExportMode) {\n      // In output: \"export\" mode, we can't use headers to request a particular\n      // segment. Instead, we encode the extra request information into the URL.\n      // This is not part of the \"public\" interface of the app; it's an internal\n      // Next.js implementation detail that the app developer should not need to\n      // concern themselves with.\n      //\n      // For example, to request a segment:\n      //\n      //   Path passed to <Link>:   /path/to/page\n      //   Path passed to fetch:    /path/to/page/__next-segments/_tree\n      //\n      //   (This is not the exact protocol, just an illustration.)\n      //\n      // Before we do that, though, we need to account for redirects. Even in\n      // output: \"export\" mode, a proxy might redirect the page to a different\n      // location, but we shouldn't assume or expect that they also redirect all\n      // the segment files, too.\n      //\n      // To check whether the page is redirected, previously we perform a range\n      // request of 64 bytes of the HTML document to check if the target page\n      // is part of this app (by checking if build id matches). Only if the target\n      // page is part of this app do we determine the final canonical URL.\n      //\n      // However, as mentioned in https://github.com/vercel/next.js/pull/85903,\n      // some popular static hosting providers (like Cloudflare Pages or Render.com)\n      // do not support range requests, in the worst case, the entire HTML instead\n      // of 64 bytes could be returned, which is wasteful.\n      //\n      // So instead, we drops the check for build id here, and simply perform\n      // a HEAD request to rejects 1xx/4xx/5xx responses, and then determine the\n      // final URL after redirects.\n      //\n      // NOTE: We could embed the route tree into the HTML document, to avoid\n      // a second request. We're not doing that currently because it would make\n      // the HTML document larger and affect normal page loads.\n      const headResponse = await fetch(url, {\n        method: 'HEAD',\n      })\n      if (headResponse.status < 200 || headResponse.status >= 400) {\n        // The target page responded w/o a successful status code\n        // Could be a WAF serving a 403, or a 5xx from a backend\n        //\n        // Note that we can't use headResponse.ok here, because\n        // Response#ok returns `false` with 3xx responses.\n        rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n        return null\n      }\n\n      urlAfterRedirects = headResponse.redirected\n        ? new URL(headResponse.url)\n        : url\n\n      response = await fetchPrefetchResponse(\n        addSegmentPathToUrlInOutputExportMode(urlAfterRedirects, segmentPath),\n        headers\n      )\n    } else {\n      // \"Server\" mode. We can use request headers instead of the pathname.\n      // TODO: The eventual plan is to get rid of our custom request headers and\n      // encode everything into the URL, using a similar strategy to the\n      // \"output: export\" block above.\n      response = await fetchPrefetchResponse(url, headers)\n      urlAfterRedirects =\n        response !== null && response.redirected ? new URL(response.url) : url\n    }\n\n    if (!response || !response.ok || !response.body) {\n      // Server responded with an error, or with a miss. We should still cache\n      // the response, but we can try again after 10 seconds.\n      rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n      return null\n    }\n\n    // TODO: The canonical URL is the href without the origin. I think\n    // historically the reason for this is because the initial canonical URL\n    // gets passed as a prop to the top-level React component, which means it\n    // needs to be computed during SSR. If it were to include the origin, it\n    // would need to always be same as location.origin on the client, to prevent\n    // a hydration mismatch. To sidestep this complexity, we omit the origin.\n    //\n    // However, since this is neither a native URL object nor a fully qualified\n    // URL string, we need to be careful about how we use it. To prevent subtle\n    // mistakes, we should create a special type for it, instead of just string.\n    // Or, we should just use a (readonly) URL object instead. The type of the\n    // prop that we pass to seed the initial state does not need to be the same\n    // type as the state itself.\n    const canonicalUrl = createHrefFromUrl(urlAfterRedirects)\n\n    // Check whether the response varies based on the Next-Url header.\n    const varyHeader = response.headers.get('vary')\n    const couldBeIntercepted =\n      varyHeader !== null && varyHeader.includes(NEXT_URL)\n\n    // TODO: The `closed` promise was originally used to track when a streaming\n    // network connection closes, so the scheduler could limit concurrent\n    // connections. Now that prefetch responses are buffered, `closed` is\n    // resolved immediately after buffering — before the outer function even\n    // returns. This mechanism is only still meaningful for dynamic (Full)\n    // prefetches, which use incremental streaming. Consider removing the\n    // `closed` plumbing for buffered prefetch paths.\n    const closed = createPromiseWithResolvers<void>()\n\n    // This checks whether the response was served from the per-segment cache,\n    // rather than the old prefetching flow. If it fails, it implies that PPR\n    // is disabled on this route.\n    const routeIsPPREnabled =\n      response.headers.get(NEXT_DID_POSTPONE_HEADER) === '2' ||\n      // In output: \"export\" mode, we can't rely on response headers. But if we\n      // receive a well-formed response, we can assume it's a static response,\n      // because all data is static in this mode.\n      isOutputExportMode\n\n    if (routeIsPPREnabled) {\n      const { stream: prefetchStream, size: responseSize } =\n        await createNonTaskyPrefetchResponseStream(response.body)\n      closed.resolve()\n      setSizeInCacheMap(entry, responseSize)\n      const serverData = await createFromNextReadableStream<RootTreePrefetch>(\n        prefetchStream,\n        headers,\n        { allowPartialStream: true }\n      )\n\n      if (\n        (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n          serverData.buildId) !== getNavigationBuildId()\n      ) {\n        // The server build does not match the client. Treat as a 404. During\n        // an actual navigation, the router will trigger an MPA navigation.\n        // TODO: We should cache the fact that this is an MPA navigation.\n        rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n        return null\n      }\n\n      // Get the params that were used to render the target page. These may\n      // be different from the params in the request URL, if the page\n      // was rewritten.\n      const renderedPathname = getRenderedPathname(response)\n      const renderedSearch = getRenderedSearch(response)\n\n      // Convert the server-sent data into the RouteTree format used by the\n      // client cache.\n      //\n      // During this traversal, we accumulate additional data into this\n      // \"accumulator\" object.\n      const acc: RouteTreeAccumulator = {\n        metadataVaryPath: null,\n        treeDivergedFromBase: false,\n      }\n      const routeTree = convertRootTreePrefetchToRouteTree(\n        serverData,\n        renderedPathname,\n        renderedSearch,\n        acc\n      )\n      const metadataVaryPath = acc.metadataVaryPath\n      if (metadataVaryPath === null) {\n        rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n        return null\n      }\n\n      discoverKnownRoute(\n        Date.now(),\n        pathname,\n        search,\n        nextUrl,\n        entry,\n        routeTree,\n        metadataVaryPath,\n        couldBeIntercepted,\n        canonicalUrl,\n        routeIsPPREnabled,\n        false // hasDynamicRewrite\n      )\n    } else {\n      // PPR is not enabled for this route. The server responds with a\n      // different format (FlightRouterState) that we need to convert.\n      // TODO: We will unify the responses eventually. I'm keeping the types\n      // separate for now because FlightRouterState has so many\n      // overloaded concerns.\n      const { stream: prefetchStream, size: responseSize } =\n        await createNonTaskyPrefetchResponseStream(response.body)\n      closed.resolve()\n      setSizeInCacheMap(entry, responseSize)\n      const serverData =\n        await createFromNextReadableStream<NavigationFlightResponse>(\n          prefetchStream,\n          headers,\n          { allowPartialStream: true }\n        )\n\n      if (\n        (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n          serverData.b) !== getNavigationBuildId()\n      ) {\n        // The server build does not match the client. Treat as a 404. During\n        // an actual navigation, the router will trigger an MPA navigation.\n        // TODO: We should cache the fact that this is an MPA navigation.\n        rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n        return null\n      }\n\n      // Read head vary params synchronously (unioning in the response-level\n      // root params). Individual segments carry their own iterables in\n      // CacheNodeSeedData; the root iterable is threaded down so each segment\n      // unions it too.\n      const headVaryParams = readVaryParams(serverData.h, serverData.r)\n      writeDynamicTreeResponseIntoCache(\n        Date.now(),\n        // The non-PPR response format is what we'd get if we prefetched these segments\n        // using the LoadingBoundary fetch strategy, so mark their cache entries accordingly.\n        FetchStrategy.LoadingBoundary,\n        response as RSCResponse<NavigationFlightResponse>,\n        serverData,\n        entry,\n        couldBeIntercepted,\n        canonicalUrl,\n        routeIsPPREnabled,\n        headVaryParams,\n        serverData.r ?? null,\n        pathname,\n        search,\n        nextUrl,\n        map\n      )\n    }\n\n    if (!couldBeIntercepted) {\n      // This route will never be intercepted. So we can use this entry for all\n      // requests to this route, regardless of the Next-Url header. This works\n      // because when reading the cache we always check for a valid\n      // non-intercepted entry first.\n\n      // Re-key the entry. The `set` implementation handles removing it from\n      // its previous position in the cache. We don't need to do anything to\n      // update the LRU, because the entry is already in it.\n      // TODO: Treat this as an upsert — should check if an entry already\n      // exists at the new keypath, and if so, whether we should keep that\n      // one instead.\n      const fulfilledVaryPath: RouteVaryPath = getFulfilledRouteVaryPath(\n        pathname,\n        search,\n        nextUrl,\n        couldBeIntercepted\n      )\n      const isRevalidation = false\n      setInCacheMap(routeCacheMap, fulfilledVaryPath, entry, isRevalidation)\n    }\n    // Return a promise that resolves when the network connection closes, so\n    // the scheduler can track the number of concurrent network connections.\n    return { value: null, closed: closed.promise }\n  } catch (error) {\n    // Either the connection itself failed, or something bad happened while\n    // decoding the response. If we're offline, reject with staleAt=-1 so the\n    // entry immediately expires and gets retried once the scheduler is\n    // re-pinged after connectivity is restored.\n    if (process.env.__NEXT_USE_OFFLINE) {\n      const { checkOfflineError } =\n        require('../offline') as typeof import('../offline')\n      if (checkOfflineError(error)) {\n        // Unlike navigations and server actions, prefetches don't await\n        // waitForConnection — they just reject the cache entry with an\n        // immediate expiration so it gets retried once the scheduler is\n        // re-pinged after connectivity is restored.\n        rejectRouteCacheEntry(entry, -1)\n        return null\n      }\n    }\n    rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n    return null\n  }\n}\n\nfunction rejectRemainingSegmentsInBundle(\n  entries: SegmentBundle,\n  staleAt: number\n): void {\n  let node: SegmentBundle | null = entries\n  while (node !== null) {\n    if (node.entry !== null && node.entry.status === EntryStatus.Pending) {\n      rejectSegmentCacheEntry(node.entry as PendingSegmentCacheEntry, staleAt)\n    }\n    node = node.parent\n  }\n}\n\n// When a static (per-segment PPR) prefetch receives an upgradeable fallback\n// shell, the localized retry loop re-issues the same fetch after this delay to\n// pick up the concrete version once the server's background regeneration\n// finishes.\nconst FALLBACK_RETRY_DELAY_MS = 2000\n\n// Maximum number of fallback retries per task, to avoid looping indefinitely\n// if the server keeps returning a fallback (e.g. misconfiguration).\nconst MAX_FALLBACK_RETRIES = 3\n\nexport async function fetchSegmentsOnCacheMiss(\n  task: PrefetchTask,\n  route: FulfilledRouteCacheEntry,\n  routeKey: RouteCacheKey,\n  tree: RouteTree,\n  segments: SegmentBundle,\n  segmentCount: number,\n  // Which walk spawned the bundle's entries. The request on the wire is\n  // identical either way; this only decides which payload of the response\n  // fulfills the entries.\n  fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): Promise<PrefetchSubtaskResult<null> | null> {\n  // This function is allowed to use async/await because it contains the actual\n  // fetch that gets issued on a cache miss. Notice it writes the result to the\n  // cache entry directly, rather than return data that is then written by\n  // the caller.\n  //\n  // Segment fetches are non-blocking so we don't need to ping the scheduler\n  // on completion.\n  let result\n  try {\n    result = await fetchSegmentsOnCacheMissImpl(route, routeKey, tree)\n  } catch (error) {\n    // The connection failed, or the response couldn't be decoded. Reject the\n    // pending entries so they don't stay Pending forever, and get retried once\n    // the entry expires. If we're offline, expire immediately (-1) so the entry\n    // is re-fetched once the scheduler is re-pinged on reconnect; otherwise\n    // apply a 10s backoff. (Unlike navigations and server actions, prefetches\n    // don't await `waitForConnection`.)\n    let staleAt = Date.now() + 10 * 1000\n    if (process.env.__NEXT_USE_OFFLINE) {\n      const { checkOfflineError } =\n        require('../offline') as typeof import('../offline')\n      if (checkOfflineError(error)) {\n        staleAt = -1\n      }\n    }\n    rejectRemainingSegmentsInBundle(segments, staleAt)\n    return null\n  }\n\n  if (result === null) {\n    // The response was fetched but isn't usable yet (server error/miss, empty\n    // data, or a build-id mismatch — the server may be transiently unready).\n    // Reject with a short backoff so the entries are retried soon.\n    rejectRemainingSegmentsInBundle(segments, Date.now() + 10 * 1000)\n    return null\n  }\n\n  const { serverResponse, shellResponse, responseSize, closed } = result\n  const now = Date.now()\n\n  writeSegmentBundleResponseVariants(\n    task.segmentCacheMap,\n    serverResponse,\n    shellResponse,\n    responseSize,\n    segments,\n    segmentCount,\n    now,\n    fetchStrategy\n  )\n\n  // If the server served an upgradeable fallback shell, drive a localized\n  // retry loop to pick up the concrete version once the server's background\n  // regeneration finishes. Only the first such response per task starts a loop\n  // (`fallbackRetryStatus === Empty`); once it leaves Empty, no second loop is\n  // started — sibling bundle responses that also got a fallback don't, and\n  // neither does a re-hover.\n  if (\n    serverResponse.isUpgradeableISRFallback &&\n    task.fallbackRetryStatus === EntryStatus.Empty &&\n    !task.isCanceled\n  ) {\n    task.fallbackRetryStatus = EntryStatus.Pending\n    // Fire-and-forget: the loop drives itself via timers and pings the task\n    // on success.\n    void retryUpgradeableFallbackPrefetch(\n      task,\n      route,\n      routeKey,\n      tree,\n      segments,\n      segmentCount,\n      fetchStrategy\n    )\n  }\n\n  return {\n    value: null,\n    closed,\n  }\n}\n\n/**\n * Issues a single segment-bundle prefetch request, validates it, and decodes\n * the response. Returns the decoded response (see the return type below)\n * on success, or `null` if the response was fetched but isn't usable yet\n * (server error/miss, empty data, or a build-id mismatch — the server may be\n * transiently unready, so it's worth retrying). THROWS if the connection failed\n * or the response couldn't be decoded; re-issuing the identical request won't\n * fix that, so callers should give up rather than retry.\n *\n * This deliberately does NOT touch the cache — it neither writes the decoded\n * segments nor rejects entries. The caller decides what to do with the result:\n * write it (`fetchSegmentsOnCacheMiss`) or ignore it and try again (the retry\n * loop). Calling this again with the same arguments reproduces the exact same\n * request.\n */\nasync function fetchSegmentsOnCacheMissImpl(\n  route: FulfilledRouteCacheEntry,\n  routeKey: RouteCacheKey,\n  tree: RouteTree\n): Promise<{\n  serverResponse: SegmentPrefetchResponse\n  responseSize: number\n  // The shell payload of the response: `serverResponse` itself when the\n  // shell IS the full response (a fully static page — callers compare by\n  // reference), a second decode of the same bytes truncated at the shell\n  // byte boundary when the shell is a strict prefix, or `null` when no\n  // shell exists.\n  shellResponse: SegmentPrefetchResponse | null\n  closed: Promise<void>\n} | null> {\n  // Use the canonical URL to request the segment, not the original URL. These\n  // are usually the same, but the canonical URL will be different if the route\n  // tree response was redirected. To avoid an extra waterfall on every segment\n  // request, we pass the redirected URL instead of the original one.\n  const url = new URL(route.canonicalUrl, location.origin)\n  const nextUrl = routeKey.nextUrl\n\n  const requestKey = tree.requestKey\n  const normalizedRequestKey =\n    requestKey === ROOT_SEGMENT_REQUEST_KEY\n      ? // The root segment is a special case. To simplify the server-side\n        // handling of these requests, we encode the root segment path as\n        // `_index` instead of as an empty string. This should be treated as\n        // an implementation detail and not as a stable part of the protocol.\n        // It just needs to match the equivalent logic that happens when\n        // prerendering the responses. It should not leak outside of Next.js.\n        ('/_index' as SegmentRequestKey)\n      : requestKey\n\n  const headers: RequestHeaders = {\n    [RSC_HEADER]: '1',\n    [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n    [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: normalizedRequestKey,\n  }\n  if (nextUrl !== null) {\n    headers[NEXT_URL] = nextUrl\n  }\n\n  const requestUrl = isOutputExportMode\n    ? // In output: \"export\" mode, we need to add the segment path to the URL.\n      addSegmentPathToUrlInOutputExportMode(url, normalizedRequestKey)\n    : url\n\n  const response = await fetchPrefetchResponse(requestUrl, headers)\n  if (\n    !response ||\n    !response.ok ||\n    // This checks whether the response was served from the per-segment cache,\n    // rather than the old prefetching flow. If it fails, it implies that PPR\n    // is disabled on this route. Theoretically this should never happen\n    // because we only issue requests for segments once we've verified that\n    // the route supports PPR.\n    (response.headers.get(NEXT_DID_POSTPONE_HEADER) !== '2' &&\n      // In output: \"export\" mode, we can't rely on response headers. But if\n      // we receive a well-formed response, we can assume it's a static\n      // response, because all data is static in this mode.\n      !isOutputExportMode) ||\n    !response.body\n  ) {\n    // Server responded with an error or a miss — fetched but not usable.\n    return null\n  }\n\n  // See TODO in fetchRouteOnCacheMiss about removing `closed` for\n  // buffered prefetch paths.\n  const closed = createPromiseWithResolvers<void>()\n\n  const {\n    stream: prefetchStream,\n    size: responseSize,\n    buffer,\n  } = await createNonTaskyPrefetchResponseStream(response.body)\n  closed.resolve()\n\n  // Parse the response. Always a SegmentPrefetchResponse with a build ID and a\n  // data array. A connection drop or malformed stream throws here, which\n  // propagates to the caller as a non-retryable failure.\n  const serverResponse =\n    await createFromNextReadableStream<SegmentPrefetchResponse>(\n      prefetchStream,\n      headers,\n      { allowPartialStream: true }\n    )\n\n  if (serverResponse.data.length === 0) {\n    return null\n  }\n  if (\n    (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n      serverResponse.buildId) !== getNavigationBuildId()\n  ) {\n    // The server build does not match the client. Treat as a 404. During\n    // an actual navigation, the router will trigger an MPA navigation.\n    return null\n  }\n\n  // Extract the shell payload, if the response carries a distinct one\n  // (positive shell byte offset): decode the buffered bytes a SECOND time,\n  // truncated at the boundary. The truncation is what produces the shell\n  // variant: each segment's param-dependent rows land past the boundary and\n  // decode as still-pending, which renders as the param fallback. It also\n  // rewinds the response's signals — `needsRuntimeRequest` and `isPartial`\n  // fulfillments past the boundary read as pending in this decode, so a\n  // post-shell runtime-data access doesn't mark the shell variant itself as\n  // needing a runtime request.\n  // (The offset is never legitimately pending or 0 in this decode: the full\n  // buffer is present, and the server only ever emits a positive offset or\n  // null. Reading 0 — the default for an unfulfilled `a` — therefore means a\n  // bug in Next.js itself, and is handled like an error: the response is\n  // treated as carrying no shell, and the scheduler skips the affected\n  // segments rather than falling back to a runtime request — see the\n  // `shellResponse === null` handling in writeSegmentBundleResponseVariants.\n  // Failing in that direction costs a shell prefetch but never leaks\n  // post-shell content into shell positions.)\n  const shellOffset = readFulfilledValue(serverResponse.a, 0)\n  let shellResponse: SegmentPrefetchResponse | null\n  if (shellOffset === null) {\n    shellResponse = serverResponse\n  } else if (shellOffset === 0) {\n    shellResponse = null\n  } else {\n    try {\n      shellResponse = await decodeBufferedStage<SegmentPrefetchResponse>(\n        buffer.subarray(0, shellOffset),\n        headers\n      )\n    } catch {\n      // The truncated prefix couldn't be decoded. Treat it as if no shell\n      // exists; the full payload is still usable. (For a StaticShell-spawned\n      // bundle this means the spawned entries are rejected — the scheduler\n      // then skips them rather than issuing a runtime substitute; see the\n      // no-shell branch in fetchSegmentsOnCacheMiss.)\n      shellResponse = null\n    }\n  }\n\n  return {\n    serverResponse,\n    responseSize,\n    shellResponse,\n    closed: closed.promise,\n  }\n}\n\n/**\n * Writes every payload of a parsed segment-bundle response into the cache.\n * The bundle's entries are fulfilled by the payload matching the walk that\n * spawned them; the other payload, when distinct, is written with a detached\n * copy of the bundle. The full payload is written first so the shell write's\n * shadow eviction sees the fresh concrete entry.\n *\n * Shared by the initial fetch (`fetchSegmentsOnCacheMiss`) and the localized\n * fallback-retry loop. The retry's bundle entries are already settled, so\n * for that caller every write is a detached upsert and the rejection below\n * is a no-op (it only touches Pending entries).\n */\nfunction writeSegmentBundleResponseVariants(\n  // The map the bundle's entries live in (pinned when the request was\n  // spawned).\n  map: CacheMap<SegmentCacheEntry>,\n  serverResponse: SegmentPrefetchResponse,\n  shellResponse: SegmentPrefetchResponse | null,\n  responseSize: number,\n  segments: SegmentBundle,\n  segmentCount: number,\n  now: number,\n  // Which walk spawned the bundle's entries; decides which payload fulfills\n  // them. See fetchSegmentsOnCacheMiss.\n  fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): void {\n  if (fetchStrategy === FetchStrategy.StaticShell) {\n    if (shellResponse !== serverResponse) {\n      writeSegmentBundleResponse(\n        map,\n        serverResponse,\n        responseSize,\n        detachEntriesFromSegmentBundle(segments),\n        segmentCount,\n        now,\n        FetchStrategy.PPR,\n        FetchStrategy.PPR\n      )\n    }\n    if (shellResponse === null) {\n      // No shell exists. Reject the spawned entries so the task isn't\n      // stranded blocking on them. Note the scheduler does NOT fall back to\n      // a runtime request for rejected segments — it skips them outright (see\n      // the Rejected case in pingSegmentBundle in scheduler.ts), so these\n      // segments get no shell prefetch and no runtime substitute until the\n      // rejection's backoff expires.\n      rejectRemainingSegmentsInBundle(segments, now + 10 * 1000)\n    } else {\n      writeSegmentBundleResponse(\n        map,\n        shellResponse,\n        responseSize,\n        segments,\n        segmentCount,\n        now,\n        FetchStrategy.StaticShell,\n        // When the shell IS the full response (no shell/full split), the\n        // entries this write fulfills carry full-tier content, so PPR is the\n        // strategy that describes it.\n        shellResponse === serverResponse\n          ? FetchStrategy.PPR\n          : FetchStrategy.StaticShell\n      )\n    }\n  } else {\n    writeSegmentBundleResponse(\n      map,\n      serverResponse,\n      responseSize,\n      segments,\n      segmentCount,\n      now,\n      FetchStrategy.PPR,\n      FetchStrategy.PPR\n    )\n    if (shellResponse !== null && shellResponse !== serverResponse) {\n      writeSegmentBundleResponse(\n        map,\n        shellResponse,\n        responseSize,\n        detachEntriesFromSegmentBundle(segments),\n        segmentCount,\n        now,\n        FetchStrategy.StaticShell,\n        FetchStrategy.StaticShell\n      )\n    }\n  }\n}\n\n/**\n * Writes one payload of a parsed segment-bundle response into the cache:\n * distributes the response size across the bundle, then walks the segments\n * list and the response's `data` array in parallel, fulfilling/upserting\n * each entry. Any segments the server didn't return are rejected so they\n * don't stay Pending forever.\n *\n * `fetchStrategy` says which of the response's payloads this call is\n * writing — StaticShell for the shell payload, PPR for the full payload —\n * which determines the vary paths the entries are keyed at.\n *\n * The walk fulfills any Pending entry in `segments`, so the caller must\n * pass the bundle only to the walk matching the entries' own strategy, and\n * a detached copy to the other. In particular, fulfilling a spawned\n * StaticShell entry with the concrete payload would leak param-dependent\n * content into shell positions: during a navigation, a pending entry can be\n * rendered as a promise that resolves to its eventual value.\n *\n * Shared by the initial fetch and the localized fallback-retry loop (which\n * re-issues the same request and upserts the upgraded result here).\n */\nfunction writeSegmentBundleResponse(\n  map: CacheMap<SegmentCacheEntry>,\n  serverResponse: SegmentPrefetchResponse,\n  responseSize: number,\n  segments: SegmentBundle,\n  segmentCount: number,\n  now: number,\n  fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell,\n  // The strategy tier that describes this payload's CONTENT, recorded on\n  // the entries it fulfills. Differs from `fetchStrategy` (which drives\n  // matching and keying) in one case: a StaticShell write whose payload IS\n  // the full response (no shell/full split) records PPR — see\n  // writeSegmentBundleResponseVariants.\n  payloadFetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): void {\n  // Distribute the response size evenly across all segments in the bundle.\n  // (When a response produces two payload writes, each write distributes the\n  // full response size — intentionally double-charging the LRU for one wire\n  // response, since it produced two live entries per segment.)\n  const averageSize = responseSize / segmentCount\n  let sizeNode: SegmentBundle | null = segments\n  while (sizeNode !== null) {\n    if (sizeNode.entry !== null) {\n      setSizeInCacheMap(sizeNode.entry, averageSize)\n    }\n    sizeNode = sizeNode.parent\n  }\n\n  const serverDataArray = serverResponse.data\n\n  // True if the server served an upgradeable fallback shell (page not yet\n  // prerendered with concrete params, but the route can be upgraded). Applies\n  // to the whole response and is recorded on each fulfilled entry.\n  const responseIsUpgradeableISRFallback =\n    serverResponse.isUpgradeableISRFallback\n\n  // Whether the render that produced this payload accessed runtime data\n  // (page-global; combined with each segment's `isPartial` below to decide\n  // the tier each entry records). Read from THIS decode's thenable status,\n  // which scopes it to the payload being written — see\n  // `SegmentPrefetchResponse['needsRuntimeRequest']` for the encoding.\n  //\n  // Reading it from the same decode that produced the entry's data is what\n  // makes the answer rewindable: a truncated shell decode reads a post-shell\n  // runtime access as pending, i.e. `false`, because the shell variant itself\n  // doesn't need that data.\n  //\n  // It is load-bearing in one direction only. A false `true` costs a wasted\n  // runtime request; a false `false` would record too high a tier and skip a\n  // runtime request that had more content.\n  const responseNeedsRuntimeRequest = readFulfilledValue(\n    serverResponse.needsRuntimeRequest,\n    false\n  )\n\n  let node: SegmentBundle | null = segments\n  let dataIndex = 0\n  while (node !== null && dataIndex < serverDataArray.length) {\n    const data = serverDataArray[dataIndex]\n\n    // Null data means this segment has prefetching disabled\n    // (prefetch: 'force-disabled' — Partial Prefetching segments have static\n    // data, so the server emits a real slot for them). Skip it without\n    // creating a cache entry.\n    if (data === null || node.tree === null) {\n      // The server's and the client's prefetch-disabled hints normally agree,\n      // so there shouldn't be a spawned entry for a segment the server\n      // skipped. But if they disagree, a Pending entry that a task blocked on\n      // would otherwise never settle, stranding the task forever. Settle\n      // it defensively.\n      if (node.entry !== null && node.entry.status === EntryStatus.Pending) {\n        rejectSegmentCacheEntry(\n          node.entry as PendingSegmentCacheEntry,\n          now + 10 * 1000\n        )\n      }\n      node = node.parent\n      dataIndex++\n      continue\n    }\n\n    // The segment's late-resolving metadata can be read synchronously\n    // because the payload was fully buffered before it was decoded (and, for\n    // a truncated shell decode, delivered as a single chunk).\n    const entryStaleAt = readFulfilledStaleAt(now, data.staleTime)\n    // Root params are emitted once at the top level of the response and\n    // unioned into each segment's set here, same as for a route-level\n    // response.\n    const varyParams = readVaryParams(\n      data.varyParams,\n      serverResponse.rootVaryParams\n    )\n    const isPartial = readFulfilledIsPartial(data.isPartial)\n\n    // A runtime prefetch can only provide more content than this entry if the\n    // render accessed runtime data AND this particular segment has holes — a\n    // fully static segment gains nothing from a runtime request no matter\n    // what the page accessed.\n    const needsRuntimeRequest = responseNeedsRuntimeRequest && isPartial\n\n    // An entry records the tier of the content that actually satisfied it,\n    // which spans both axes: shell-vs-concrete AND static-vs-runtime.\n    //\n    // When this payload fully satisfied the segment — no runtime request\n    // needed — the content is as complete as a RUNTIME response of the same\n    // variant would have been, so it records that runtime tier. That's what\n    // lets the scheduler decide \"would a runtime request return more?\" by\n    // comparing tiers alone, with no separate signal to consult.\n    //\n    // Otherwise the content is only as complete as the static tier it was\n    // requested at, so a follow-up runtime request can still supersede it.\n    const recordedFetchStrategy = !needsRuntimeRequest\n      ? payloadFetchStrategy === FetchStrategy.StaticShell\n        ? FetchStrategy.RuntimeShell\n        : FetchStrategy.PPRRuntime\n      : fetchStrategy\n\n    // Key the entry by which params the server said this segment depends on.\n    // Reusing one copy across param values is the point of the shell, but it\n    // requires knowing the content doesn't depend on those params, and the\n    // server's report is the direct evidence of that.\n    //\n    // Without that report, assume every param varies. The exception is a\n    // shell variant, which reduces param-dependent content to param\n    // fallbacks, so it really is good for any value of them.\n    const payloadVaryPath =\n      process.env.__NEXT_VARY_PARAMS && varyParams !== null\n        ? getFulfilledSegmentVaryPath(node.tree.varyPath, varyParams)\n        : getSegmentVaryPathForRequest(payloadFetchStrategy, node.tree)\n\n    const nodeEntry = node.entry\n    if (nodeEntry !== null && nodeEntry.status === EntryStatus.Pending) {\n      // We own this entry — fulfill it directly.\n      const fulfilledEntry = fulfillSegmentCacheEntry(\n        nodeEntry as PendingSegmentCacheEntry,\n        data.rsc,\n        entryStaleAt,\n        isPartial,\n        responseIsUpgradeableISRFallback,\n        recordedFetchStrategy\n      )\n      // Move the entry to that key. This is load-bearing rather than a no-op:\n      // a task spawns its entries before it knows what the response will\n      // contain, so the key it guessed can be more reusable than the response\n      // turned out to deserve.\n      //\n      // Pass the concrete lookup path — the most specific path a read for\n      // this segment position would use — so that if the entry lands at a\n      // more generic key, a stale entry at a more specific one can't shadow\n      // it. See evictShadowingSegmentEntries. The upsert (rather than a bare\n      // set) applies the usual precedence rules, so a concurrent task's more\n      // complete response already in this slot isn't downgraded.\n      upsertSegmentEntry(\n        now,\n        map,\n        payloadVaryPath,\n        fulfilledEntry,\n        node.tree.varyPath\n      )\n    } else {\n      // We don't own this entry. Create a detached entry and attempt to\n      // upsert it into this payload's slot.\n      const detachedEntry = createDetachedSegmentCacheEntry(now)\n      const fulfilledEntry = fulfillSegmentCacheEntry(\n        upgradeToPendingSegment(detachedEntry, fetchStrategy),\n        data.rsc,\n        entryStaleAt,\n        isPartial,\n        responseIsUpgradeableISRFallback,\n        recordedFetchStrategy\n      )\n      upsertSegmentEntry(\n        now,\n        map,\n        payloadVaryPath,\n        fulfilledEntry,\n        node.tree.varyPath\n      )\n    }\n\n    node = node.parent\n    dataIndex++\n  }\n\n  // If the server returned fewer segments than expected, reject any\n  // remaining pending entries so they don't stay Pending forever.\n  if (node !== null) {\n    rejectRemainingSegmentsInBundle(node, now + 10 * 1000)\n  }\n}\n\n/**\n * Clones a SegmentBundle chain with every `entry` removed, so a write walk\n * over it is pure detached upserts. Used for the payload that does NOT\n * match the bundle's spawned entries (see writeSegmentBundleResponse).\n */\nfunction detachEntriesFromSegmentBundle(\n  segments: SegmentBundle\n): SegmentBundle {\n  const head: SegmentBundle = {\n    tree: segments.tree,\n    entry: null,\n    parent: null,\n  }\n  let clonedTail = head\n  let node = segments.parent\n  while (node !== null) {\n    const clonedNode: SegmentBundle = {\n      tree: node.tree,\n      entry: null,\n      parent: null,\n    }\n    clonedTail.parent = clonedNode\n    clonedTail = clonedNode\n    node = node.parent\n  }\n  return head\n}\n\n// TODO: Consolidate the read* helpers below with the ones in\n// vary-params-decoding — they all perform a version of the same synchronous\n// read of a buffered decode's late-resolving values.\n\n/**\n * Reads a segment's partialness from its `isPartial` promise. (Unlike the\n * values read via `readFulfilledValue` below, the fulfillment value here is\n * void — partialness is encoded as the ABSENCE of a fulfillment.) The server\n * fulfills it only for a fully-static segment and leaves it pending for a\n * partial one (see `SegmentPrefetch['isPartial']`), so partial == not\n * fulfilled. The read is synchronous because the response is fully buffered\n * before it's decoded, so a fulfillment is already visible on the thenable's\n * status — the same trick `readVaryParams` uses for the vary params iterables.\n */\nfunction readFulfilledIsPartial(isPartial: Promise<void>): boolean {\n  const thenable = isPartial as PromiseLike<void> & { status?: string }\n  // Force Flight to unwrap a received-but-not-yet-settled row. A pending row,\n  // or a truncated shell decode whose fulfillment landed past the boundary,\n  // stays non-fulfilled — read as partial, which is correct either way.\n  thenable.then(noop, noop)\n  return thenable.status !== 'fulfilled'\n}\n\n/**\n * Reads a late-resolving value off a fully-buffered decode's thenable status,\n * using the same trick as above. Returns `valueIfUnresolved` for a row that\n * is pending or absent in this decode — e.g. one whose fulfillment landed\n * past a truncated shell decode's boundary. That's what scopes a response's\n * late-resolving signals to the payload being decoded.\n */\nfunction readFulfilledValue<T>(\n  valueFromServer: Promise<T>,\n  valueIfUnresolved: T\n): T {\n  const thenable = valueFromServer as PromiseLike<T> & {\n    status?: string\n    value?: T\n  }\n  // Force Flight to unwrap a received-but-not-yet-settled row.\n  thenable.then(noop, noop)\n  if (thenable.status === 'fulfilled' && thenable.value !== undefined) {\n    return thenable.value\n  }\n  return valueIfUnresolved\n}\n\n/**\n * Reads a stale-at time from the staleTime async iterable of a fully-buffered\n * response — segment bundles and stage decodes, which go through\n * `createNonTaskyPrefetchResponseStream`. Because the bytes are all present,\n * each yielded value is already visible on its chunk's thenable status (the\n * same trick `readVaryParams` uses), so this drains synchronously and takes\n * the last value (the final staleTime, as `resolveStaleAt` does for the\n * async case). A missing iterable, or a truncated shell decode whose value\n * landed past the boundary, reads as absent and falls back to the static\n * stale time.\n *\n * For the one response kind that isn't buffered when read — a dynamic `Full`\n * response (fetchStrategy.Full with Partial Prefetching disabled) — use\n * `resolveStaleAt` instead, since its values aren't materialized synchronously.\n */\nfunction readFulfilledStaleAt(\n  now: number,\n  staleTime: AsyncIterable<number> | undefined\n): number {\n  if (staleTime === undefined) {\n    return now + STATIC_STALETIME_MS\n  }\n  const iterator = staleTime[Symbol.asyncIterator]()\n  let staleTimeSeconds: number | undefined\n  while (true) {\n    const chunk = iterator.next() as PromiseLike<IteratorResult<number>> & {\n      status?: string\n      value?: IteratorResult<number>\n    }\n    chunk.then(noop, noop)\n    if (chunk.status !== 'fulfilled' || chunk.value === undefined) {\n      break\n    }\n    if (chunk.value.done) {\n      break\n    }\n    staleTimeSeconds = chunk.value.value\n  }\n  if (staleTimeSeconds === undefined || isNaN(staleTimeSeconds)) {\n    return now + STATIC_STALETIME_MS\n  }\n  return now + getStaleTimeMs(staleTimeSeconds)\n}\n\nconst noop = () => {}\n\n/**\n * The localized retry loop for an upgradeable fallback shell. Re-issues the\n * exact same segment-bundle request (via `fetchSegmentsOnCacheMissImpl`) up to\n * MAX_FALLBACK_RETRIES times, FALLBACK_RETRY_DELAY_MS apart, until the server\n * returns the concrete (upgraded) version. On success it upserts the upgraded\n * segments (so they aren't re-fetched) and pings the task, so the task's\n * *other* fallback segments get re-attempted. If every attempt is still a\n * fallback (or fails), it gives up.\n *\n * A loop runs at most once per task, ever (the caller gates on\n * `fallbackRetryStatus === Empty`, set to `Pending` before this runs and never\n * reset to `Empty`). The sleep timer is never `clearTimeout`-ed, so the awaited\n * sleep always settles; the loop simply checks `isCanceled` after waking and\n * bails if the task was canceled in the meantime. On success the status becomes\n * `Fulfilled`; on any non-success exit (exhausted retries, fetch error, or\n * cancel) it becomes `Rejected`.\n */\nasync function retryUpgradeableFallbackPrefetch(\n  task: PrefetchTask,\n  route: FulfilledRouteCacheEntry,\n  routeKey: RouteCacheKey,\n  tree: RouteTree,\n  segments: SegmentBundle,\n  segmentCount: number,\n  // The strategy the initial fetch wrote its payloads with; the upgraded\n  // result is written through the same payload fork so the same cache slots\n  // (including the shell paths) are upgraded.\n  fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): Promise<void> {\n  for (let attempt = 0; attempt < MAX_FALLBACK_RETRIES; attempt++) {\n    await new Promise<void>((resolve) =>\n      setTimeout(resolve, FALLBACK_RETRY_DELAY_MS)\n    )\n    if (task.isCanceled) {\n      break\n    }\n\n    let result\n    try {\n      result = await fetchSegmentsOnCacheMissImpl(route, routeKey, tree)\n    } catch {\n      // A hard failure (connection dropped, or the response couldn't be\n      // decoded). Re-issuing the identical request won't fix it, so give up.\n      break\n    }\n    if (task.isCanceled) {\n      break\n    }\n    if (result === null) {\n      // Got a response that wasn't usable yet (the server hasn't finished\n      // regenerating). Try again, or give up once the budget is exhausted.\n      continue\n    }\n    if (result.serverResponse.isUpgradeableISRFallback) {\n      // Still a fallback shell — the server hasn't finished regenerating yet.\n      continue\n    }\n\n    // Success: the server returned the concrete (upgraded) version. Write it\n    // back through the same payload fork as the initial fetch, so every slot\n    // the initial fetch wrote — including the shell paths, even when the\n    // upgraded response is fully static (shell === full) — is upgraded. The\n    // bundle's entries were already settled by the initial fetch, so every\n    // write is a detached upsert that replaces the fallback. Mark the loop\n    // fulfilled and ping the task; its other fallback segments are now\n    // allowed to revalidate.\n    const { serverResponse, shellResponse, responseSize } = result\n    const now = Date.now()\n    writeSegmentBundleResponseVariants(\n      task.segmentCacheMap,\n      serverResponse,\n      shellResponse,\n      responseSize,\n      segments,\n      segmentCount,\n      now,\n      fetchStrategy\n    )\n    task.fallbackRetryStatus = EntryStatus.Fulfilled\n    pingPrefetchTask(task)\n    return\n  }\n\n  // The loop finished without success (exhausted its retries, broke out on a\n  // fetch error, or the task was canceled). It won't run again for this task.\n  task.fallbackRetryStatus = EntryStatus.Rejected\n}\n\n// TODO: The inlined prefetch flow below is temporary. Eventually, inlining\n// will be the default behavior controlled by a size heuristic rather than a\n// boolean flag. At that point, the per-segment and inlined fetch paths will\n// merge, and these separate functions will be removed.\n//\nexport async function fetchSegmentPrefetchesUsingDynamicRequest(\n  task: PrefetchTask,\n  route: FulfilledRouteCacheEntry,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.RuntimeShell\n    | FetchStrategy.Full,\n  dynamicRequestTree: FlightRouterState,\n  spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): Promise<PrefetchSubtaskResult<null> | null> {\n  const key = task.key\n  const url = new URL(route.canonicalUrl, location.origin)\n  const nextUrl = key.nextUrl\n\n  if (\n    spawnedEntries.size === 1 &&\n    spawnedEntries.has(route.metadata.requestKey)\n  ) {\n    // The only thing pending is the head. Instruct the server to\n    // skip over everything else.\n    // TODO: Lift this logic into the caller. Or perhaps unify the\n    // \"request tree\" and the spawnedEntries into the same type so they are\n    // guaranteed to always been in sync.\n    dynamicRequestTree = MetadataOnlyRequestTree\n  }\n\n  const headers: RequestHeaders = {\n    [RSC_HEADER]: '1',\n    [NEXT_ROUTER_STATE_TREE_HEADER]:\n      prepareFlightRouterStateForRequest(dynamicRequestTree),\n  }\n  if (nextUrl !== null) {\n    headers[NEXT_URL] = nextUrl\n  }\n  switch (fetchStrategy) {\n    case FetchStrategy.Full: {\n      // We omit the prefetch header from a full prefetch because it's essentially\n      // just a navigation request that happens ahead of time — it should include\n      // all the same data in the response.\n      break\n    }\n    case FetchStrategy.PPRRuntime: {\n      headers[NEXT_ROUTER_PREFETCH_HEADER] = '2'\n      break\n    }\n    case FetchStrategy.RuntimeShell: {\n      headers[NEXT_ROUTER_PREFETCH_HEADER] = '3'\n      break\n    }\n    case FetchStrategy.LoadingBoundary: {\n      headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n      break\n    }\n    default: {\n      fetchStrategy satisfies never\n    }\n  }\n\n  try {\n    const response = await fetchPrefetchResponse(url, headers)\n    if (!response || !response.ok || !response.body) {\n      // Server responded with an error, or with a miss. We should still cache\n      // the response, but we can try again after 10 seconds.\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n      return null\n    }\n\n    const renderedSearch = getRenderedSearch(response)\n    if (renderedSearch !== route.renderedSearch) {\n      // The search params that were used to render the target page are\n      // different from the search params in the request URL. This only happens\n      // when there's a dynamic rewrite in between the tree prefetch and the\n      // data prefetch.\n      // TODO: For now, since this is an edge case, we reject the prefetch, but\n      // the proper way to handle this is to evict the stale route tree entry\n      // then fill the cache with the new response.\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n      return null\n    }\n\n    // Track when the network connection closes. Only meaningful for Full\n    // (dynamic) prefetches which use incremental streaming. For buffered\n    // paths, this is resolved immediately — see TODO in fetchRouteOnCacheMiss.\n    const closed = createPromiseWithResolvers<void>()\n\n    let fulfilledEntries: Array<FulfilledSegmentCacheEntry> | null = null\n    let prefetchStream: ReadableStream<Uint8Array>\n    let bufferedResponseSize: number | null = null\n    if (fetchStrategy === FetchStrategy.Full) {\n      // Full prefetches are dynamic responses stored in the prefetch cache.\n      // They don't carry vary params or other cache metadata, so there's no\n      // need to buffer them. Use the incremental version to allow data to be\n      // processed as it arrives.\n      prefetchStream = createIncrementalPrefetchResponseStream(\n        response.body,\n        closed.resolve,\n        function onResponseSizeUpdate(totalBytesReceivedSoFar) {\n          // When processing a dynamic response, we don't know how large each\n          // individual segment is, so approximate by assigning each segment\n          // the average of the total response size.\n          if (fulfilledEntries === null) {\n            // Haven't received enough data yet to know which segments\n            // were included.\n            return\n          }\n          const averageSize = totalBytesReceivedSoFar / fulfilledEntries.length\n          for (const entry of fulfilledEntries) {\n            setSizeInCacheMap(entry, averageSize)\n          }\n        }\n      )\n    } else {\n      const { stream, size } = await createNonTaskyPrefetchResponseStream(\n        response.body\n      )\n      closed.resolve()\n      prefetchStream = stream\n      bufferedResponseSize = size\n    }\n\n    const [serverData, cacheData] = await Promise.all([\n      createFromNextReadableStream<NavigationFlightResponse>(\n        prefetchStream,\n        headers,\n        { allowPartialStream: true }\n      ),\n      response.cacheData,\n    ])\n\n    const now = Date.now()\n    const staleAt = await resolveStaleAt(now, serverData.s, response)\n    const buildId =\n      response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b\n\n    // Check if a reusable App Shell can be extracted from the main response.\n    let serverDataThatSatisfiesSpawnedEntries: NavigationFlightResponse\n    // The shell and full response have independent stale times. Track the\n    // staleAt that corresponds to whatever payload the spawned entries get\n    // filled with below.\n    let staleAtForSpawnedEntries = staleAt\n    if (cacheData === null) {\n      // No shell can be extracted without cache metadata (only present when\n      // Cached Navigations is enabled). For routes without a distinct App Shell\n      // the extraction below is a no-op anyway (`resolveShellStageData` returns\n      // null), so this just short-circuits that case.\n      serverDataThatSatisfiesSpawnedEntries = serverData\n    } else {\n      const shellStageData = await resolveShellStageData(\n        cacheData,\n        serverData,\n        headers\n      )\n      if (shellStageData === null) {\n        // No App Shell can be extracted. This usually means the entire response\n        // _is_ the App Shell. The other possibility (for now, until the feature\n        // is fully stabilized) is that App Shells are not yet enabled. Either\n        // way, there's nothing extra for us to do: fulfill the pending entries\n        // using the response from the server.\n        serverDataThatSatisfiesSpawnedEntries = serverData\n      } else {\n        // Successfully extracted an App Shell that is a subset of the main\n        // response. Depending on the type of prefetch this is, we need to\n        // decide whether to fulfill the pending entries with the shell or with\n        // the entire response. In either scenario, we'll be inserting _both_\n        // versions of the response into the cache; the extra logic is only\n        // here so that we don't fulfill pending shell entries with something\n        // that's more concrete than what they expect.\n        // TODO: The only reason this matters is because during a navigation,\n        // if a segment is still pending, we render a promise that resolves to\n        // the eventual value of that segment. But that means we cannot\n        // eventually resolve that segment to something more concrete than what\n        // was already requested. Hence the extra logic here. A cleaner way to\n        // model this, though, is whenever we render a promise that resolves to\n        // the result of a pending entry, do one additional cache look-up right\n        // after the promise resolves, to ensure we never get a mismatching\n        // entry. Leaving this for a follow up.\n        // shellStageData is a fully-buffered stage decode, so read staleTime\n        // synchronously off the thenable status.\n        const shellStaleAt = readFulfilledStaleAt(now, shellStageData.s)\n        if (fetchStrategy === FetchStrategy.RuntimeShell) {\n          // This is a Shell prefetch, so the pending entries must be fulfilled\n          // with the shell.\n          serverDataThatSatisfiesSpawnedEntries = shellStageData\n          staleAtForSpawnedEntries = shellStaleAt\n\n          // Separately, we'll also cache the entire response, by upserting it\n          // into the cache.\n          writePrerenderResponseIntoCache(\n            now,\n            FetchStrategy.PPR,\n            serverData.f,\n            buildId,\n            serverData.h,\n            serverData.r ?? null,\n            staleAt,\n            dynamicRequestTree,\n            renderedSearch,\n            cacheData.isResponsePartial,\n            task.segmentCacheMap\n          )\n        } else {\n          // This is _not_ a Shell prefetch, so the pending entries should be\n          // fulfilled with the entire response.\n          serverDataThatSatisfiesSpawnedEntries = serverData\n\n          // Additionally, we might as well upsert the extracted Shell into the\n          // cache, too.\n\n          // `shellStageData` is only provided in cases where the shell is\n          // different from the main response. If they are equivalent, this\n          // branch is skipped. So it follows that any shell data reaches\n          // this path must be partial -- it does not represent the entire\n          // UI of the target page.\n          const isShellStagePartial = true\n          writePrerenderResponseIntoCache(\n            now,\n            FetchStrategy.RuntimeShell,\n            shellStageData.f,\n            buildId,\n            shellStageData.h,\n            shellStageData.r ?? null,\n            shellStaleAt,\n            dynamicRequestTree,\n            renderedSearch,\n            isShellStagePartial,\n            task.segmentCacheMap\n          )\n        }\n      }\n    }\n\n    // Read head vary params synchronously (unioning in the response-level root\n    // params). Individual segments carry their own iterables in\n    // CacheNodeSeedData; the root iterable is threaded down so each segment\n    // unions it too.\n    const rootVaryParamsIterable =\n      serverDataThatSatisfiesSpawnedEntries.r ?? null\n    const headVaryParams = readVaryParams(\n      serverDataThatSatisfiesSpawnedEntries.h,\n      rootVaryParamsIterable\n    )\n\n    // PPRRuntime and RuntimeShell prefetches are partial when the server\n    // marks the response as '~' (Partial). RuntimeShell additionally omits\n    // every dynamic suspense boundary below the App Shell, so its segments\n    // are always partial regardless of what the server marker says.\n    // Full/LoadingBoundary prefetches are always complete.\n    const isResponsePartial =\n      fetchStrategy === FetchStrategy.RuntimeShell ||\n      (fetchStrategy === FetchStrategy.PPRRuntime &&\n        (cacheData?.isResponsePartial ?? false))\n\n    const flightDatas = normalizeFlightData(\n      serverDataThatSatisfiesSpawnedEntries.f\n    )\n    if (typeof flightDatas === 'string') {\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n      return null\n    }\n    const navigationSeed = convertServerPatchToFullTree(\n      now,\n      dynamicRequestTree,\n      flightDatas,\n      renderedSearch,\n      // Not needed for prefetch responses; pass unknown to use the default.\n      UnknownDynamicStaleTime\n    )\n\n    if (\n      navigationSeed.treeDivergedFromBase &&\n      // A head-only request uses the MetadataOnlyRequestTree stub rather than\n      // a tree derived from the route entry, so divergence from it carries\n      // no signal.\n      // TODO: This special case goes away once convertServerPatchToFullTree\n      // diffs against the base RouteTree (route.tree) instead of the\n      // request tree.\n      dynamicRequestTree !== MetadataOnlyRequestTree\n    ) {\n      // The server rendered a different route tree than the one we requested:\n      // the URL has a rewrite that behaves dynamically, so the params baked\n      // into the request are wrong and the server can never fulfill it. Mark\n      // the route entry — which doubles as the stored prediction pattern, so\n      // this also disables a bad prediction (see matchKnownRoute) that would\n      // otherwise be re-derived on every retry — and invalidate entries that\n      // were derived from it. This mirrors dispatchRetryDueToTreeMismatch on\n      // the navigation path. It can't loop: the refetched route entry is\n      // built from the server's response, so it only mismatches again if the\n      // rewrite's behavior changes again.\n      markRouteEntryAsDynamicRewrite(route)\n      invalidateRouteCacheEntries(key.nextUrl, task.treeAtTimeOfPrefetch)\n      // Reject with an immediate expiration instead of the usual backoff: the\n      // invalidation above triggers a re-prefetch, which per the above does\n      // not loop.\n      // TODO: Consider also bounding retries with a counter on the task\n      // object, so a prefetch that repeatedly fails to settle backs off\n      // regardless of the reason.\n      rejectSegmentEntriesIfStillPending(spawnedEntries, -1)\n      return null\n    }\n\n    // Aside from writing the data into the cache, this function also returns\n    // the entries that were fulfilled, so we can streamingly update their sizes\n    // in the LRU as more data comes in.\n    fulfilledEntries = writeDynamicRenderResponseIntoCache(\n      now,\n      fetchStrategy,\n      flightDatas,\n      buildId,\n      isResponsePartial,\n      headVaryParams,\n      rootVaryParamsIterable,\n      staleAtForSpawnedEntries,\n      navigationSeed,\n      spawnedEntries,\n      task.segmentCacheMap\n    )\n\n    // For buffered responses, update LRU sizes now that we know which\n    // entries were fulfilled.\n    if (\n      bufferedResponseSize !== null &&\n      fulfilledEntries !== null &&\n      fulfilledEntries.length > 0\n    ) {\n      const averageSize = bufferedResponseSize / fulfilledEntries.length\n      for (const entry of fulfilledEntries) {\n        setSizeInCacheMap(entry, averageSize)\n      }\n    }\n\n    // Return a promise that resolves when the network connection closes, so\n    // the scheduler can track the number of concurrent network connections.\n    return { value: null, closed: closed.promise }\n  } catch (error) {\n    if (process.env.__NEXT_USE_OFFLINE) {\n      const { checkOfflineError } =\n        require('../offline') as typeof import('../offline')\n      if (checkOfflineError(error)) {\n        // Unlike navigations and server actions, prefetches don't await\n        // waitForConnection — they just reject the cache entry with an\n        // immediate expiration so it gets retried once the scheduler is\n        // re-pinged after connectivity is restored.\n        rejectSegmentEntriesIfStillPending(spawnedEntries, -1)\n        return null\n      }\n    }\n    rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n    return null\n  }\n}\n\nfunction writeDynamicTreeResponseIntoCache(\n  now: number,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.Full,\n  response: RSCResponse<NavigationFlightResponse>,\n  serverData: NavigationFlightResponse,\n  entry: PendingRouteCacheEntry,\n  couldBeIntercepted: boolean,\n  canonicalUrl: string,\n  routeIsPPREnabled: boolean,\n  headVaryParams: VaryParams | null,\n  rootVaryParamsIterable: VaryParamsIterable | null,\n  originalPathname: string,\n  originalSearch: NormalizedSearch,\n  nextUrl: string | null,\n  // The spawning task's `PrefetchTask.segmentCacheMap`.\n  map: CacheMap<SegmentCacheEntry>\n): void {\n  const renderedSearch = getRenderedSearch(response)\n\n  const normalizedFlightDataResult = normalizeFlightData(serverData.f)\n  if (\n    // A string result means navigating to this route will result in an\n    // MPA navigation.\n    typeof normalizedFlightDataResult === 'string' ||\n    normalizedFlightDataResult.length !== 1\n  ) {\n    rejectRouteCacheEntry(entry, now + 10 * 1000)\n    return\n  }\n  const flightData = normalizedFlightDataResult[0]\n  if (!flightData.isRootRender) {\n    // Unexpected response format.\n    rejectRouteCacheEntry(entry, now + 10 * 1000)\n    return\n  }\n\n  const flightRouterState = flightData.tree\n  // If the response was postponed, segments may contain dynamic holes.\n  // The head has its own partiality flag (flightDataEntry.isHeadPartial)\n  // which is handled separately in writeDynamicRenderResponseIntoCache.\n  const isResponsePartial =\n    response.headers.get(NEXT_DID_POSTPONE_HEADER) === '1'\n\n  // Convert the server-sent data into the RouteTree format used by the\n  // client cache.\n  //\n  // During this traversal, we accumulate additional data into this\n  // \"accumulator\" object.\n  const acc: RouteTreeAccumulator = {\n    metadataVaryPath: null,\n    treeDivergedFromBase: false,\n  }\n  const routeTree = convertRootFlightRouterStateToRouteTree(\n    flightRouterState,\n    renderedSearch,\n    acc\n  )\n  const metadataVaryPath = acc.metadataVaryPath\n  if (metadataVaryPath === null) {\n    rejectRouteCacheEntry(entry, now + 10 * 1000)\n    return\n  }\n\n  discoverKnownRoute(\n    now,\n    originalPathname,\n    originalSearch,\n    nextUrl,\n    entry,\n    routeTree,\n    metadataVaryPath,\n    couldBeIntercepted,\n    canonicalUrl,\n    routeIsPPREnabled,\n    false // hasDynamicRewrite\n  )\n\n  // If the server sent segment data as part of the response, we should write\n  // it into the cache to prevent a second, redundant prefetch request.\n  // TODO: This is a leftover branch from before Client Segment Cache was\n  // enabled everywhere. Tree prefetches should never include segment data.  We\n  // can delete it. Leaving for a subsequent PR.\n  const navigationSeed = convertServerPatchToFullTree(\n    now,\n    flightRouterState,\n    normalizedFlightDataResult,\n    renderedSearch,\n    UnknownDynamicStaleTime\n  )\n  const buildId =\n    response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b\n  writeDynamicRenderResponseIntoCache(\n    now,\n    fetchStrategy,\n    normalizedFlightDataResult,\n    buildId,\n    isResponsePartial,\n    headVaryParams,\n    rootVaryParamsIterable,\n    getStaleAtFromHeader(now, response),\n    navigationSeed,\n    null,\n    map\n  )\n}\n\nfunction rejectSegmentEntriesIfStillPending(\n  entries: Map<SegmentRequestKey, SegmentCacheEntry>,\n  staleAt: number\n): Array<FulfilledSegmentCacheEntry> {\n  const fulfilledEntries = []\n  for (const entry of entries.values()) {\n    if (entry.status === EntryStatus.Pending) {\n      rejectSegmentCacheEntry(entry, staleAt)\n    } else if (entry.status === EntryStatus.Fulfilled) {\n      fulfilledEntries.push(entry)\n    }\n  }\n  return fulfilledEntries\n}\n\nexport function writeDynamicRenderResponseIntoCache(\n  now: number,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPR\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.RuntimeShell\n    | FetchStrategy.Full,\n  flightDatas: NormalizedFlightData[],\n  buildId: string | undefined,\n  isResponsePartial: boolean,\n  headVaryParams: VaryParams | null,\n  rootVaryParamsIterable: VaryParamsIterable | null,\n  staleAt: number,\n  navigationSeed: NavigationSeed,\n  spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null,\n  // The map the work that spawned this response's request is bound to: the\n  // spawning task's `PrefetchTask.segmentCacheMap` for prefetches, the\n  // navigation's map for navigation-side writes. Binding the write to the\n  // requesting work means a response that lands after a testing-lock scope\n  // boundary still writes into the map its entries live in.\n  map: CacheMap<SegmentCacheEntry>\n): Array<FulfilledSegmentCacheEntry> | null {\n  if (buildId && buildId !== getNavigationBuildId()) {\n    // The server build does not match the client. Treat as a 404. During\n    // an actual navigation, the router will trigger an MPA navigation.\n    if (spawnedEntries !== null) {\n      rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)\n    }\n    return null\n  }\n\n  const routeTree = navigationSeed.routeTree\n  const metadataTree =\n    navigationSeed.metadataVaryPath !== null\n      ? createMetadataRouteTree(navigationSeed.metadataVaryPath)\n      : null\n\n  for (const flightDataEntry of flightDatas) {\n    const seedData = flightDataEntry.seedData\n    if (seedData !== null) {\n      // The data sent by the server represents only a subtree of the app. We\n      // need to find the part of the task tree that matches the response.\n      //\n      // segmentPath represents the parent path of subtree. It's a repeating\n      // pattern of parallel route key and segment:\n      //\n      //   [string, Segment, string, Segment, string, Segment, ...]\n      const segmentPath = flightDataEntry.segmentPath\n      let tree = routeTree\n      for (let i = 0; i < segmentPath.length; i += 2) {\n        const parallelRouteKey: string = segmentPath[i]\n        const childTree = tree?.slots?.get(parallelRouteKey)\n        if (childTree !== undefined) {\n          tree = childTree\n        } else {\n          if (spawnedEntries !== null) {\n            rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)\n          }\n          return null\n        }\n      }\n\n      writeSeedDataIntoCache(\n        now,\n        // A response write is bound to the map its entries live in (the\n        // spawning task's `PrefetchTask.segmentCacheMap`).\n        map,\n        fetchStrategy,\n        tree,\n        staleAt,\n        seedData,\n        isResponsePartial,\n        rootVaryParamsIterable,\n        spawnedEntries\n      )\n    }\n\n    const head = flightDataEntry.head\n    if (head !== null && metadataTree !== null) {\n      // When Cache Components is enabled, the server's `isHeadPartial` flag\n      // (isPossiblyPartialHead in app-render.tsx) is unreliable: it's computed\n      // before the head is serialized, so it's conservatively `true` for every\n      // statically-generated PPR page — even pages whose head is actually\n      // complete — and it's `false` for runtime/dynamic responses whose head is\n      // actually partial (e.g. a route with an async `generateMetadata`). So we\n      // ignore it and derive the head's partiality from whether the response\n      // itself was partial, exactly as we do for segments (see\n      // `writeSeedDataIntoCache`). A non-partial response carries a complete\n      // head; a partial (postponed) one does not.\n      //\n      // Without Cache Components, the server sends the correct isHeadPartial.\n      const isHeadPartial = process.env.__NEXT_CACHE_COMPONENTS\n        ? isResponsePartial\n        : flightDataEntry.isHeadPartial\n\n      fulfillEntrySpawnedByRuntimePrefetch(\n        now,\n        // A response write is bound to the map its entries live in (the\n        // spawning task's `PrefetchTask.segmentCacheMap`).\n        map,\n        fetchStrategy,\n        head,\n        isHeadPartial,\n        staleAt,\n        // For head entries, use the head-specific vary params passed as\n        // parameter.\n        headVaryParams,\n        metadataTree,\n        spawnedEntries\n      )\n    }\n  }\n  // Any entry that's still pending was intentionally not rendered by the\n  // server, because it was inside the loading boundary. Mark them as rejected\n  // so we know not to fetch them again.\n  // TODO: If PPR is enabled on some routes but not others, then it's possible\n  // that a different page is able to do a per-segment prefetch of one of the\n  // segments we're marking as rejected here. We should mark on the segment\n  // somehow that the reason for the rejection is because of a non-PPR prefetch.\n  // That way a per-segment prefetch knows to disregard the rejection.\n  if (spawnedEntries !== null) {\n    const fulfilledEntries = rejectSegmentEntriesIfStillPending(\n      spawnedEntries,\n      now + 10 * 1000\n    )\n    return fulfilledEntries\n  }\n  return null\n}\n\nfunction writeSeedDataIntoCache(\n  now: number,\n  map: CacheMap<SegmentCacheEntry>,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPR\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.RuntimeShell\n    | FetchStrategy.Full,\n  tree: RouteTree,\n  staleAt: number,\n  seedData: CacheNodeSeedData,\n  isResponsePartial: boolean,\n  rootVaryParamsIterable: VaryParamsIterable | null,\n  entriesOwnedByCurrentTask: Map<\n    SegmentRequestKey,\n    PendingSegmentCacheEntry\n  > | null\n) {\n  // This function is used to write the result of a runtime server request\n  // (CacheNodeSeedData) into the prefetch cache.\n  const rsc = seedData[0]\n  const isPartial = rsc === null || isResponsePartial\n  // Each segment carries its own vary params iterable in the seed data, which\n  // drains to the set of params the segment accessed during render. A null\n  // iterable means tracking was not enabled (not a prerender). readVaryParams\n  // unions in the response-level root params.\n  const varyParams = readVaryParams(seedData[4], rootVaryParamsIterable)\n  fulfillEntrySpawnedByRuntimePrefetch(\n    now,\n    // A response write is bound to the map its entries live in (the spawning\n    // task's `PrefetchTask.segmentCacheMap`).\n    map,\n    fetchStrategy,\n    rsc,\n    isPartial,\n    staleAt,\n    varyParams,\n    tree,\n    entriesOwnedByCurrentTask\n  )\n\n  // Recursively write the child data into the cache.\n  const slots = tree.slots\n  if (slots !== null) {\n    const seedDataChildren = seedData[1]\n    for (const [parallelRouteKey, childTree] of slots) {\n      const childSeedData: CacheNodeSeedData | null | void =\n        seedDataChildren[parallelRouteKey]\n      if (childSeedData !== null && childSeedData !== undefined) {\n        writeSeedDataIntoCache(\n          now,\n          map,\n          fetchStrategy,\n          childTree,\n          staleAt,\n          childSeedData,\n          isResponsePartial,\n          rootVaryParamsIterable,\n          entriesOwnedByCurrentTask\n        )\n      }\n    }\n  }\n}\n\nfunction fulfillEntrySpawnedByRuntimePrefetch(\n  now: number,\n  map: CacheMap<SegmentCacheEntry>,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPR\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.RuntimeShell\n    | FetchStrategy.Full,\n  rsc: React.ReactNode,\n  isPartial: boolean,\n  staleAt: number,\n  segmentVaryParams: Set<string> | null,\n  tree: RouteTree,\n  entriesOwnedByCurrentTask: Map<\n    SegmentRequestKey,\n    PendingSegmentCacheEntry\n  > | null\n) {\n  // Decide whether to re-key the entry under a more generic vary path based on\n  // which params the segment actually depends on.\n  //\n  // Skip re-keying for Full prefetches: as of today, `varyParams` tracking only\n  // works within the static stage portion of a response. A Full prefetch\n  // response covers all stages, and we can't track params during the dynamic\n  // stage without dead-locking the Flight stream, so the server-reported set is\n  // incomplete and can't be trusted for the full response. Re-keying with an\n  // untrustworthy set could replace concrete params with Fallback and let\n  // unrelated URLs read each other's content from the cache.\n  //\n  // For RuntimeShell prefetches, always re-key to the precomputed shell vary\n  // path. A shell entry is spawned at a concrete param path but is reusable\n  // across all of them; tree.shellVaryPath (root-param values kept, every other\n  // param replaced with Fallback) is exactly the path that shell reads look it\n  // up under.\n  let fulfilledVaryPath: SegmentVaryPath | null = null\n  if (process.env.__NEXT_VARY_PARAMS) {\n    if (fetchStrategy === FetchStrategy.RuntimeShell) {\n      fulfilledVaryPath = tree.shellVaryPath\n    } else if (\n      fetchStrategy !== FetchStrategy.Full &&\n      segmentVaryParams !== null\n    ) {\n      fulfilledVaryPath = getFulfilledSegmentVaryPath(\n        tree.varyPath,\n        segmentVaryParams\n      )\n    }\n  }\n\n  // We should only write into cache entries that are owned by us. Or create\n  // a new one and write into that. We must never write over an entry that was\n  // created by a different task, because that causes data races.\n  const ownedEntry =\n    entriesOwnedByCurrentTask !== null\n      ? entriesOwnedByCurrentTask.get(tree.requestKey)\n      : undefined\n  if (ownedEntry !== undefined) {\n    const fulfilledEntry = fulfillSegmentCacheEntry(\n      ownedEntry,\n      rsc,\n      staleAt,\n      isPartial,\n      // Dynamic-request (Full/Runtime) responses are not ISR fallbacks.\n      false,\n      fetchStrategy\n    )\n    // Re-key the entry at its canonical path. When `varyParams` produced a\n    // generalized path above, use that; otherwise fall back to the request's\n    // own keying (this is load-bearing for entries spawned as revalidations:\n    // without the re-key they'd stay in their Revalidation slot forever,\n    // invisible to canonical reads, and the partial entry that prompted the\n    // revalidation would keep serving navigations). Full responses are\n    // excluded, matching the varyParams re-key: they're spawned as canonical\n    // entries at their final path, and their vary tracking can't be trusted\n    // for re-keying (see the fulfilledVaryPath derivation above).\n    const canonicalVaryPath =\n      fulfilledVaryPath !== null\n        ? fulfilledVaryPath\n        : fetchStrategy !== FetchStrategy.Full\n          ? getSegmentVaryPathForRequest(fetchStrategy, tree)\n          : null\n    if (canonicalVaryPath !== null) {\n      const isRevalidation = false\n      setInCacheMap(map, canonicalVaryPath, fulfilledEntry, isRevalidation)\n      // The re-key moved the entry to a more generic path (and, for a spawned\n      // revalidation, vacated its Revalidation slot). A stale settled entry\n      // at a more specific path — e.g. the partial entry that prompted the\n      // revalidation — would shadow every read at the concrete lookup path,\n      // causing the scheduler to keep re-reading the stale entry and respawn\n      // the revalidation forever. Evict it so the fulfilled entry is\n      // reachable. See evictShadowingSegmentEntries.\n      evictShadowingSegmentEntries(now, map, tree.varyPath, fulfilledEntry)\n    }\n  } else {\n    // There's no matching entry. Attempt to create a new one.\n    let possiblyNewEntry: SegmentCacheEntry | null = getFromCacheMap(\n      now,\n      getCurrentSegmentCacheVersion(),\n      map,\n      tree.varyPath,\n      false,\n      false\n    )\n    if (possiblyNewEntry === null) {\n      possiblyNewEntry = insertEmptySegmentCacheEntry(\n        now,\n        map,\n        fetchStrategy,\n        tree\n      )\n    }\n    if (possiblyNewEntry.status === EntryStatus.Empty) {\n      // Confirmed this is a new entry. We can fulfill it.\n      const newEntry = possiblyNewEntry\n      const fulfilledEntry = fulfillSegmentCacheEntry(\n        upgradeToPendingSegment(newEntry, fetchStrategy),\n        rsc,\n        staleAt,\n        isPartial,\n        // Dynamic-request (Full/Runtime) responses are not ISR fallbacks.\n        false,\n        fetchStrategy\n      )\n      if (fulfilledVaryPath !== null) {\n        const isRevalidation = false\n        setInCacheMap(map, fulfilledVaryPath, fulfilledEntry, isRevalidation)\n        // Same as the owned-entry re-key above. Usually the entry really is\n        // new — the read a moment ago returned nothing at the concrete lookup\n        // path, so nothing can shadow it and this is a no-op — but this\n        // branch also claims a pre-existing Empty entry, and re-keying that\n        // away can expose a stale settled entry at an intermediate path.\n        evictShadowingSegmentEntries(now, map, tree.varyPath, fulfilledEntry)\n      }\n    } else {\n      // There was already an entry in the cache. But we may be able to\n      // replace it with the new one from the server.\n      const newEntry = fulfillSegmentCacheEntry(\n        upgradeToPendingSegment(\n          createDetachedSegmentCacheEntry(now),\n          fetchStrategy\n        ),\n        rsc,\n        staleAt,\n        isPartial,\n        // Dynamic-request (Full/Runtime) responses are not ISR fallbacks.\n        false,\n        fetchStrategy\n      )\n      const varyPath =\n        fulfilledVaryPath !== null\n          ? fulfilledVaryPath\n          : getSegmentVaryPathForRequest(fetchStrategy, tree)\n      // Pass the concrete lookup path so that if the entry was re-keyed to\n      // a more generic path, any stale settled entry at a more specific path\n      // that would shadow it is evicted (the upsert handles this; the other\n      // branches above call evictShadowingSegmentEntries themselves).\n      upsertSegmentEntry(now, map, varyPath, newEntry, tree.varyPath)\n    }\n  }\n}\n\nasync function fetchPrefetchResponse<T>(\n  url: URL,\n  headers: RequestHeaders\n): Promise<RSCResponse<T> | null> {\n  const fetchPriority = 'low'\n  // When issuing a prefetch request, don't immediately decode the response; we\n  // use the lower level `createFromResponse` API instead because we need to do\n  // some extra processing of the response stream. See\n  // `createNonTaskyPrefetchResponseStream` for more details.\n  const shouldImmediatelyDecode = false\n  const response = await createFetch<T>(\n    url,\n    headers,\n    fetchPriority,\n    shouldImmediatelyDecode\n  )\n  if (!response.ok) {\n    return null\n  }\n\n  // Check the content type\n  if (isOutputExportMode) {\n    // In output: \"export\" mode, we relaxed about the content type, since it's\n    // not Next.js that's serving the response. If the status is OK, assume the\n    // response is valid. If it's not a valid response, the Flight client won't\n    // be able to decode it, and we'll treat it as a miss.\n  } else {\n    const contentType = response.headers.get('content-type')\n    const isFlightResponse =\n      contentType && contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n    if (!isFlightResponse) {\n      return null\n    }\n  }\n  return response\n}\n\nexport async function createNonTaskyPrefetchResponseStream(\n  body: ReadableStream<Uint8Array>,\n  byteLimit?: number\n): Promise<{\n  stream: ReadableStream<Uint8Array>\n  size: number\n  // The materialized response bytes backing `stream`. Exposed so callers that\n  // need to decode the same response a second time (e.g. the static App Shell\n  // extraction, which re-decodes a truncated prefix of the buffer) don't have\n  // to buffer the body twice. Most callers only use `stream` and `size`.\n  buffer: Uint8Array\n}> {\n  // Buffer the entire response before passing it to the Flight client. This\n  // ensures that when Flight processes the stream, all model data is available\n  // synchronously. This is important for readVaryParams, which synchronously\n  // checks the thenable status — if data arrived in multiple network chunks,\n  // the thenables might not yet be fulfilled.\n  //\n  // TODO: There are too many intermediate stream transformations in the\n  // prefetch response pipeline (e.g. stripIsPartialByte, this function).\n  // These could all be consolidated into a single transformation. Refactor\n  // once the cached navigations experiment lands.\n  //\n  // Read the response from the network, optionally truncating at byteLimit.\n  const reader = body.getReader()\n  const chunks: Uint8Array[] = []\n  let size = 0\n  while (true) {\n    const { done, value } = await reader.read()\n    if (done) break\n    if (byteLimit !== undefined && size + value.byteLength >= byteLimit) {\n      const remaining = byteLimit - size\n      if (remaining > 0) {\n        chunks.push(\n          value.byteLength > remaining ? value.subarray(0, remaining) : value\n        )\n        size += remaining\n      }\n      reader.cancel()\n      break\n    }\n    chunks.push(value)\n    size += value.byteLength\n  }\n  // Concatenate into a single chunk so that Flight's processBinaryChunk\n  // processes all rows synchronously in one call. Multiple chunks would not\n  // be sufficient: even though reader.read() resolves as a microtask for\n  // already-enqueued data, the `await` continuation from\n  // createFromReadableStream can interleave between chunks. If the root\n  // model row isn't the first row (e.g. outlined values come first), the\n  // PromiseResolveThenableJob from `await` can cause the root to initialize\n  // eagerly, scheduling the continuation before remaining chunks (including\n  // promise value rows) are processed. A single chunk avoids this.\n  let buffer: Uint8Array\n  if (chunks.length === 1) {\n    buffer = chunks[0]\n  } else if (chunks.length > 1) {\n    buffer = new Uint8Array(size)\n    let offset = 0\n    for (const chunk of chunks) {\n      buffer.set(chunk, offset)\n      offset += chunk.byteLength\n    }\n  } else {\n    buffer = new Uint8Array(0)\n  }\n  const stream = new ReadableStream<Uint8Array>({\n    start(controller) {\n      controller.enqueue(buffer)\n      controller.close()\n    },\n  })\n  return { stream, size, buffer }\n}\n\n/**\n * Creates a streaming (non-buffered) prefetch response stream for dynamic/Full\n * prefetches. These are essentially dynamic responses that get stored in the\n * prefetch cache — they don't carry vary params or other cache metadata that\n * requires synchronous thenable resolution, so there's no need to buffer them.\n * They should continue to stream so consumers can process data as it arrives.\n */\nfunction createIncrementalPrefetchResponseStream(\n  originalFlightStream: ReadableStream<Uint8Array>,\n  onStreamClose: () => void,\n  onResponseSizeUpdate: (size: number) => void\n): ReadableStream<Uint8Array> {\n  // While processing the original stream, we incrementally update the size\n  // of the cache entry in the LRU.\n  let totalByteLength = 0\n  const reader = originalFlightStream.getReader()\n  return new ReadableStream({\n    async pull(controller) {\n      while (true) {\n        const { done, value } = await reader.read()\n        if (!done) {\n          // Pass to the target stream and keep consuming the Flight response\n          // from the server.\n          controller.enqueue(value)\n\n          // Incrementally update the size of the cache entry in the LRU.\n          totalByteLength += value.byteLength\n          onResponseSizeUpdate(totalByteLength)\n          continue\n        }\n        controller.close()\n        onStreamClose()\n        return\n      }\n    },\n  })\n}\n\nfunction addSegmentPathToUrlInOutputExportMode(\n  url: URL,\n  segmentPath: SegmentRequestKey\n): URL {\n  if (isOutputExportMode) {\n    // In output: \"export\" mode, we cannot use a header to encode the segment\n    // path. Instead, we append it to the end of the pathname.\n    const staticUrl = new URL(url)\n    const routeDir = staticUrl.pathname.endsWith('/')\n      ? staticUrl.pathname.slice(0, -1)\n      : staticUrl.pathname\n    const staticExportFilename =\n      convertSegmentPathToStaticExportFilename(segmentPath)\n    staticUrl.pathname = `${routeDir}/${staticExportFilename}`\n    return staticUrl\n  }\n  return url\n}\n\n/**\n * Checks whether the new fetch strategy is likely to provide more content than the old one.\n *\n * Generally, when an app uses dynamic data, a \"more specific\" fetch strategy is expected to provide more content:\n * - `LoadingBoundary` only provides static layouts\n * - `StaticShell` provides the App Shell variant extracted from a static response —\n *   param-dependent content reduced to pending fallbacks, and never any content that\n *   depends on session data (cookies, headers)\n * - `RuntimeShell` provides the App Shell rendered by a runtime request, which can\n *   additionally include shell content that depends on session data\n * - `PPR` can provide shells for each segment (even for segments that use dynamic data),\n *   including prerendered param-dependent content at concrete paths\n * - `PPRRuntime` can additionally include content that uses searchParams, params, or cookies\n * - `Full` includes all the content, even if it uses dynamic data\n *\n * However, it's possible that a more specific fetch strategy *won't* give us more content if:\n * - a segment is fully static\n *   (then, `PPR`/`PPRRuntime`/`Full` will all yield equivalent results)\n * - providing searchParams/params/cookies doesn't reveal any more content, e.g. because of an `await connection()`\n *   (then, `PPR` and `PPRRuntime` will yield equivalent results, only `Full` will give us more)\n * Because of this, when comparing two segments, we should also check if the existing segment is partial.\n * If it's not partial, then there's no need to prefetch it again, even using a \"more specific\" strategy.\n * There's currently no way to know if `PPRRuntime` will yield more data that `PPR`, so we have to assume it will.\n *\n * Also note that, in practice, we don't expect to be comparing `LoadingBoundary` to `PPR`/`PPRRuntime`,\n * because a non-PPR-enabled route wouldn't ever use the latter strategies. It might however use `Full`.\n */\nexport function canNewFetchStrategyProvideMoreContent(\n  currentStrategy: FetchStrategy,\n  newStrategy: FetchStrategy\n): boolean {\n  return currentStrategy < newStrategy\n}\n\nfunction getStaleAtFromHeader(\n  now: number,\n  response: RSCResponse<unknown>\n): number {\n  const staleTimeSeconds = parseInt(\n    response.headers.get(NEXT_ROUTER_STALE_TIME_HEADER) ?? '',\n    10\n  )\n\n  const staleTimeMs = !isNaN(staleTimeSeconds)\n    ? getStaleTimeMs(staleTimeSeconds)\n    : STATIC_STALETIME_MS\n\n  return now + staleTimeMs\n}\n\n/**\n * Reads a stale-at time by `await`ing the staleTime async iterable (last\n * yielded value wins) and, if a `response` is given and the iterable yields\n * nothing, falling back to the `Next-Router-Stale-Time` header.\n *\n * The async form is required for the two things `readFulfilledStaleAt` can't\n * do: the header fallback, and reading a dynamic `Full` response\n * (fetchStrategy.Full with Partial Prefetching disabled) — the one response\n * kind that isn't buffered before it's read, so its iterable values must be\n * awaited rather than drained synchronously off their thenable status.\n *\n * Buffered responses (static PPR, runtime prefetch, stage decodes) don't need\n * the async form: segment bundles and the shell-stage decode already read\n * staleTime synchronously via `readFulfilledStaleAt`, and the remaining\n * buffered callers here could be moved to it too.\n */\nexport async function resolveStaleAt(\n  now: number,\n  staleTimeIterable: AsyncIterable<number> | undefined,\n  response?: RSCResponse<unknown>\n): Promise<number> {\n  if (staleTimeIterable !== undefined) {\n    // Iterate the async iterable and take the last yielded value. The server\n    // yields updated staleTime values during the render; the last one is the\n    // final staleTime.\n    let staleTimeSeconds: number | undefined\n    for await (const value of staleTimeIterable) {\n      staleTimeSeconds = value\n    }\n\n    if (staleTimeSeconds !== undefined) {\n      const staleTimeMs = isNaN(staleTimeSeconds)\n        ? STATIC_STALETIME_MS\n        : getStaleTimeMs(staleTimeSeconds)\n\n      return now + staleTimeMs\n    }\n  }\n\n  if (response !== undefined) {\n    return getStaleAtFromHeader(now, response)\n  }\n\n  return now + STATIC_STALETIME_MS\n}\n\n/**\n * Writes a prerender response into the segment cache at the vary path\n * determined by `fetchStrategy`. Default segments are skipped (by\n * `writeSeedDataIntoCache`) to avoid caching fallback content that would\n * block refreshes from overwriting with dynamic data.\n */\nexport function writePrerenderResponseIntoCache(\n  now: number,\n  fetchStrategy: FetchStrategy.PPR | FetchStrategy.RuntimeShell,\n  flightData: FlightData,\n  buildId: string | undefined,\n  headVaryParamsIterable: VaryParamsIterable | null,\n  rootVaryParamsIterable: VaryParamsIterable | null,\n  staleAt: number,\n  baseTree: FlightRouterState,\n  renderedSearch: string,\n  isResponsePartial: boolean,\n  // The map the work that spawned this response's request is bound to. See\n  // writeDynamicRenderResponseIntoCache.\n  map: CacheMap<SegmentCacheEntry>\n): void {\n  // Root params are emitted once at the top level; readVaryParams unions them\n  // into the head, and they're threaded down to each segment below.\n  const headVaryParams = readVaryParams(\n    headVaryParamsIterable,\n    rootVaryParamsIterable\n  )\n\n  const flightDatas = normalizeFlightData(flightData)\n  if (typeof flightDatas === 'string') {\n    return\n  }\n  const navigationSeed = convertServerPatchToFullTree(\n    now,\n    baseTree,\n    flightDatas,\n    renderedSearch,\n    UnknownDynamicStaleTime\n  )\n  writeDynamicRenderResponseIntoCache(\n    now,\n    fetchStrategy,\n    flightDatas,\n    buildId,\n    isResponsePartial,\n    headVaryParams,\n    rootVaryParamsIterable,\n    staleAt,\n    navigationSeed,\n    null, // spawnedEntries — no pre-created entries; will create or upsert\n    map\n  )\n}\n\n/**\n * Decodes an embedded runtime prefetch Flight stream, normalizes the flight\n * data, and derives a `NavigationSeed` from the base tree.\n *\n * Returns `null` if the response triggers an MPA navigation.\n */\nexport async function processRuntimePrefetchStream(\n  now: number,\n  runtimePrefetchStream: ReadableStream<Uint8Array>,\n  baseTree: FlightRouterState,\n  renderedSearch: string\n): Promise<{\n  flightDatas: NormalizedFlightData[]\n  navigationSeed: NavigationSeed\n  buildId: string | undefined\n  isResponsePartial: boolean\n  headVaryParams: VaryParams | null\n  rootVaryParamsIterable: VaryParamsIterable | null\n  staleAt: number\n} | null> {\n  const { stream, isPartial } = await stripIsPartialByte(runtimePrefetchStream)\n\n  const serverData =\n    await createFromNextReadableStream<NavigationFlightResponse>(\n      stream,\n      undefined,\n      { allowPartialStream: true }\n    )\n\n  // Root params are emitted once at the top level; readVaryParams unions them\n  // into the head, and we return the iterable so the caller can union it into\n  // each segment too.\n  const rootVaryParamsIterable = serverData.r ?? null\n  const headVaryParams = readVaryParams(serverData.h, rootVaryParamsIterable)\n\n  const staleAt = await resolveStaleAt(now, serverData.s)\n\n  const flightDatas = normalizeFlightData(serverData.f)\n  if (typeof flightDatas === 'string') {\n    return null\n  }\n  const navigationSeed = convertServerPatchToFullTree(\n    now,\n    baseTree,\n    flightDatas,\n    renderedSearch,\n    UnknownDynamicStaleTime\n  )\n\n  return {\n    flightDatas,\n    navigationSeed,\n    buildId: serverData.b,\n    isResponsePartial: isPartial,\n    headVaryParams,\n    rootVaryParamsIterable,\n    staleAt,\n  }\n}\n\n/**\n * Strips the leading isPartial byte from an RSC response stream.\n *\n * The server prepends a single byte: '~' (0x7e) for partial, '#' (0x23) for\n * complete. These bytes cannot appear as the first byte of a valid RSC Flight\n * response (Flight rows start with a hex digit or ':').\n *\n * If the first byte is not a recognized marker, the stream is returned intact\n * and `isPartial` is determined by the cachedNavigations experimental flag.\n */\nexport async function stripIsPartialByte(\n  stream: ReadableStream<Uint8Array>\n): Promise<{ stream: ReadableStream<Uint8Array>; isPartial: boolean }> {\n  // When there is no recognized marker byte, the fallback depends on whether\n  // Cached Navigations is enabled. When enabled, dynamic navigation responses\n  // don't have a marker but may contain dynamic holes, so they are treated as\n  // partial. When disabled, unmarked responses are treated as non-partial.\n  const defaultIsPartial = !!process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\n\n  const reader = stream.getReader()\n  const { done, value } = await reader.read()\n\n  if (done || !value || value.byteLength === 0) {\n    return {\n      stream: new ReadableStream({ start: (c) => c.close() }),\n      isPartial: defaultIsPartial,\n    }\n  }\n\n  const firstByte = value[0]\n  const hasMarker = firstByte === 0x23 || firstByte === 0x7e\n  const isPartial = hasMarker ? firstByte === 0x7e : defaultIsPartial\n\n  const remainder = hasMarker\n    ? value.byteLength > 1\n      ? value.subarray(1)\n      : null\n    : value\n\n  return {\n    isPartial,\n    stream: new ReadableStream<Uint8Array>({\n      start(controller) {\n        if (remainder) {\n          controller.enqueue(remainder)\n        }\n      },\n      async pull(controller) {\n        const result = await reader.read()\n        if (result.done) {\n          controller.close()\n        } else {\n          controller.enqueue(result.value)\n        }\n      },\n    }),\n  }\n}\n"],"names":["EntryStatus","MetadataOnlyRequestTree","attemptToFulfillDynamicSegmentFromBFCache","attemptToUpgradeSegmentFromBFCache","canNewFetchStrategyProvideMoreContent","convertReusedFlightRouterStateToRouteTree","convertRootFlightRouterStateToRouteTree","convertRouteTreeToFlightRouterState","createDetachedSegmentCacheEntry","createMetadataRouteTree","createNonTaskyPrefetchResponseStream","deprecated_requestOptimisticRouteCacheEntry","fetchRouteOnCacheMiss","fetchSegmentPrefetchesUsingDynamicRequest","fetchSegmentsOnCacheMiss","fulfillRouteCacheEntry","getCurrentRouteCacheVersion","getCurrentSegmentCacheVersion","getStaleTimeMs","invalidateEntirePrefetchCache","invalidateRouteCacheEntries","invalidateSegmentCacheEntries","markRouteEntryAsDynamicRewrite","overwriteRevalidatingSegmentCacheEntry","pingInvalidationListeners","processRuntimePrefetchStream","readOrCreateRevalidatingSegmentEntry","readOrCreateRouteCacheEntry","readOrCreateSegmentCacheEntry","readRouteCacheEntry","readSegmentCacheEntryForNavigation","resolveStaleAt","segmentCacheMap","stripIsPartialByte","upgradeToPendingSegment","upsertSegmentEntry","waitForSegmentCacheEntry","writeDynamicRenderResponseIntoCache","writePrerenderResponseIntoCache","writeRouteIntoCache","staleTimeSeconds","Math","max","isOutputExportMode","process","env","NODE_ENV","__NEXT_CONFIG_OUTPUT","routeCacheMap","createCacheMap","invalidationListeners","currentRouteCacheVersion","currentSegmentCacheVersion","nextUrl","tree","pingVisibleLinks","attachInvalidationListener","task","onInvalidate","Set","add","notifyInvalidationListener","error","reportError","console","tasks","isPrefetchTaskDirty","now","key","varyPath","getRouteVaryPath","pathname","search","isRevalidation","existingEntry","getFromCacheMap","__NEXT_OPTIMISTIC_ROUTING","matchKnownRoute","map","restrictToShell","lookupVaryPath","__NEXT_EXPOSE_TESTING_API","getShellSegmentVaryPath","fulfilled","readRevalidatingSegmentCacheEntry","pendingEntry","promiseWithResolvers","promise","createPromiseWithResolvers","createDetachedRouteCacheEntry","canonicalUrl","status","Empty","blockedTasks","metadata","couldBeIntercepted","supportsPerSegmentPrefetching","hasDynamicRewrite","renderedSearch","ref","size","staleAt","Infinity","version","setInCacheMap","requestedUrl","requestedSearch","urlWithoutSearchParams","URL","routeWithNoSearchParams","createPrefetchRequestKey","href","Fulfilled","canonicalUrlForRouteWithNoSearchParams","origin","optimisticCanonicalSearch","optimisticRenderedSearch","optimisticUrl","location","optimisticCanonicalUrl","createHrefFromUrl","optimisticRouteTree","deprecated_createOptimisticRouteTree","optimisticMetadataTree","optimisticEntry","newRenderedSearch","clonedSlots","originalSlots","slots","Map","parallelRouteKey","childTree","set","isPage","requestKey","segment","shellVaryPath","refreshState","clonePageVaryPathWithNewSearchParams","prefetchHints","fetchStrategy","insertEmptySegmentCacheEntry","varyPathForRequest","getSegmentVaryPathForRequest","emptyEntry","isExistingSegmentEntryPreferred","candidateEntry","isPartial","isValueExpired","Pending","pingBlockedTasks","evictShadowingSegmentEntries","i","shadowEntry","Rejected","deleteFromCacheMap","FetchStrategy","PPR","rsc","isUpgradeableISRFallback","Full","bfcacheEntry","readFromBFCache","dynamicPrefetchStaleAt","navigatedAt","STATIC_STALETIME_MS","pendingSegment","fulfillSegmentCacheEntry","newEntry","segmentVaryPath","upserted","entry","pingPrefetchTask","metadataVaryPath","HEAD_REQUEST_KEY","getRenderedSearchFromVaryPath","fulfilledEntry","PrefetchHint","InliningHintsStale","getFulfilledRouteVaryPath","segmentCacheEntry","resolve","rejectRouteCacheEntry","rejectedEntry","rejectSegmentCacheEntry","convertRootTreePrefetchToRouteTree","rootTree","renderedPathname","acc","pathnameParts","splitPathnameIntoParts","index","rootSegment","ROOT_SEGMENT_REQUEST_KEY","convertTreePrefetchToRouteTree","prefetch","partialVaryPath","pathnamePartsIndex","prefetchSlots","finalizeLayoutVaryPath","childPrefetch","childSegmentName","name","childParam","param","childDoesAppearInURL","childSegment","childPartialVaryPath","childParamValue","parseDynamicParamFromURLPart","type","childParamKey","getCacheKeyForDynamicParam","appendLayoutVaryPath","IsRootLayoutOrAbove","siblings","doesStaticSegmentAppearInURL","childPathnamePartsIndex","childRequestKeyPart","createSegmentRequestKeyPart","childRequestKey","appendSegmentRequestKeyPart","endsWith","PAGE_SEGMENT_KEY","finalizePageVaryPath","finalizeMetadataVaryPath","flightRouterState","convertFlightRouterStateToRouteTree","parentRouteTree","parentPartialVaryPath","getPartialPageVaryPath","getPartialLayoutVaryPath","parentRequestKey","requestKeyPart","parentRenderedSearch","originalSegment","isRootParam","compressedRefreshState","Array","isArray","paramCacheKey","paramName","parallelRoutes","childRouterState","routeTree","segmentPath","headers","RSC_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_URL","url","response","urlAfterRedirects","headResponse","fetch","method","Date","redirected","fetchPrefetchResponse","addSegmentPathToUrlInOutputExportMode","ok","body","varyHeader","get","includes","closed","routeIsPPREnabled","NEXT_DID_POSTPONE_HEADER","stream","prefetchStream","responseSize","setSizeInCacheMap","serverData","createFromNextReadableStream","allowPartialStream","NEXT_NAV_DEPLOYMENT_ID_HEADER","buildId","getNavigationBuildId","getRenderedPathname","getRenderedSearch","treeDivergedFromBase","discoverKnownRoute","b","headVaryParams","readVaryParams","h","r","writeDynamicTreeResponseIntoCache","LoadingBoundary","fulfilledVaryPath","value","__NEXT_USE_OFFLINE","checkOfflineError","require","rejectRemainingSegmentsInBundle","entries","node","parent","FALLBACK_RETRY_DELAY_MS","MAX_FALLBACK_RETRIES","route","routeKey","segments","segmentCount","result","fetchSegmentsOnCacheMissImpl","serverResponse","shellResponse","writeSegmentBundleResponseVariants","fallbackRetryStatus","isCanceled","retryUpgradeableFallbackPrefetch","normalizedRequestKey","requestUrl","buffer","data","length","shellOffset","readFulfilledValue","a","decodeBufferedStage","subarray","StaticShell","writeSegmentBundleResponse","detachEntriesFromSegmentBundle","payloadFetchStrategy","averageSize","sizeNode","serverDataArray","responseIsUpgradeableISRFallback","responseNeedsRuntimeRequest","needsRuntimeRequest","dataIndex","entryStaleAt","readFulfilledStaleAt","staleTime","varyParams","rootVaryParams","readFulfilledIsPartial","recordedFetchStrategy","RuntimeShell","PPRRuntime","payloadVaryPath","__NEXT_VARY_PARAMS","getFulfilledSegmentVaryPath","nodeEntry","detachedEntry","head","clonedTail","clonedNode","thenable","then","noop","valueFromServer","valueIfUnresolved","undefined","iterator","Symbol","asyncIterator","chunk","next","done","isNaN","attempt","Promise","setTimeout","dynamicRequestTree","spawnedEntries","has","NEXT_ROUTER_STATE_TREE_HEADER","prepareFlightRouterStateForRequest","rejectSegmentEntriesIfStillPending","fulfilledEntries","bufferedResponseSize","createIncrementalPrefetchResponseStream","onResponseSizeUpdate","totalBytesReceivedSoFar","cacheData","all","s","serverDataThatSatisfiesSpawnedEntries","staleAtForSpawnedEntries","shellStageData","resolveShellStageData","shellStaleAt","f","isResponsePartial","isShellStagePartial","rootVaryParamsIterable","flightDatas","normalizeFlightData","navigationSeed","convertServerPatchToFullTree","UnknownDynamicStaleTime","treeAtTimeOfPrefetch","originalPathname","originalSearch","normalizedFlightDataResult","flightData","isRootRender","getStaleAtFromHeader","values","push","metadataTree","flightDataEntry","seedData","writeSeedDataIntoCache","isHeadPartial","__NEXT_CACHE_COMPONENTS","fulfillEntrySpawnedByRuntimePrefetch","entriesOwnedByCurrentTask","seedDataChildren","childSeedData","segmentVaryParams","ownedEntry","canonicalVaryPath","possiblyNewEntry","fetchPriority","shouldImmediatelyDecode","createFetch","contentType","isFlightResponse","startsWith","RSC_CONTENT_TYPE_HEADER","byteLimit","reader","getReader","chunks","read","byteLength","remaining","cancel","Uint8Array","offset","ReadableStream","start","controller","enqueue","close","originalFlightStream","onStreamClose","totalByteLength","pull","staticUrl","routeDir","slice","staticExportFilename","convertSegmentPathToStaticExportFilename","currentStrategy","newStrategy","parseInt","NEXT_ROUTER_STALE_TIME_HEADER","staleTimeMs","staleTimeIterable","headVaryParamsIterable","baseTree","runtimePrefetchStream","defaultIsPartial","__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS","c","firstByte","hasMarker","remainder"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAwFSA,WAAW;eAAXA,qBAAW;;IAqQPC,uBAAuB;eAAvBA;;IA+3BGC,yCAAyC;eAAzCA;;IAmDAC,kCAAkC;eAAl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