Unverified Commit 9cd05eae authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Implement runtime prefetching via segment opt-in (#83072)

Follow-up to #82905.

When prefetching a link, we should perform a runtime prefetch for any
segment that

- has runtime prefetching enabled
- is not a shared layout

or

- is a child of a segment that meets the above criteria.

Anything that doesn't meet those criteria will be prefetched statically,
i.e. the behavior before this PR. In other words, we disregard the
`prefetch` config of shared layouts when deciding whether to perform a
runtime prefetch.

This means if you opt into runtime prefetching in a layout, navigating
to a page inside that layout for the first time will perform a runtime
prefetch, but navigating across multiple pages inside that layout will
be static (until/unless there's a child that has also opted into runtime
prefetching).

For example, given a route structure like `/store/[id]`, where
`/store/layout.tsx` has runtime prefetching enabled, but
`/store/[id]/page.tsx` does not:

- A Link from `/home` to `/store/1` results in a **runtime prefetch**
- A Link from `/store/1` to `/store/2` results in a **static prefetch**

If we didn't make this distinction, then opting into prefetching in a
layout would override the config of everything inside it.

(However, the most common pattern will be to set this config at the page
level, where the distinction doesn't matter, since there are no child
segments.)

---------
Co-authored-by: 's avatarJanka Uryga <lolzatu2@gmail.com>
parent d3bc0371
...@@ -121,6 +121,12 @@ export type RouteTree = { ...@@ -121,6 +121,12 @@ export type RouteTree = {
// this value is disregarded, because in that model `loading.tsx` is treated // this value is disregarded, because in that model `loading.tsx` is treated
// like any other Suspense boundary.) // like any other Suspense boundary.)
hasLoadingBoundary: HasLoadingBoundary hasLoadingBoundary: HasLoadingBoundary
// Indicates whether this route has a runtime prefetch that we can request.
// This is determined by the server; it's 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.
hasRuntimePrefetch: boolean
} }
type RouteCacheEntryShared = { type RouteCacheEntryShared = {
...@@ -147,10 +153,10 @@ type RouteCacheEntryShared = { ...@@ -147,10 +153,10 @@ type RouteCacheEntryShared = {
* Rejected depending on the response from the server. * Rejected depending on the response from the server.
*/ */
export const enum EntryStatus { export const enum EntryStatus {
Empty, Empty = 0,
Pending, Pending = 1,
Fulfilled, Fulfilled = 2,
Rejected, Rejected = 3,
} }
type PendingRouteCacheEntry = RouteCacheEntryShared & { type PendingRouteCacheEntry = RouteCacheEntryShared & {
...@@ -431,8 +437,8 @@ export function readRouteCacheEntry( ...@@ -431,8 +437,8 @@ export function readRouteCacheEntry(
return readExactRouteCacheEntry(now, key.href, key.nextUrl) return readExactRouteCacheEntry(now, key.href, key.nextUrl)
} }
export function getSegmentKeypathForTask( export function getSegmentKeypath(
task: PrefetchTask, fetchStrategy: FetchStrategy,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
cacheKey: SegmentCacheKey cacheKey: SegmentCacheKey
): Prefix<SegmentCacheKeypath> { ): Prefix<SegmentCacheKeypath> {
...@@ -443,11 +449,11 @@ export function getSegmentKeypathForTask( ...@@ -443,11 +449,11 @@ export function getSegmentKeypathForTask(
// If we're fetching using PPR, we do not need to include the search params in // If we're fetching using PPR, we do not need to include the search params in
// the cache key, because the search params are treated as dynamic data. The // the cache key, because the search params are treated as dynamic data. The
// cache entry is valid for all possible search param values. // cache entry is valid for all possible search param values.
const isDynamicTask = const isDynamic =
task.fetchStrategy === FetchStrategy.Full || fetchStrategy === FetchStrategy.Full ||
task.fetchStrategy === FetchStrategy.PPRRuntime || fetchStrategy === FetchStrategy.PPRRuntime ||
!route.isPPREnabled !route.isPPREnabled
return isDynamicTask && cacheKey.endsWith('/' + PAGE_SEGMENT_KEY) return isDynamic && cacheKey.endsWith('/' + PAGE_SEGMENT_KEY)
? [cacheKey, route.renderedSearch] ? [cacheKey, route.renderedSearch]
: [cacheKey] : [cacheKey]
} }
...@@ -481,7 +487,7 @@ export function readSegmentCacheEntry( ...@@ -481,7 +487,7 @@ export function readSegmentCacheEntry(
// is the common case because PPR/static prerenders always treat search params // is the common case because PPR/static prerenders always treat search params
// as dynamic. // as dynamic.
// //
// See corresponding logic in `getSegmentKeypathForTask`. // See corresponding logic in `getSegmentKeypath`.
const entryWithoutSearchParams = readExactSegmentCacheEntry(now, [cacheKey]) const entryWithoutSearchParams = readExactSegmentCacheEntry(now, [cacheKey])
return entryWithoutSearchParams return entryWithoutSearchParams
} }
...@@ -744,11 +750,11 @@ export function requestOptimisticRouteCacheEntry( ...@@ -744,11 +750,11 @@ export function requestOptimisticRouteCacheEntry(
*/ */
export function readOrCreateSegmentCacheEntry( export function readOrCreateSegmentCacheEntry(
now: number, now: number,
task: PrefetchTask, fetchStrategy: FetchStrategy,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
cacheKey: SegmentCacheKey cacheKey: SegmentCacheKey
): SegmentCacheEntry { ): SegmentCacheEntry {
const keypath = getSegmentKeypathForTask(task, route, cacheKey) const keypath = getSegmentKeypath(fetchStrategy, route, cacheKey)
const existingEntry = readExactSegmentCacheEntry(now, keypath) const existingEntry = readExactSegmentCacheEntry(now, keypath)
if (existingEntry !== null) { if (existingEntry !== null) {
return existingEntry return existingEntry
...@@ -1158,6 +1164,7 @@ function convertTreePrefetchToRouteTree( ...@@ -1158,6 +1164,7 @@ function convertTreePrefetchToRouteTree(
// This field is only relevant to dynamic routes. For a PPR/static route, // This field is only relevant to dynamic routes. For a PPR/static route,
// there's always some partial loading state we can fetch. // there's always some partial loading state we can fetch.
hasLoadingBoundary: HasLoadingBoundary.SegmentHasLoadingBoundary, hasLoadingBoundary: HasLoadingBoundary.SegmentHasLoadingBoundary,
hasRuntimePrefetch: prefetch.hasRuntimePrefetch,
} }
} }
...@@ -1251,6 +1258,10 @@ function convertFlightRouterStateToRouteTree( ...@@ -1251,6 +1258,10 @@ function convertFlightRouterStateToRouteTree(
flightRouterState[5] !== undefined flightRouterState[5] !== undefined
? flightRouterState[5] ? flightRouterState[5]
: HasLoadingBoundary.SubtreeHasNoLoadingBoundary, : HasLoadingBoundary.SubtreeHasNoLoadingBoundary,
// Non-static tree responses are only used by apps that haven't adopted
// Cache Components. So this is always false.
hasRuntimePrefetch: false,
} }
} }
...@@ -2036,7 +2047,7 @@ function writeSeedDataIntoCache( ...@@ -2036,7 +2047,7 @@ function writeSeedDataIntoCache(
// There's no matching entry. Attempt to create a new one. // There's no matching entry. Attempt to create a new one.
const possiblyNewEntry = readOrCreateSegmentCacheEntry( const possiblyNewEntry = readOrCreateSegmentCacheEntry(
now, now,
task, fetchStrategy,
route, route,
cacheKey cacheKey
) )
...@@ -2065,7 +2076,7 @@ function writeSeedDataIntoCache( ...@@ -2065,7 +2076,7 @@ function writeSeedDataIntoCache(
) )
upsertSegmentEntry( upsertSegmentEntry(
now, now,
getSegmentKeypathForTask(task, route, cacheKey), getSegmentKeypath(fetchStrategy, route, cacheKey),
newEntry newEntry
) )
} }
......
...@@ -359,7 +359,7 @@ function readRenderSnapshotFromCache( ...@@ -359,7 +359,7 @@ function readRenderSnapshotFromCache(
) )
// We don't need this information in a render snapshot, so this can just be a placeholder. // We don't need this information in a render snapshot, so this can just be a placeholder.
const shouldUseRuntimePrefetch = false const hasRuntimePrefetch = false
return { return {
flightRouterState: [ flightRouterState: [
...@@ -375,7 +375,7 @@ function readRenderSnapshotFromCache( ...@@ -375,7 +375,7 @@ function readRenderSnapshotFromCache(
childSeedDatas, childSeedDatas,
loading, loading,
isPartial, isPartial,
shouldUseRuntimePrefetch, hasRuntimePrefetch,
], ],
} }
} }
......
...@@ -24,7 +24,7 @@ import { ...@@ -24,7 +24,7 @@ import {
upgradeToPendingSegment, upgradeToPendingSegment,
waitForSegmentCacheEntry, waitForSegmentCacheEntry,
resetRevalidatingSegmentEntry, resetRevalidatingSegmentEntry,
getSegmentKeypathForTask, getSegmentKeypath,
canNewFetchStrategyProvideMoreContent, canNewFetchStrategyProvideMoreContent,
} from './cache' } from './cache'
import type { RouteCacheKey } from './cache-key' import type { RouteCacheKey } from './cache-key'
...@@ -116,11 +116,11 @@ export type PrefetchTask = { ...@@ -116,11 +116,11 @@ export type PrefetchTask = {
phase: PrefetchPhase phase: PrefetchPhase
/** /**
* Temporary state for tracking the currently running task. This is currently * These fields are temporary state for tracking the currently running task.
* used to track whether a task deferred some work to run background at * They are reset after each iteration of the task queue.
* priority, but we might need it for additional state in the future.
*/ */
hasBackgroundWork: boolean hasBackgroundWork: boolean
spawnedRuntimePrefetches: Set<SegmentCacheKey> | null
/** /**
* True if the prefetch was cancelled. * True if the prefetch was cancelled.
...@@ -224,6 +224,7 @@ export function schedulePrefetchTask( ...@@ -224,6 +224,7 @@ export function schedulePrefetchTask(
priority, priority,
phase: PrefetchPhase.RouteTree, phase: PrefetchPhase.RouteTree,
hasBackgroundWork: false, hasBackgroundWork: false,
spawnedRuntimePrefetches: null,
fetchStrategy, fetchStrategy,
sortId: sortIdCounter++, sortId: sortIdCounter++,
isCanceled: false, isCanceled: false,
...@@ -441,10 +442,11 @@ function processQueueInMicrotask() { ...@@ -441,10 +442,11 @@ function processQueueInMicrotask() {
const route = readOrCreateRouteCacheEntry(now, task) const route = readOrCreateRouteCacheEntry(now, task)
const exitStatus = pingRootRouteTree(now, task, route) const exitStatus = pingRootRouteTree(now, task, route)
// The `hasBackgroundWork` field is only valid for a single attempt. Reset // These fields are only valid for a single attempt. Reset them after each
// it immediately upon exit. // iteration of the task queue.
const hasBackgroundWork = task.hasBackgroundWork const hasBackgroundWork = task.hasBackgroundWork
task.hasBackgroundWork = false task.hasBackgroundWork = false
task.spawnedRuntimePrefetches = null
switch (exitStatus) { switch (exitStatus) {
case PrefetchTaskExitStatus.InProgress: case PrefetchTaskExitStatus.InProgress:
...@@ -575,15 +577,68 @@ function pingRootRouteTree( ...@@ -575,15 +577,68 @@ function pingRootRouteTree(
: task.fetchStrategy : task.fetchStrategy
switch (fetchStrategy) { switch (fetchStrategy) {
case FetchStrategy.PPR: case FetchStrategy.PPR: {
// Individually prefetch the static shell for each segment. This is // For Cache Components pages, each segment may be prefetched
// the default prefetching behavior for static routes, or when PPR is // statically or using a runtime request, based on various
// enabled. It will not include any dynamic data. // configurations and heuristics. We'll do this in two passes: first
return pingPPRRouteTree(now, task, route, tree) // traverse the tree and perform all the static prefetches.
//
// Then, if there are any segments that need a runtime request,
// do another pass to perform a runtime prefetch.
const exitStatus = pingSharedPartOfCacheComponentsTree(
now,
task,
route,
task.treeAtTimeOfPrefetch,
tree
)
if (exitStatus === PrefetchTaskExitStatus.InProgress) {
// Child yielded without finishing.
return PrefetchTaskExitStatus.InProgress
}
const spawnedRuntimePrefetches = task.spawnedRuntimePrefetches
if (spawnedRuntimePrefetches !== null) {
// During the first pass, we discovered segments that require a
// runtime prefetch. Do a second pass to construct a request tree.
const spawnedEntries = new Map<
SegmentCacheKey,
PendingSegmentCacheEntry
>()
const requestTree = pingRuntimePrefetches(
now,
task,
route,
tree,
spawnedRuntimePrefetches,
spawnedEntries
)
let needsDynamicRequest = spawnedEntries.size > 0
if (needsDynamicRequest) {
// Perform a dynamic prefetch request and populate the cache with
// the result.
spawnPrefetchSubtask(
fetchSegmentPrefetchesUsingDynamicRequest(
task,
route,
FetchStrategy.PPRRuntime,
requestTree,
spawnedEntries
)
)
}
}
return PrefetchTaskExitStatus.Done
}
case FetchStrategy.Full: case FetchStrategy.Full:
case FetchStrategy.PPRRuntime: case FetchStrategy.PPRRuntime:
case FetchStrategy.LoadingBoundary: { case FetchStrategy.LoadingBoundary: {
// Prefetch multiple segments using a single dynamic request. // Prefetch multiple segments using a single dynamic request.
// TODO: We can consolidate this branch with previous one by modeling
// it as if the first segment in the new tree has runtime prefetching
// enabled. Will do this as a follow-up refactor. Might want to remove
// the special metatdata case below first. In the meantime, it's not
// really that much duplication, just would be nice to remove one of
// these codepaths.
const spawnedEntries = new Map< const spawnedEntries = new Map<
SegmentCacheKey, SegmentCacheKey,
PendingSegmentCacheEntry PendingSegmentCacheEntry
...@@ -656,14 +711,133 @@ function pingRootRouteTree( ...@@ -656,14 +711,133 @@ function pingRootRouteTree(
return PrefetchTaskExitStatus.Done return PrefetchTaskExitStatus.Done
} }
function pingPPRRouteTree( function pingSharedPartOfCacheComponentsTree(
now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
oldTree: FlightRouterState,
newTree: RouteTree
): PrefetchTaskExitStatus {
// When Cache Components is enabled (or PPR, or a fully static route when PPR
// is disabled; those cases are treated equivalently to Cache Components), we
// start by prefetching each segment individually. Once we reach the "new"
// part of the tree — the part that doesn't exist on the current page — we
// may choose to switch to a runtime prefetch instead, based on the
// information sent by the server in the route tree.
//
// The traversal starts in the "shared" part of the tree. Once we reach the
// "new" part of the tree, we switch to a different traversal,
// pingNewPartOfCacheComponentsTree.
// Prefetch this segment's static data.
const segment = readOrCreateSegmentCacheEntry(
now,
task.fetchStrategy,
route,
newTree.cacheKey
)
pingStaticSegmentData(now, task, route, segment, task.key, newTree)
// Recursively ping the children.
const oldTreeChildren = oldTree[1]
const newTreeChildren = newTree.slots
if (newTreeChildren !== null) {
for (const parallelRouteKey in newTreeChildren) {
if (!hasNetworkBandwidth(task)) {
// Stop prefetching segments until there's more bandwidth.
return PrefetchTaskExitStatus.InProgress
}
const newTreeChild = newTreeChildren[parallelRouteKey]
const newTreeChildSegment = newTreeChild.segment
const oldTreeChild: FlightRouterState | void =
oldTreeChildren[parallelRouteKey]
const oldTreeChildSegment: FlightRouterStateSegment | void =
oldTreeChild?.[0]
let childExitStatus
if (
oldTreeChildSegment !== undefined &&
doesCurrentSegmentMatchCachedSegment(
route,
newTreeChildSegment,
oldTreeChildSegment
)
) {
// We're still in the "shared" part of the tree.
childExitStatus = pingSharedPartOfCacheComponentsTree(
now,
task,
route,
oldTreeChild,
newTreeChild
)
} else {
// We've entered the "new" part of the tree. Switch
// traversal functions.
childExitStatus = pingNewPartOfCacheComponentsTree(
now,
task,
route,
newTreeChild
)
}
if (childExitStatus === PrefetchTaskExitStatus.InProgress) {
// Child yielded without finishing.
return PrefetchTaskExitStatus.InProgress
}
}
}
return PrefetchTaskExitStatus.Done
}
function pingNewPartOfCacheComponentsTree(
now: number, now: number,
task: PrefetchTask, task: PrefetchTask,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
tree: RouteTree tree: RouteTree
): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done { ): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {
const segment = readOrCreateSegmentCacheEntry(now, task, route, tree.cacheKey) // We're now prefetching in the "new" part of the tree, the part that doesn't
pingPerSegment(now, task, route, segment, task.key, tree) // exist on the current page. (In other words, we're deeper than the
// shared layouts.) Segments in here default to being prefetched statically.
// However, if the server instructs us to, we may switch to a runtime
// prefetch instead. Traverse the tree and check at each segment.
if (tree.hasRuntimePrefetch) {
// This route has a runtime prefetch response. Since we're below the shared
// layout, everything from this point should be prefetched using a single,
// combined runtime request, rather than using per-segment static requests.
// This is true even if some of the child segments are known to be fully
// static — once we've decided to perform a runtime prefetch, we might as
// well respond with the static segments in the same roundtrip. (That's how
// regular navigations work, too.) We'll still skip over segments that are
// already cached, though.
//
// It's the server's responsibility to set a reasonable value of
// `hasRuntimePrefetch`. Currently it's user-defined, but eventually, the
// server may send a value of `false` even if the user opts in, if it
// determines during build that the route is always fully static. There are
// more optimizations we can do once we implement fallback param
// tracking, too.
//
// Use the task object to collect the segments that need a runtime prefetch.
// This will signal to the outer task queue that a second traversal is
// required to construct a request tree.
if (task.spawnedRuntimePrefetches === null) {
task.spawnedRuntimePrefetches = new Set([tree.cacheKey])
} else {
task.spawnedRuntimePrefetches.add(tree.cacheKey)
}
// Then exit the traversal without prefetching anything further.
return PrefetchTaskExitStatus.Done
}
// This segment should not be runtime prefetched. Prefetch its static data.
const segment = readOrCreateSegmentCacheEntry(
now,
task.fetchStrategy,
route,
tree.cacheKey
)
pingStaticSegmentData(now, task, route, segment, task.key, tree)
if (tree.slots !== null) { if (tree.slots !== null) {
if (!hasNetworkBandwidth(task)) { if (!hasNetworkBandwidth(task)) {
// Stop prefetching segments until there's more bandwidth. // Stop prefetching segments until there's more bandwidth.
...@@ -672,7 +846,12 @@ function pingPPRRouteTree( ...@@ -672,7 +846,12 @@ function pingPPRRouteTree(
// Recursively ping the children. // Recursively ping the children.
for (const parallelRouteKey in tree.slots) { for (const parallelRouteKey in tree.slots) {
const childTree = tree.slots[parallelRouteKey] const childTree = tree.slots[parallelRouteKey]
const childExitStatus = pingPPRRouteTree(now, task, route, childTree) const childExitStatus = pingNewPartOfCacheComponentsTree(
now,
task,
route,
childTree
)
if (childExitStatus === PrefetchTaskExitStatus.InProgress) { if (childExitStatus === PrefetchTaskExitStatus.InProgress) {
// Child yielded without finishing. // Child yielded without finishing.
return PrefetchTaskExitStatus.InProgress return PrefetchTaskExitStatus.InProgress
...@@ -852,7 +1031,12 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary( ...@@ -852,7 +1031,12 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
let refetchMarker: 'refetch' | 'inside-shared-layout' | null = let refetchMarker: 'refetch' | 'inside-shared-layout' | null =
refetchMarkerContext === null ? 'inside-shared-layout' : null refetchMarkerContext === null ? 'inside-shared-layout' : null
const segment = readOrCreateSegmentCacheEntry(now, task, route, tree.cacheKey) const segment = readOrCreateSegmentCacheEntry(
now,
task.fetchStrategy,
route,
tree.cacheKey
)
switch (segment.status) { switch (segment.status) {
case EntryStatus.Empty: { case EntryStatus.Empty: {
// This segment is not cached. Add a refetch marker so the server knows // This segment is not cached. Add a refetch marker so the server knows
...@@ -955,7 +1139,17 @@ function pingRouteTreeAndIncludeDynamicData( ...@@ -955,7 +1139,17 @@ function pingRouteTreeAndIncludeDynamicData(
// explicit "refetch" marker so the server knows where to start rendering. // explicit "refetch" marker so the server knows where to start rendering.
// Once the server starts rendering along a path, it keeps rendering the // Once the server starts rendering along a path, it keeps rendering the
// entire subtree. // entire subtree.
const segment = readOrCreateSegmentCacheEntry(now, task, route, tree.cacheKey) const segment = readOrCreateSegmentCacheEntry(
now,
// Note that `fetchStrategy` might be different from `task.fetchStrategy`,
// and we have to use the former here.
// We can have a task with `FetchStrategy.PPR` where some of its segments are configured to
// always use runtime prefetching (via `export const prefetch`), and those should check for
// entries that include search params.
fetchStrategy,
route,
tree.cacheKey
)
let spawnedSegment: PendingSegmentCacheEntry | null = null let spawnedSegment: PendingSegmentCacheEntry | null = null
...@@ -981,7 +1175,6 @@ function pingRouteTreeAndIncludeDynamicData( ...@@ -981,7 +1175,6 @@ function pingRouteTreeAndIncludeDynamicData(
// In either case, we need to include it in the request to get a more specific (or full) version. // In either case, we need to include it in the request to get a more specific (or full) version.
spawnedSegment = pingFullSegmentRevalidation( spawnedSegment = pingFullSegmentRevalidation(
now, now,
task,
route, route,
segment, segment,
tree, tree,
...@@ -1002,7 +1195,6 @@ function pingRouteTreeAndIncludeDynamicData( ...@@ -1002,7 +1195,6 @@ function pingRouteTreeAndIncludeDynamicData(
) { ) {
spawnedSegment = pingFullSegmentRevalidation( spawnedSegment = pingFullSegmentRevalidation(
now, now,
task,
route, route,
segment, segment,
tree, tree,
...@@ -1050,7 +1242,59 @@ function pingRouteTreeAndIncludeDynamicData( ...@@ -1050,7 +1242,59 @@ function pingRouteTreeAndIncludeDynamicData(
return requestTree return requestTree
} }
function pingPerSegment( function pingRuntimePrefetches(
now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
tree: RouteTree,
spawnedRuntimePrefetches: Set<SegmentCacheKey>,
spawnedEntries: Map<string, PendingSegmentCacheEntry>
): FlightRouterState {
// Construct a request tree (FlightRouterState) for a runtime prefetch. If
// a segment is part of the runtime prefetch, the tree is constructed by
// diffing against what's already in the prefetch cache. Otherwise, we send
// a regular FlightRouterState with no special markers.
//
// See pingRouteTreeAndIncludeDynamicData for details.
if (spawnedRuntimePrefetches.has(tree.cacheKey)) {
// This segment needs a runtime prefetch.
return pingRouteTreeAndIncludeDynamicData(
now,
task,
route,
tree,
false,
spawnedEntries,
FetchStrategy.PPRRuntime
)
}
let requestTreeChildren: Record<string, FlightRouterState> = {}
const slots = tree.slots
if (slots !== null) {
for (const parallelRouteKey in slots) {
const childTree = slots[parallelRouteKey]
requestTreeChildren[parallelRouteKey] = pingRuntimePrefetches(
now,
task,
route,
childTree,
spawnedRuntimePrefetches,
spawnedEntries
)
}
}
// This segment is not part of the runtime prefetch. Clone the base tree.
const requestTree: FlightRouterState = [
tree.segment,
requestTreeChildren,
null,
null,
]
return requestTree
}
function pingStaticSegmentData(
now: number, now: number,
task: PrefetchTask, task: PrefetchTask,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
...@@ -1159,7 +1403,7 @@ function pingPPRSegmentRevalidation( ...@@ -1159,7 +1403,7 @@ function pingPPRSegmentRevalidation(
// Spawn a prefetch request and upsert the segment into the cache // Spawn a prefetch request and upsert the segment into the cache
// upon completion. // upon completion.
upsertSegmentOnCompletion( upsertSegmentOnCompletion(
task, task.fetchStrategy,
route, route,
tree.cacheKey, tree.cacheKey,
spawnPrefetchSubtask( spawnPrefetchSubtask(
...@@ -1188,7 +1432,6 @@ function pingPPRSegmentRevalidation( ...@@ -1188,7 +1432,6 @@ function pingPPRSegmentRevalidation(
function pingFullSegmentRevalidation( function pingFullSegmentRevalidation(
now: number, now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
currentSegment: SegmentCacheEntry, currentSegment: SegmentCacheEntry,
tree: RouteTree, tree: RouteTree,
...@@ -1209,7 +1452,7 @@ function pingFullSegmentRevalidation( ...@@ -1209,7 +1452,7 @@ function pingFullSegmentRevalidation(
fetchStrategy fetchStrategy
) )
upsertSegmentOnCompletion( upsertSegmentOnCompletion(
task, fetchStrategy,
route, route,
tree.cacheKey, tree.cacheKey,
waitForSegmentCacheEntry(pendingSegment) waitForSegmentCacheEntry(pendingSegment)
...@@ -1234,7 +1477,7 @@ function pingFullSegmentRevalidation( ...@@ -1234,7 +1477,7 @@ function pingFullSegmentRevalidation(
fetchStrategy fetchStrategy
) )
upsertSegmentOnCompletion( upsertSegmentOnCompletion(
task, fetchStrategy,
route, route,
tree.cacheKey, tree.cacheKey,
waitForSegmentCacheEntry(pendingSegment) waitForSegmentCacheEntry(pendingSegment)
...@@ -1261,7 +1504,7 @@ function pingFullSegmentRevalidation( ...@@ -1261,7 +1504,7 @@ function pingFullSegmentRevalidation(
const noop = () => {} const noop = () => {}
function upsertSegmentOnCompletion( function upsertSegmentOnCompletion(
task: PrefetchTask, fetchStrategy: FetchStrategy,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
cacheKey: SegmentCacheKey, cacheKey: SegmentCacheKey,
promise: Promise<FulfilledSegmentCacheEntry | null> promise: Promise<FulfilledSegmentCacheEntry | null>
...@@ -1270,7 +1513,7 @@ function upsertSegmentOnCompletion( ...@@ -1270,7 +1513,7 @@ function upsertSegmentOnCompletion(
promise.then((fulfilled) => { promise.then((fulfilled) => {
if (fulfilled !== null) { if (fulfilled !== null) {
// Received new data. Attempt to replace the existing entry in the cache. // Received new data. Attempt to replace the existing entry in the cache.
const keypath = getSegmentKeypathForTask(task, route, cacheKey) const keypath = getSegmentKeypath(fetchStrategy, route, cacheKey)
upsertSegmentEntry(Date.now(), keypath, fulfilled) upsertSegmentEntry(Date.now(), keypath, fulfilled)
} }
}, noop) }, noop)
......
...@@ -51,7 +51,7 @@ export type TreePrefetch = { ...@@ -51,7 +51,7 @@ export type TreePrefetch = {
} }
/** Whether this segment should be fetched using a runtime prefetch */ /** Whether this segment should be fetched using a runtime prefetch */
shouldUseRuntimePrefetch: boolean hasRuntimePrefetch: boolean
// Extra fields that only exist so we can reconstruct a FlightRouterState on // Extra fields that only exist so we can reconstruct a FlightRouterState on
// the client. We may be able to unify TreePrefetch and FlightRouterState // the client. We may be able to unify TreePrefetch and FlightRouterState
...@@ -281,7 +281,7 @@ function collectSegmentDataImpl( ...@@ -281,7 +281,7 @@ function collectSegmentDataImpl(
slotMetadata[parallelRouteKey] = childTree slotMetadata[parallelRouteKey] = childTree
} }
const shouldUseRuntimePrefetch = seedData !== null ? seedData[5] : false const hasRuntimePrefetch = seedData !== null ? seedData[5] : false
if (seedData !== null) { if (seedData !== null) {
// Spawn a task to write the segment data to a new Flight stream. // Spawn a task to write the segment data to a new Flight stream.
...@@ -324,7 +324,7 @@ function collectSegmentDataImpl( ...@@ -324,7 +324,7 @@ function collectSegmentDataImpl(
// case there's a bug and we need to revert. // case there's a bug and we need to revert.
// TODO: Remove once clientParamParsing is enabled everywhere. // TODO: Remove once clientParamParsing is enabled everywhere.
paramKey: isClientParamParsingEnabled ? null : paramKey, paramKey: isClientParamParsingEnabled ? null : paramKey,
shouldUseRuntimePrefetch, hasRuntimePrefetch,
slots: slotMetadata, slots: slotMetadata,
isRootLayout: route[4] === true, isRootLayout: route[4] === true,
} }
......
...@@ -229,7 +229,7 @@ async function createComponentTreeInternal( ...@@ -229,7 +229,7 @@ async function createComponentTreeInternal(
? (layoutOrPageMod as AppSegmentConfig).unstable_prefetch ? (layoutOrPageMod as AppSegmentConfig).unstable_prefetch
: undefined : undefined
/** Whether this segment should use a runtime prefetch instead of a static prefetch. */ /** Whether this segment should use a runtime prefetch instead of a static prefetch. */
const shouldUseRuntimePrefetch = prefetchConfig === 'unstable_runtime' const hasRuntimePrefetch = prefetchConfig === 'unstable_runtime'
const [Forbidden, forbiddenStyles] = const [Forbidden, forbiddenStyles] =
authInterrupts && forbidden authInterrupts && forbidden
...@@ -704,7 +704,7 @@ async function createComponentTreeInternal( ...@@ -704,7 +704,7 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
shouldUseRuntimePrefetch, hasRuntimePrefetch,
] ]
} }
...@@ -737,7 +737,7 @@ async function createComponentTreeInternal( ...@@ -737,7 +737,7 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
true, true,
shouldUseRuntimePrefetch, hasRuntimePrefetch,
] ]
} }
...@@ -843,7 +843,7 @@ async function createComponentTreeInternal( ...@@ -843,7 +843,7 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
shouldUseRuntimePrefetch, hasRuntimePrefetch,
] ]
} else { } else {
const SegmentComponent = Component const SegmentComponent = Component
...@@ -1021,7 +1021,7 @@ async function createComponentTreeInternal( ...@@ -1021,7 +1021,7 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
shouldUseRuntimePrefetch, hasRuntimePrefetch,
] ]
} }
} }
......
...@@ -229,7 +229,7 @@ export type CacheNodeSeedData = [ ...@@ -229,7 +229,7 @@ export type CacheNodeSeedData = [
loading: LoadingModuleData | Promise<LoadingModuleData>, loading: LoadingModuleData | Promise<LoadingModuleData>,
isPartial: boolean, isPartial: boolean,
/** TODO: this doesn't feel like it belongs here, because it's only used during build, in `collectSegmentData` */ /** TODO: this doesn't feel like it belongs here, because it's only used during build, in `collectSegmentData` */
shouldUseRuntimePrefetch: boolean, hasRuntimePrefetch: boolean,
] ]
export type FlightDataSegment = [ export type FlightDataSegment = [
......
...@@ -53,6 +53,16 @@ export default async function Page() { ...@@ -53,6 +53,16 @@ export default async function Page() {
/> />
</li> </li>
</ul> </ul>
<h2>shared layout prefetching - segment config</h2>
<ul>
<li>
This link deliberately doesn't specify a `prefetch` prop, because the
page has a segment-level prefetch config:
<br />
<DebugLinkAccordion href="/segment-config/runtime-prefetchable" />
</li>
</ul>
</main> </main>
) )
} }
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { DebugRenderKind } from '../../../shared'
// No `export const unstable_prefetch = ...` is needed, we default to static
export default async function SubLayout({ children }) {
return (
<main>
<div>
<h3>Sub-layout</h3>
<DebugRenderKind />
<p id="static-content-sub-layout">
This sub-layout uses cookies, but did not specify that it should be
runtime prefetchable, so it should be prefetched statically by
default.
</p>
<Suspense
fallback={
<div id="runtime-prefetchable-fallback-sub-layout">Loading ...</div>
}
>
<RuntimePrefetchable />
</Suspense>
</div>
<hr />
{children}
</main>
)
}
async function RuntimePrefetchable() {
await cookies()
return (
<div id="runtime-prefetchable-content-sub-layout">
Runtime-prefetchable content from sub-layout
</div>
)
}
...@@ -6,7 +6,20 @@ export const unstable_prefetch = 'unstable_runtime' ...@@ -6,7 +6,20 @@ export const unstable_prefetch = 'unstable_runtime'
export default function Page() { export default function Page() {
return ( return (
<main> <main>
<h1>A page that should use a runtime prefetch</h1> <h1 style={{ color: 'green' }}>
A runtime-prefetchable child of a runtime-prefetchable layout
</h1>
<p id="static-content-page">
This page has two relevant parent layouts:
<br />
1. A runtime-prefetchable shared layout layout.
<br />
2. A statically-prefetchable sub-layout not shared with other pages.
<br />
<br />
We should use a runtime prefetch for it without any overrides on Link,
but its sub-layout should be prefetched statically.
</p>
<Suspense fallback="Loading..."> <Suspense fallback="Loading...">
<RuntimePrefetchable /> <RuntimePrefetchable />
</Suspense> </Suspense>
...@@ -16,5 +29,9 @@ export default function Page() { ...@@ -16,5 +29,9 @@ export default function Page() {
async function RuntimePrefetchable() { async function RuntimePrefetchable() {
await cookies() await cookies()
return <div>Runtime-prefetchable content</div> return (
<div id="runtime-prefetchable-content-page">
Runtime-prefetchable content from page
</div>
)
} }
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
// Technically, no `export const unstable_prefetch = ...` is needed, because we default to static,
// this is just to make sure that we excercise the codepaths for it
export const unstable_prefetch = 'unstable_static'
export default function Page() {
return (
<main>
<h1 style={{ color: 'green' }}>Statically prefetchable</h1>
<p id="static-content-page">
This page is a child of a runtime-prefetchable layout that is not
configured as runtime-prefetchable. We should not use a runtime prefetch
for it.
</p>
<Suspense fallback="Loading...">
<RuntimePrefetchable />
</Suspense>
<Suspense fallback="Loading...">
<DynamicContent />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
await cookies()
return (
<div id="runtime-prefetchable-content-page">
Runtime-prefetchable content from page
</div>
)
}
async function DynamicContent() {
await connection()
return <div id="dynamic-content-page">Dynamic Content from page</div>
}
// No `export const unstable_prefetch = ...` is needed, we default to static
export default function Page() {
return (
<main>
<h1 style={{ color: 'green' }}>Fully statically prefetchable</h1>
<p id="static-content-page">
This page is a statically-prefetchable child of a runtime-prefetchable
layout. We should not use a runtime prefetch for it.
</p>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { DebugRenderKind } from '../../shared'
export const unstable_prefetch = 'unstable_runtime'
export default async function Layout({ children }) {
return (
<main>
<div>
<h2>Shared layout</h2>
<DebugRenderKind />
<p id="static-content-layout">
This shared layout uses cookies and no uncached IO, so it should be
completely runtime-prefetchable.
</p>
<Suspense fallback="Loading ...">
<RuntimePrefetchable />
</Suspense>
</div>
<hr />
{children}
</main>
)
}
async function RuntimePrefetchable() {
await cookies()
return (
<div id="runtime-prefetchable-content-layout">
Runtime-prefetchable content from shared layout
</div>
)
}
import { cookies } from 'next/headers'
import { DebugLinkAccordion } from '../../../components/link-accordion'
import { Suspense } from 'react'
// No `export const unstable_prefetch = ...` is needed, we default to static
// (but see page description for more on the actual behavior)
export default function Page() {
return (
<main>
<h1>Child of a runtime prefetchable layout</h1>
<div>
<p>
When this page is prefetched from outside of the{' '}
<code>/segment-config/runtime-prefetchable</code> segment, the page
contents will be runtime-prefetched (despite this segment not being
marked as runtime-prefetchable) because the parent layout is marked as
runtime-prefetchable.
</p>
<Suspense fallback="Loading...">
<RuntimePrefetchable />
</Suspense>
</div>
<ul>
<li>
A page that shares some layouts with this page, and should use a
static prefetch:
<br />
<DebugLinkAccordion href="/segment-config/runtime-prefetchable/configured-as-static" />
</li>
<li>
A page that shares some layouts with this page, and should use a
runtime prefetch:
<br />
<DebugLinkAccordion href="/segment-config/runtime-prefetchable/configured-as-runtime" />
</li>
<li>
A page that shares some layouts with this page, and has a fully static
page segment
<br />
<DebugLinkAccordion href="/segment-config/runtime-prefetchable/fully-static" />
</li>
</ul>
</main>
)
}
async function RuntimePrefetchable() {
await cookies()
return (
<div id="runtime-prefetchable-content-page">
Runtime-prefetchable content from page
</div>
)
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { Playwright as NextBrowser } from '../../../../lib/next-webdriver'
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act' import { createRouterAct } from '../router-act'
...@@ -534,7 +535,15 @@ describe('layout sharing in non-static prefetches', () => { ...@@ -534,7 +535,15 @@ describe('layout sharing in non-static prefetches', () => {
`input[data-prefetch="auto"][data-link-accordion="/runtime-prefetchable-layout/two"]` `input[data-prefetch="auto"][data-link-accordion="/runtime-prefetchable-layout/two"]`
) )
await linkToggle.click() await linkToggle.click()
}) }, [
// Should not fetch the shared layout, because that was already prefetched
{
includes: 'Shared layout',
block: 'reject',
},
// Should fetch the static part of page two
{ includes: 'Page two' },
])
// Navigate to page two. We need to request the page segment dynamically, but the shared layout should be cached. // Navigate to page two. We need to request the page segment dynamically, but the shared layout should be cached.
await act(async () => { await act(async () => {
...@@ -566,6 +575,204 @@ describe('layout sharing in non-static prefetches', () => { ...@@ -566,6 +575,204 @@ describe('layout sharing in non-static prefetches', () => {
'Dynamic content from page two' 'Dynamic content from page two'
) )
}) })
describe('segment-level prefetch config', () => {
const clientNavigateToSegmentConfigPage = async (
browser: NextBrowser,
act: ReturnType<typeof createRouterAct>
) => {
// Reveal the link to trigger a (automatic) runtime prefetch for the segment-config entrypoint page
await act(async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/segment-config/runtime-prefetchable"]`
)
await linkToggle.click()
}, [
{
includes: 'runtime-prefetchable-content-layout',
},
])
// Navigate to the segment-config entrypoint page.
// The layout is configured as runtime prefetchable, but the page is not.
// Both contain runtime-prefetchable content,
// but nothing dynamic, so we shouldn't need any extra requests.
//
// Note that the page itself doesn't specify that it should use a runtime prefetch,
// but we'll currently automatically include it in the runtime prefetch request
// that we're doing because of the layout's config.
await act(async () => {
await browser
.elementByCss(`a[href="/segment-config/runtime-prefetchable"]`)
.click()
}, 'no-requests')
}
it('does not unnecessarily use a runtime prefetch for sub-pages of runtime-prefetchable layouts', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// First, we move from the starting page to another page that has a runtime-prefetchable layout.
await clientNavigateToSegmentConfigPage(browser, act)
// Now we're on a page that uses the runtime-prefetchable layout,
// sub-pages of the same layout that are configured as static shouldn't automatically issue a runtime prefetch.
await act(async () => {
await browser
.elementByCss(
`input[data-link-accordion="/segment-config/runtime-prefetchable/configured-as-static"]`
)
.click()
}, [
// We should not prefetch anything from the parent layout again.
{ includes: 'static-content-layout', block: 'reject' },
{ includes: 'runtime-prefetchable-content-layout', block: 'reject' },
// We should prefetch the static content for the page, but nothing more.
{ includes: 'static-content-page' },
{ includes: 'dynamic-content-page', block: 'reject' },
{ includes: 'runtime-prefetchable-content-page', block: 'reject' },
])
})
it('statically prefetches a fully-static page segment if all its runtime-prefetchable parents are available', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// First, we move from the starting page to another page that has a runtime-prefetchable layout.
await clientNavigateToSegmentConfigPage(browser, act)
// Now we're on a page that uses the runtime-prefetchable layout,
// sub-pages of the same layout that are configured as static shouldn't automatically issue a runtime prefetch.
await act(async () => {
await browser
.elementByCss(
`input[data-link-accordion="/segment-config/runtime-prefetchable/fully-static"]`
)
.click()
}, [
// We should not prefetch anything from the parent layout again.
{ includes: 'static-content-layout', block: 'reject' },
{ includes: 'runtime-prefetchable-content-layout', block: 'reject' },
// We should prefetch the static content for the page, but nothing more.
{ includes: 'static-content-page' },
])
// The page segment is fully static, so we shouldn't need any extra requests to navigate to it.
await act(async () => {
await browser
.elementByCss(
`a[href="/segment-config/runtime-prefetchable/fully-static"]`
)
.click()
}, 'no-requests')
expect(
await (await browser.elementById('static-content-page')).isVisible()
).toBeTrue()
})
it('uses a runtime prefetch for sub-pages of runtime-prefetchable layouts if requested', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// First, we move from the starting page to another page that has a runtime-prefetchable layout.
await clientNavigateToSegmentConfigPage(browser, act)
// Sub-pages of this layout that are configured as runtime-prefetchable should be prefetched as such.
// However, if the page also has a sub-layout (not shared with the current page)
// that is configured as static, that part shouldn't be runtime-prefetched.
//
// Note that this is a sub-optimal configuration -- in a real app, we'd likely want the sub-layout
// to be runtime-prefetched as well, because it contains some runtime-prefetchable content.
// However, this is deliberately set up this way to assert that we don't do a runtime prefetch unless requested.
await act(async () => {
await browser
.elementByCss(
`input[data-link-accordion="/segment-config/runtime-prefetchable/configured-as-runtime"]`
)
.click()
}, [
// We should not prefetch anything from the parent layout again.
{ includes: 'static-content-layout', block: 'reject' },
{ includes: 'runtime-prefetchable-content-layout', block: 'reject' },
{
// We should *not* prefetch the runtime parts of the sub-layout,
// because it's not configured as runtime-prefetchable.
includes: 'runtime-prefetchable-content-sub-layout',
block: 'reject',
},
// ...but we should prefetch the runtime parts of the page.
{ includes: 'runtime-prefetchable-content-page' },
{ includes: 'dynamic-content-page', block: 'reject' },
])
// Navigate to the runtime-prefetchable sub-page.
await act(async () => {
// We should be able to display what we've prefetched before the navigation request resolves.
await act(async () => {
await browser
.elementByCss(
`a[href="/segment-config/runtime-prefetchable/configured-as-runtime"]`
)
.click()
}, 'block')
// The sub-layout should show static content, but not runtime-prefetchable content.
expect(
await (
await browser.elementById('static-content-sub-layout')
).isVisible()
).toBeTrue()
expect(
await (
await browser.elementById(
'runtime-prefetchable-fallback-sub-layout'
)
).isVisible()
).toBeTrue()
// The sub-page should show static/runtime-prefetchable content.
expect(
await (await browser.elementById('static-content-page')).isVisible()
).toBeTrue()
expect(
await (
await browser.elementById('runtime-prefetchable-content-page')
).isVisible()
).toBeTrue()
})
// After the navigation, we should see the content that wasn't prefetched.
// (because the sub-layout was configured as static)
expect(
await (
await browser.elementById('runtime-prefetchable-content-sub-layout')
).isVisible()
).toBeTrue()
})
})
}) })
function defer(callback: () => Promise<void>) { function defer(callback: () => Promise<void>) {
......
// This is technically unnecessary, because this page is static
// and a runtime prefetch won't do any better than a static one,
// but it's useful to exercise this codepath.
// In the future, this test can be used to check whether we correctly
// *skip* a runtime prefetch if a page was prerendered as static.
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
......
...@@ -2,6 +2,8 @@ import { cookies } from 'next/headers' ...@@ -2,6 +2,8 @@ import { cookies } from 'next/headers'
import { Suspense } from 'react' import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared' import { cachedDelay, DebugRenderKind } from '../../../shared'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
......
...@@ -3,6 +3,8 @@ import { Suspense } from 'react' ...@@ -3,6 +3,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
......
...@@ -2,6 +2,8 @@ import { Suspense } from 'react' ...@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
type Params = { id: string } type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) { export default async function Page({ params }: { params: Promise<Params> }) {
......
...@@ -2,6 +2,8 @@ import { Suspense } from 'react' ...@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
type AnySearchParams = { [key: string]: string | string[] | undefined } type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({ export default async function Page({
......
...@@ -2,6 +2,8 @@ import { cookies } from 'next/headers' ...@@ -2,6 +2,8 @@ import { cookies } from 'next/headers'
import { Suspense } from 'react' import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared' import { cachedDelay, DebugRenderKind } from '../../../shared'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
......
...@@ -3,6 +3,8 @@ import { Suspense } from 'react' ...@@ -3,6 +3,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
......
...@@ -2,6 +2,8 @@ import { Suspense } from 'react' ...@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
......
...@@ -2,6 +2,8 @@ import { Suspense } from 'react' ...@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
type Params = { id: string } type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) { export default async function Page({ params }: { params: Promise<Params> }) {
......
...@@ -2,6 +2,8 @@ import { Suspense } from 'react' ...@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
type AnySearchParams = { [key: string]: string | string[] | undefined } type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({ export default async function Page({
......
...@@ -11,7 +11,7 @@ export default async function Page() { ...@@ -11,7 +11,7 @@ export default async function Page() {
cookies + dynamic content cookies + dynamic content
<ul> <ul>
<li> <li>
<DebugLinkAccordion href="/in-page/cookies" prefetch={true} /> <DebugLinkAccordion href="/in-page/cookies" />
</li> </li>
</ul> </ul>
</li> </li>
...@@ -20,16 +20,10 @@ export default async function Page() { ...@@ -20,16 +20,10 @@ export default async function Page() {
search params + dynamic content search params + dynamic content
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-page/search-params?searchParam=123" />
href="/in-page/search-params?searchParam=123"
prefetch={true}
/>
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-page/search-params?searchParam=456" />
href="/in-page/search-params?searchParam=456"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -37,16 +31,10 @@ export default async function Page() { ...@@ -37,16 +31,10 @@ export default async function Page() {
dynamic params + dynamic content dynamic params + dynamic content
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-page/dynamic-params/123" />
href="/in-page/dynamic-params/123"
prefetch={true}
/>
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-page/dynamic-params/456" />
href="/in-page/dynamic-params/456"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -54,10 +42,7 @@ export default async function Page() { ...@@ -54,10 +42,7 @@ export default async function Page() {
only cookies only cookies
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-page/cookies-only" />
href="/in-page/cookies-only"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -71,10 +56,7 @@ export default async function Page() { ...@@ -71,10 +56,7 @@ export default async function Page() {
cookies in private cache + dynamic content cookies in private cache + dynamic content
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-private-cache/cookies" />
href="/in-private-cache/cookies"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -82,16 +64,10 @@ export default async function Page() { ...@@ -82,16 +64,10 @@ export default async function Page() {
dynamic params in private cache + dynamic content dynamic params in private cache + dynamic content
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-private-cache/dynamic-params/123" />
href="/in-private-cache/dynamic-params/123"
prefetch={true}
/>
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-private-cache/dynamic-params/456" />
href="/in-private-cache/dynamic-params/456"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -99,16 +75,10 @@ export default async function Page() { ...@@ -99,16 +75,10 @@ export default async function Page() {
search params in private cache + dynamic content search params in private cache + dynamic content
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-private-cache/search-params?searchParam=123" />
href="/in-private-cache/search-params?searchParam=123"
prefetch={true}
/>
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-private-cache/search-params?searchParam=456" />
href="/in-private-cache/search-params?searchParam=456"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -116,10 +86,7 @@ export default async function Page() { ...@@ -116,10 +86,7 @@ export default async function Page() {
only cookies in private cache only cookies in private cache
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-private-cache/cookies-only" />
href="/in-private-cache/cookies-only"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -127,10 +94,7 @@ export default async function Page() { ...@@ -127,10 +94,7 @@ export default async function Page() {
Date.now() in private cache Date.now() in private cache
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/in-private-cache/date-now" />
href="/in-private-cache/date-now"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -144,10 +108,7 @@ export default async function Page() { ...@@ -144,10 +108,7 @@ export default async function Page() {
cookies() promise passed to public cache + dynamic content cookies() promise passed to public cache + dynamic content
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/passed-to-public-cache/cookies" />
href="/passed-to-public-cache/cookies"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -155,16 +116,10 @@ export default async function Page() { ...@@ -155,16 +116,10 @@ export default async function Page() {
dynamic params promise passed to public cache + dynamic content dynamic params promise passed to public cache + dynamic content
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/passed-to-public-cache/dynamic-params/123" />
href="/passed-to-public-cache/dynamic-params/123"
prefetch={true}
/>
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/passed-to-public-cache/dynamic-params/456" />
href="/passed-to-public-cache/dynamic-params/456"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -172,16 +127,10 @@ export default async function Page() { ...@@ -172,16 +127,10 @@ export default async function Page() {
search params promise passed to public cache + dynamic content search params promise passed to public cache + dynamic content
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/passed-to-public-cache/search-params?searchParam=123" />
href="/passed-to-public-cache/search-params?searchParam=123"
prefetch={true}
/>
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/passed-to-public-cache/search-params?searchParam=456" />
href="/passed-to-public-cache/search-params?searchParam=456"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -189,10 +138,7 @@ export default async function Page() { ...@@ -189,10 +138,7 @@ export default async function Page() {
only cookies passed to public cache (no dynamic content) only cookies passed to public cache (no dynamic content)
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion href="/passed-to-public-cache/cookies-only" />
href="/passed-to-public-cache/cookies-only"
prefetch={true}
/>
</li> </li>
</ul> </ul>
</li> </li>
...@@ -290,7 +236,7 @@ export default async function Page() { ...@@ -290,7 +236,7 @@ export default async function Page() {
<h2>misc</h2> <h2>misc</h2>
<ul> <ul>
<li> <li>
<DebugLinkAccordion href="/fully-static" prefetch={true} /> <DebugLinkAccordion href="/fully-static" />
</li> </li>
</ul> </ul>
</main> </main>
......
...@@ -2,6 +2,8 @@ import { cookies } from 'next/headers' ...@@ -2,6 +2,8 @@ import { cookies } from 'next/headers'
import { Suspense } from 'react' import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared' import { cachedDelay, DebugRenderKind } from '../../../shared'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
......
...@@ -3,6 +3,8 @@ import { Suspense } from 'react' ...@@ -3,6 +3,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared' import { cachedDelay, DebugRenderKind } from '../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
......
...@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind } from '../../../../shared' ...@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
export const unstable_prefetch = 'unstable_runtime'
type Params = { id: string } type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) { export default async function Page({ params }: { params: Promise<Params> }) {
......
...@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind } from '../../../shared' ...@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
export const unstable_prefetch = 'unstable_runtime'
type AnySearchParams = { [key: string]: string | string[] | undefined } type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({ export default async function Page({
......
...@@ -2,6 +2,9 @@ import { Suspense } from 'react' ...@@ -2,6 +2,9 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { lang } from 'next/root-params' import { lang } from 'next/root-params'
import { cookies } from 'next/headers'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
...@@ -12,12 +15,16 @@ export default async function Page() { ...@@ -12,12 +15,16 @@ export default async function Page() {
always be available in static prerenders, so a runtime prefetch should always be available in static prerenders, so a runtime prefetch should
have them too. have them too.
</p> </p>
<StaticallyPrefetchable /> <Suspense fallback="Loading 1...">
<RuntimePrefetchable />
</Suspense>
</main> </main>
) )
} }
async function StaticallyPrefetchable() { async function RuntimePrefetchable() {
await cookies()
const currentLang = await lang() const currentLang = await lang()
await cachedDelay([__filename, currentLang]) await cachedDelay([__filename, currentLang])
return ( return (
......
...@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared' ...@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { lang } from 'next/root-params' import { lang } from 'next/root-params'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
...@@ -14,13 +16,13 @@ export default async function Page() { ...@@ -14,13 +16,13 @@ export default async function Page() {
they should be part of a runtime prefetch. they should be part of a runtime prefetch.
</p> </p>
<Suspense fallback="Loading 1..."> <Suspense fallback="Loading 1...">
<DynamicallyPrefetchable /> <RuntimePrefetchable />
</Suspense> </Suspense>
</main> </main>
) )
} }
async function DynamicallyPrefetchable() { async function RuntimePrefetchable() {
const currentLang = await privateCache() const currentLang = await privateCache()
return ( return (
<div style={{ border: '1px solid blue', padding: '1em' }}> <div style={{ border: '1px solid blue', padding: '1em' }}>
......
...@@ -16,13 +16,11 @@ export default async function Page() { ...@@ -16,13 +16,11 @@ export default async function Page() {
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={`/with-root-param/${currentLang}/in-page/root-params`} href={`/with-root-param/${currentLang}/in-page/root-params`}
prefetch={true}
/> />
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={`/with-root-param/${otherLang}/in-page/root-params`} href={`/with-root-param/${otherLang}/in-page/root-params`}
prefetch={true}
/> />
</li> </li>
</ul> </ul>
...@@ -39,13 +37,11 @@ export default async function Page() { ...@@ -39,13 +37,11 @@ export default async function Page() {
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={`/with-root-param/${currentLang}/in-private-cache/root-params`} href={`/with-root-param/${currentLang}/in-private-cache/root-params`}
prefetch={true}
/> />
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={`/with-root-param/${otherLang}/in-private-cache/root-params`} href={`/with-root-param/${otherLang}/in-private-cache/root-params`}
prefetch={true}
/> />
</li> </li>
</ul> </ul>
...@@ -62,13 +58,11 @@ export default async function Page() { ...@@ -62,13 +58,11 @@ export default async function Page() {
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={`/with-root-param/${currentLang}/passed-to-public-cache/root-params`} href={`/with-root-param/${currentLang}/passed-to-public-cache/root-params`}
prefetch={true}
/> />
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={`/with-root-param/${otherLang}/passed-to-public-cache/root-params`} href={`/with-root-param/${otherLang}/passed-to-public-cache/root-params`}
prefetch={true}
/> />
</li> </li>
</ul> </ul>
......
...@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared' ...@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { lang } from 'next/root-params' import { lang } from 'next/root-params'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
...@@ -14,13 +16,13 @@ export default async function Page() { ...@@ -14,13 +16,13 @@ export default async function Page() {
a hanging input. a hanging input.
</p> </p>
<Suspense fallback="Loading 1..."> <Suspense fallback="Loading 1...">
<DynamicallyPrefetchable /> <RuntimePrefetchable />
</Suspense> </Suspense>
</main> </main>
) )
} }
async function DynamicallyPrefetchable() { async function RuntimePrefetchable() {
const currentLang = await publicCache(lang()) const currentLang = await publicCache(lang())
return ( return (
<div style={{ border: '1px solid blue', padding: '1em' }}> <div style={{ border: '1px solid blue', padding: '1em' }}>
......
...@@ -2,7 +2,7 @@ import { nextTestSetup } from 'e2e-utils' ...@@ -2,7 +2,7 @@ import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act' import { createRouterAct } from '../router-act'
describe('<Link prefetch={true}> (runtime prefetch)', () => { describe('runtime prefetching', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({ const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export const unstable_prefetch = 'unstable_runtime'
export default function Layout({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_prefetch = 'unstable_static'
export default function Page() {
return (
<main>
<h1>A page that should use a static prefetch</h1>
<Suspense fallback="Loading...">
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <div>Dynamic content</div>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
// No exported prefetch value.
// export const unstable_prefetch = ...
export default function Page() {
return (
<main>
<h1>A page that should use a static prefetch</h1>
<Suspense fallback="Loading...">
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <div>Dynamic content</div>
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<ul>
<li>
<LinkAccordion href="/prefetch-static">
/prefetch-static
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/prefetch-runtime">
/prefetch-runtime
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/nested-prefetch-static">
/nested-prefetch-static
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/no-prefetch">/no-prefetch</LinkAccordion>
</li>
</ul>
</main>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_prefetch = 'unstable_static'
export default function Page() {
return (
<main>
<h1>A page that should use a static prefetch</h1>
<Suspense fallback="Loading...">
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <div>Dynamic content</div>
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link prefetch={prefetch} href={href}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
import { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
cacheComponents: true,
clientSegmentCache: true,
// This is automatically enabled when running with `__NEXT_EXPERIMENTAL_PPR`,
// which lets us exercise both modes.
// clientParamParsing: true,
},
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import {
createRequestTracker,
RequestTracker,
} from '../../../../lib/e2e-utils/request-tracker'
import {
RootTreePrefetch,
TreePrefetch,
} from 'next/dist/server/app-render/collect-segment-data'
describe('export const unstable_prefetch = ...', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('disabled in development', () => {})
return
}
// TODO: these tests aren't very good, but since the client-side part isn't implmented yet,
// asserting on what the tree prefetch response contains is the best we can do.
// They should be replaced with `act()` tests when the client-side changes are made.
async function captureTreePrefetchResponse(
requestTracker: RequestTracker,
action: () => Promise<void>
): Promise<string> {
const [, response] = await requestTracker.captureResponse(action, {
async request(req) {
const headers = req.headers()
return headers['next-router-segment-prefetch'] === '/_tree'
},
})
return response.text()
}
/** Hackily parse the first row of the RSC response. */
function parseRouteTreeFromTreePrefetchResponse(response: string) {
// Get row 0, the root object.
const rowMatch = response.match(/(?:^|\n)0:(.*?)\n/)
if (!rowMatch) {
throw new Error('Failed to find row 0 in route tree flight data')
}
// `tree` is essentially plain JSON, so it's fine to not do full RSC parsing.
const data = JSON.parse(rowMatch[1]) as RootTreePrefetch
return data.tree
}
it('does not mark for segments with prefetch: "static" as runtime-prefetchable', async () => {
const browser = await next.browser('/')
const requestTracker = createRequestTracker(browser)
// Reveal the link to trigger a runtime prefetch for one value of the dynamic param
const response = await captureTreePrefetchResponse(
requestTracker,
async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/prefetch-static"]`
)
await linkToggle.click()
}
)
expect(parseRouteTreeFromTreePrefetchResponse(response)).toEqual(
expect.objectContaining({
name: '',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: 'prefetch-static',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: '__PAGE__',
shouldUseRuntimePrefetch: false, // <-----------------
}),
},
}),
},
})
)
})
it('marks segments with prefetch: "runtime" as runtime-prefetchable', async () => {
const browser = await next.browser('/')
const requestTracker = createRequestTracker(browser)
// Reveal the link to trigger a runtime prefetch for one value of the dynamic param
const response = await captureTreePrefetchResponse(
requestTracker,
async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/prefetch-runtime"]`
)
await linkToggle.click()
}
)
expect(parseRouteTreeFromTreePrefetchResponse(response)).toEqual(
expect.objectContaining({
name: '',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: 'prefetch-runtime',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: '__PAGE__',
shouldUseRuntimePrefetch: true, // <-----------------
slots: null,
}),
},
}),
},
})
)
})
it('defaults segments to static if no config is specified', async () => {
const browser = await next.browser('/')
const requestTracker = createRequestTracker(browser)
// Reveal the link to trigger a runtime prefetch for one value of the dynamic param
const response = await captureTreePrefetchResponse(
requestTracker,
async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/no-prefetch"]`
)
await linkToggle.click()
}
)
expect(parseRouteTreeFromTreePrefetchResponse(response)).toEqual(
expect.objectContaining({
name: '',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: 'no-prefetch',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: '__PAGE__',
shouldUseRuntimePrefetch: false, // <-----------------
slots: null,
}),
},
}),
},
}) satisfies TreePrefetch
)
})
it('does not mark a "static" segment that is a child of a "runtime" segment as runtime-prefetchable', async () => {
const browser = await next.browser('/')
const requestTracker = createRequestTracker(browser)
// Reveal the link to trigger a runtime prefetch for one value of the dynamic param
const response = await captureTreePrefetchResponse(
requestTracker,
async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/nested-prefetch-static"]`
)
await linkToggle.click()
}
)
expect(parseRouteTreeFromTreePrefetchResponse(response)).toEqual(
expect.objectContaining({
name: '',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: 'nested-prefetch-static',
shouldUseRuntimePrefetch: true, // <-----------------
slots: {
children: expect.objectContaining({
name: '__PAGE__',
shouldUseRuntimePrefetch: false, // <-----------------
slots: null,
}),
},
}),
},
}) satisfies TreePrefetch
)
})
})
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