Unverified Commit df247d1b authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Move prefetch hints from CacheNodeSeedData to FlightRouterState (#90066)

## Summary

Prefetch hints were previously stored in CacheNodeSeedData — the payload
the server sends for each segment's React content. This moves them to
FlightRouterState, the route tree structure that the server sends
alongside the seed data. FlightRouterState is a better home because
prefetch hints describe properties of the route structure (loading
boundaries, instant configs) rather than properties of the rendered
content. It also ensures that hints are always available during
navigations, not just prefetches.

Since this changes the FlightRouterState tuple layout anyway, it also
folds the existing `isRootLayout` boolean and `HasLoadingBoundary` enum
into the same bitmask field at FlightRouterState[4].

## Test plan

- Existing unit tests updated for new format
(`flight-data-helpers.test.ts`, `types.test.ts`)
- MPA navigation test validates root layout change detection via bitmask
- `prefetch-true-instant` e2e test validates Link `prefetch={true}`
behavior with instant routes
parent 55ea60e6
import { computeChangedPath } from './compute-changed-path'
import { PrefetchHint } from '../../../shared/lib/app-router-types'
describe('computeChangedPath', () => {
it('should return the correct path', () => {
......@@ -27,7 +28,7 @@ describe('computeChangedPath', () => {
},
undefined,
undefined,
true,
PrefetchHint.IsRootLayout,
],
[
'',
......@@ -52,7 +53,7 @@ describe('computeChangedPath', () => {
},
undefined,
undefined,
true,
PrefetchHint.IsRootLayout,
]
)
).toBe('/')
......
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types'
import type { RouteTree } from '../segment-cache/cache'
export function isNavigatingToNewRootLayout(
......@@ -26,12 +27,16 @@ export function isNavigatingToNewRootLayout(
}
// Current tree root layout found
if (currentTree[4]) {
const currentIsRootLayout =
((currentTree[4] ?? 0) & PrefetchHint.IsRootLayout) !== 0
const nextIsRootLayout =
(nextTree.prefetchHints & PrefetchHint.IsRootLayout) !== 0
if (currentIsRootLayout) {
// If the next tree doesn't have the root layout flag, it must have changed.
return !nextTree.isRootLayout
return !nextIsRootLayout
}
// Current tree didn't have its root layout here, must have changed.
if (nextTree.isRootLayout) {
if (nextIsRootLayout) {
return true
}
......
......@@ -6,6 +6,7 @@ import type {
} from '../../../shared/lib/app-router-types'
import type { CacheNode } from '../../../shared/lib/app-router-types'
import type { HeadData } from '../../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types'
import {
PAGE_SEGMENT_KEY,
DEFAULT_SEGMENT_KEY,
......@@ -315,7 +316,9 @@ function updateCacheNodeOnNavigation(
// We're currently traversing the part of the tree that was also part of
// the previous route. If we discover a root layout, then we don't need to
// trigger an MPA navigation.
const childDidFindRootLayout = didFindRootLayout || newRouteTree.isRootLayout
const childDidFindRootLayout =
didFindRootLayout ||
(newRouteTree.prefetchHints & PrefetchHint.IsRootLayout) !== 0
let shouldRefreshDynamicData: boolean = false
switch (freshness) {
......@@ -534,7 +537,7 @@ function updateCacheNodeOnNavigation(
? [refreshState.canonicalUrl, refreshState.renderedSearch]
: null,
null,
newRouteTree.isRootLayout,
newRouteTree.prefetchHints,
]
return {
......@@ -670,7 +673,7 @@ function createCacheNodeOnNavigation(
patchedRouterStateChildren,
null,
null,
newRouteTree.isRootLayout,
newRouteTree.prefetchHints,
]
return {
......
import React from 'react'
import type {
FlightData,
FlightRouterState,
import {
PrefetchHint,
type FlightData,
type FlightRouterState,
} from '../../../shared/lib/app-router-types'
import { shouldHardNavigate } from './should-hard-navigate'
......@@ -19,7 +20,7 @@ describe('shouldHardNavigate', () => {
},
undefined,
undefined,
true,
PrefetchHint.IsRootLayout,
]
const initialRouterStateTree = getInitialRouterStateTree()
const getFlightData = (): FlightData => {
......@@ -78,7 +79,7 @@ describe('shouldHardNavigate', () => {
},
null,
null,
true,
PrefetchHint.IsRootLayout,
]
const initialRouterStateTree = getInitialRouterStateTree()
const getFlightData = (): FlightData => {
......@@ -135,7 +136,7 @@ describe('shouldHardNavigate', () => {
},
null,
null,
true,
PrefetchHint.IsRootLayout,
]
const initialRouterStateTree = getInitialRouterStateTree()
const getFlightData = (): FlightData => {
......
......@@ -11,7 +11,6 @@ import {
readVaryParams,
type VaryParams,
} from '../../../shared/lib/segment-cache/vary-params-decoding'
import { HasLoadingBoundary } from '../../../shared/lib/app-router-types'
import {
NEXT_DID_POSTPONE_HEADER,
NEXT_INSTANT_PREFETCH_HEADER,
......@@ -145,20 +144,9 @@ type RouteTreeShared = {
slots: null | {
[parallelRouteKey: string]: RouteTree
}
isRootLayout: boolean
// If this is a dynamic route, indicates whether there is a loading boundary
// somewhere in the tree. If not, we can skip the prefetch for the data,
// because we know it would be an empty response. (For a static/PPR route,
// this value is disregarded, because in that model `loading.tsx` is treated
// like any other Suspense boundary.)
hasLoadingBoundary: HasLoadingBoundary
// Bitmask of PrefetchHint flags. Indicates whether this segment has a
// runtime prefetch, and whether the subtree contains any instant configs.
// Determined by the server; not purely a user configuration because the
// server may determine that a route is fully static and doesn't need
// runtime prefetching regardless of the configuration.
// Bitmask of PrefetchHint flags. Encodes route structure metadata:
// root layout, loading boundaries, instant configs, and runtime prefetch
// hints.
prefetchHints: number
}
......@@ -721,8 +709,7 @@ function deprecated_createOptimisticRouteTree(
),
isPage: true,
slots: clonedSlots,
isRootLayout: tree.isRootLayout,
hasLoadingBoundary: tree.hasLoadingBoundary,
prefetchHints: tree.prefetchHints,
}
}
......@@ -734,8 +721,6 @@ function deprecated_createOptimisticRouteTree(
varyPath: tree.varyPath,
isPage: false,
slots: clonedSlots,
isRootLayout: tree.isRootLayout,
hasLoadingBoundary: tree.hasLoadingBoundary,
prefetchHints: tree.prefetchHints,
}
}
......@@ -1017,8 +1002,6 @@ export function createMetadataRouteTree(
// one. If this logic ever gets more complex we can change this to an enum.
isPage: true,
slots: null,
isRootLayout: false,
hasLoadingBoundary: HasLoadingBoundary.SubtreeHasNoLoadingBoundary,
prefetchHints: 0,
}
return metadata
......@@ -1318,10 +1301,6 @@ function convertTreePrefetchToRouteTree(
varyPath: varyPath as any,
isPage: isPage as boolean as any,
slots,
isRootLayout: prefetch.isRootLayout,
// This field is only relevant to dynamic routes. For a PPR/static route,
// there's always some partial loading state we can fetch.
hasLoadingBoundary: HasLoadingBoundary.SegmentHasLoadingBoundary,
prefetchHints: prefetch.prefetchHints,
}
}
......@@ -1501,15 +1480,7 @@ function convertFlightRouterStateToRouteTree(
varyPath: varyPath as any,
isPage: isPage as boolean as any,
slots,
isRootLayout: flightRouterState[4] === true,
hasLoadingBoundary:
flightRouterState[5] !== undefined
? flightRouterState[5]
: HasLoadingBoundary.SubtreeHasNoLoadingBoundary,
// Non-static tree responses are only used by apps that haven't adopted
// Cache Components. So this is always 0.
prefetchHints: 0,
prefetchHints: flightRouterState[4] ?? 0,
}
}
......@@ -1529,7 +1500,6 @@ export function convertRouteTreeToFlightRouterState(
parallelRoutes,
null,
null,
routeTree.isRootLayout,
]
return flightRouterState
}
......@@ -2349,7 +2319,7 @@ function writeSeedDataIntoCache(
// (CacheNodeSeedData) into the prefetch cache.
const rsc = seedData[0]
const isPartial = rsc === null || isResponsePartial
const varyParamsThenable = seedData[5]
const varyParamsThenable = seedData[4]
// Each segment carries its own vary params thenable in the seed data. The
// thenable resolves to the set of params the segment accessed during render.
// A null thenable means tracking was not enabled (not a prerender).
......
......@@ -764,7 +764,6 @@ function convertServerPatchToFullTreeImpl(
newSeedDataChildren,
null,
isEmptySeedDataPartial,
0,
null,
]
......
......@@ -797,8 +797,7 @@ function reifyRouteTree(
segment: newSegment,
refreshState: pattern.refreshState,
slots: newSlots,
isRootLayout: pattern.isRootLayout,
hasLoadingBoundary: pattern.hasLoadingBoundary,
prefetchHints: pattern.prefetchHints,
isPage: true,
varyPath: newVaryPath,
......@@ -814,8 +813,7 @@ function reifyRouteTree(
segment: newSegment,
refreshState: pattern.refreshState,
slots: newSlots,
isRootLayout: pattern.isRootLayout,
hasLoadingBoundary: pattern.hasLoadingBoundary,
prefetchHints: pattern.prefetchHints,
isPage: false,
varyPath: newVaryPath,
......
......@@ -3,10 +3,7 @@ import type {
Segment as FlightRouterStateSegment,
Segment,
} from '../../../shared/lib/app-router-types'
import {
HasLoadingBoundary,
PrefetchHint,
} from '../../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types'
import { matchSegment } from '../match-segments'
import {
readOrCreateRouteCacheEntry,
......@@ -1107,8 +1104,10 @@ function diffRouteTreeAgainstCurrent(
// anywhere in the tree, the server will never return any data, so
// we can skip the request.
const subtreeHasLoadingBoundary =
newTreeChild.hasLoadingBoundary !==
HasLoadingBoundary.SubtreeHasNoLoadingBoundary
(newTreeChild.prefetchHints &
(PrefetchHint.SegmentHasLoadingBoundary |
PrefetchHint.SubtreeHasLoadingBoundary)) !==
0
const requestTreeChild = subtreeHasLoadingBoundary
? pingPPRDisabledRouteTreeUpToLoadingBoundary(
now,
......@@ -1179,7 +1178,6 @@ function diffRouteTreeAgainstCurrent(
requestTreeChildren,
null,
null,
newTree.isRootLayout,
]
return requestTree
}
......@@ -1239,7 +1237,7 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
case EntryStatus.Fulfilled: {
// The segment is already cached.
const segmentHasLoadingBoundary =
tree.hasLoadingBoundary === HasLoadingBoundary.SegmentHasLoadingBoundary
(tree.prefetchHints & PrefetchHint.SegmentHasLoadingBoundary) !== 0
if (segmentHasLoadingBoundary) {
// This segment has a loading boundary, which means the server won't
// render its children. So there's nothing left to prefetch along this
......@@ -1287,7 +1285,6 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
requestTreeChildren,
null,
refetchMarker,
tree.isRootLayout,
]
return requestTree
}
......@@ -1407,7 +1404,6 @@ function pingRouteTreeAndIncludeDynamicData(
requestTreeChildren,
null,
refetchMarker,
tree.isRootLayout,
]
return requestTree
}
......
import { prepareFlightRouterStateForRequest } from './flight-data-helpers'
import {
HasLoadingBoundary,
PrefetchHint,
type FlightRouterState,
} from '../shared/lib/app-router-types'
......@@ -12,8 +12,7 @@ describe('prepareFlightRouterStateForRequest', () => {
{},
['/some/url', ''],
'refetch',
true,
1,
PrefetchHint.IsRootLayout | 1,
]
const result = prepareFlightRouterStateForRequest(flightRouterState, true)
......@@ -130,50 +129,34 @@ describe('prepareFlightRouterStateForRequest', () => {
})
describe('optional fields preservation', () => {
it('should preserve isRootLayout when true', () => {
it('should preserve prefetchHints with IsRootLayout', () => {
const flightRouterState: FlightRouterState = [
'segment',
{},
null,
null,
true,
PrefetchHint.IsRootLayout,
]
const result = prepareFlightRouterStateForRequest(flightRouterState)
const decoded = JSON.parse(decodeURIComponent(result))
expect(decoded[4]).toBe(true)
expect(decoded[4]).toBe(PrefetchHint.IsRootLayout)
})
it('should preserve isRootLayout when false', () => {
it('should preserve prefetchHints with SegmentHasLoadingBoundary', () => {
const flightRouterState: FlightRouterState = [
'segment',
{},
null,
null,
false,
PrefetchHint.SegmentHasLoadingBoundary,
]
const result = prepareFlightRouterStateForRequest(flightRouterState)
const decoded = JSON.parse(decodeURIComponent(result))
expect(decoded[4]).toBe(false)
})
it('should preserve hasLoadingBoundary', () => {
const flightRouterState: FlightRouterState = [
'segment',
{},
null,
null,
undefined,
1, // HasLoadingBoundary value
]
const result = prepareFlightRouterStateForRequest(flightRouterState)
const decoded = JSON.parse(decodeURIComponent(result))
expect(decoded[5]).toBe(1)
expect(decoded[4]).toBe(PrefetchHint.SegmentHasLoadingBoundary)
})
it('should handle minimal FlightRouterState (only segment and parallelRoutes)', () => {
......@@ -262,14 +245,12 @@ describe('prepareFlightRouterStateForRequest', () => {
{},
['/modal/path', ''],
null,
false,
HasLoadingBoundary.SegmentHasLoadingBoundary,
PrefetchHint.SegmentHasLoadingBoundary,
],
},
['/dashboard/url', ''],
'refetch',
true,
1,
PrefetchHint.IsRootLayout | PrefetchHint.SegmentHasLoadingBoundary,
],
sidebar: [
['slug', 'user-123', 'd', null],
......@@ -280,8 +261,7 @@ describe('prepareFlightRouterStateForRequest', () => {
},
['/main/url', ''],
'inside-shared-layout',
true,
1,
PrefetchHint.IsRootLayout | PrefetchHint.SegmentHasLoadingBoundary,
]
const result = prepareFlightRouterStateForRequest(complexState)
......@@ -291,22 +271,24 @@ describe('prepareFlightRouterStateForRequest', () => {
expect(decoded[0]).toBe('__PAGE__') // search params stripped
expect(decoded[2]).toBeNull() // URL stripped
expect(decoded[3]).toBe('inside-shared-layout') // server marker preserved
expect(decoded[4]).toBe(true) // isRootLayout preserved
expect(decoded[5]).toBe(1) // hasLoadingBoundary preserved
expect(decoded[4]).toBe(
PrefetchHint.IsRootLayout | PrefetchHint.SegmentHasLoadingBoundary
) // prefetchHints preserved
// Children route checks
const childrenRoute = decoded[1].children
expect(childrenRoute[2]).toBeNull() // URL stripped
expect(childrenRoute[3]).toBe('refetch') // server marker preserved
expect(childrenRoute[4]).toBe(true) // isRootLayout preserved
expect(childrenRoute[4]).toBe(
PrefetchHint.IsRootLayout | PrefetchHint.SegmentHasLoadingBoundary
) // prefetchHints preserved
// Modal route checks
const modalRoute = childrenRoute[1].modal
expect(modalRoute[0]).toBe('__PAGE__') // search params stripped
expect(modalRoute[2]).toBeNull() // URL stripped
expect(modalRoute[3]).toBeNull() // 'refresh' marker stripped
expect(modalRoute[4]).toBe(false) // isRootLayout preserved
expect(modalRoute[5]).toBe(HasLoadingBoundary.SegmentHasLoadingBoundary) // hasLoadingBoundary preserved
expect(modalRoute[4]).toBe(PrefetchHint.SegmentHasLoadingBoundary) // prefetchHints preserved
// Sidebar route (dynamic segment) checks
const sidebarRoute = decoded[1].sidebar
......
......@@ -251,8 +251,7 @@ function stripClientOnlyDataFromFlightRouterState(
parallelRoutes,
_refreshState, // Intentionally unused - URLs are client-only
refreshMarker,
isRootLayout,
hasLoadingBoundary,
prefetchHints,
] = flightRouterState
// Strip client-only data from the segment
......@@ -272,11 +271,8 @@ function stripClientOnlyDataFromFlightRouterState(
}
// Append optional fields if present
if (isRootLayout !== undefined) {
result[4] = isRootLayout
}
if (hasLoadingBoundary !== undefined) {
result[5] = hasLoadingBoundary
if (prefetchHints !== undefined) {
result[4] = prefetchHints
}
// Everything else is used only by the client and is not needed for requests.
......
......@@ -1525,7 +1525,7 @@ async function getRSCPayload(
workStore,
} = ctx
const initialTree = createFlightRouterStateFromLoaderTree(
const initialTree = await createFlightRouterStateFromLoaderTree(
tree,
getDynamicParamFromSegment,
query
......@@ -1689,7 +1689,7 @@ async function getErrorRSCPayload(
createElement(Metadata, null)
)
const initialTree = createFlightRouterStateFromLoaderTree(
const initialTree = await createFlightRouterStateFromLoaderTree(
tree,
getDynamicParamFromSegment,
query
......@@ -1724,7 +1724,6 @@ async function getErrorRSCPayload(
{},
null,
false,
0, // We don't currently support runtime prefetching for error pages.
null, // varyParams - not tracked for error pages
]
......
......@@ -68,13 +68,6 @@ export type TreePrefetch = {
/** Bitmask of PrefetchHint flags for this segment and its subtree */
prefetchHints: number
// Extra fields that only exist so we can reconstruct a FlightRouterState on
// the client. We may be able to unify TreePrefetch and FlightRouterState
// after some refactoring, but in the meantime it would be wasteful to add a
// bunch of new prefetch-only fields to FlightRouterState. So think of
// TreePrefetch as a superset of FlightRouterState.
isRootLayout: boolean
}
export type SegmentPrefetch = {
......@@ -345,14 +338,14 @@ function collectSegmentDataImpl(
slotMetadata[parallelRouteKey] = childTree
}
const prefetchHints = seedData !== null ? seedData[4] : 0
const prefetchHints = route[4] ?? 0
// Determine which params this segment varies on.
// Read the vary params thenable directly from the seed data. By the time
// collectSegmentData runs, the thenable should be fulfilled. If it's not
// fulfilled or null, treat as unknown (null means we can't share cache
// entries across param values).
const varyParamsThenable = seedData !== null ? seedData[5] : null
const varyParamsThenable = seedData !== null ? seedData[4] : null
const varyParams =
varyParamsThenable !== null ? readVaryParams(varyParamsThenable) : null
......@@ -404,7 +397,6 @@ function collectSegmentDataImpl(
param,
prefetchHints,
slots: slotMetadata,
isRootLayout: route[4] === true,
}
}
......
import type { ComponentType } from 'react'
import {
PrefetchHint,
type CacheNodeSeedData,
type LoadingModuleData,
import type {
CacheNodeSeedData,
LoadingModuleData,
} from '../../shared/lib/app-router-types'
import type { PreloadCallbacks } from './types'
import {
......@@ -42,7 +41,6 @@ import {
getConventionPathByType,
isNextjsBuiltinFilePath,
} from './segment-explorer-path'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
/**
* Use the provided loader tree to create the React Component tree.
......@@ -226,17 +224,6 @@ async function createComponentTreeInternal(
})
: []
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
let prefetchHints = 0
if (instantConfig && typeof instantConfig === 'object') {
prefetchHints |= PrefetchHint.SubtreeHasInstant
if (instantConfig.prefetch === 'runtime') {
prefetchHints |= PrefetchHint.HasRuntimePrefetch
}
}
const [Forbidden, forbiddenStyles] =
authInterrupts && forbidden
? await createComponentStylesAndScripts({
......@@ -697,7 +684,6 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
prefetchHints,
// No user-provided component, so no params will be accessed. Use the
// pre-resolved empty tracker.
emptyVaryParamsAccumulator
......@@ -737,7 +723,6 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
true,
prefetchHints,
// force-dynamic postpones without rendering the component, so no params
// are accessed. The vary params are empty.
emptyVaryParamsAccumulator
......@@ -865,7 +850,6 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
prefetchHints,
varyParamsAccumulator
)
} else {
......@@ -1080,7 +1064,6 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
prefetchHints,
varyParamsAccumulator
)
}
......@@ -1232,7 +1215,6 @@ function createSeedData(
parallelRoutes: Record<string, CacheNodeSeedData | null>,
loading: LoadingModuleData | null,
isPossiblyPartialResponse: boolean,
prefetchHints: number,
varyParamsAccumulator: VaryParamsAccumulator | null
): CacheNodeSeedData {
if (loading !== null) {
......@@ -1248,22 +1230,11 @@ function createSeedData(
children: rsc,
})
}
// Propagate SubtreeHasInstant from children so the root reflects the
// entire subtree.
// TODO: We should send the prefetch hints bitmask as part of the route tree,
// rather than the CacheNodeSeedData.
for (const key in parallelRoutes) {
const child = parallelRoutes[key]
if (child !== null) {
prefetchHints |= child[4] & PrefetchHint.SubtreeHasInstant
}
}
return [
rsc,
parallelRoutes,
null,
isPossiblyPartialResponse,
prefetchHints,
varyParamsAccumulator ? getVaryParamsThenable(varyParamsAccumulator) : null,
]
}
import type { LoaderTree } from '../lib/app-dir-module'
import {
HasLoadingBoundary,
PrefetchHint,
type FlightRouterState,
} from '../../shared/lib/app-router-types'
import type { GetDynamicParamFromSegment } from './app-render'
import { addSearchParamsIfPageSegment } from '../../shared/lib/segment'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
function createFlightRouterStateFromLoaderTreeImpl(
async function createFlightRouterStateFromLoaderTreeImpl(
loaderTree: LoaderTree,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
includeHasLoadingBoundary: boolean,
didFindRootLayout: boolean
): FlightRouterState {
const [segment, parallelRoutes, { layout, loading }] = loaderTree
): Promise<FlightRouterState> {
const [segment, parallelRoutes, { layout, loading, page }] = loaderTree
const dynamicParam = getDynamicParamFromSegment(loaderTree)
const treeSegment = dynamicParam ? dynamicParam.treeSegment : segment
......@@ -22,83 +22,93 @@ function createFlightRouterStateFromLoaderTreeImpl(
{},
]
// Load the layout or page module to check for unstable_instant config
const mod = layout ? await layout[0]() : page ? await page[0]() : undefined
const instantConfig = mod
? (mod as AppSegmentConfig).unstable_instant
: undefined
let prefetchHints = 0
// Mark the first segment that has a layout as the "root" layout
if (!didFindRootLayout && typeof layout !== 'undefined') {
didFindRootLayout = true
segmentTree[4] = true
prefetchHints |= PrefetchHint.IsRootLayout
}
if (instantConfig && typeof instantConfig === 'object') {
prefetchHints |= PrefetchHint.SubtreeHasInstant
if (instantConfig.prefetch === 'runtime') {
prefetchHints |= PrefetchHint.HasRuntimePrefetch
}
}
// Check if this segment has a loading boundary
if (loading) {
prefetchHints |= PrefetchHint.SegmentHasLoadingBoundary
}
let childHasLoadingBoundary = false
const children: FlightRouterState[1] = {}
for (const parallelRouteKey in parallelRoutes) {
const child = createFlightRouterStateFromLoaderTreeImpl(
const child = await createFlightRouterStateFromLoaderTreeImpl(
parallelRoutes[parallelRouteKey],
getDynamicParamFromSegment,
searchParams,
includeHasLoadingBoundary,
didFindRootLayout
)
if (
includeHasLoadingBoundary &&
child[5] !== HasLoadingBoundary.SubtreeHasNoLoadingBoundary
) {
childHasLoadingBoundary = true
// Propagate subtree flags from children
if (child[4] !== undefined) {
prefetchHints |=
child[4] &
(PrefetchHint.SubtreeHasInstant |
PrefetchHint.SubtreeHasLoadingBoundary)
// If a child has a loading boundary (either directly or in its subtree),
// propagate that as SubtreeHasLoadingBoundary to this segment.
if (
child[4] &
(PrefetchHint.SegmentHasLoadingBoundary |
PrefetchHint.SubtreeHasLoadingBoundary)
) {
prefetchHints |= PrefetchHint.SubtreeHasLoadingBoundary
}
}
children[parallelRouteKey] = child
}
segmentTree[1] = children
if (includeHasLoadingBoundary) {
// During a route tree prefetch, the FlightRouterState includes whether a
// tree has a loading boundary. The client uses this to determine if it can
// skip the data prefetch request — if `hasLoadingBoundary` is `false`, the
// data prefetch response will be empty, so there's no reason to request it.
// NOTE: It would be better to accumulate this while building the loader
// tree so we don't have to keep re-deriving it, but since this won't be
// once PPR is enabled everywhere, it's not that important.
segmentTree[5] = loading
? HasLoadingBoundary.SegmentHasLoadingBoundary
: childHasLoadingBoundary
? HasLoadingBoundary.SubtreeHasLoadingBoundary
: HasLoadingBoundary.SubtreeHasNoLoadingBoundary
if (prefetchHints !== 0) {
segmentTree[4] = prefetchHints
}
return segmentTree
}
export function createFlightRouterStateFromLoaderTree(
export async function createFlightRouterStateFromLoaderTree(
loaderTree: LoaderTree,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any
) {
const includeHasLoadingBoundary = false
): Promise<FlightRouterState> {
const didFindRootLayout = false
return createFlightRouterStateFromLoaderTreeImpl(
loaderTree,
getDynamicParamFromSegment,
searchParams,
includeHasLoadingBoundary,
didFindRootLayout
)
}
export function createRouteTreePrefetch(
export async function createRouteTreePrefetch(
loaderTree: LoaderTree,
getDynamicParamFromSegment: GetDynamicParamFromSegment
): FlightRouterState {
): Promise<FlightRouterState> {
// Search params should not be added to page segment's cache key during a
// route tree prefetch request, because they do not affect the structure of
// the route. The client cache has its own logic to handle search params.
const searchParams = {}
// During a route tree prefetch, we include `hasLoadingBoundary` in
// the response.
const includeHasLoadingBoundary = true
const didFindRootLayout = false
return createFlightRouterStateFromLoaderTreeImpl(
loaderTree,
getDynamicParamFromSegment,
searchParams,
includeHasLoadingBoundary,
didFindRootLayout
)
}
......@@ -1053,23 +1053,14 @@ function deserializeFromChunks<T>(
type SegmentData = {
node: React.ReactNode | null
isPartial: boolean
prefetchHints: number
varyParams: VaryParamsThenable | null
}
function createSegmentData(seedData: CacheNodeSeedData): SegmentData {
const [
node,
_parallelRoutesData,
_unused,
isPartial,
prefetchHints,
varyParams,
] = seedData
const [node, _parallelRoutesData, _unused, isPartial, varyParams] = seedData
return {
node,
isPartial,
prefetchHints,
varyParams,
}
}
......@@ -1084,7 +1075,6 @@ function getCacheNodeSeedDataFromSegment(
slots,
/* unused (previously `loading`) */ null,
data.isPartial,
data.prefetchHints,
data.varyParams,
]
}
......
......@@ -17,7 +17,7 @@ const validFixtures = [
},
null,
null,
true,
0b10000, // PrefetchHint.IsRootLayout
],
[
['a', 'b', 'c', null],
......@@ -52,7 +52,7 @@ const invalidFixtures = [
invalid: 'invalid',
},
],
// invalid isRootLayout
// invalid refresh marker (number instead of string)
[
['a', 'b', 'c', null],
{
......
......@@ -75,7 +75,7 @@ export const flightRouterStateSchema: s.Describe<any> = s.tuple([
])
)
),
s.optional(s.boolean()),
s.optional(s.number()),
])
export type ServerOnInstrumentationRequestError = (
......
......@@ -151,8 +151,11 @@ export async function walkTreeWithFlightRouterState({
const routerState = parsedRequestHeaders.isRouteTreePrefetchRequest
? // Route tree prefetch requests contain some extra information
createRouteTreePrefetch(loaderTreeToFilter, getDynamicParamFromSegment)
: createFlightRouterStateFromLoaderTree(
await createRouteTreePrefetch(
loaderTreeToFilter,
getDynamicParamFromSegment
)
: await createFlightRouterStateFromLoaderTree(
loaderTreeToFilter,
getDynamicParamFromSegment,
query
......@@ -178,8 +181,11 @@ export async function walkTreeWithFlightRouterState({
? flightRouterState[0]
: actualSegment
const routerState = parsedRequestHeaders.isRouteTreePrefetchRequest
? createRouteTreePrefetch(loaderTreeToFilter, getDynamicParamFromSegment)
: createFlightRouterStateFromLoaderTree(
? await createRouteTreePrefetch(
loaderTreeToFilter,
getDynamicParamFromSegment
)
: await createFlightRouterStateFromLoaderTree(
loaderTreeToFilter,
getDynamicParamFromSegment,
query
......@@ -205,7 +211,7 @@ export async function walkTreeWithFlightRouterState({
? flightRouterState[0]
: actualSegment
const routerState = createFlightRouterStateFromLoaderTree(
const routerState = await createFlightRouterStateFromLoaderTree(
// Create router state using the slice of the loaderTree
loaderTreeToFilter,
getDynamicParamFromSegment,
......@@ -325,7 +331,7 @@ export async function createFullTreeFlightDataForNavigation({
getDynamicParamFromSegment,
} = ctx
const routerState = createFlightRouterStateFromLoaderTree(
const routerState = await createFlightRouterStateFromLoaderTree(
loaderTree,
getDynamicParamFromSegment,
query
......
......@@ -131,13 +131,12 @@ export type FlightRouterState = [
* overloaded with concerns.
*/
refresh?: 'refetch' | 'inside-shared-layout' | 'metadata-only' | null,
isRootLayout?: boolean,
/**
* Only present when responding to a tree prefetch request. Indicates whether
* there is a loading boundary somewhere in the tree. The client cache uses
* this to determine if it can skip the data prefetch request.
* Bitmask of PrefetchHint flags. Encodes route structure metadata:
* root layout, loading boundaries, instant configs, and runtime prefetch
* hints. Only set when non-zero.
*/
hasLoadingBoundary?: HasLoadingBoundary,
prefetchHints?: number,
]
/**
......@@ -152,24 +151,21 @@ export type FlightRouterState = [
*/
export type CompressedRefreshState = [url: string, renderedSearch: string]
export const enum HasLoadingBoundary {
// There is a loading boundary in this particular segment
SegmentHasLoadingBoundary = 1,
// There is a loading boundary somewhere in the subtree (but not in
// this segment)
SubtreeHasLoadingBoundary = 2,
// There is no loading boundary in this segment or any of its descendants
SubtreeHasNoLoadingBoundary = 3,
}
export const enum PrefetchHint {
// This segment has a runtime prefetch enabled (via unstable_instant with
// prefetch: 'runtime'). Per-segment only, does not propagate to ancestors.
HasRuntimePrefetch = 0b01,
HasRuntimePrefetch = 0b00001,
// This segment or one of its descendants has an instant config defined
// (any truthy unstable_instant, regardless of prefetch mode). Propagates
// upward so the root segment reflects the entire subtree.
SubtreeHasInstant = 0b10,
SubtreeHasInstant = 0b00010,
// This segment itself has a loading.tsx boundary.
SegmentHasLoadingBoundary = 0b00100,
// A descendant segment (but not this one) has a loading.tsx boundary.
// Propagates upward so the root reflects the entire subtree.
SubtreeHasLoadingBoundary = 0b01000,
// This segment is the root layout of the application.
IsRootLayout = 0b10000,
}
/**
......@@ -203,8 +199,6 @@ export type CacheNodeSeedData = [
// TODO: This field is no longer used. Remove it.
loading: null,
isPartial: boolean,
/** TODO: this doesn't feel like it belongs here, because it's only used during build, in `collectSegmentData` */
prefetchHints: number,
/**
* A thenable that resolves to the set of route params this segment accessed
* during server rendering. Used by the client router to determine cache key
......
......@@ -212,7 +212,7 @@ describe('app dir - prefetching', () => {
'prefetch-auto',
{
children: [
['slug', 'justputit', 'd'],
['slug', 'justputit', 'd', null],
{ children: ['__PAGE__', {}] },
],
},
......@@ -220,7 +220,7 @@ describe('app dir - prefetching', () => {
},
null,
null,
true,
16, // PrefetchHint.IsRootLayout
])
)
const response = await next.fetch(`/prefetch-auto/justputit?_rsc=dcqtr`, {
......@@ -255,7 +255,7 @@ describe('app dir - prefetching', () => {
},
null,
null,
true,
16, // PrefetchHint.IsRootLayout
])
)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment