{"version":3,"sources":["../../../../../src/client/components/router-reducer/ppr-navigations.ts"],"sourcesContent":["import type {\n  CacheNodeSeedData,\n  FlightRouterState,\n  Segment,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type { HeadData, ScrollRef } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport {\n  PAGE_SEGMENT_KEY,\n  DEFAULT_SEGMENT_KEY,\n  NOT_FOUND_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { fetchServerResponse } from './fetch-server-response'\nimport { dispatchAppRouterAction } from '../use-action-queue'\nimport {\n  ACTION_SERVER_PATCH,\n  type ServerPatchAction,\n} from './router-reducer-types'\nimport { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'\nimport { getLastCommittedTree } from './reducers/committed-state'\nimport {\n  convertServerPatchToFullTree,\n  type NavigationSeed,\n} from '../segment-cache/navigation'\nimport {\n  type RouteTree,\n  type RefreshState,\n  type FulfilledRouteCacheEntry,\n  convertReusedFlightRouterStateToRouteTree,\n  readSegmentCacheEntry,\n  waitForSegmentCacheEntry,\n  markRouteEntryAsDynamicRewrite,\n  invalidateRouteCacheEntries,\n  getStaleAt,\n  writeStaticStageResponseIntoCache,\n  processRuntimePrefetchStream,\n  writeDynamicRenderResponseIntoCache,\n  EntryStatus,\n} from '../segment-cache/cache'\nimport { FetchStrategy } from '../segment-cache/types'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\nimport {\n  getRenderedSearchFromVaryPath,\n  type PageVaryPath,\n} from '../segment-cache/vary-path'\nimport {\n  readFromBFCache,\n  readFromBFCacheDuringRegularNavigation,\n  writeToBFCache,\n  writeHeadToBFCache,\n  updateBFCacheEntryStaleAt,\n  computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\n\n// This is yet another tree type that is used to track pending promises that\n// need to be fulfilled once the dynamic data is received. The terminal nodes of\n// this tree represent the new Cache Node trees that were created during this\n// request. We can't use the Cache Node tree or Route State tree directly\n// because those include reused nodes, too. This tree is discarded as soon as\n// the navigation response is received.\nexport type NavigationTask = {\n  status: NavigationTaskStatus\n  // The router state that corresponds to the tree that this Task represents.\n  route: FlightRouterState\n  // The CacheNode that corresponds to the tree that this Task represents.\n  node: CacheNode\n  // The tree sent to the server during the dynamic request. If all the segments\n  // are static, then this will be null, and no server request is required.\n  // Otherwise, this is the same as `route`, except with the `refetch` marker\n  // set on the top-most segment that needs to be fetched.\n  dynamicRequestTree: FlightRouterState | null\n  // The URL that should be used to fetch the dynamic data. This is only set\n  // when the segment cannot be refetched from the current route, because it's\n  // part of a \"default\" parallel slot that was reused during a navigation.\n  refreshState: RefreshState | null\n  children: Map<string, NavigationTask> | null\n}\n\nexport const enum FreshnessPolicy {\n  Default,\n  Hydration,\n  HistoryTraversal,\n  RefreshAll,\n  HMRRefresh,\n  Gesture,\n}\n\nconst enum NavigationTaskStatus {\n  Pending,\n  Fulfilled,\n  Rejected,\n}\n\n/**\n * When a NavigationTask finishes, there may or may not be data still missing,\n * necessitating a retry.\n */\nconst enum NavigationTaskExitStatus {\n  /**\n   * No additional navigation is required.\n   */\n  Done = 0,\n  /**\n   * Some data failed to load, presumably due to a route tree mismatch. Perform\n   * a soft retry to reload the entire tree.\n   */\n  SoftRetry = 1,\n  /**\n   * Some data failed to load in an unrecoverable way, e.g. in an inactive\n   * parallel route. Fall back to a hard (MPA-style) retry.\n   */\n  HardRetry = 2,\n}\n\nexport type NavigationRequestAccumulation = {\n  separateRefreshUrls: Set<string> | null\n  /**\n   * Set when a navigation creates new leaf segments that should be\n   * scrolled to. Stays null when no new segments are created (e.g.\n   * during a refresh where the route structure didn't change).\n   */\n  scrollRef: ScrollRef | null\n}\n\nconst noop = () => {}\n\nexport function createInitialCacheNodeForHydration(\n  navigatedAt: number,\n  initialTree: RouteTree,\n  seedData: CacheNodeSeedData | null,\n  seedHead: HeadData,\n  seedDynamicStaleAt: number\n): NavigationTask {\n  // Create the initial cache node tree, using the data embedded into the\n  // HTML document.\n  const accumulation: NavigationRequestAccumulation = {\n    separateRefreshUrls: null,\n    scrollRef: null,\n  }\n  const task = createCacheNodeOnNavigation(\n    navigatedAt,\n    initialTree,\n    null,\n    FreshnessPolicy.Hydration,\n    seedData,\n    seedHead,\n    seedDynamicStaleAt,\n    false,\n    accumulation\n  )\n  return task\n}\n\n// Creates a new Cache Node tree (i.e. copy-on-write) that represents the\n// optimistic result of a navigation, using both the current Cache Node tree and\n// data that was prefetched prior to navigation.\n//\n// At the moment we call this function, we haven't yet received the navigation\n// response from the server. It could send back something completely different\n// from the tree that was prefetched — due to rewrites, default routes, parallel\n// routes, etc.\n//\n// But in most cases, it will return the same tree that we prefetched, just with\n// the dynamic holes filled in. So we optimistically assume this will happen,\n// and accept that the real result could be arbitrarily different.\n//\n// We'll reuse anything that was already in the previous tree, since that's what\n// the server does.\n//\n// New segments (ones that don't appear in the old tree) are assigned an\n// unresolved promise. The data for these promises will be fulfilled later, when\n// the navigation response is received.\n//\n// The tree can be rendered immediately after it is created (that's why this is\n// a synchronous function). Any new trees that do not have prefetch data will\n// suspend during rendering, until the dynamic data streams in.\n//\n// Returns a Task object, which contains both the updated Cache Node and a path\n// to the pending subtrees that need to be resolved by the navigation response.\n//\n// A return value of `null` means there were no changes, and the previous tree\n// can be reused without initiating a server request.\nexport function startPPRNavigation(\n  navigatedAt: number,\n  oldUrl: URL,\n  oldRenderedSearch: string,\n  oldCacheNode: CacheNode | null,\n  oldRouterState: FlightRouterState,\n  newRouteTree: RouteTree,\n  newMetadataVaryPath: PageVaryPath | null,\n  freshness: FreshnessPolicy,\n  seedData: CacheNodeSeedData | null,\n  seedHead: HeadData | null,\n  seedDynamicStaleAt: number,\n  isSamePageNavigation: boolean,\n  accumulation: NavigationRequestAccumulation\n): NavigationTask | null {\n  const didFindRootLayout = false\n  const parentNeedsDynamicRequest = false\n  const parentRefreshState = null\n  const oldRootRefreshState: RefreshState = {\n    canonicalUrl: createHrefFromUrl(oldUrl),\n    renderedSearch: oldRenderedSearch as NormalizedSearch,\n  }\n  return updateCacheNodeOnNavigation(\n    navigatedAt,\n    oldUrl,\n    oldCacheNode !== null ? oldCacheNode : undefined,\n    oldRouterState,\n    newRouteTree,\n    newMetadataVaryPath,\n    freshness,\n    didFindRootLayout,\n    seedData,\n    seedHead,\n    seedDynamicStaleAt,\n    isSamePageNavigation,\n    parentNeedsDynamicRequest,\n    oldRootRefreshState,\n    parentRefreshState,\n    accumulation\n  )\n}\n\nfunction updateCacheNodeOnNavigation(\n  navigatedAt: number,\n  oldUrl: URL,\n  oldCacheNode: CacheNode | void,\n  oldRouterState: FlightRouterState,\n  newRouteTree: RouteTree,\n  newMetadataVaryPath: PageVaryPath | null,\n  freshness: FreshnessPolicy,\n  didFindRootLayout: boolean,\n  seedData: CacheNodeSeedData | null,\n  seedHead: HeadData | null,\n  seedDynamicStaleAt: number,\n  isSamePageNavigation: boolean,\n  parentNeedsDynamicRequest: boolean,\n  oldRootRefreshState: RefreshState,\n  parentRefreshState: RefreshState | null,\n  accumulation: NavigationRequestAccumulation\n): NavigationTask | null {\n  // Check if this segment matches the one in the previous route.\n  const oldSegment = oldRouterState[0]\n  const newSegment = createSegmentFromRouteTree(newRouteTree)\n  if (!matchSegment(newSegment, oldSegment)) {\n    // This segment does not match the previous route. We're now entering the\n    // new part of the target route. Switch to the \"create\" path.\n    if (\n      // Check if the route tree changed before we reached a layout. (The\n      // highest-level layout in a route tree is referred to as the \"root\"\n      // layout.) This could mean that we're navigating between two different\n      // root layouts. When this happens, we perform a full-page (MPA-style)\n      // navigation.\n      //\n      // However, the algorithm for deciding where to start rendering a route\n      // (i.e. the one performed in order to reach this function) is stricter\n      // than the one used to detect a change in the root layout. So just\n      // because we're re-rendering a segment outside of the root layout does\n      // not mean we should trigger a full-page navigation.\n      //\n      // Specifically, we handle dynamic parameters differently: two segments\n      // are considered the same even if their parameter values are different.\n      //\n      // Refer to isNavigatingToNewRootLayout for details.\n      //\n      // Note that we only have to perform this extra traversal if we didn't\n      // already discover a root layout in the part of the tree that is\n      // unchanged. We also only need to compare the subtree that is not\n      // shared. In the common case, this branch is skipped completely.\n      (!didFindRootLayout &&\n        isNavigatingToNewRootLayout(oldRouterState, newRouteTree)) ||\n      // The global Not Found route (app/global-not-found.tsx) is a special\n      // case, because it acts like a root layout, but in the router tree, it\n      // is rendered in the same position as app/layout.tsx.\n      //\n      // Any navigation to the global Not Found route should trigger a\n      // full-page navigation.\n      //\n      // TODO: We should probably model this by changing the key of the root\n      // segment when this happens. Then the root layout check would work\n      // as expected, without a special case.\n      newSegment === NOT_FOUND_SEGMENT_KEY\n    ) {\n      return null\n    }\n    return createCacheNodeOnNavigation(\n      navigatedAt,\n      newRouteTree,\n      newMetadataVaryPath,\n      freshness,\n      seedData,\n      seedHead,\n      seedDynamicStaleAt,\n      parentNeedsDynamicRequest,\n      accumulation\n    )\n  }\n\n  const newSlots = newRouteTree.slots\n  const oldRouterStateChildren = oldRouterState[1]\n  const seedDataChildren = seedData !== null ? seedData[1] : null\n\n  // We're currently traversing the part of the tree that was also part of\n  // the previous route. If we discover a root layout, then we don't need to\n  // trigger an MPA navigation.\n  const childDidFindRootLayout =\n    didFindRootLayout ||\n    (newRouteTree.prefetchHints & PrefetchHint.IsRootLayout) !== 0\n\n  let shouldRefreshDynamicData: boolean = false\n  switch (freshness) {\n    case FreshnessPolicy.Default:\n    case FreshnessPolicy.HistoryTraversal:\n    case FreshnessPolicy.Hydration:\n    case FreshnessPolicy.Gesture:\n      shouldRefreshDynamicData = false\n      break\n    case FreshnessPolicy.RefreshAll:\n    case FreshnessPolicy.HMRRefresh:\n      shouldRefreshDynamicData = true\n      break\n    default:\n      freshness satisfies never\n      break\n  }\n\n  // TODO: We're not consistent about how we do this check. Some places\n  // check if the segment starts with PAGE_SEGMENT_KEY, but most seem to\n  // check if there any any children, which is why I'm doing it here. We\n  // should probably encode an empty children set as `null` though. Either\n  // way, we should update all the checks to be consistent.\n  const isLeafSegment = newSlots === null\n\n  // Get the data for this segment. Since it was part of the previous route,\n  // usually we just clone the data from the old CacheNode. However, during a\n  // refresh or a revalidation, there won't be any existing CacheNode. So we\n  // may need to consult the prefetch cache, like we would for a new segment.\n  let newCacheNode: CacheNode\n  let needsDynamicRequest: boolean\n  if (\n    oldCacheNode !== undefined &&\n    !shouldRefreshDynamicData &&\n    // During a same-page navigation, we always refetch the page segments\n    !(isLeafSegment && isSamePageNavigation)\n  ) {\n    // Reuse the existing CacheNode\n    const dropPrefetchRsc = false\n    newCacheNode = reuseSharedCacheNode(dropPrefetchRsc, oldCacheNode)\n    needsDynamicRequest = false\n  } else {\n    // If this is part of a refresh, ignore the existing CacheNode and create a\n    // new one.\n    const seedRsc = seedData !== null ? seedData[0] : null\n    const result = createCacheNodeForSegment(\n      navigatedAt,\n      newRouteTree,\n      seedRsc,\n      newMetadataVaryPath,\n      seedHead,\n      freshness,\n      seedDynamicStaleAt\n    )\n    newCacheNode = result.cacheNode\n    needsDynamicRequest = result.needsDynamicRequest\n\n    // Carry forward the old node's scrollRef. This preserves scroll\n    // intent when a prior navigation's cache node is replaced by a\n    // refresh before the scroll handler has had a chance to fire —\n    // e.g. when router.push() and router.refresh() are called in the\n    // same startTransition batch.\n    if (oldCacheNode !== undefined) {\n      newCacheNode.scrollRef = oldCacheNode.scrollRef\n    }\n  }\n\n  // During a refresh navigation, there's a special case that happens when\n  // entering a \"default\" slot. The default slot may not be part of the\n  // current route; it may have been reused from an older route. If so,\n  // we need to fetch its data from the old route's URL rather than current\n  // route's URL. Keep track of this as we traverse the tree.\n  const maybeRefreshState = newRouteTree.refreshState\n  const refreshState =\n    maybeRefreshState !== undefined && maybeRefreshState !== null\n      ? // This segment is not present in the current route. Track its\n        // refresh URL as we continue traversing the tree.\n        maybeRefreshState\n      : // Inherit the refresh URL from the parent.\n        parentRefreshState\n\n  // If this segment itself needs to fetch new data from the server, then by\n  // definition it is being refreshed. Track its refresh URL so we know which\n  // URL to request the data from.\n  if (needsDynamicRequest && refreshState !== null) {\n    accumulateRefreshUrl(accumulation, refreshState)\n  }\n\n  // As we diff the trees, we may sometimes modify (copy-on-write, not mutate)\n  // the Route Tree that was returned by the server — for example, in the case\n  // of default parallel routes, we preserve the currently active segment. To\n  // avoid mutating the original tree, we clone the router state children along\n  // the return path.\n  let patchedRouterStateChildren: {\n    [parallelRouteKey: string]: FlightRouterState\n  } = {}\n  let taskChildren = null\n\n  // Most navigations require a request to fetch additional data from the\n  // server, either because the data was not already prefetched, or because the\n  // target route contains dynamic data that cannot be prefetched.\n  //\n  // However, if the target route is fully static, and it's already completely\n  // loaded into the segment cache, then we can skip the server request.\n  //\n  // This starts off as `false`, and is set to `true` if any of the child\n  // routes requires a dynamic request.\n  let childNeedsDynamicRequest = false\n  // As we traverse the children, we'll construct a FlightRouterState that can\n  // be sent to the server to request the dynamic data. If it turns out that\n  // nothing in the subtree is dynamic (i.e. childNeedsDynamicRequest is false\n  // at the end), then this will be discarded.\n  // TODO: We can probably optimize the format of this data structure to only\n  // include paths that are dynamic. Instead of reusing the\n  // FlightRouterState type.\n  let dynamicRequestTreeChildren: {\n    [parallelRouteKey: string]: FlightRouterState\n  } = {}\n\n  let newCacheNodeSlots: Record<string, CacheNode> | null = null\n  if (newSlots !== null) {\n    const oldCacheNodeSlots =\n      oldCacheNode !== undefined ? oldCacheNode.slots : null\n\n    newCacheNode.slots = newCacheNodeSlots = {}\n    taskChildren = new Map()\n    for (let parallelRouteKey in newSlots) {\n      let newRouteTreeChild: RouteTree = newSlots[parallelRouteKey]\n      const oldRouterStateChild: FlightRouterState | void =\n        oldRouterStateChildren[parallelRouteKey]\n      if (oldRouterStateChild === undefined) {\n        // This should never happen, but if it does, it suggests a malformed\n        // server response. Trigger a full-page navigation.\n        return null\n      }\n\n      let seedDataChild: CacheNodeSeedData | void | null =\n        seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null\n\n      const oldSegmentChild = oldRouterStateChild[0]\n      let newSegmentChild = createSegmentFromRouteTree(newRouteTreeChild)\n      let seedHeadChild = seedHead\n      if (\n        // Skip this branch during a history traversal. We restore the tree that\n        // was stashed in the history entry as-is.\n        freshness !== FreshnessPolicy.HistoryTraversal &&\n        newSegmentChild === DEFAULT_SEGMENT_KEY &&\n        oldSegmentChild !== DEFAULT_SEGMENT_KEY\n      ) {\n        // This is a \"default\" segment. These are never sent by the server during\n        // a soft navigation; instead, the client reuses whatever segment was\n        // already active in that slot on the previous route.\n        newRouteTreeChild = reuseActiveSegmentInDefaultSlot(\n          newRouteTree,\n          parallelRouteKey,\n          oldRootRefreshState,\n          oldRouterStateChild\n        )\n        newSegmentChild = createSegmentFromRouteTree(newRouteTreeChild)\n\n        // Since we're switching to a different route tree, these are no\n        // longer valid, because they correspond to the outer tree.\n        seedDataChild = null\n        seedHeadChild = null\n      }\n\n      const oldCacheNodeChild =\n        oldCacheNodeSlots !== null\n          ? oldCacheNodeSlots[parallelRouteKey]\n          : undefined\n\n      const taskChild = updateCacheNodeOnNavigation(\n        navigatedAt,\n        oldUrl,\n        oldCacheNodeChild,\n        oldRouterStateChild,\n        newRouteTreeChild,\n        newMetadataVaryPath,\n        freshness,\n        childDidFindRootLayout,\n        seedDataChild ?? null,\n        seedHeadChild,\n        seedDynamicStaleAt,\n        isSamePageNavigation,\n        parentNeedsDynamicRequest || needsDynamicRequest,\n        oldRootRefreshState,\n        refreshState,\n        accumulation\n      )\n\n      if (taskChild === null) {\n        // One of the child tasks discovered a change to the root layout.\n        // Immediately unwind from this recursive traversal. This will trigger a\n        // full-page navigation.\n        return null\n      }\n\n      // Recursively propagate up the child tasks.\n      taskChildren.set(parallelRouteKey, taskChild)\n      newCacheNodeSlots[parallelRouteKey] = taskChild.node\n\n      // The child tree's route state may be different from the prefetched\n      // route sent by the server. We need to clone it as we traverse back up\n      // the tree.\n      const taskChildRoute = taskChild.route\n      patchedRouterStateChildren[parallelRouteKey] = taskChildRoute\n\n      const dynamicRequestTreeChild = taskChild.dynamicRequestTree\n      if (dynamicRequestTreeChild !== null) {\n        // Something in the child tree is dynamic.\n        childNeedsDynamicRequest = true\n        dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n      } else {\n        dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute\n      }\n    }\n  }\n\n  const newFlightRouterState: FlightRouterState = [\n    createSegmentFromRouteTree(newRouteTree),\n    patchedRouterStateChildren,\n    refreshState !== null\n      ? [refreshState.canonicalUrl, refreshState.renderedSearch]\n      : null,\n    null,\n    newRouteTree.prefetchHints,\n  ]\n\n  return {\n    status: needsDynamicRequest\n      ? NavigationTaskStatus.Pending\n      : NavigationTaskStatus.Fulfilled,\n    route: newFlightRouterState,\n    node: newCacheNode,\n    dynamicRequestTree: createDynamicRequestTree(\n      newFlightRouterState,\n      dynamicRequestTreeChildren,\n      needsDynamicRequest,\n      childNeedsDynamicRequest,\n      parentNeedsDynamicRequest\n    ),\n    refreshState,\n    children: taskChildren,\n  }\n}\n\n/**\n * Assigns a ScrollRef to a new leaf CacheNode so the scroll handler\n * knows to scroll to it after navigation. All leaves in the same\n * navigation share the same ScrollRef — the first segment to scroll\n * consumes it, preventing others from also scrolling.\n *\n * This is only called inside `createCacheNodeOnNavigation`, which only\n * runs when segments diverge from the previous route. So for a refresh\n * where the route structure stays the same, segments match, the update\n * path is taken, and this function is never called — no scroll ref is\n * assigned. A scroll ref is only assigned when the route actually\n * changed (e.g. a redirect, or a dynamic condition on the server that\n * produces a different route).\n *\n * Skipped during hydration (initial render should not scroll) and\n * history traversal (scroll restoration is handled separately).\n */\nfunction accumulateScrollRef(\n  freshness: FreshnessPolicy,\n  cacheNode: CacheNode,\n  accumulation: NavigationRequestAccumulation\n): void {\n  switch (freshness) {\n    case FreshnessPolicy.Default:\n    case FreshnessPolicy.Gesture:\n    case FreshnessPolicy.RefreshAll:\n    case FreshnessPolicy.HMRRefresh:\n      if (accumulation.scrollRef === null) {\n        accumulation.scrollRef = { current: true }\n      }\n      cacheNode.scrollRef = accumulation.scrollRef\n      break\n    case FreshnessPolicy.Hydration:\n      // Initial render — no scroll.\n      break\n    case FreshnessPolicy.HistoryTraversal:\n      // Back/forward — scroll restoration is handled separately.\n      break\n    default:\n      freshness satisfies never\n      break\n  }\n}\n\nfunction createCacheNodeOnNavigation(\n  navigatedAt: number,\n  newRouteTree: RouteTree,\n  newMetadataVaryPath: PageVaryPath | null,\n  freshness: FreshnessPolicy,\n  seedData: CacheNodeSeedData | null,\n  seedHead: HeadData | null,\n  seedDynamicStaleAt: number,\n  parentNeedsDynamicRequest: boolean,\n  accumulation: NavigationRequestAccumulation\n): NavigationTask {\n  // Same traversal as updateCacheNodeNavigation, but simpler. We switch to this\n  // path once we reach the part of the tree that was not in the previous route.\n  // We don't need to diff against the old tree, we just need to create a new\n  // one. We also don't need to worry about any refresh-related logic.\n  //\n  // For the most part, this is a subset of updateCacheNodeOnNavigation, so any\n  // change that happens in this function likely needs to be applied to that\n  // one, too. However there are some places where the behavior intentionally\n  // diverges, which is why we keep them separate.\n\n  const newSegment = createSegmentFromRouteTree(newRouteTree)\n\n  const newSlots = newRouteTree.slots\n  const seedDataChildren = seedData !== null ? seedData[1] : null\n\n  const seedRsc = seedData !== null ? seedData[0] : null\n  const result = createCacheNodeForSegment(\n    navigatedAt,\n    newRouteTree,\n    seedRsc,\n    newMetadataVaryPath,\n    seedHead,\n    freshness,\n    seedDynamicStaleAt\n  )\n  const newCacheNode = result.cacheNode\n  const needsDynamicRequest = result.needsDynamicRequest\n\n  const isLeafSegment = newSlots === null\n  if (isLeafSegment) {\n    accumulateScrollRef(freshness, newCacheNode, accumulation)\n  }\n\n  let patchedRouterStateChildren: {\n    [parallelRouteKey: string]: FlightRouterState\n  } = {}\n  let taskChildren = null\n\n  let childNeedsDynamicRequest = false\n  let dynamicRequestTreeChildren: {\n    [parallelRouteKey: string]: FlightRouterState\n  } = {}\n\n  let newCacheNodeSlots: Record<string, CacheNode> | null = null\n  if (newSlots !== null) {\n    newCacheNode.slots = newCacheNodeSlots = {}\n    taskChildren = new Map()\n    for (let parallelRouteKey in newSlots) {\n      const newRouteTreeChild: RouteTree = newSlots[parallelRouteKey]\n      const seedDataChild: CacheNodeSeedData | void | null =\n        seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null\n\n      const taskChild = createCacheNodeOnNavigation(\n        navigatedAt,\n        newRouteTreeChild,\n        newMetadataVaryPath,\n        freshness,\n        seedDataChild ?? null,\n        seedHead,\n        seedDynamicStaleAt,\n        parentNeedsDynamicRequest || needsDynamicRequest,\n        accumulation\n      )\n\n      taskChildren.set(parallelRouteKey, taskChild)\n      newCacheNodeSlots[parallelRouteKey] = taskChild.node\n\n      const taskChildRoute = taskChild.route\n      patchedRouterStateChildren[parallelRouteKey] = taskChildRoute\n\n      const dynamicRequestTreeChild = taskChild.dynamicRequestTree\n      if (dynamicRequestTreeChild !== null) {\n        childNeedsDynamicRequest = true\n        dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n      } else {\n        dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute\n      }\n    }\n  }\n\n  const newFlightRouterState: FlightRouterState = [\n    newSegment,\n    patchedRouterStateChildren,\n    null,\n    null,\n    newRouteTree.prefetchHints,\n  ]\n\n  return {\n    status: needsDynamicRequest\n      ? NavigationTaskStatus.Pending\n      : NavigationTaskStatus.Fulfilled,\n    route: newFlightRouterState,\n    node: newCacheNode,\n    dynamicRequestTree: createDynamicRequestTree(\n      newFlightRouterState,\n      dynamicRequestTreeChildren,\n      needsDynamicRequest,\n      childNeedsDynamicRequest,\n      parentNeedsDynamicRequest\n    ),\n    // This route is not part of the current tree, so there's no reason to\n    // track the refresh URL.\n    refreshState: null,\n    children: taskChildren,\n  }\n}\n\nfunction createSegmentFromRouteTree(newRouteTree: RouteTree): Segment {\n  if (newRouteTree.isPage) {\n    // In a dynamic server response, the server embeds the search params into\n    // the segment key, but in a static one it's omitted. The client handles\n    // this inconsistency by adding the search params back right at the end.\n    //\n    // TODO: The only thing this is used for is to create a cache key for\n    // ChildSegmentMap. But we already track the `renderedSearch` everywhere as\n    // part of the varyPath. The plan is get rid of ChildSegmentMap and\n    // store the page data in a CacheMap using the varyPath, like we do\n    // for prefetches. Then we can remove it from the segment key.\n    //\n    // As an incremental step, we can grab the search params from the varyPath.\n    const renderedSearch = getRenderedSearchFromVaryPath(newRouteTree.varyPath)\n    if (renderedSearch === null) {\n      return PAGE_SEGMENT_KEY\n    }\n    // This is based on equivalent logic in addSearchParamsIfPageSegment, used\n    // on the server.\n    const stringifiedQuery = JSON.stringify(\n      Object.fromEntries(new URLSearchParams(renderedSearch))\n    )\n    return stringifiedQuery !== '{}'\n      ? PAGE_SEGMENT_KEY + '?' + stringifiedQuery\n      : PAGE_SEGMENT_KEY\n  }\n  return newRouteTree.segment\n}\n\nfunction patchRouterStateWithNewChildren(\n  baseRouterState: FlightRouterState,\n  newChildren: { [parallelRouteKey: string]: FlightRouterState }\n): FlightRouterState {\n  const clone: FlightRouterState = [baseRouterState[0], newChildren]\n  // Based on equivalent logic in apply-router-state-patch-to-tree, but should\n  // confirm whether we need to copy all of these fields. Not sure the server\n  // ever sends, e.g. the refetch marker.\n  if (2 in baseRouterState) {\n    clone[2] = baseRouterState[2]\n  }\n  if (3 in baseRouterState) {\n    clone[3] = baseRouterState[3]\n  }\n  if (4 in baseRouterState) {\n    clone[4] = baseRouterState[4]\n  }\n  return clone\n}\n\nfunction createDynamicRequestTree(\n  newRouterState: FlightRouterState,\n  dynamicRequestTreeChildren: Record<string, FlightRouterState>,\n  needsDynamicRequest: boolean,\n  childNeedsDynamicRequest: boolean,\n  parentNeedsDynamicRequest: boolean\n): FlightRouterState | null {\n  // Create a FlightRouterState that instructs the server how to render the\n  // requested segment.\n  //\n  // Or, if neither this segment nor any of the children require a new data,\n  // then we return `null` to skip the request.\n  let dynamicRequestTree: FlightRouterState | null = null\n  if (needsDynamicRequest) {\n    dynamicRequestTree = patchRouterStateWithNewChildren(\n      newRouterState,\n      dynamicRequestTreeChildren\n    )\n    // The \"refetch\" marker is set on the top-most segment that requires new\n    // data. We can omit it if a parent was already marked.\n    if (!parentNeedsDynamicRequest) {\n      dynamicRequestTree[3] = 'refetch'\n    }\n  } else if (childNeedsDynamicRequest) {\n    // This segment does not request new data, but at least one of its\n    // children does.\n    dynamicRequestTree = patchRouterStateWithNewChildren(\n      newRouterState,\n      dynamicRequestTreeChildren\n    )\n  } else {\n    dynamicRequestTree = null\n  }\n  return dynamicRequestTree\n}\n\nfunction accumulateRefreshUrl(\n  accumulation: NavigationRequestAccumulation,\n  refreshState: RefreshState\n) {\n  // This is a refresh navigation, and we're inside a \"default\" slot that's\n  // not part of the current route; it was reused from an older route. In\n  // order to get fresh data for this reused route, we need to issue a\n  // separate request using the old route's URL.\n  //\n  // Track these extra URLs in the accumulated result. Later, we'll construct\n  // an appropriate request for each unique URL in the final set. The reason\n  // we don't do it immediately here is so we can deduplicate multiple\n  // instances of the same URL into a single request. See\n  // listenForDynamicRequest for more details.\n  const refreshUrl = refreshState.canonicalUrl\n  const separateRefreshUrls = accumulation.separateRefreshUrls\n  if (separateRefreshUrls === null) {\n    accumulation.separateRefreshUrls = new Set([refreshUrl])\n  } else {\n    separateRefreshUrls.add(refreshUrl)\n  }\n}\n\nfunction reuseActiveSegmentInDefaultSlot(\n  parentRouteTree: RouteTree,\n  parallelRouteKey: string,\n  oldRootRefreshState: RefreshState,\n  oldRouterState: FlightRouterState\n): RouteTree {\n  // This is a \"default\" segment. These are never sent by the server during a\n  // soft navigation; instead, the client reuses whatever segment was already\n  // active in that slot on the previous route. This means if we later need to\n  // refresh the segment, it will have to be refetched from the previous route's\n  // URL. We store it in the Flight Router State.\n\n  let reusedUrl: string\n  let reusedRenderedSearch: NormalizedSearch\n  const oldRefreshState = oldRouterState[2]\n  if (oldRefreshState !== undefined && oldRefreshState !== null) {\n    // This segment was already reused from an even older route. Keep its\n    // existing URL and refresh state.\n    reusedUrl = oldRefreshState[0]\n    reusedRenderedSearch = oldRefreshState[1] as NormalizedSearch\n  } else {\n    // Since this route didn't already have a refresh state, it must have been\n    // reachable from the root of the old route. So we use the refresh state\n    // that represents the old route.\n    reusedUrl = oldRootRefreshState.canonicalUrl\n    reusedRenderedSearch = oldRootRefreshState.renderedSearch\n  }\n\n  const acc = { metadataVaryPath: null }\n  const reusedRouteTree = convertReusedFlightRouterStateToRouteTree(\n    parentRouteTree,\n    parallelRouteKey,\n    oldRouterState,\n    reusedRenderedSearch,\n    acc\n  )\n  reusedRouteTree.refreshState = {\n    canonicalUrl: reusedUrl,\n    renderedSearch: reusedRenderedSearch,\n  }\n  return reusedRouteTree\n}\n\nfunction reuseSharedCacheNode(\n  dropPrefetchRsc: boolean,\n  existingCacheNode: CacheNode\n): CacheNode {\n  // Clone the CacheNode that was already present in the previous tree.\n  // Carry forward the scrollRef so scroll intent from a prior navigation\n  // survives tree rebuilds (e.g. push + refresh in the same batch).\n  return createCacheNode(\n    existingCacheNode.rsc,\n    dropPrefetchRsc ? null : existingCacheNode.prefetchRsc,\n    existingCacheNode.head,\n    dropPrefetchRsc ? null : existingCacheNode.prefetchHead,\n    existingCacheNode.scrollRef\n  )\n}\n\nfunction createCacheNodeForSegment(\n  now: number,\n  tree: RouteTree,\n  seedRsc: React.ReactNode | null,\n  metadataVaryPath: PageVaryPath | null,\n  seedHead: HeadData | null,\n  freshness: FreshnessPolicy,\n  dynamicStaleAt: number\n): { cacheNode: CacheNode; needsDynamicRequest: boolean } {\n  // Construct a new CacheNode using data from the BFCache, the client's\n  // Segment Cache, or seeded from a server response.\n  //\n  // If there's a cache miss, or if we only have a partial hit, we'll render\n  // the partial state immediately, and spawn a request to the server to fill\n  // in the missing data.\n  //\n  // If the segment is fully cached on the client already, we can omit this\n  // segment from the server request.\n  //\n  // If we already have a dynamic data response associated with this navigation,\n  // as in the case of a Server Action-initiated redirect or refresh, we may\n  // also be able to use that data without spawning a new request. (This is\n  // referred to as the \"seed\" data.)\n\n  const isPage = tree.isPage\n\n  // During certain kinds of navigations, we may be able to render from\n  // the BFCache.\n  switch (freshness) {\n    case FreshnessPolicy.Default: {\n      // Check BFCache during regular navigations. The entry's staleAt\n      // determines whether it's still fresh. This is used when\n      // staleTimes.dynamic is configured globally or when a page exports\n      // unstable_dynamicStaleTime for per-page control.\n      const bfcacheEntry = readFromBFCacheDuringRegularNavigation(\n        now,\n        tree.varyPath\n      )\n      if (bfcacheEntry !== null) {\n        return {\n          cacheNode: createCacheNode(\n            bfcacheEntry.rsc,\n            bfcacheEntry.prefetchRsc,\n            bfcacheEntry.head,\n            bfcacheEntry.prefetchHead\n          ),\n          needsDynamicRequest: false,\n        }\n      }\n      break\n    }\n    case FreshnessPolicy.Hydration: {\n      // This is not related to the BFCache but it is a special case.\n      //\n      // We should never spawn network requests during hydration. We must treat\n      // the initial payload as authoritative, because the initial page load is\n      // used as a last-ditch mechanism for recovering the app.\n      //\n      // This is also an important safety check because if this leaks into the\n      // server rendering path (which theoretically it never should because the\n      // server payload should be consistent), the server would hang because these\n      // promises would never resolve.\n      //\n      // TODO: There is an existing case where the global \"not found\" boundary\n      // triggers this path. But it does render correctly despite that. That's an\n      // unusual render path so it's not surprising, but we should look into\n      // modeling it in a more consistent way. See also the /_notFound special\n      // case in updateCacheNodeOnNavigation.\n      const rsc = seedRsc\n      const prefetchRsc = null\n      const head = isPage ? seedHead : null\n      const prefetchHead = null\n      writeToBFCache(\n        now,\n        tree.varyPath,\n        rsc,\n        prefetchRsc,\n        head,\n        prefetchHead,\n        dynamicStaleAt\n      )\n      if (isPage && metadataVaryPath !== null) {\n        writeHeadToBFCache(\n          now,\n          metadataVaryPath,\n          head,\n          prefetchHead,\n          dynamicStaleAt\n        )\n      }\n      return {\n        cacheNode: createCacheNode(rsc, prefetchRsc, head, prefetchHead),\n        needsDynamicRequest: false,\n      }\n    }\n    case FreshnessPolicy.HistoryTraversal:\n      const bfcacheEntry = readFromBFCache(tree.varyPath)\n      if (bfcacheEntry !== null) {\n        // Only show prefetched data if the dynamic data is still pending. This\n        // avoids a flash back to the prefetch state in a case where it's highly\n        // likely to have already streamed in.\n        //\n        // Tehnically, what we're actually checking is whether the dynamic\n        // network response was received. But since it's a streaming response,\n        // this does not mean that all the dynamic data has fully streamed in.\n        // It just means that _some_ of the dynamic data was received. But as a\n        // heuristic, we assume that the rest dynamic data will stream in\n        // quickly, so it's still better to skip the prefetch state.\n        const oldRsc = bfcacheEntry.rsc\n        const oldRscDidResolve =\n          !isDeferredRsc(oldRsc) || oldRsc.status !== 'pending'\n        const dropPrefetchRsc = oldRscDidResolve\n        return {\n          cacheNode: createCacheNode(\n            bfcacheEntry.rsc,\n            dropPrefetchRsc ? null : bfcacheEntry.prefetchRsc,\n            bfcacheEntry.head,\n            dropPrefetchRsc ? null : bfcacheEntry.prefetchHead\n          ),\n          needsDynamicRequest: false,\n        }\n      }\n      break\n    case FreshnessPolicy.RefreshAll:\n    case FreshnessPolicy.HMRRefresh:\n    case FreshnessPolicy.Gesture:\n      // Don't consult the BFCache.\n      break\n    default:\n      freshness satisfies never\n      break\n  }\n\n  let cachedRsc: React.ReactNode | null = null\n  let isCachedRscPartial: boolean = true\n\n  const segmentEntry = readSegmentCacheEntry(now, tree.varyPath)\n  if (segmentEntry !== null) {\n    switch (segmentEntry.status) {\n      case EntryStatus.Fulfilled: {\n        // Happy path: a cache hit\n        cachedRsc = segmentEntry.rsc\n        isCachedRscPartial = segmentEntry.isPartial\n        break\n      }\n      case EntryStatus.Pending: {\n        // We haven't received data for this segment yet, but there's already\n        // an in-progress request. Since it's extremely likely to arrive\n        // before the dynamic data response, we might as well use it.\n        const promiseForFulfilledEntry = waitForSegmentCacheEntry(segmentEntry)\n        cachedRsc = promiseForFulfilledEntry.then((entry) =>\n          entry !== null ? entry.rsc : null\n        )\n        // Because the request is still pending, we typically don't know yet\n        // whether the response will be partial. We shouldn't skip this segment\n        // during the dynamic navigation request. Otherwise, we might need to\n        // do yet another request to fill in the remaining data, creating\n        // a waterfall.\n        //\n        // The one exception is if this segment is being fetched with via\n        // prefetch={true} (i.e. the \"force stale\" or \"full\" strategy). If so,\n        // we can assume the response will be full. This field is set to `false`\n        // for such segments.\n        isCachedRscPartial = segmentEntry.isPartial\n        break\n      }\n      case EntryStatus.Empty:\n      case EntryStatus.Rejected: {\n        break\n      }\n      default: {\n        segmentEntry satisfies never\n        break\n      }\n    }\n  }\n\n  // Now combine the cached data with the seed data to determine what we can\n  // render immediately, versus what needs to stream in later.\n\n  // A partial state to show immediately while we wait for the final data to\n  // arrive. If `rsc` is already a complete value (not partial), or if we\n  // don't have any useful partial state, this will be `null`.\n  let prefetchRsc: React.ReactNode | null\n  // The final, resolved segment data. If the data is missing, this will be a\n  // promise that resolves to the eventual data. A resolved value of `null`\n  // means the data failed to load; the LayoutRouter will suspend indefinitely\n  // until the router updates again (refer to finishNavigationTask).\n  let rsc: React.ReactNode | null\n  let doesSegmentNeedDynamicRequest: boolean\n\n  if (seedRsc !== null) {\n    // We already have a dynamic server response for this segment.\n    if (isCachedRscPartial) {\n      // The seed data may still be streaming in, so it's worth showing the\n      // partial cached state in the meantime.\n      prefetchRsc = cachedRsc\n      rsc = seedRsc\n    } else {\n      // We already have a completely cached segment. Ignore the seed data,\n      // which may still be streaming in. This shouldn't happen in the normal\n      // case because the client will inform the server which segments are\n      // already fully cached, and the server will skip rendering them.\n      prefetchRsc = null\n      rsc = cachedRsc\n    }\n    doesSegmentNeedDynamicRequest = false\n  } else {\n    if (isCachedRscPartial) {\n      // The cached data contains dynamic holes, or it's missing entirely. We'll\n      // show the partial state immediately (if available), and stream in the\n      // final data.\n      //\n      // Create a pending promise that we can later write to when the\n      // data arrives from the server.\n      prefetchRsc = cachedRsc\n      rsc = createDeferredRsc()\n    } else {\n      // The data is fully cached.\n      prefetchRsc = null\n      rsc = cachedRsc\n    }\n    doesSegmentNeedDynamicRequest = isCachedRscPartial\n  }\n\n  // If this is a page segment, we need to do the same for the head. This\n  // follows analogous logic to the segment data above.\n  // TODO: We don't need to store the head on the page segment's CacheNode; we\n  // can lift it to the main state object. Then we can also delete\n  // findHeadCache.\n\n  let prefetchHead: HeadData | null = null\n  let head: React.ReactNode | null = null\n  let doesHeadNeedDynamicRequest: boolean = isPage\n\n  if (isPage) {\n    let cachedHead: HeadData | null = null\n    let isCachedHeadPartial: boolean = true\n    if (metadataVaryPath !== null) {\n      const metadataEntry = readSegmentCacheEntry(now, metadataVaryPath)\n      if (metadataEntry !== null) {\n        switch (metadataEntry.status) {\n          case EntryStatus.Fulfilled: {\n            cachedHead = metadataEntry.rsc\n            isCachedHeadPartial = metadataEntry.isPartial\n            break\n          }\n          case EntryStatus.Pending: {\n            cachedHead = waitForSegmentCacheEntry(metadataEntry).then(\n              (entry) => (entry !== null ? entry.rsc : null)\n            )\n            isCachedHeadPartial = metadataEntry.isPartial\n            break\n          }\n          case EntryStatus.Empty:\n          case EntryStatus.Rejected: {\n            break\n          }\n          default: {\n            metadataEntry satisfies never\n            break\n          }\n        }\n      }\n    }\n\n    if (process.env.__NEXT_OPTIMISTIC_ROUTING && isCachedHeadPartial) {\n      // TODO: When optimistic routing is enabled, don't block on waiting for\n      // the viewport to resolve. This is a temporary workaround until Vary\n      // Params are tracked when rendering the metadata. We'll fix it before\n      // this feature is stable. However, it's not a critical issue because 1)\n      // it will stream in eventually anyway 2) metadata is wrapped in an\n      // internal Suspense boundary, so is always non-blocking; this only\n      // affects the viewport node, which is meant to blocking, however... 3)\n      // before Segment Cache landed this wasn't always the case, anyway, so\n      // it's unlikely that many people are relying on this behavior. Still,\n      // will be fixed before stable. It's the very next step in the sequence of\n      // work on this project.\n      //\n      // This line of code works because the App Router treats `null` as\n      // \"no renderable head available\", rather than an empty head. React treats\n      // an empty string as empty.\n      cachedHead = ''\n    }\n\n    if (seedHead !== null) {\n      if (isCachedHeadPartial) {\n        prefetchHead = cachedHead\n        head = seedHead\n      } else {\n        prefetchHead = null\n        head = cachedHead\n      }\n      doesHeadNeedDynamicRequest = false\n    } else {\n      if (isCachedHeadPartial) {\n        prefetchHead = cachedHead\n        head = createDeferredRsc()\n      } else {\n        prefetchHead = null\n        head = cachedHead\n      }\n      doesHeadNeedDynamicRequest = isCachedHeadPartial\n    }\n  }\n\n  // Now that we're creating a new segment, write its data to the BFCache. A\n  // subsequent back/forward navigation will reuse this same data, until or\n  // unless it's cleared by a refresh/revalidation.\n  //\n  // Skip BFCache writes for optimistic navigations since they are transient\n  // and will be replaced by the canonical navigation.\n  if (freshness !== FreshnessPolicy.Gesture) {\n    writeToBFCache(\n      now,\n      tree.varyPath,\n      rsc,\n      prefetchRsc,\n      head,\n      prefetchHead,\n      dynamicStaleAt\n    )\n    if (isPage && metadataVaryPath !== null) {\n      writeHeadToBFCache(\n        now,\n        metadataVaryPath,\n        head,\n        prefetchHead,\n        dynamicStaleAt\n      )\n    }\n  }\n\n  return {\n    cacheNode: createCacheNode(rsc, prefetchRsc, head, prefetchHead),\n    // TODO: We should store this field on the CacheNode itself. I think we can\n    // probably unify NavigationTask, CacheNode, and DeferredRsc into a\n    // single type. Or at least CacheNode and DeferredRsc.\n    needsDynamicRequest:\n      doesSegmentNeedDynamicRequest || doesHeadNeedDynamicRequest,\n  }\n}\n\nfunction createCacheNode(\n  rsc: React.ReactNode | null,\n  prefetchRsc: React.ReactNode | null,\n  head: React.ReactNode | null,\n  prefetchHead: HeadData | null,\n  scrollRef: ScrollRef | null = null\n): CacheNode {\n  return {\n    rsc,\n    prefetchRsc,\n    head,\n    prefetchHead,\n    slots: null,\n    scrollRef,\n  }\n}\n\n// Represents whether the previuos navigation resulted in a route tree mismatch.\n// A mismatch results in a refresh of the page. If there are two successive\n// mismatches, we will fall back to an MPA navigation, to prevent a retry loop.\nlet previousNavigationDidMismatch = false\n\n// Writes a dynamic server response into the tree created by\n// updateCacheNodeOnNavigation. All pending promises that were spawned by the\n// navigation will be resolved, either with dynamic data from the server, or\n// `null` to indicate that the data is missing.\n//\n// A `null` value will trigger a lazy fetch during render, which will then patch\n// up the tree using the same mechanism as the non-PPR implementation\n// (serverPatchReducer).\n//\n// Usually, the server will respond with exactly the subset of data that we're\n// waiting for — everything below the nearest shared layout. But technically,\n// the server can return anything it wants.\n//\n// This does _not_ create a new tree; it modifies the existing one in place.\n// Which means it must follow the Suspense rules of cache safety.\nexport function spawnDynamicRequests(\n  task: NavigationTask,\n  primaryUrl: URL,\n  nextUrl: string | null,\n  freshnessPolicy: FreshnessPolicy,\n  accumulation: NavigationRequestAccumulation,\n  // The route cache entry used for this navigation, if it came from route\n  // prediction. Passed through so it can be marked as having a dynamic rewrite\n  // if the server returns a different pathname than expected (indicating\n  // dynamic rewrite behavior that varies by param value).\n  routeCacheEntry: FulfilledRouteCacheEntry | null,\n  // The original navigation's push/replace intent. Threaded through to the\n  // server-patch retry logic so it can inherit the intent if the original\n  // transition hasn't committed yet.\n  navigateType: 'push' | 'replace'\n): void {\n  const dynamicRequestTree = task.dynamicRequestTree\n  if (dynamicRequestTree === null) {\n    // This navigation was fully cached. There are no dynamic requests to spawn.\n    previousNavigationDidMismatch = false\n    return\n  }\n\n  // This is intentionally not an async function to discourage the caller from\n  // awaiting the result. Any subsequent async operations spawned by this\n  // function should result in a separate navigation task, rather than\n  // block the original one.\n  //\n  // In this function we spawn (but do not await) all the network requests that\n  // block the navigation, and collect the promises. The next function,\n  // `finishNavigationTask`, can await the promises in any order without\n  // accidentally introducing a network waterfall.\n  const primaryRequestPromise = fetchMissingDynamicData(\n    task,\n    dynamicRequestTree,\n    primaryUrl,\n    nextUrl,\n    freshnessPolicy,\n    routeCacheEntry\n  )\n\n  const separateRefreshUrls = accumulation.separateRefreshUrls\n  let refreshRequestPromises: Array<\n    ReturnType<typeof fetchMissingDynamicData>\n  > | null = null\n  if (separateRefreshUrls !== null) {\n    // There are multiple URLs that we need to request the data from. This\n    // happens when a \"default\" parallel route slot is present in the tree, and\n    // its data cannot be fetched from the current route. We need to split the\n    // combined dynamic request tree into separate requests per URL.\n\n    // TODO: Create a scoped dynamic request tree that omits anything that\n    // is not relevant to the given URL. Without doing this, the server may\n    // sometimes render more data than necessary; this is not a regression\n    // compared to the pre-Segment Cache implementation, though, just an\n    // optimization we can make in the future.\n\n    // Construct a request tree for each additional refresh URL. This will\n    // prune away everything except the parts of the tree that match the\n    // given refresh URL.\n    refreshRequestPromises = []\n    const canonicalUrl = createHrefFromUrl(primaryUrl)\n    for (const refreshUrl of separateRefreshUrls) {\n      if (refreshUrl === canonicalUrl) {\n        // We already initiated a request for the this URL, above. Skip it.\n        // TODO: This only happens because the main URL is not tracked as\n        // part of the separateRefreshURLs set. There's probably a better way\n        // to structure this so this case doesn't happen.\n        continue\n      }\n      // TODO: Create a scoped dynamic request tree that omits anything that\n      // is not relevant to the given URL. Without doing this, the server may\n      // sometimes render more data than necessary; this is not a regression\n      // compared to the pre-Segment Cache implementation, though, just an\n      // optimization we can make in the future.\n      // const scopedDynamicRequestTree = splitTaskByURL(task, refreshUrl)\n      const scopedDynamicRequestTree = dynamicRequestTree\n      if (scopedDynamicRequestTree !== null) {\n        refreshRequestPromises.push(\n          fetchMissingDynamicData(\n            task,\n            scopedDynamicRequestTree,\n            new URL(refreshUrl, location.origin),\n            // TODO: Just noticed that this should actually the Next-Url at the\n            // time the refresh URL was set, not the current Next-Url. Need to\n            // start tracking this alongside the refresh URL. In the meantime,\n            // if a refresh fails due to a mismatch, it will trigger a\n            // hard refresh.\n            nextUrl,\n            freshnessPolicy,\n            routeCacheEntry\n          )\n        )\n      }\n    }\n  }\n\n  // Further async operations are moved into this separate function to\n  // discourage sequential network requests.\n  const voidPromise = finishNavigationTask(\n    task,\n    nextUrl,\n    primaryRequestPromise,\n    refreshRequestPromises,\n    routeCacheEntry,\n    navigateType\n  )\n  // `finishNavigationTask` is responsible for error handling, so we can attach\n  // noop callbacks to this promise.\n  voidPromise.then(noop, noop)\n}\n\nasync function finishNavigationTask(\n  task: NavigationTask,\n  nextUrl: string | null,\n  primaryRequestPromise: ReturnType<typeof fetchMissingDynamicData>,\n  refreshRequestPromises: Array<\n    ReturnType<typeof fetchMissingDynamicData>\n  > | null,\n  routeCacheEntry: FulfilledRouteCacheEntry | null,\n  navigateType: 'push' | 'replace'\n): Promise<void> {\n  // Wait for all the requests to finish, or for the first one to fail.\n  let exitStatus = await waitForRequestsToFinish(\n    primaryRequestPromise,\n    refreshRequestPromises\n  )\n\n  // Once the all the requests have finished, check the tree for any remaining\n  // pending tasks. If anything is still pending, it means the server response\n  // does not match the client, and we must refresh to get back to a consistent\n  // state. We can skip this step if we already detected a mismatch during the\n  // first phase; it doesn't matter in that case because we're going to refresh\n  // the whole tree regardless.\n  if (exitStatus === NavigationTaskExitStatus.Done) {\n    exitStatus = abortRemainingPendingTasks(task, null, null)\n  }\n\n  switch (exitStatus) {\n    case NavigationTaskExitStatus.Done: {\n      // The task has completely finished. There's no missing data. Exit.\n      previousNavigationDidMismatch = false\n      return\n    }\n    case NavigationTaskExitStatus.SoftRetry: {\n      // Some data failed to finish loading. Trigger a soft retry.\n      // TODO: As an extra precaution against soft retry loops, consider\n      // tracking whether a navigation was itself triggered by a retry. If two\n      // happen in a row, fall back to a hard retry.\n      const isHardRetry = false\n      const primaryRequestResult = await primaryRequestPromise\n      dispatchRetryDueToTreeMismatch(\n        isHardRetry,\n        primaryRequestResult.url,\n        nextUrl,\n        primaryRequestResult.seed,\n        task.route,\n        routeCacheEntry,\n        navigateType\n      )\n      return\n    }\n    case NavigationTaskExitStatus.HardRetry: {\n      // Some data failed to finish loading in a non-recoverable way, such as a\n      // network error. Trigger an MPA navigation.\n      //\n      // Hard navigating/refreshing is how we prevent an infinite retry loop\n      // caused by a network error — when the network fails, we fall back to the\n      // browser behavior for offline navigations. In the future, Next.js may\n      // introduce its own custom handling of offline navigations, but that\n      // doesn't exist yet.\n      const isHardRetry = true\n      const primaryRequestResult = await primaryRequestPromise\n      dispatchRetryDueToTreeMismatch(\n        isHardRetry,\n        primaryRequestResult.url,\n        nextUrl,\n        primaryRequestResult.seed,\n        task.route,\n        routeCacheEntry,\n        navigateType\n      )\n      return\n    }\n    default: {\n      return exitStatus satisfies never\n    }\n  }\n}\n\nfunction waitForRequestsToFinish(\n  primaryRequestPromise: ReturnType<typeof fetchMissingDynamicData>,\n  refreshRequestPromises: Array<\n    ReturnType<typeof fetchMissingDynamicData>\n  > | null\n) {\n  // Custom async combinator logic. This could be replaced by Promise.any but\n  // we don't assume that's available.\n  //\n  // Each promise resolves once the server responsds and the data is written\n  // into the CacheNode tree. Resolve the combined promise once all the\n  // requests finish.\n  //\n  // Or, resolve as soon as one of the requests fails, without waiting for the\n  // others to finish.\n  return new Promise<NavigationTaskExitStatus>((resolve) => {\n    const onFulfill = (result: { exitStatus: NavigationTaskExitStatus }) => {\n      if (result.exitStatus === NavigationTaskExitStatus.Done) {\n        remainingCount--\n        if (remainingCount === 0) {\n          // All the requests finished successfully.\n          resolve(NavigationTaskExitStatus.Done)\n        }\n      } else {\n        // One of the requests failed. Exit with a failing status.\n        // NOTE: It's possible for one of the requests to fail with SoftRetry\n        // and a later one to fail with HardRetry. In this case, we choose to\n        // retry immediately, rather than delay the retry until all the requests\n        // finish. If it fails again, we will hard retry on the next\n        // attempt, anyway.\n        resolve(result.exitStatus)\n      }\n    }\n    // onReject shouldn't ever be called because fetchMissingDynamicData's\n    // entire body is wrapped in a try/catch. This is just defensive.\n    const onReject = () => resolve(NavigationTaskExitStatus.HardRetry)\n\n    // Attach the listeners to the promises.\n    let remainingCount = 1\n    primaryRequestPromise.then(onFulfill, onReject)\n    if (refreshRequestPromises !== null) {\n      remainingCount += refreshRequestPromises.length\n      refreshRequestPromises.forEach((refreshRequestPromise) =>\n        refreshRequestPromise.then(onFulfill, onReject)\n      )\n    }\n  })\n}\n\nfunction dispatchRetryDueToTreeMismatch(\n  isHardRetry: boolean,\n  retryUrl: URL,\n  retryNextUrl: string | null,\n  seed: NavigationSeed | null,\n  baseTree: FlightRouterState,\n  // The route cache entry used for this navigation, if it came from route\n  // prediction. If the navigation results in a mismatch, we mark it as having\n  // a dynamic rewrite so future predictions bail out.\n  routeCacheEntry: FulfilledRouteCacheEntry | null,\n  // The original navigation's push/replace intent.\n  originalNavigateType: 'push' | 'replace'\n) {\n  // If the navigation used a route prediction, mark it as having a dynamic\n  // rewrite since it resulted in a mismatch.\n  if (routeCacheEntry !== null) {\n    markRouteEntryAsDynamicRewrite(routeCacheEntry)\n  } else if (seed !== null) {\n    // Even without a direct reference to the route cache entry, we can still\n    // mark the route as having a dynamic rewrite by traversing the known route\n    // tree. This handles cases where the navigation didn't originate from a\n    // route prediction, but still needs to mark the pattern.\n    const metadataVaryPath = seed.metadataVaryPath\n    if (metadataVaryPath !== null) {\n      const now = Date.now()\n      discoverKnownRoute(\n        now,\n        retryUrl.pathname,\n        retryNextUrl,\n        null,\n        seed.routeTree,\n        metadataVaryPath,\n        false, // couldBeIntercepted - doesn't matter, we're just marking hasDynamicRewrite\n        createHrefFromUrl(retryUrl),\n        false, // supportsPerSegmentPrefetching - doesn't matter, we're just marking hasDynamicRewrite\n        true // hasDynamicRewrite\n      )\n    }\n  }\n\n  // Invalidate all route cache entries. Other entries may have been derived\n  // from the template before we knew it had a dynamic rewrite. This also\n  // triggers re-prefetching of visible links.\n  invalidateRouteCacheEntries(retryNextUrl, baseTree)\n\n  // If this is the second time in a row that a navigation resulted in a\n  // mismatch, fall back to a hard (MPA) refresh.\n  isHardRetry = isHardRetry || previousNavigationDidMismatch\n  previousNavigationDidMismatch = true\n\n  // If the original navigation hasn't committed to the browser history yet\n  // (the transition suspended before React committed), inherit its push/replace\n  // intent. Otherwise, the pushState already ran, so use 'replace' to avoid\n  // creating a duplicate history entry.\n  //\n  // This works because React entangles the retry's state update with the\n  // original pending transition — they commit together as a single batch,\n  // so the navigate type from the retry is what HistoryUpdater ultimately sees.\n  //\n  // TODO: Ideally this check would happen right before we schedule the React\n  // update (i.e., closer to where the action is dispatched into the queue),\n  // not here where the action is constructed. But the current action queue\n  // doesn't provide a natural place for that. Revisit when we refactor the\n  // action queue into a more reactive navigation model.\n  const lastCommitted = getLastCommittedTree()\n  const retryNavigateType: 'push' | 'replace' =\n    lastCommitted !== null && baseTree !== lastCommitted\n      ? originalNavigateType\n      : 'replace'\n\n  const retryAction: ServerPatchAction = {\n    type: ACTION_SERVER_PATCH,\n    previousTree: baseTree,\n    url: retryUrl,\n    nextUrl: retryNextUrl,\n    seed,\n    mpa: isHardRetry,\n    navigateType: retryNavigateType,\n  }\n  dispatchAppRouterAction(retryAction)\n}\n\nasync function fetchMissingDynamicData(\n  task: NavigationTask,\n  dynamicRequestTree: FlightRouterState,\n  url: URL,\n  nextUrl: string | null,\n  freshnessPolicy: FreshnessPolicy,\n  routeCacheEntry: FulfilledRouteCacheEntry | null\n): Promise<{\n  exitStatus: NavigationTaskExitStatus\n  url: URL\n  seed: NavigationSeed | null\n}> {\n  try {\n    const result = await fetchServerResponse(url, {\n      flightRouterState: dynamicRequestTree,\n      nextUrl,\n      isHmrRefresh: freshnessPolicy === FreshnessPolicy.HMRRefresh,\n    })\n    if (typeof result === 'string') {\n      // fetchServerResponse will return an href to indicate that the SPA\n      // navigation failed. For example, if the server triggered a hard\n      // redirect, or the fetch request errored. Initiate an MPA navigation\n      // to the given href.\n      return {\n        exitStatus: NavigationTaskExitStatus.HardRetry,\n        url: new URL(result, location.origin),\n        seed: null,\n      }\n    }\n    const now = Date.now()\n\n    const seed = convertServerPatchToFullTree(\n      now,\n      task.route,\n      result.flightData,\n      result.renderedSearch,\n      result.dynamicStaleTime\n    )\n\n    // If the navigation lock is active, wait for it to be released before\n    // writing the dynamic data. This allows tests to assert on the prefetched\n    // UI state.\n    if (process.env.__NEXT_EXPOSE_TESTING_API) {\n      await waitForNavigationLock()\n    }\n\n    if (routeCacheEntry !== null && result.staticStageData !== null) {\n      const { response: staticStageResponse, isResponsePartial } =\n        result.staticStageData\n\n      getStaleAt(now, staticStageResponse.s)\n        .then((staleAt) => {\n          const buildId =\n            result.responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n            staticStageResponse.b\n\n          writeStaticStageResponseIntoCache(\n            now,\n            staticStageResponse.f,\n            buildId,\n            staticStageResponse.h,\n            staleAt,\n            dynamicRequestTree,\n            result.renderedSearch,\n            isResponsePartial\n          )\n        })\n        .catch(() => {\n          // The static stage processing failed. Not fatal — the navigation\n          // completed normally, we just won't write into the cache.\n        })\n    }\n\n    if (routeCacheEntry !== null && result.runtimePrefetchStream !== null) {\n      processRuntimePrefetchStream(\n        now,\n        result.runtimePrefetchStream,\n        dynamicRequestTree,\n        result.renderedSearch\n      )\n        .then((processed) => {\n          if (processed !== null) {\n            writeDynamicRenderResponseIntoCache(\n              now,\n              FetchStrategy.PPRRuntime,\n              processed.flightDatas,\n              processed.buildId,\n              processed.isResponsePartial,\n              processed.headVaryParams,\n              processed.staleAt,\n              processed.navigationSeed,\n              null\n            )\n          }\n        })\n        .catch(() => {\n          // The runtime prefetch cache write failed. Not fatal — the\n          // navigation completed normally, we just won't cache runtime data.\n        })\n    }\n\n    // result.dynamicStaleTime is in seconds (from the server's `d` field).\n    // Convert to an absolute timestamp using the centralized helper.\n    const dynamicStaleAt = computeDynamicStaleAt(now, result.dynamicStaleTime)\n\n    const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(\n      task,\n      seed.routeTree,\n      seed.data,\n      seed.head,\n      dynamicStaleAt,\n      result.debugInfo\n    )\n\n    return {\n      exitStatus: didReceiveUnknownParallelRoute\n        ? NavigationTaskExitStatus.SoftRetry\n        : NavigationTaskExitStatus.Done,\n      url: new URL(result.canonicalUrl, location.origin),\n      seed,\n    }\n  } catch {\n    // This shouldn't happen because fetchServerResponse's entire body is\n    // wrapped in a try/catch. If it does, though, it implies the server failed\n    // to respond with any tree at all. So we must fall back to a hard retry.\n    return {\n      exitStatus: NavigationTaskExitStatus.HardRetry,\n      url: url,\n      seed: null,\n    }\n  }\n}\n\nfunction writeDynamicDataIntoNavigationTask(\n  task: NavigationTask,\n  serverRouteTree: RouteTree,\n  dynamicData: CacheNodeSeedData | null,\n  dynamicHead: HeadData,\n  dynamicStaleAt: number,\n  debugInfo: Array<any> | null\n): boolean {\n  if (task.status === NavigationTaskStatus.Pending && dynamicData !== null) {\n    task.status = NavigationTaskStatus.Fulfilled\n    finishPendingCacheNode(task.node, dynamicData, dynamicHead, debugInfo)\n\n    // Update the BFCache entry's staleAt for this segment with the value\n    // from the dynamic response. This applies the per-page\n    // unstable_dynamicStaleTime if set, or the default DYNAMIC_STALETIME_MS.\n    // We only update segments that received dynamic data — static segments\n    // are unaffected.\n    updateBFCacheEntryStaleAt(serverRouteTree.varyPath, dynamicStaleAt)\n  }\n\n  const taskChildren = task.children\n  const serverChildren = serverRouteTree.slots\n  const dynamicDataChildren = dynamicData !== null ? dynamicData[1] : null\n\n  // Detect whether the server sends a parallel route slot that the client\n  // doesn't know about.\n  let didReceiveUnknownParallelRoute = false\n\n  if (taskChildren !== null) {\n    if (serverChildren !== null) {\n      for (const parallelRouteKey in serverChildren) {\n        const serverRouteTreeChild: RouteTree = serverChildren[parallelRouteKey]\n        const dynamicDataChild: CacheNodeSeedData | null | void =\n          dynamicDataChildren !== null\n            ? dynamicDataChildren[parallelRouteKey]\n            : null\n\n        const taskChild = taskChildren.get(parallelRouteKey)\n        if (taskChild === undefined) {\n          // The server sent a child segment that the client doesn't know about.\n          //\n          // When we receive an unknown parallel route, we must consider it a\n          // mismatch. This is unlike the case where the segment itself\n          // mismatches, because multiple routes can be active simultaneously.\n          // But a given layout should never have a mismatching set of\n          // child slots.\n          //\n          // Theoretically, this should only happen in development during an HMR\n          // refresh, because the set of parallel routes for a layout does not\n          // change over the lifetime of a build/deployment. In production, we\n          // should have already mismatched on either the build id or the segment\n          // path. But as an extra precaution, we validate in prod, too.\n          didReceiveUnknownParallelRoute = true\n        } else {\n          const taskSegment = taskChild.route[0]\n          const serverSegment = createSegmentFromRouteTree(serverRouteTreeChild)\n          if (\n            matchSegment(serverSegment, taskSegment) &&\n            dynamicDataChild !== null &&\n            dynamicDataChild !== undefined\n          ) {\n            // Found a match for this task. Keep traversing down the task tree.\n            const childDidReceiveUnknownParallelRoute =\n              writeDynamicDataIntoNavigationTask(\n                taskChild,\n                serverRouteTreeChild,\n                dynamicDataChild,\n                dynamicHead,\n                dynamicStaleAt,\n                debugInfo\n              )\n            if (childDidReceiveUnknownParallelRoute) {\n              didReceiveUnknownParallelRoute = true\n            }\n          }\n        }\n      }\n    } else {\n      if (serverChildren !== null) {\n        // The server sent a child segment that the client doesn't know about.\n        didReceiveUnknownParallelRoute = true\n      }\n    }\n  }\n\n  return didReceiveUnknownParallelRoute\n}\n\nfunction finishPendingCacheNode(\n  cacheNode: CacheNode,\n  dynamicData: CacheNodeSeedData,\n  dynamicHead: HeadData,\n  debugInfo: Array<any> | null\n): void {\n  // Writes a dynamic response into an existing Cache Node tree. This does _not_\n  // create a new tree, it updates the existing tree in-place. So it must follow\n  // the Suspense rules of cache safety — it can resolve pending promises, but\n  // it cannot overwrite existing data. It can add segments to the tree (because\n  // a missing segment will cause the layout router to suspend).\n  // but it cannot delete them.\n  //\n  // We must resolve every promise in the tree, or else it will suspend\n  // indefinitely. If we did not receive data for a segment, we will resolve its\n  // data promise to `null` to trigger a lazy fetch during render.\n\n  // Use the dynamic data from the server to fulfill the deferred RSC promise\n  // on the Cache Node.\n  const rsc = cacheNode.rsc\n  const dynamicSegmentData = dynamicData[0]\n\n  if (dynamicSegmentData === null) {\n    // This is an empty CacheNode; this particular server request did not\n    // render this segment. There may be a separate pending request that will,\n    // though, so we won't abort the task until all pending requests finish.\n    return\n  }\n\n  if (rsc === null) {\n    // This is a lazy cache node. We can overwrite it. This is only safe\n    // because we know that the LayoutRouter suspends if `rsc` is `null`.\n    cacheNode.rsc = dynamicSegmentData\n  } else if (isDeferredRsc(rsc)) {\n    // This is a deferred RSC promise. We can fulfill it with the data we just\n    // received from the server. If it was already resolved by a different\n    // navigation, then this does nothing because we can't overwrite data.\n    rsc.resolve(dynamicSegmentData, debugInfo)\n  } else {\n    // This is not a deferred RSC promise, nor is it empty, so it must have\n    // been populated by a different navigation. We must not overwrite it.\n  }\n\n  // Check if this is a leaf segment. If so, it will have a `head` property with\n  // a pending promise that needs to be resolved with the dynamic head from\n  // the server.\n  const head = cacheNode.head\n  if (isDeferredRsc(head)) {\n    head.resolve(dynamicHead, debugInfo)\n  }\n}\n\nfunction abortRemainingPendingTasks(\n  task: NavigationTask,\n  error: any,\n  debugInfo: Array<any> | null\n): NavigationTaskExitStatus {\n  let exitStatus\n  if (task.status === NavigationTaskStatus.Pending) {\n    // The data for this segment is still missing.\n    task.status = NavigationTaskStatus.Rejected\n    abortPendingCacheNode(task.node, error, debugInfo)\n\n    // If the server failed to fulfill the data for this segment, it implies\n    // that the route tree received from the server mismatched the tree that\n    // was previously prefetched.\n    //\n    // In an app with fully static routes and no proxy-driven redirects or\n    // rewrites, this should never happen, because the route for a URL would\n    // always be the same across multiple requests. So, this implies that some\n    // runtime routing condition changed, likely in a proxy, without being\n    // pushed to the client.\n    //\n    // When this happens, we treat this the same as a refresh(). The entire\n    // tree will be re-rendered from the root.\n    if (task.refreshState === null) {\n      // Trigger a \"soft\" refresh. Essentially the same as calling `refresh()`\n      // in a Server Action.\n      exitStatus = NavigationTaskExitStatus.SoftRetry\n    } else {\n      // The mismatch was discovered inside an inactive parallel route. This\n      // implies the inactive parallel route is no longer reachable at the URL\n      // that originally rendered it. Fall back to an MPA refresh.\n      // TODO: An alternative could be to trigger a soft refresh but to _not_\n      // re-use the inactive parallel routes this time. Similar to what would\n      // happen if were to do a hard refrehs, but without the HTML page.\n      exitStatus = NavigationTaskExitStatus.HardRetry\n    }\n  } else {\n    // This segment finished. (An error here is treated as Done because they are\n    // surfaced to the application during render.)\n    exitStatus = NavigationTaskExitStatus.Done\n  }\n\n  const taskChildren = task.children\n  if (taskChildren !== null) {\n    for (const [, taskChild] of taskChildren) {\n      const childExitStatus = abortRemainingPendingTasks(\n        taskChild,\n        error,\n        debugInfo\n      )\n      // Propagate the exit status up the tree. The statuses are ordered by\n      // their precedence.\n      if (childExitStatus > exitStatus) {\n        exitStatus = childExitStatus\n      }\n    }\n  }\n\n  return exitStatus\n}\n\nfunction abortPendingCacheNode(\n  cacheNode: CacheNode,\n  error: any,\n  debugInfo: Array<any> | null\n): void {\n  const rsc = cacheNode.rsc\n  if (isDeferredRsc(rsc)) {\n    if (error === null) {\n      // This will trigger a lazy fetch during render.\n      rsc.resolve(null, debugInfo)\n    } else {\n      // This will trigger an error during rendering.\n      rsc.reject(error, debugInfo)\n    }\n  }\n\n  // Check if this is a leaf segment. If so, it will have a `head` property with\n  // a pending promise that needs to be resolved. If an error was provided, we\n  // will not resolve it with an error, since this is rendered at the root of\n  // the app. We want the segment to error, not the entire app.\n  const head = cacheNode.head\n  if (isDeferredRsc(head)) {\n    head.resolve(null, debugInfo)\n  }\n}\n\nconst DEFERRED = Symbol()\n\ntype PendingDeferredRsc<T> = Promise<T> & {\n  status: 'pending'\n  resolve: (value: T, debugInfo: Array<any> | null) => void\n  reject: (error: any, debugInfo: Array<any> | null) => void\n  tag: Symbol\n  _debugInfo: Array<any>\n}\n\ntype FulfilledDeferredRsc<T> = Promise<T> & {\n  status: 'fulfilled'\n  value: T\n  resolve: (value: T, debugInfo: Array<any> | null) => void\n  reject: (error: any, debugInfo: Array<any> | null) => void\n  tag: Symbol\n  _debugInfo: Array<any>\n}\n\ntype RejectedDeferredRsc<T> = Promise<T> & {\n  status: 'rejected'\n  reason: any\n  resolve: (value: T, debugInfo: Array<any> | null) => void\n  reject: (error: any, debugInfo: Array<any> | null) => void\n  tag: Symbol\n  _debugInfo: Array<any>\n}\n\ntype DeferredRsc<T extends React.ReactNode = React.ReactNode> =\n  | PendingDeferredRsc<T>\n  | FulfilledDeferredRsc<T>\n  | RejectedDeferredRsc<T>\n\n// This type exists to distinguish a DeferredRsc from a Flight promise. It's a\n// compromise to avoid adding an extra field on every Cache Node, which would be\n// awkward because the pre-PPR parts of codebase would need to account for it,\n// too. We can remove it once type Cache Node type is more settled.\nexport function isDeferredRsc(value: any): value is DeferredRsc {\n  return value && typeof value === 'object' && value.tag === DEFERRED\n}\n\nfunction createDeferredRsc<\n  T extends React.ReactNode = React.ReactNode,\n>(): PendingDeferredRsc<T> {\n  // Create an unresolved promise that represents data derived from a Flight\n  // response. The promise will be resolved later as soon as we start receiving\n  // data from the server, i.e. as soon as the Flight client decodes and returns\n  // the top-level response object.\n\n  // The `_debugInfo` field contains profiling information. Promises that are\n  // created by Flight already have this info added by React; for any derived\n  // promise created by the router, we need to transfer the Flight debug info\n  // onto the derived promise.\n  //\n  // The debug info represents the latency between the start of the navigation\n  // and the start of rendering. (It does not represent the time it takes for\n  // whole stream to finish.)\n  const debugInfo: Array<any> = []\n\n  let resolve: any\n  let reject: any\n  const pendingRsc = new Promise<T>((res, rej) => {\n    resolve = res\n    reject = rej\n  }) as PendingDeferredRsc<T>\n  pendingRsc.status = 'pending'\n  pendingRsc.resolve = (value: T, responseDebugInfo: Array<any> | null) => {\n    if (pendingRsc.status === 'pending') {\n      const fulfilledRsc: FulfilledDeferredRsc<T> = pendingRsc as any\n      fulfilledRsc.status = 'fulfilled'\n      fulfilledRsc.value = value\n      if (responseDebugInfo !== null) {\n        // Transfer the debug info to the derived promise.\n        debugInfo.push.apply(debugInfo, responseDebugInfo)\n      }\n      resolve(value)\n    }\n  }\n  pendingRsc.reject = (error: any, responseDebugInfo: Array<any> | null) => {\n    if (pendingRsc.status === 'pending') {\n      const rejectedRsc: RejectedDeferredRsc<T> = pendingRsc as any\n      rejectedRsc.status = 'rejected'\n      rejectedRsc.reason = error\n      if (responseDebugInfo !== null) {\n        // Transfer the debug info to the derived promise.\n        debugInfo.push.apply(debugInfo, responseDebugInfo)\n      }\n      reject(error)\n    }\n  }\n  pendingRsc.tag = DEFERRED\n  pendingRsc._debugInfo = debugInfo\n\n  return pendingRsc\n}\n\n/**\n * Helper for the Instant Navigation Testing API. Waits for the navigation lock\n * to be released before returning. The network request has already completed by\n * the time this is called, so this only delays writing the dynamic data.\n *\n * Not exposed in production builds by default.\n */\nasync function waitForNavigationLock(): Promise<void> {\n  if (process.env.__NEXT_EXPOSE_TESTING_API) {\n    const { waitForNavigationLockIfActive } =\n      require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock')\n    await waitForNavigationLockIfActive()\n  }\n}\n"],"names":["PrefetchHint","PAGE_SEGMENT_KEY","DEFAULT_SEGMENT_KEY","NOT_FOUND_SEGMENT_KEY","matchSegment","createHrefFromUrl","fetchServerResponse","dispatchAppRouterAction","ACTION_SERVER_PATCH","isNavigatingToNewRootLayout","getLastCommittedTree","convertServerPatchToFullTree","convertReusedFlightRouterStateToRouteTree","readSegmentCacheEntry","waitForSegmentCacheEntry","markRouteEntryAsDynamicRewrite","invalidateRouteCacheEntries","getStaleAt","writeStaticStageResponseIntoCache","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","EntryStatus","FetchStrategy","discoverKnownRoute","NEXT_NAV_DEPLOYMENT_ID_HEADER","getRenderedSearchFromVaryPath","readFromBFCache","readFromBFCacheDuringRegularNavigation","writeToBFCache","writeHeadToBFCache","updateBFCacheEntryStaleAt","computeDynamicStaleAt","FreshnessPolicy","noop","createInitialCacheNodeForHydration","navigatedAt","initialTree","seedData","seedHead","seedDynamicStaleAt","accumulation","separateRefreshUrls","scrollRef","task","createCacheNodeOnNavigation","startPPRNavigation","oldUrl","oldRenderedSearch","oldCacheNode","oldRouterState","newRouteTree","newMetadataVaryPath","freshness","isSamePageNavigation","didFindRootLayout","parentNeedsDynamicRequest","parentRefreshState","oldRootRefreshState","canonicalUrl","renderedSearch","updateCacheNodeOnNavigation","undefined","oldSegment","newSegment","createSegmentFromRouteTree","newSlots","slots","oldRouterStateChildren","seedDataChildren","childDidFindRootLayout","prefetchHints","IsRootLayout","shouldRefreshDynamicData","isLeafSegment","newCacheNode","needsDynamicRequest","dropPrefetchRsc","reuseSharedCacheNode","seedRsc","result","createCacheNodeForSegment","cacheNode","maybeRefreshState","refreshState","accumulateRefreshUrl","patchedRouterStateChildren","taskChildren","childNeedsDynamicRequest","dynamicRequestTreeChildren","newCacheNodeSlots","oldCacheNodeSlots","Map","parallelRouteKey","newRouteTreeChild","oldRouterStateChild","seedDataChild","oldSegmentChild","newSegmentChild","seedHeadChild","reuseActiveSegmentInDefaultSlot","oldCacheNodeChild","taskChild","set","node","taskChildRoute","route","dynamicRequestTreeChild","dynamicRequestTree","newFlightRouterState","status","createDynamicRequestTree","children","accumulateScrollRef","current","isPage","varyPath","stringifiedQuery","JSON","stringify","Object","fromEntries","URLSearchParams","segment","patchRouterStateWithNewChildren","baseRouterState","newChildren","clone","newRouterState","refreshUrl","Set","add","parentRouteTree","reusedUrl","reusedRenderedSearch","oldRefreshState","acc","metadataVaryPath","reusedRouteTree","existingCacheNode","createCacheNode","rsc","prefetchRsc","head","prefetchHead","now","tree","dynamicStaleAt","bfcacheEntry","oldRsc","oldRscDidResolve","isDeferredRsc","cachedRsc","isCachedRscPartial","segmentEntry","Fulfilled","isPartial","Pending","promiseForFulfilledEntry","then","entry","Empty","Rejected","doesSegmentNeedDynamicRequest","createDeferredRsc","doesHeadNeedDynamicRequest","cachedHead","isCachedHeadPartial","metadataEntry","process","env","__NEXT_OPTIMISTIC_ROUTING","previousNavigationDidMismatch","spawnDynamicRequests","primaryUrl","nextUrl","freshnessPolicy","routeCacheEntry","navigateType","primaryRequestPromise","fetchMissingDynamicData","refreshRequestPromises","scopedDynamicRequestTree","push","URL","location","origin","voidPromise","finishNavigationTask","exitStatus","waitForRequestsToFinish","abortRemainingPendingTasks","isHardRetry","primaryRequestResult","dispatchRetryDueToTreeMismatch","url","seed","Promise","resolve","onFulfill","remainingCount","onReject","length","forEach","refreshRequestPromise","retryUrl","retryNextUrl","baseTree","originalNavigateType","Date","pathname","routeTree","lastCommitted","retryNavigateType","retryAction","type","previousTree","mpa","flightRouterState","isHmrRefresh","flightData","dynamicStaleTime","__NEXT_EXPOSE_TESTING_API","waitForNavigationLock","staticStageData","response","staticStageResponse","isResponsePartial","s","staleAt","buildId","responseHeaders","get","b","f","h","catch","runtimePrefetchStream","processed","PPRRuntime","flightDatas","headVaryParams","navigationSeed","didReceiveUnknownParallelRoute","writeDynamicDataIntoNavigationTask","data","debugInfo","serverRouteTree","dynamicData","dynamicHead","finishPendingCacheNode","serverChildren","dynamicDataChildren","serverRouteTreeChild","dynamicDataChild","taskSegment","serverSegment","childDidReceiveUnknownParallelRoute","dynamicSegmentData","error","abortPendingCacheNode","childExitStatus","reject","DEFERRED","Symbol","value","tag","pendingRsc","res","rej","responseDebugInfo","fulfilledRsc","apply","rejectedRsc","reason","_debugInfo","waitForNavigationLockIfActive","require"],"mappings":"AAOA,SAASA,YAAY,QAAQ,uCAAsC;AACnE,SACEC,gBAAgB,EAChBC,mBAAmB,EACnBC,qBAAqB,QAChB,8BAA6B;AACpC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,mBAAmB,QAAQ,0BAAyB;AAC7D,SAASC,uBAAuB,QAAQ,sBAAqB;AAC7D,SACEC,mBAAmB,QAEd,yBAAwB;AAC/B,SAASC,2BAA2B,QAAQ,qCAAoC;AAChF,SAASC,oBAAoB,QAAQ,6BAA4B;AACjE,SACEC,4BAA4B,QAEvB,8BAA6B;AACpC,SAIEC,yCAAyC,EACzCC,qBAAqB,EACrBC,wBAAwB,EACxBC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,UAAU,EACVC,iCAAiC,EACjCC,4BAA4B,EAC5BC,mCAAmC,EACnCC,WAAW,QACN,yBAAwB;AAC/B,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SAASC,6BAA6B,QAAQ,yBAAwB;AAEtE,SACEC,6BAA6B,QAExB,6BAA4B;AACnC,SACEC,eAAe,EACfC,sCAAsC,EACt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