{"version":3,"sources":["../../../../src/client/components/segment-cache/cache.ts"],"sourcesContent":["import type {\n  TreePrefetch,\n  RootTreePrefetch,\n  SegmentPrefetch,\n  InlinedPrefetchResponse,\n  InlinedSegmentPrefetch,\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 {\n  readVaryParams,\n  type VaryParams,\n  type VaryParamsThenable,\n} from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport {\n  NEXT_DID_POSTPONE_HEADER,\n  NEXT_INSTANT_PREFETCH_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  type RSCResponse,\n  type RequestHeaders,\n} from '../router-reducer/fetch-server-response'\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  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 {\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  type CacheMap,\n  type UnknownMapEntry,\n} 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  refreshState: RefreshState | null\n  slots: null | {\n    [parallelRouteKey: string]: RouteTree\n  }\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  // Map-related fields.\n  ref: UnknownMapEntry | null\n  size: number\n  staleAt: number\n  version: number\n}\n\n/**\n * Tracks the status of a cache entry as it progresses from no data (Empty),\n * waiting for server data (Pending), and finished (either Fulfilled or\n * Rejected depending on the response from the server.\n */\nexport const enum EntryStatus {\n  Empty = 0,\n  Pending = 1,\n  Fulfilled = 2,\n  Rejected = 3,\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  // 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  hasDynamicRewrite: boolean\n}\n\nexport type RouteCacheEntry =\n  | PendingRouteCacheEntry\n  | FulfilledRouteCacheEntry\n  | RejectedRouteCacheEntry\n\ntype SegmentCacheEntryShared = {\n  fetchStrategy: FetchStrategy\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  rsc: null\n  isPartial: true\n  promise: null\n}\n\nexport type PendingSegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Pending\n  rsc: null\n  isPartial: boolean\n  promise: null | PromiseWithResolvers<FulfilledSegmentCacheEntry | null>\n}\n\ntype RejectedSegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Rejected\n  rsc: null\n  isPartial: true\n  promise: null\n}\n\nexport type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Fulfilled\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\nconst isOutputExportMode =\n  process.env.NODE_ENV === 'production' &&\n  process.env.__NEXT_CONFIG_OUTPUT === 'export'\n\nconst MetadataOnlyRequestTree: FlightRouterState = [\n  '',\n  {},\n  null,\n  'metadata-only',\n]\n\nlet routeCacheMap: CacheMap<RouteCacheEntry> = createCacheMap()\nlet 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  )\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(key.pathname, key.search)\n  }\n\n  return null\n}\n\nexport function readSegmentCacheEntry(\n  now: number,\n  varyPath: SegmentVaryPath\n): SegmentCacheEntry | null {\n  const isRevalidation = false\n  return getFromCacheMap(\n    now,\n    getCurrentSegmentCacheVersion(),\n    segmentCacheMap,\n    varyPath,\n    isRevalidation\n  )\n}\n\nfunction readRevalidatingSegmentCacheEntry(\n  now: number,\n  varyPath: SegmentVaryPath\n): SegmentCacheEntry | null {\n  const isRevalidation = true\n  return getFromCacheMap(\n    now,\n    getCurrentSegmentCacheVersion(),\n    segmentCacheMap,\n    varyPath,\n    isRevalidation\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    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: Record<string, RouteTree> | null = null\n  const originalSlots = tree.slots\n  if (originalSlots !== null) {\n    clonedSlots = {}\n    for (const parallelRouteKey in originalSlots) {\n      const childTree = originalSlots[parallelRouteKey]\n      clonedSlots[parallelRouteKey] = deprecated_createOptimisticRouteTree(\n        childTree,\n        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    return {\n      requestKey: tree.requestKey,\n      segment: tree.segment,\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    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  fetchStrategy: FetchStrategy,\n  tree: RouteTree\n): SegmentCacheEntry {\n  const existingEntry = readSegmentCacheEntry(now, tree.varyPath)\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 = false\n  setInCacheMap(\n    segmentCacheMap,\n    varyPathForRequest,\n    pendingEntry,\n    isRevalidation\n  )\n  return pendingEntry\n}\n\nexport function readOrCreateRevalidatingSegmentEntry(\n  now: number,\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(now, tree.varyPath)\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(\n    segmentCacheMap,\n    varyPathForRequest,\n    pendingEntry,\n    isRevalidation\n  )\n  return pendingEntry\n}\n\nexport function overwriteRevalidatingSegmentCacheEntry(\n  now: number,\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(\n    segmentCacheMap,\n    varyPathForRequest,\n    pendingEntry,\n    isRevalidation\n  )\n  return pendingEntry\n}\n\nexport function upsertSegmentEntry(\n  now: number,\n  varyPath: SegmentVaryPath,\n  candidateEntry: SegmentCacheEntry\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 = readSegmentCacheEntry(now, varyPath)\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 (\n      // We fetched the new segment using a different, less specific fetch strategy\n      // than the segment we already have in the cache, so it can't 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      // We're going to leave revalidating entry in the cache so that it doesn't\n      // get revalidated again unnecessarily. Downgrade the Fulfilled entry to\n      // Rejected and null out the data so it can be garbage collected. We leave\n      // `staleAt` intact to prevent subsequent revalidation attempts only until\n      // the entry expires.\n      const rejectedEntry: RejectedSegmentCacheEntry = candidateEntry as any\n      rejectedEntry.status = EntryStatus.Rejected\n      rejectedEntry.rsc = null\n      return null\n    }\n\n    // Evict the existing entry from the cache.\n    deleteFromCacheMap(existingEntry)\n  }\n\n  const isRevalidation = false\n  setInCacheMap(segmentCacheMap, varyPath, candidateEntry, isRevalidation)\n  return candidateEntry\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    // 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    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  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    )\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  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    )\n    const segmentVaryPath = getSegmentVaryPathForRequest(\n      FetchStrategy.Full,\n      tree\n    )\n    const upserted = upsertSegmentEntry(now, segmentVaryPath, newEntry)\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    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  fulfilledEntry.staleAt = now + STATIC_STALETIME_MS\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  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 renderedSearch = fulfilledEntry.renderedSearch\n  const varyPath = getFulfilledRouteVaryPath(\n    pathname,\n    renderedSearch,\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): 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  // 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  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}\n\ntype RouteTreeAccumulator = {\n  metadataVaryPath: PageVaryPath | null\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 = renderedPathname.split('/').filter((p) => p !== '')\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: { [parallelRouteKey: 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 = {}\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        )\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[parallelRouteKey] = convertTreePrefetchToRouteTree(\n        childPrefetch,\n        childSegment,\n        childPartialVaryPath,\n        childRequestKey,\n        pathnameParts,\n        childPathnamePartsIndex,\n        renderedSearch,\n        acc\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    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  // 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    )\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: { [parallelRouteKey: 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 = {\n        [parallelRouteKey]: childTree,\n      }\n    } else {\n      slots[parallelRouteKey] = childTree\n    }\n  }\n\n  return {\n    requestKey,\n    segment,\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  if (routeTree.slots !== null) {\n    for (const parallelRouteKey in routeTree.slots) {\n      parallelRoutes[parallelRouteKey] = convertRouteTreeToFlightRouterState(\n        routeTree.slots[parallelRouteKey]\n      )\n    }\n  }\n  const flightRouterState: FlightRouterState = [\n    routeTree.segment,\n    parallelRoutes,\n    null,\n    null,\n  ]\n  return flightRouterState\n}\n\nexport async function fetchRouteOnCacheMiss(\n  entry: PendingRouteCacheEntry,\n  key: RouteCacheKey\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  // Tell the server to perform a static pre-render for the Instant Navigation\n  // Testing API. Static pre-renders don't normally happen during development.\n  addInstantPrefetchHeaderIfLocked(headers)\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 (\n      !response ||\n      !response.ok ||\n      // 204 is a Cache miss. Though theoretically this shouldn't happen when\n      // PPR is enabled, because we always respond to route tree requests, even\n      // if it needs to be blockingly generated on demand.\n      response.status === 204 ||\n      !response.body\n    ) {\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 = { metadataVaryPath: null }\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        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. Individual segments carry their\n      // own thenables in CacheNodeSeedData.\n      const headVaryParamsThenable = serverData.h\n      const headVaryParams =\n        headVaryParamsThenable !== null\n          ? readVaryParams(headVaryParamsThenable)\n          : null\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        pathname,\n        nextUrl\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.\n    rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n    return null\n  }\n}\n\nexport async function fetchSegmentOnCacheMiss(\n  route: FulfilledRouteCacheEntry,\n  segmentCacheEntry: PendingSegmentCacheEntry,\n  routeKey: RouteCacheKey,\n  tree: RouteTree\n): Promise<PrefetchSubtaskResult<FulfilledSegmentCacheEntry> | 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\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  // Tell the server to perform a static pre-render for the Instant Navigation\n  // Testing API. Static pre-renders don't normally happen during development.\n  addInstantPrefetchHeaderIfLocked(headers)\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  try {\n    const response = await fetchPrefetchResponse(requestUrl, headers)\n    if (\n      !response ||\n      !response.ok ||\n      response.status === 204 || // Cache miss\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 with a miss. We should still cache\n      // the response, but we can try again after 10 seconds.\n      rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\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 { stream: prefetchStream, size: responseSize } =\n      await createNonTaskyPrefetchResponseStream(response.body)\n    closed.resolve()\n    setSizeInCacheMap(segmentCacheEntry, responseSize)\n    const serverData = await createFromNextReadableStream<SegmentPrefetch>(\n      prefetchStream,\n      headers,\n      { allowPartialStream: true }\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      rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n      return null\n    }\n    const now = Date.now()\n    const staleAt = now + getStaleTimeMs(serverData.staleTime)\n    const fulfilledEntry = fulfillSegmentCacheEntry(\n      segmentCacheEntry,\n      serverData.rsc,\n      staleAt,\n      serverData.isPartial\n    )\n\n    // If the server tells us which params the segment varies by, we can re-key\n    // the entry to a more generic vary path. This allows the entry to be reused\n    // across different param values for params that the segment doesn't\n    // actually depend on.\n    const varyParams = serverData.varyParams\n    const fulfilledVaryPath =\n      process.env.__NEXT_VARY_PARAMS && varyParams !== null\n        ? getFulfilledSegmentVaryPath(tree.varyPath, varyParams)\n        : getSegmentVaryPathForRequest(segmentCacheEntry.fetchStrategy, tree)\n    // Re-key and upsert the entry at the fulfilled vary path. This ensures\n    // the entry is stored at the most generic path possible based on which\n    // params the segment actually depends on.\n    upsertSegmentEntry(now, fulfilledVaryPath, fulfilledEntry)\n\n    return {\n      value: fulfilledEntry,\n      // Return a promise that resolves when the network connection closes, so\n      // the scheduler can track the number of concurrent network connections.\n      closed: closed.promise,\n    }\n  } catch (error) {\n    // Either the connection itself failed, or something bad happened while\n    // decoding the response.\n    rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n    return null\n  }\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//\n// The call site in the scheduler is guarded by\n// process.env.__NEXT_PREFETCH_INLINING, so these functions are\n// dead-code-eliminated from the client bundle when the feature is disabled.\n\nexport async function fetchInlinedSegmentsOnCacheMiss(\n  route: FulfilledRouteCacheEntry,\n  routeKey: RouteCacheKey,\n  tree: RouteTree,\n  spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): Promise<PrefetchSubtaskResult<null> | null> {\n  // When prefetch inlining is enabled, all segment data for a route is bundled\n  // into a single /_inlined response instead of individual per-segment\n  // requests. This function fetches that response and walks the tree to fill\n  // all segment cache entries at once.\n  const url = new URL(route.canonicalUrl, location.origin)\n  const nextUrl = routeKey.nextUrl\n\n  const headers: RequestHeaders = {\n    [RSC_HEADER]: '1',\n    [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n    [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: '/' + PAGE_SEGMENT_KEY,\n  }\n  if (nextUrl !== null) {\n    headers[NEXT_URL] = nextUrl\n  }\n  addInstantPrefetchHeaderIfLocked(headers)\n\n  try {\n    const response = await fetchPrefetchResponse(url, headers)\n    if (\n      !response ||\n      !response.ok ||\n      response.status === 204 ||\n      (response.headers.get(NEXT_DID_POSTPONE_HEADER) !== '2' &&\n        !isOutputExportMode) ||\n      !response.body\n    ) {\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\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 { stream: prefetchStream } =\n      await createNonTaskyPrefetchResponseStream(response.body)\n    closed.resolve()\n    const serverData =\n      await createFromNextReadableStream<InlinedPrefetchResponse>(\n        prefetchStream,\n        headers,\n        { allowPartialStream: true }\n      )\n\n    if (\n      (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n        serverData.tree.segment.buildId) !== getNavigationBuildId()\n    ) {\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n      return null\n    }\n\n    const now = Date.now()\n\n    // Walk the inlined tree in parallel with the RouteTree and fill\n    // segment cache entries.\n    fillInlinedSegmentEntries(now, route, tree, serverData.tree, spawnedEntries)\n\n    // Fill the head entry.\n    const headStaleAt = now + getStaleTimeMs(serverData.head.staleTime)\n    const headKey = route.metadata.requestKey\n    const ownedHeadEntry = spawnedEntries.get(headKey)\n    if (ownedHeadEntry !== undefined) {\n      fulfillSegmentCacheEntry(\n        ownedHeadEntry,\n        serverData.head.rsc,\n        headStaleAt,\n        serverData.head.isPartial\n      )\n    } else {\n      // The head was already cached. Try to upsert if the entry is empty.\n      const existingEntry = readOrCreateSegmentCacheEntry(\n        now,\n        FetchStrategy.PPR,\n        route.metadata\n      )\n      if (existingEntry.status === EntryStatus.Empty) {\n        fulfillSegmentCacheEntry(\n          upgradeToPendingSegment(existingEntry, FetchStrategy.PPR),\n          serverData.head.rsc,\n          headStaleAt,\n          serverData.head.isPartial\n        )\n      }\n    }\n\n    // Reject any remaining entries that were not fulfilled by the response.\n    rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n\n    return { value: null, closed: closed.promise }\n  } catch (error) {\n    rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n    return null\n  }\n}\n\nfunction fillInlinedSegmentEntries(\n  now: number,\n  route: FulfilledRouteCacheEntry,\n  tree: RouteTree,\n  inlinedNode: InlinedSegmentPrefetch,\n  spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): void {\n  // Check if the spawned entries map has an entry for this segment's key.\n  const segment = inlinedNode.segment\n  const staleAt = now + getStaleTimeMs(segment.staleTime)\n  const ownedEntry = spawnedEntries.get(tree.requestKey)\n  if (ownedEntry !== undefined) {\n    // We own this entry. Fulfill it directly.\n    fulfillSegmentCacheEntry(\n      ownedEntry,\n      segment.rsc,\n      staleAt,\n      segment.isPartial\n    )\n  } else {\n    // Not owned by us — this is extra data from the inlined response for a\n    // segment that was already cached. Try to upsert if the entry is empty.\n    const existingEntry = readOrCreateSegmentCacheEntry(\n      now,\n      FetchStrategy.PPR,\n      tree\n    )\n    if (existingEntry.status === EntryStatus.Empty) {\n      fulfillSegmentCacheEntry(\n        upgradeToPendingSegment(existingEntry, FetchStrategy.PPR),\n        segment.rsc,\n        staleAt,\n        segment.isPartial\n      )\n    }\n  }\n\n  // Recurse into children.\n  if (tree.slots !== null && inlinedNode.slots !== null) {\n    for (const parallelRouteKey in tree.slots) {\n      const childTree = tree.slots[parallelRouteKey]\n      const childInlinedNode = inlinedNode.slots[parallelRouteKey]\n      if (childInlinedNode !== undefined) {\n        fillInlinedSegmentEntries(\n          now,\n          route,\n          childTree,\n          childInlinedNode,\n          spawnedEntries\n        )\n      }\n    }\n  }\n}\n\nexport async function fetchSegmentPrefetchesUsingDynamicRequest(\n  task: PrefetchTask,\n  route: FulfilledRouteCacheEntry,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPRRuntime\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    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.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    // Read head vary params synchronously. Individual segments carry their\n    // own thenables in CacheNodeSeedData.\n    const headVaryParamsThenable = serverData.h\n    const headVaryParams =\n      headVaryParamsThenable !== null\n        ? readVaryParams(headVaryParamsThenable)\n        : null\n\n    const now = Date.now()\n    const staleAt = await getStaleAt(now, serverData.s, response)\n    // PPRRuntime prefetches are partial when the server marks the response\n    // as '~' (Partial). Full/LoadingBoundary prefetches are always complete.\n    const isResponsePartial =\n      fetchStrategy === FetchStrategy.PPRRuntime &&\n      (cacheData?.isResponsePartial ?? false)\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    const buildId =\n      response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b\n    const flightDatas = normalizeFlightData(serverData.f)\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    fulfilledEntries = writeDynamicRenderResponseIntoCache(\n      now,\n      fetchStrategy,\n      flightDatas,\n      buildId,\n      isResponsePartial,\n      headVaryParams,\n      staleAt,\n      navigationSeed,\n      spawnedEntries\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    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  originalPathname: string,\n  nextUrl: string | null\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 = { metadataVaryPath: null }\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    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    getStaleAtFromHeader(now, response),\n    navigationSeed,\n    null\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.Full,\n  flightDatas: NormalizedFlightData[],\n  buildId: string | undefined,\n  isResponsePartial: boolean,\n  headVaryParams: VaryParams | null,\n  staleAt: number,\n  navigationSeed: NavigationSeed,\n  spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null\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        if (tree?.slots?.[parallelRouteKey] !== undefined) {\n          tree = tree.slots[parallelRouteKey]\n        } else {\n          if (spawnedEntries !== null) {\n            rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)\n          }\n          return null\n        }\n      }\n\n      writeSeedDataIntoCache(\n        now,\n        fetchStrategy,\n        tree,\n        staleAt,\n        seedData,\n        isResponsePartial,\n        spawnedEntries\n      )\n    }\n\n    const head = flightDataEntry.head\n    if (head !== null && metadataTree !== null) {\n      // When Cache Components is enabled, the server conservatively marks\n      // the head as partial during static generation (isPossiblyPartialHead\n      // in app-render.tsx), even for fully static pages where the head is\n      // actually complete. When the response is non-partial, we override\n      // this since the server confirmed no dynamic content exists.\n      //\n      // Without Cache Components, the server always sends the correct\n      // isHeadPartial value, so no override is needed.\n      const isHeadPartial =\n        !isResponsePartial && process.env.__NEXT_CACHE_COMPONENTS\n          ? false\n          : flightDataEntry.isHeadPartial\n\n      fulfillEntrySpawnedByRuntimePrefetch(\n        now,\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  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPR\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.Full,\n  tree: RouteTree,\n  staleAt: number,\n  seedData: CacheNodeSeedData,\n  isResponsePartial: boolean,\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  const varyParamsThenable = seedData[4]\n  // Each segment carries its own vary params thenable in the seed data. The\n  // thenable resolves to the set of params the segment accessed during render.\n  // A null thenable means tracking was not enabled (not a prerender).\n  const varyParams =\n    varyParamsThenable !== null ? readVaryParams(varyParamsThenable) : null\n  fulfillEntrySpawnedByRuntimePrefetch(\n    now,\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 in slots) {\n      const childTree = slots[parallelRouteKey]\n      const childSeedData: CacheNodeSeedData | null | void =\n        seedDataChildren[parallelRouteKey]\n      if (childSeedData !== null && childSeedData !== undefined) {\n        writeSeedDataIntoCache(\n          now,\n          fetchStrategy,\n          childTree,\n          staleAt,\n          childSeedData,\n          isResponsePartial,\n          entriesOwnedByCurrentTask\n        )\n      }\n    }\n  }\n}\n\nfunction fulfillEntrySpawnedByRuntimePrefetch(\n  now: number,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPR\n    | FetchStrategy.PPRRuntime\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  // 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    )\n    // Re-key the entry based on which params the segment actually depends on.\n    if (process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null) {\n      const fulfilledVaryPath = getFulfilledSegmentVaryPath(\n        tree.varyPath,\n        segmentVaryParams\n      )\n      const isRevalidation = false\n      setInCacheMap(\n        segmentCacheMap,\n        fulfilledVaryPath,\n        fulfilledEntry,\n        isRevalidation\n      )\n    }\n  } else {\n    // There's no matching entry. Attempt to create a new one.\n    const possiblyNewEntry = readOrCreateSegmentCacheEntry(\n      now,\n      fetchStrategy,\n      tree\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      )\n      // Re-key the entry based on which params the segment actually depends on.\n      if (process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null) {\n        const fulfilledVaryPath = getFulfilledSegmentVaryPath(\n          tree.varyPath,\n          segmentVaryParams\n        )\n        const isRevalidation = false\n        setInCacheMap(\n          segmentCacheMap,\n          fulfilledVaryPath,\n          fulfilledEntry,\n          isRevalidation\n        )\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      )\n      // Use the fulfilled vary path if available, otherwise fall back to\n      // the request vary path.\n      const varyPath =\n        process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null\n          ? getFulfilledSegmentVaryPath(tree.varyPath, segmentVaryParams)\n          : getSegmentVaryPathForRequest(fetchStrategy, tree)\n      upsertSegmentEntry(now, varyPath, newEntry)\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\nasync function createNonTaskyPrefetchResponseStream(\n  body: ReadableStream<Uint8Array>\n): Promise<{ stream: ReadableStream<Uint8Array>; size: number }> {\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 entire response from the network.\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    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 }\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 * - `PPR` can provide shells for each segment (even for segments that use dynamic data)\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\n/**\n * Adds the instant prefetch header if the navigation lock is active.\n * Uses a lazy require to ensure dead code elimination.\n */\nfunction addInstantPrefetchHeaderIfLocked(\n  headers: Record<string, string>\n): void {\n  if (process.env.__NEXT_EXPOSE_TESTING_API) {\n    const { isNavigationLocked } =\n      require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n    if (isNavigationLocked()) {\n      headers[NEXT_INSTANT_PREFETCH_HEADER] = '1'\n    }\n  }\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 the stale time from an async iterable or a response header and\n * returns a staleAt timestamp.\n *\n * TODO: Buffer the response and then read the iterable values\n * synchronously, similar to readVaryParams. This would avoid the need to\n * make this async, and we could also use it in\n * writeDynamicTreeResponseIntoCache. This will also be needed when React\n * starts leaving async iterables hanging when the outer RSC stream is\n * aborted e.g. due to sync I/O (with unstable_allowPartialStream).\n */\nexport async function getStaleAt(\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 the static stage of a navigation response into the segment cache.\n * When `isResponsePartial` is false, segments are written as non-partial with\n * `FetchStrategy.Full` so no dynamic follow-up is needed. Default segments\n * are skipped (by `writeSeedDataIntoCache`) to avoid caching fallback content\n * that would block refreshes from overwriting with dynamic data.\n */\nexport function writeStaticStageResponseIntoCache(\n  now: number,\n  flightData: FlightData,\n  buildId: string | undefined,\n  headVaryParamsThenable: VaryParamsThenable | null,\n  staleAt: number,\n  baseTree: FlightRouterState,\n  renderedSearch: string,\n  isResponsePartial: boolean\n): void {\n  const fetchStrategy = isResponsePartial\n    ? FetchStrategy.PPR\n    : FetchStrategy.Full\n\n  const headVaryParams =\n    headVaryParamsThenable !== null\n      ? readVaryParams(headVaryParamsThenable)\n      : null\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    staleAt,\n    navigationSeed,\n    null // spawnedEntries — no pre-created entries; will create or upsert\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  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  const headVaryParamsThenable = serverData.h\n  const headVaryParams =\n    headVaryParamsThenable !== null\n      ? readVaryParams(headVaryParamsThenable)\n      : null\n\n  const staleAt = await getStaleAt(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    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","attemptToFulfillDynamicSegmentFromBFCache","attemptToUpgradeSegmentFromBFCache","canNewFetchStrategyProvideMoreContent","convertReusedFlightRouterStateToRouteTree","convertRootFlightRouterStateToRouteTree","convertRouteTreeToFlightRouterState","createDetachedSegmentCacheEntry","createMetadataRouteTree","deprecated_requestOptimisticRouteCacheEntry","fetchInlinedSegmentsOnCacheMiss","fetchRouteOnCacheMiss","fetchSegmentOnCacheMiss","fetchSegmentPrefetchesUsingDynamicRequest","fulfillRouteCacheEntry","getCurrentRouteCacheVersion","getCurrentSegmentCacheVersion","getStaleAt","getStaleTimeMs","invalidateEntirePrefetchCache","invalidateRouteCacheEntries","invalidateSegmentCacheEntries","markRouteEntryAsDynamicRewrite","overwriteRevalidatingSegmentCacheEntry","pingInvalidationListeners","processRuntimePrefetchStream","readOrCreateRevalidatingSegmentEntry","readOrCreateRouteCacheEntry","readOrCreateSegmentCacheEntry","readRouteCacheEntry","readSegmentCacheEntry","stripIsPartialByte","upgradeToPendingSegment","upsertSegmentEntry","waitForSegmentCacheEntry","writeDynamicRenderResponseIntoCache","writeRouteIntoCache","writeStaticStageResponseIntoCache","staleTimeSeconds","Math","max","isOutputExportMode","process","env","NODE_ENV","__NEXT_CONFIG_OUTPUT","MetadataOnlyRequestTree","routeCacheMap","createCacheMap","segmentCacheMap","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","readRevalidatingSegmentCacheEntry","pendingEntry","promiseWithResolvers","promise","createPromiseWithResolvers","createDetachedRouteCacheEntry","canonicalUrl","status","blockedTasks","metadata","couldBeIntercepted","supportsPerSegmentPrefetching","renderedSearch","ref","size","staleAt","Infinity","version","setInCacheMap","requestedUrl","requestedSearch","urlWithoutSearchParams","URL","routeWithNoSearchParams","createPrefetchRequestKey","href","canonicalUrlForRouteWithNoSearchParams","origin","optimisticCanonicalSearch","optimisticRenderedSearch","optimisticUrl","location","optimisticCanonicalUrl","createHrefFromUrl","optimisticRouteTree","deprecated_createOptimisticRouteTree","optimisticMetadataTree","optimisticEntry","hasDynamicRewrite","newRenderedSearch","clonedSlots","originalSlots","slots","parallelRouteKey","childTree","isPage","requestKey","segment","refreshState","clonePageVaryPathWithNewSearchParams","prefetchHints","fetchStrategy","varyPathForRequest","getSegmentVaryPathForRequest","candidateEntry","isValueExpired","isPartial","rejectedEntry","rsc","deleteFromCacheMap","emptyEntry","FetchStrategy","PPR","Full","bfcacheEntry","readFromBFCache","dynamicPrefetchStaleAt","navigatedAt","STATIC_STALETIME_MS","pendingSegment","fulfillSegmentCacheEntry","newEntry","segmentVaryPath","upserted","pingBlockedTasks","entry","pingPrefetchTask","metadataVaryPath","HEAD_REQUEST_KEY","getRenderedSearchFromVaryPath","fulfilledEntry","getFulfilledRouteVaryPath","segmentCacheEntry","resolve","rejectRouteCacheEntry","rejectSegmentCacheEntry","convertRootTreePrefetchToRouteTree","rootTree","renderedPathname","acc","pathnameParts","split","filter","p","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","siblings","doesStaticSegmentAppearInURL","childPathnamePartsIndex","childRequestKeyPart","createSegmentRequestKeyPart","childRequestKey","appendSegmentRequestKeyPart","endsWith","PAGE_SEGMENT_KEY","finalizePageVaryPath","finalizeMetadataVaryPath","flightRouterState","convertFlightRouterStateToRouteTree","parentRouteTree","parentPartialVaryPath","getPartialPageVaryPath","getPartialLayoutVaryPath","parentRequestKey","requestKeyPart","parentRenderedSearch","originalSegment","compressedRefreshState","Array","isArray","paramCacheKey","paramName","parallelRoutes","childRouterState","routeTree","segmentPath","headers","RSC_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_URL","addInstantPrefetchHeaderIfLocked","url","response","urlAfterRedirects","headResponse","fetch","method","Date","redirected","fetchPrefetchResponse","addSegmentPathToUrlInOutputExportMode","ok","body","varyHeader","get","includes","closed","routeIsPPREnabled","NEXT_DID_POSTPONE_HEADER","stream","prefetchStream","responseSize","createNonTaskyPrefetchResponseStream","setSizeInCacheMap","serverData","createFromNextReadableStream","allowPartialStream","NEXT_NAV_DEPLOYMENT_ID_HEADER","buildId","getNavigationBuildId","getRenderedPathname","getRenderedSearch","discoverKnownRoute","b","headVaryParamsThenable","h","headVaryParams","readVaryParams","writeDynamicTreeResponseIntoCache","LoadingBoundary","fulfilledVaryPath","value","route","routeKey","normalizedRequestKey","requestUrl","staleTime","varyParams","__NEXT_VARY_PARAMS","getFulfilledSegmentVaryPath","spawnedEntries","rejectSegmentEntriesIfStillPending","fillInlinedSegmentEntries","headStaleAt","head","headKey","ownedHeadEntry","undefined","inlinedNode","ownedEntry","childInlinedNode","dynamicRequestTree","has","NEXT_ROUTER_STATE_TREE_HEADER","prepareFlightRouterStateForRequest","PPRRuntime","fulfilledEntries","bufferedResponseSize","createIncrementalPrefetchResponseStream","onResponseSizeUpdate","totalBytesReceivedSoFar","averageSize","length","cacheData","Promise","all","s","isResponsePartial","flightDatas","normalizeFlightData","f","navigationSeed","convertServerPatchToFullTree","UnknownDynamicStaleTime","originalPathname","normalizedFlightDataResult","flightData","isRootRender","getStaleAtFromHeader","entries","values","push","metadataTree","flightDataEntry","seedData","i","writeSeedDataIntoCache","isHeadPartial","__NEXT_CACHE_COMPONENTS","fulfillEntrySpawnedByRuntimePrefetch","entriesOwnedByCurrentTask","varyParamsThenable","seedDataChildren","childSeedData","segmentVaryParams","possiblyNewEntry","fetchPriority","shouldImmediatelyDecode","createFetch","contentType","isFlightResponse","startsWith","RSC_CONTENT_TYPE_HEADER","reader","getReader","chunks","done","read","byteLength","buffer","Uint8Array","offset","chunk","set","ReadableStream","start","controller","enqueue","close","originalFlightStream","onStreamClose","totalByteLength","pull","staticUrl","routeDir","slice","staticExportFilename","convertSegmentPathToStaticExportFilename","currentStrategy","newStrategy","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","NEXT_INSTANT_PREFETCH_HEADER","parseInt","NEXT_ROUTER_STALE_TIME_HEADER","staleTimeMs","isNaN","staleTimeIterable","baseTree","runtimePrefetchStream","defaultIsPartial","__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS","c","firstByte","hasMarker","remainder","subarray","result"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA+LkBA,WAAW;eAAXA;;IAwuBFC,yCAAyC;eAAzCA;;IAgDAC,kCAAkC;eAAlCA;;IAi3DAC,qCAAqC;eAArCA;;IAh/CAC,yCAAyC;eAAzCA;;IAdAC,uCA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