Unverified Commit 5a3a3d19 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Reorganize client router modules (#97402)

Pure structural refactor, no behavior changes.

This continues some of the clean-up work I've been doing in the client
router now that more of the implementation has settled, post-Segment
Cache and Instant Navigations.

I have two primary motivations here. The first is purely
maintainability. The current module structure is a mess, and the naming
is misleading when browsing the codebase for the first time.

The second motivation is to prepare for an upcoming rewrite of the
router queue. There will likely be two simultaneous implementations for
a while as the new one settles, so it's extra important the interface
into the router queue is well-defined. I want the fork between the two
worlds to be as clean as possible. This is a similar approach to the one
I took when rewriting the prefetching implementation.

Some of the key name changes:

- ppr-navigations.ts → render-tree.ts. This module's responsibility is
to create the tree that gets passed into React for rendering, currently
called the CacheNode tree. I considered renaming it to cache-node.ts,
but I kept it more generic because I have plans to refactor that type
soon.
- segment-cache/navigation.ts → app-router-state.ts. This module's
responsibility is to compute the next AppRouterState given inputs. It
does perform network requests, but it's conceptually a "pure" operation.
It doesn't deal with any of the router queueing logic. This is the most
reducer-y of the code that still exists, and along with render-tree.ts,
it will remain mostly shared between the old and new state machine
implementations.
- navigator.ts. This is a new module I created to act as the single
entry point for router-level operations: push, replace, navigate,
traverse, restore, refresh, hmrRefresh. This is the primary place where
we'll fork the old and new queue implementations. It's also how we'll
ensure the inactive implementation gets dead-code-eliminated properly
while the two implementations live side-by-side.
parent d1aeb1ce
...@@ -2,6 +2,12 @@ import { startTransition } from 'react' ...@@ -2,6 +2,12 @@ import { startTransition } from 'react'
import { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types' import { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types'
import { dispatchAppRouterAction } from './components/use-action-queue' import { dispatchAppRouterAction } from './components/use-action-queue'
/**
* Invoke a Server Action. The returned promise resolves with the action's
* return value once the response has been processed. Navigation and
* revalidation side effects of the action are handled by the router; they are
* not observable through the returned promise.
*/
export async function callServer(actionId: string, actionArgs: any[]) { export async function callServer(actionId: string, actionArgs: any[]) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
startTransition(() => { startTransition(() => {
......
...@@ -301,21 +301,19 @@ function linkClicked( ...@@ -301,21 +301,19 @@ function linkClicked(
} }
} }
const { dispatchNavigateAction } = const { navigate } =
// TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
// ast-grep-ignore: no-typeof-window-require-tsx // ast-grep-ignore: no-typeof-window-require-tsx
require('../components/app-router-instance') as typeof import('../components/app-router-instance') require('../components/navigator') as typeof import('../components/navigator')
React.startTransition(() => { navigate(
dispatchNavigateAction( href,
href, replace ? 'replace' : 'push',
replace ? 'replace' : 'push', scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default,
scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default, linkInstanceRef.current,
linkInstanceRef.current, transitionTypes,
transitionTypes, prefetchIntent
prefetchIntent )
)
})
} }
} }
......
...@@ -6,39 +6,24 @@ import { ...@@ -6,39 +6,24 @@ import {
ACTION_SERVER_ACTION, ACTION_SERVER_ACTION,
ACTION_NAVIGATE, ACTION_NAVIGATE,
ACTION_RESTORE, ACTION_RESTORE,
type NavigateAction,
ACTION_HMR_REFRESH,
PrefetchKind,
ScrollBehavior, ScrollBehavior,
type AppHistoryState,
} from './router-reducer/router-reducer-types' } from './router-reducer/router-reducer-types'
import { reducer } from './router-reducer/router-reducer' import { reducer } from './router-reducer/router-reducer'
import { addTransitionType, startTransition } from 'react' import { startTransition } from 'react'
import { isThenable } from '../../shared/lib/is-thenable' import { isThenable } from '../../shared/lib/is-thenable'
import { import { navigate } from './app-router-state'
FetchStrategy, import { dispatchGestureState } from './use-action-queue'
type PrefetchTaskFetchStrategy, import { FreshnessPolicy } from './render-tree'
} from './segment-cache/types'
import { prefetch as prefetchWithSegmentCache } from './segment-cache/prefetch'
import { navigate } from './segment-cache/navigation'
import {
dispatchAppRouterAction,
dispatchGestureState,
} from './use-action-queue'
import { resetKnownRoutes } from './segment-cache/optimistic-routes'
import { FreshnessPolicy } from './router-reducer/ppr-navigations'
import { addBasePath } from '../add-base-path' import { addBasePath } from '../add-base-path'
import { isExternalURL } from './app-router-utils' import { isExternalURL } from './app-router-utils'
import type { import type {
AppRouterInstance, AppRouterInstance,
NavigateOptions, NavigateOptions,
PrefetchOptions,
} from '../../shared/lib/app-router-context.shared-runtime' } from '../../shared/lib/app-router-context.shared-runtime'
import { setLinkForCurrentNavigation, type LinkInstance } from './links'
import type { RouterTransitionPrefetchIntent } from '../router-transition-types'
import type { GlobalErrorComponent } from './builtin/global-error' import type { GlobalErrorComponent } from './builtin/global-error'
import { isJavaScriptURLString } from '../lib/javascript-url' import { isJavaScriptURLString } from '../lib/javascript-url'
import { startRouterTransition } from './router-transition' import { push, replace, refresh, hmrRefresh } from './navigator'
import { prefetchRoute } from './prefetch'
export type DispatchStatePromise = React.Dispatch<ReducerState> export type DispatchStatePromise = React.Dispatch<ReducerState>
...@@ -269,72 +254,6 @@ export function getCurrentAppRouterState(): AppRouterState | null { ...@@ -269,72 +254,6 @@ export function getCurrentAppRouterState(): AppRouterState | null {
return globalActionQueue !== null ? globalActionQueue.state : null return globalActionQueue !== null ? globalActionQueue.state : null
} }
function getAppRouterActionQueue(): AppRouterActionQueue {
if (globalActionQueue === null) {
throw new Error(
'Internal Next.js error: Router action dispatched before initialization.'
)
}
return globalActionQueue
}
export function dispatchNavigateAction(
href: string,
navigateType: NavigateAction['navigateType'],
scrollBehavior: ScrollBehavior,
linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined,
prefetchIntent: RouterTransitionPrefetchIntent | null
): void {
// TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway.
if (transitionTypes) {
for (const type of transitionTypes) {
addTransitionType(type)
}
}
const url = new URL(addBasePath(href), location.href)
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url
}
setLinkForCurrentNavigation(linkInstanceRef)
startRouterTransition(
href,
navigateType,
getAppRouterActionQueue().state.tree,
prefetchIntent
)
dispatchAppRouterAction({
type: ACTION_NAVIGATE,
url,
isExternalUrl: isExternalURL(url),
locationSearch: location.search,
scrollBehavior,
navigateType,
})
}
export function dispatchTraverseAction(
href: string,
historyState: AppHistoryState | undefined
) {
startRouterTransition(
href,
'traverse',
getAppRouterActionQueue().state.tree,
null
)
dispatchAppRouterAction({
type: ACTION_RESTORE,
url: new URL(href),
historyState,
})
}
/** /**
* (Experimental) Perform a gesture navigation. This dispatches through React's * (Experimental) Perform a gesture navigation. This dispatches through React's
* useOptimistic instead of the main action queue, allowing the state to be * useOptimistic instead of the main action queue, allowing the state to be
...@@ -391,10 +310,6 @@ function gesturePush(href: string, options?: NavigateOptions): void { ...@@ -391,10 +310,6 @@ function gesturePush(href: string, options?: NavigateOptions): void {
} }
} }
// Tracks the newest HMR refresh generation so that a newer refresh can abort
// the request of the one it supersedes. Development only.
let activeHmrRefreshController: AbortController | null = null
/** /**
* The app router that is exposed through `useRouter`. These are public API * The app router that is exposed through `useRouter`. These are public API
* methods. Internal Next.js code should call the lower level methods directly * methods. Internal Next.js code should call the lower level methods directly
...@@ -403,121 +318,11 @@ let activeHmrRefreshController: AbortController | null = null ...@@ -403,121 +318,11 @@ let activeHmrRefreshController: AbortController | null = null
export const publicAppRouterInstance: AppRouterInstance = { export const publicAppRouterInstance: AppRouterInstance = {
back: () => window.history.back(), back: () => window.history.back(),
forward: () => window.history.forward(), forward: () => window.history.forward(),
prefetch: prefetch: prefetchRoute,
// Unlike the old implementation, the Segment Cache doesn't store its replace: replace,
// data in the router reducer state; it writes into a global mutable push: push,
// cache. So we don't need to dispatch an action. refresh: refresh,
(href: string, options?: PrefetchOptions) => { hmrRefresh: hmrRefresh,
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
const actionQueue = getAppRouterActionQueue()
const prefetchKind = options?.kind ?? PrefetchKind.AUTO
// We don't currently offer a way to issue a runtime prefetch via `router.prefetch()`.
// This will be possible when we update its API to not take a PrefetchKind.
let fetchStrategy: PrefetchTaskFetchStrategy
switch (prefetchKind) {
case PrefetchKind.AUTO: {
// We default to PPR. We'll discover whether or not the route supports it with the initial prefetch.
fetchStrategy = FetchStrategy.PPR
break
}
case PrefetchKind.FULL: {
fetchStrategy = FetchStrategy.Full
break
}
default: {
prefetchKind satisfies never
// Despite typescript thinking that this can't happen,
// we might get an unexpected value from user code.
// We don't know what they want, but we know they want a prefetch,
// so use the default.
fetchStrategy = FetchStrategy.PPR
}
}
prefetchWithSegmentCache(
href,
actionQueue.state.nextUrl,
actionQueue.state.tree,
fetchStrategy,
options?.onInvalidate ?? null
)
},
replace: (href: string, options?: NavigateOptions) => {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
startTransition(() => {
dispatchNavigateAction(
href,
'replace',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
})
},
push: (href: string, options?: NavigateOptions) => {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
startTransition(() => {
dispatchNavigateAction(
href,
'push',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
})
},
refresh: () => {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_REFRESH,
})
})
},
hmrRefresh: () => {
if (process.env.NODE_ENV !== 'development') {
throw new Error(
'hmrRefresh can only be used in development mode. Please use refresh instead.'
)
} else {
// Reset the known routes table so that route predictions are cleared
// when routes change during development.
resetKnownRoutes()
let signal: AbortSignal | undefined
if (process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION) {
// Abort the superseded generation before scheduling the new one, so its
// request is torn down as early as possible. Halting (not rejecting)
// makes the abort safe regardless of order.
activeHmrRefreshController?.abort()
activeHmrRefreshController = new AbortController()
signal = activeHmrRefreshController.signal
}
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_HMR_REFRESH,
signal,
})
})
}
},
// Default value. Each route segment provides its own value at runtime. Refer // Default value. Each route segment provides its own value at runtime. Refer
// to `useRouter()`. // to `useRouter()`.
bfcacheId: '0', bfcacheId: '0',
......
import type { import type {
FlightRouterState, FlightRouterState,
ScrollRef, ScrollRef,
} from '../../../shared/lib/app-router-types' } from '../../shared/lib/app-router-types'
import type { CacheNode } from '../../../shared/lib/app-router-types' import type { CacheNode } from '../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types' import { PrefetchHint } from '../../shared/lib/app-router-types'
import { fetchServerResponse } from '../router-reducer/fetch-server-response' import { fetchServerResponse } from './router-reducer/fetch-server-response'
import { import {
startPPRNavigation, startPPRNavigation,
spawnDynamicRequests, spawnDynamicRequests,
...@@ -12,8 +12,8 @@ import { ...@@ -12,8 +12,8 @@ import {
beginLockedNavigation, beginLockedNavigation,
type NavigationLock, type NavigationLock,
type NavigationRequestAccumulation, type NavigationRequestAccumulation,
} from '../router-reducer/ppr-navigations' } from './render-tree'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url' import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import { import {
EntryStatus, EntryStatus,
segmentCacheMap, segmentCacheMap,
...@@ -23,23 +23,29 @@ import { ...@@ -23,23 +23,29 @@ import {
spawnStaticStageCacheWrite, spawnStaticStageCacheWrite,
writeRuntimePrefetchStreamIntoCache, writeRuntimePrefetchStreamIntoCache,
type FulfilledRouteCacheEntry, type FulfilledRouteCacheEntry,
} from './cache' } from './segment-cache/cache'
import { discoverKnownRoute } from './optimistic-routes' import { discoverKnownRoute } from './segment-cache/optimistic-routes'
import { createCacheKey, type NormalizedSearch } from './cache-key' import {
import type { CacheMap } from './cache-map' createCacheKey,
import { schedulePrefetchTask } from './scheduler' type NormalizedSearch,
import { PrefetchPriority, FetchStrategy } from './types' } from './segment-cache/cache-key'
import { getLinkForCurrentNavigation } from '../links' import type { CacheMap } from './segment-cache/cache-map'
import type { AppRouterState } from '../router-reducer/router-reducer-types' import { schedulePrefetchTask } from './segment-cache/scheduler'
import { ScrollBehavior } from '../router-reducer/router-reducer-types' import { PrefetchPriority, FetchStrategy } from './segment-cache/types'
import { computeChangedPath } from '../router-reducer/compute-changed-path' import { getLinkForCurrentNavigation } from './links'
import { isJavaScriptURLString } from '../../lib/javascript-url' import type { AppRouterState } from './router-reducer/router-reducer-types'
import { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache' import { ScrollBehavior } from './router-reducer/router-reducer-types'
import { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages' import { computeChangedPath } from './router-reducer/compute-changed-path'
import { isJavaScriptURLString } from '../lib/javascript-url'
import {
UnknownDynamicStaleTime,
computeDynamicStaleAt,
} from './segment-cache/bfcache'
import { createLinkPrefetchPartialError } from '../../shared/lib/instant-messages'
import { import {
createNavigationSeed, createNavigationSeed,
type NavigationSeed, type NavigationSeed,
} from './decode-server-response' } from './segment-cache/decode-server-response'
/** /**
* Navigate to a new URL, using the Segment Cache to construct a response. * Navigate to a new URL, using the Segment Cache to construct a response.
...@@ -71,7 +77,7 @@ export function navigate( ...@@ -71,7 +77,7 @@ export function navigate(
// requested. // requested.
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { isNavigationLocked } = const { isNavigationLocked } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock') require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
if (isNavigationLocked()) { if (isNavigationLocked()) {
// Signal that a new locked navigation is starting. This force-resolves the // Signal that a new locked navigation is starting. This force-resolves the
// previous locked navigation's withheld data (so a reused shared segment // previous locked navigation's withheld data (so a reused shared segment
...@@ -304,7 +310,7 @@ export function navigateToKnownRoute( ...@@ -304,7 +310,7 @@ export function navigateToKnownRoute(
let restrictToShell = false let restrictToShell = false
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { shouldRestrictNavigationToShell } = const { shouldRestrictNavigationToShell } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock') require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
const link = getLinkForCurrentNavigation() const link = getLinkForCurrentNavigation()
restrictToShell = shouldRestrictNavigationToShell( restrictToShell = shouldRestrictNavigationToShell(
navigationSeed.routeTree.prefetchHints, navigationSeed.routeTree.prefetchHints,
...@@ -867,7 +873,7 @@ async function ensurePrefetchThenNavigate( ...@@ -867,7 +873,7 @@ async function ensurePrefetchThenNavigate(
// cares about has settled — so the navigation below reads present data // cares about has settled — so the navigation below reads present data
// rather than a still-in-flight entry. // rather than a still-in-flight entry.
const { beginNavigationLockPrefetch } = const { beginNavigationLockPrefetch } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock') require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
const navigationLockPrefetch = beginNavigationLockPrefetch() const navigationLockPrefetch = beginNavigationLockPrefetch()
const prefetchTask = schedulePrefetchTask( const prefetchTask = schedulePrefetchTask(
cacheKey, cacheKey,
...@@ -906,7 +912,7 @@ async function ensurePrefetchThenNavigate( ...@@ -906,7 +912,7 @@ async function ensurePrefetchThenNavigate(
// document load transition it to captured-MPA. // document load transition it to captured-MPA.
if (!result.pushRef.mpaNavigation) { if (!result.pushRef.mpaNavigation) {
const { updateCapturedSPAToTree } = const { updateCapturedSPAToTree } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock') require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
updateCapturedSPAToTree(currentFlightRouterState, result.tree) updateCapturedSPAToTree(currentFlightRouterState, result.tree)
} }
......
import React, { import React, {
useEffect, useEffect,
useMemo, useMemo,
startTransition,
useInsertionEffect, useInsertionEffect,
useDeferredValue, useDeferredValue,
} from 'react' } from 'react'
...@@ -11,7 +10,6 @@ import { ...@@ -11,7 +10,6 @@ import {
GlobalLayoutRouterContext, GlobalLayoutRouterContext,
} from '../../shared/lib/app-router-context.shared-runtime' } from '../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } from '../../shared/lib/app-router-types' import type { CacheNode } from '../../shared/lib/app-router-types'
import { ACTION_RESTORE } from './router-reducer/router-reducer-types'
import type { import type {
AppHistoryState, AppHistoryState,
AppRouterState, AppRouterState,
...@@ -24,7 +22,7 @@ import { ...@@ -24,7 +22,7 @@ import {
NavigationPromisesContext, NavigationPromisesContext,
type NavigationPromises, type NavigationPromises,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { dispatchAppRouterAction, useActionQueue } from './use-action-queue' import { useActionQueue } from './use-action-queue'
import { setLastCommittedTree } from './router-reducer/reducers/committed-state' import { setLastCommittedTree } from './router-reducer/reducers/committed-state'
import { AppRouterAnnouncer } from './app-router-announcer' import { AppRouterAnnouncer } from './app-router-announcer'
import { RedirectBoundary } from './redirect-boundary' import { RedirectBoundary } from './redirect-boundary'
...@@ -38,11 +36,11 @@ import { ...@@ -38,11 +36,11 @@ import {
} from './router-reducer/compute-changed-path' } from './router-reducer/compute-changed-path'
import { useNavFailureHandler } from './nav-failure-handler' import { useNavFailureHandler } from './nav-failure-handler'
import { import {
dispatchTraverseAction,
publicAppRouterInstance, publicAppRouterInstance,
type AppRouterActionQueue, type AppRouterActionQueue,
type GlobalErrorState, type GlobalErrorState,
} from './app-router-instance' } from './app-router-instance'
import { legacyUrgentBFCacheRestore, restore, traverse } from './navigator'
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect' import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { isRedirectError } from './redirect-error' import { isRedirectError } from './redirect-error'
import { pingVisibleLinks } from './links' import { pingVisibleLinks } from './links'
...@@ -99,14 +97,7 @@ function handlePopState(state: PopStateEvent['state']): void { ...@@ -99,14 +97,7 @@ function handlePopState(state: PopStateEvent['state']): void {
return return
} }
// TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously traverse(window.location.href, state.__PRIVATE_NEXTJS_INTERNALS_TREE)
// Without startTransition works if the cache is there for this path
startTransition(() => {
dispatchTraverseAction(
window.location.href,
state.__PRIVATE_NEXTJS_INTERNALS_TREE
)
})
} }
function HistoryUpdater({ function HistoryUpdater({
...@@ -288,11 +279,10 @@ function Router({ ...@@ -288,11 +279,10 @@ function Router({
// of the last MPA navigation. // of the last MPA navigation.
globalMutable.pendingMpaPath = undefined globalMutable.pendingMpaPath = undefined
dispatchAppRouterAction({ legacyUrgentBFCacheRestore(
type: ACTION_RESTORE, new URL(window.location.href),
url: new URL(window.location.href), window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE
historyState: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE, )
})
} }
window.addEventListener('pageshow', handlePageShow) window.addEventListener('pageshow', handlePageShow)
...@@ -377,13 +367,7 @@ function Router({ ...@@ -377,13 +367,7 @@ function Router({
const appHistoryState: AppHistoryState | undefined = const appHistoryState: AppHistoryState | undefined =
window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE
startTransition(() => { restore(new URL(url ?? href, href), appHistoryState)
dispatchAppRouterAction({
type: ACTION_RESTORE,
url: new URL(url ?? href, href),
historyState: appHistoryState,
})
})
} }
/** /**
......
...@@ -48,7 +48,7 @@ import { ...@@ -48,7 +48,7 @@ import {
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { getParamValueFromCacheKey } from '../route-params' import { getParamValueFromCacheKey } from '../route-params'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { isDeferredRsc } from './router-reducer/ppr-navigations' import { isDeferredRsc } from './render-tree'
const enum ScrollTargetState { const enum ScrollTargetState {
NoClientRects, NoClientRects,
......
// This module is the router's operation interface: one function per
// user-facing operation, called directly by the corresponding entry points
// (Link, the public router methods, the history event handlers).
//
// The navigator owns the startTransition for its operations, along with the
// centralized safety checks; callers must invoke these functions
// synchronously within the originating event.
//
// Server Actions are not a navigator operation: the action queue is
// semantically separate from the router state queue. Its entry point is
// callServer (app-call-server.ts).
//
// The legacy reducer action objects are an implementation detail of the
// current action queue; they are constructed here and never by callers.
//
// This is also the seam where an experimental rewrite of the router state
// machine will fork from the existing implementation, so nothing above this
// interface may depend on how the operations are processed.
import { addTransitionType, startTransition } from 'react'
import {
ACTION_HMR_REFRESH,
ACTION_NAVIGATE,
ACTION_REFRESH,
ACTION_RESTORE,
type AppHistoryState,
type AppRouterState,
type NavigateAction,
ScrollBehavior,
} from './router-reducer/router-reducer-types'
import type { NavigateOptions } from '../../shared/lib/app-router-context.shared-runtime'
import { dispatchAppRouterAction } from './use-action-queue'
import { getCurrentAppRouterState } from './app-router-instance'
import { setLinkForCurrentNavigation, type LinkInstance } from './links'
import type { RouterTransitionPrefetchIntent } from '../router-transition-types'
import { startRouterTransition } from './router-transition'
import { addBasePath } from '../add-base-path'
import { isExternalURL } from './app-router-utils'
import { isJavaScriptURLString } from '../lib/javascript-url'
import { resetKnownRoutes } from './segment-cache/optimistic-routes'
function getRequiredAppRouterState(): AppRouterState {
const state = getCurrentAppRouterState()
if (state === null) {
throw new Error(
'Internal Next.js error: Router action dispatched before initialization.'
)
}
return state
}
export function navigate(
href: string,
navigateType: NavigateAction['navigateType'],
scrollBehavior: ScrollBehavior,
linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined,
prefetchIntent: RouterTransitionPrefetchIntent | null
): void {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
startTransition(() => {
// TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway.
if (transitionTypes) {
for (const type of transitionTypes) {
addTransitionType(type)
}
}
const url = new URL(addBasePath(href), location.href)
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url
}
setLinkForCurrentNavigation(linkInstanceRef)
startRouterTransition(
href,
navigateType,
getRequiredAppRouterState().tree,
prefetchIntent
)
dispatchAppRouterAction({
type: ACTION_NAVIGATE,
url,
isExternalUrl: isExternalURL(url),
locationSearch: location.search,
scrollBehavior,
navigateType,
})
})
}
export function push(href: string, options?: NavigateOptions): void {
navigate(
href,
'push',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
}
export function replace(href: string, options?: NavigateOptions): void {
navigate(
href,
'replace',
options?.scroll === false
? ScrollBehavior.NoScroll
: ScrollBehavior.Default,
null,
options?.transitionTypes,
null
)
}
export function traverse(
href: string,
historyState: AppHistoryState | undefined
): void {
startTransition(() => {
startRouterTransition(
href,
'traverse',
getRequiredAppRouterState().tree,
null
)
restore(new URL(href), historyState)
})
}
/**
* Sync the router state to a history entry that was written by something
* other than a router navigation (a userland pushState/replaceState, or a
* bfcache restore). Unlike a traversal, this does not represent a transition
* between routes.
*/
export function restore(
url: URL,
historyState: AppHistoryState | undefined
): void {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url,
historyState,
})
})
}
/**
* The bfcache `pageshow` restore (see the pageshow handler in app-router.tsx).
* Unlike every other navigator operation, this dispatches as a deliberately
* urgent (non-transition) update: the restored state reset must render before
* anything else can observe the stale mpaNavigation state and re-fire the MPA
* navigation the restore exists to prevent. As a transition it would be
* interruptible, and an intervening urgent render could commit against the
* stale state first.
*
* This is a preserved legacy special case. It will not be carried into the
* concurrent router queue, which handles bfcache restore through its own
* design.
*/
export function legacyUrgentBFCacheRestore(
url: URL,
historyState: AppHistoryState | undefined
): void {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url,
historyState,
})
}
export function refresh(): void {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_REFRESH,
})
})
}
// Tracks the newest HMR refresh generation so that a newer refresh can abort
// the request of the one it supersedes. Development only.
let activeHmrRefreshController: AbortController | null = null
// Development only.
export function hmrRefresh(): void {
if (process.env.NODE_ENV !== 'development') {
throw new Error(
'hmrRefresh can only be used in development mode. Please use refresh instead.'
)
} else {
// Reset the known routes table so that route predictions are cleared
// when routes change during development.
resetKnownRoutes()
let signal: AbortSignal | undefined
if (process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION) {
// Abort the superseded generation before scheduling the new one, so its
// request is torn down as early as possible. Halting (not rejecting)
// makes the abort safe regardless of order.
activeHmrRefreshController?.abort()
activeHmrRefreshController = new AbortController()
signal = activeHmrRefreshController.signal
}
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_HMR_REFRESH,
signal,
})
})
}
}
import type { FlightRouterState } from '../../../shared/lib/app-router-types' import type { FlightRouterState } from '../../shared/lib/app-router-types'
import { createPrefetchURL } from '../app-router-utils' import type { PrefetchOptions } from '../../shared/lib/app-router-context.shared-runtime'
import { createCacheKey } from './cache-key' import { PrefetchKind } from './router-reducer/router-reducer-types'
import { schedulePrefetchTask } from './scheduler' import { createPrefetchURL } from './app-router-utils'
import { PrefetchPriority, type PrefetchTaskFetchStrategy } from './types' import { getCurrentAppRouterState } from './app-router-instance'
import { isJavaScriptURLString } from '../lib/javascript-url'
import { createCacheKey } from './segment-cache/cache-key'
import { schedulePrefetchTask } from './segment-cache/scheduler'
import {
FetchStrategy,
PrefetchPriority,
type PrefetchTaskFetchStrategy,
} from './segment-cache/types'
/**
* The public prefetch operation, exposed through `router.prefetch`. Converts
* the public options into a fetch strategy, reads the current router state,
* and drives the Segment Cache.
*
* Unlike the old implementation, the Segment Cache doesn't store its data in
* the router reducer state; it writes into a global mutable cache. So we
* don't need to dispatch an action.
*/
export function prefetchRoute(href: string, options?: PrefetchOptions): void {
if (isJavaScriptURLString(href)) {
throw new Error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
}
const state = getCurrentAppRouterState()
if (state === null) {
throw new Error(
'Internal Next.js error: Router action dispatched before initialization.'
)
}
const prefetchKind = options?.kind ?? PrefetchKind.AUTO
// We don't currently offer a way to issue a runtime prefetch via `router.prefetch()`.
// This will be possible when we update its API to not take a PrefetchKind.
let fetchStrategy: PrefetchTaskFetchStrategy
switch (prefetchKind) {
case PrefetchKind.AUTO: {
// We default to PPR. We'll discover whether or not the route supports it with the initial prefetch.
fetchStrategy = FetchStrategy.PPR
break
}
case PrefetchKind.FULL: {
fetchStrategy = FetchStrategy.Full
break
}
default: {
prefetchKind satisfies never
// Despite typescript thinking that this can't happen,
// we might get an unexpected value from user code.
// We don't know what they want, but we know they want a prefetch,
// so use the default.
fetchStrategy = FetchStrategy.PPR
}
}
prefetch(
href,
state.nextUrl,
state.tree,
fetchStrategy,
options?.onInvalidate ?? null
)
}
/** /**
* Entrypoint for prefetching a URL into the Segment Cache. * Entrypoint for prefetching a URL into the Segment Cache.
......
import type { import type {
FlightRouterState, FlightRouterState,
Segment, Segment,
} from '../../../shared/lib/app-router-types' } from '../../shared/lib/app-router-types'
import type { CacheNode } from '../../../shared/lib/app-router-types' import type { CacheNode } from '../../shared/lib/app-router-types'
import type { HeadData, ScrollRef } from '../../../shared/lib/app-router-types' import type { HeadData, ScrollRef } from '../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types' import { PrefetchHint } from '../../shared/lib/app-router-types'
import { import {
PAGE_SEGMENT_KEY, PAGE_SEGMENT_KEY,
DEFAULT_SEGMENT_KEY, DEFAULT_SEGMENT_KEY,
NOT_FOUND_SEGMENT_KEY, NOT_FOUND_SEGMENT_KEY,
} from '../../../shared/lib/segment' } from '../../shared/lib/segment'
import { matchSegment } from '../match-segments' import { matchSegment } from './match-segments'
import { createHrefFromUrl } from './create-href-from-url' import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import { fetchServerResponse } from './fetch-server-response' import { fetchServerResponse } from './router-reducer/fetch-server-response'
import { dispatchAppRouterAction } from '../use-action-queue' import { dispatchAppRouterAction } from './use-action-queue'
import { import {
ACTION_SERVER_PATCH, ACTION_SERVER_PATCH,
type ServerPatchAction, type ServerPatchAction,
} from './router-reducer-types' } from './router-reducer/router-reducer-types'
import { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from './router-reducer/is-navigating-to-new-root-layout'
import { getLastCommittedTree } from './reducers/committed-state' import { getLastCommittedTree } from './router-reducer/reducers/committed-state'
import { import {
createNavigationSeed, createNavigationSeed,
type NavigationSeed, type NavigationSeed,
} from '../segment-cache/decode-server-response' } from './segment-cache/decode-server-response'
import { import {
segmentCacheMap, segmentCacheMap,
type SegmentCacheEntry, type SegmentCacheEntry,
...@@ -39,15 +39,15 @@ import { ...@@ -39,15 +39,15 @@ import {
spawnStaticStageCacheWrite, spawnStaticStageCacheWrite,
writeRuntimePrefetchStreamIntoCache, writeRuntimePrefetchStreamIntoCache,
EntryStatus, EntryStatus,
} from '../segment-cache/cache' } from './segment-cache/cache'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes' import { discoverKnownRoute } from './segment-cache/optimistic-routes'
import { urlSearchParamsToParsedUrlQuery } from '../../route-params' import { urlSearchParamsToParsedUrlQuery } from '../route-params'
import type { NormalizedSearch } from '../segment-cache/cache-key' import type { NormalizedSearch } from './segment-cache/cache-key'
import type { CacheMap } from '../segment-cache/cache-map' import type { CacheMap } from './segment-cache/cache-map'
import { import {
getRenderedSearchFromVaryPath, getRenderedSearchFromVaryPath,
type PageVaryPath, type PageVaryPath,
} from '../segment-cache/vary-path' } from './segment-cache/vary-path'
import { import {
readFromBFCache, readFromBFCache,
readFromBFCacheDuringRegularNavigation, readFromBFCacheDuringRegularNavigation,
...@@ -55,7 +55,7 @@ import { ...@@ -55,7 +55,7 @@ import {
writeHeadToBFCache, writeHeadToBFCache,
updateBFCacheEntryStaleAt, updateBFCacheEntryStaleAt,
computeDynamicStaleAt, computeDynamicStaleAt,
} from '../segment-cache/bfcache' } from './segment-cache/bfcache'
// This is yet another tree type that is used to track pending promises that // This is yet another tree type that is used to track pending promises that
// need to be fulfilled once the dynamic data is received. The terminal nodes of // need to be fulfilled once the dynamic data is received. The terminal nodes of
...@@ -2293,7 +2293,7 @@ function createDeferredRsc< ...@@ -2293,7 +2293,7 @@ function createDeferredRsc<
export function getCurrentNavigationLock(): NavigationLock | null { export function getCurrentNavigationLock(): NavigationLock | null {
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { getCurrentNavigationGate } = const { getCurrentNavigationGate } =
require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock') require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
return getCurrentNavigationGate() return getCurrentNavigationGate()
} }
return null return null
...@@ -2311,7 +2311,7 @@ export function getCurrentNavigationLock(): NavigationLock | null { ...@@ -2311,7 +2311,7 @@ export function getCurrentNavigationLock(): NavigationLock | null {
export function beginLockedNavigation(): NavigationLock | null { export function beginLockedNavigation(): NavigationLock | null {
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { beginLockedNavigation: begin } = const { beginLockedNavigation: begin } =
require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock') require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
return begin() return begin()
} }
return null return null
...@@ -2326,7 +2326,7 @@ export function beginLockedNavigation(): NavigationLock | null { ...@@ -2326,7 +2326,7 @@ export function beginLockedNavigation(): NavigationLock | null {
export function resetNavigationLockToPending(): void { export function resetNavigationLockToPending(): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { resetNavigationLockToPending: reset } = const { resetNavigationLockToPending: reset } =
require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock') require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')
reset() reset()
} }
} }
...@@ -5,7 +5,7 @@ import { extractPathFromFlightRouterState } from './compute-changed-path' ...@@ -5,7 +5,7 @@ import { extractPathFromFlightRouterState } from './compute-changed-path'
import type { AppRouterState } from './router-reducer-types' import type { AppRouterState } from './router-reducer-types'
import { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport' import { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'
import { createInitialCacheNodeForHydration } from './ppr-navigations' import { createInitialCacheNodeForHydration } from '../render-tree'
import { import {
writeRuntimePrefetchStreamIntoCache, writeRuntimePrefetchStreamIntoCache,
spawnStaticStageCacheWrite, spawnStaticStageCacheWrite,
......
...@@ -4,7 +4,7 @@ import type { ...@@ -4,7 +4,7 @@ import type {
ReducerState, ReducerState,
} from '../router-reducer-types' } from '../router-reducer-types'
import { refreshDynamicData } from './refresh-reducer' import { refreshDynamicData } from './refresh-reducer'
import { FreshnessPolicy } from '../ppr-navigations' import { FreshnessPolicy } from '../../render-tree'
export function hmrRefreshReducer( export function hmrRefreshReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
......
...@@ -7,9 +7,9 @@ import type { ...@@ -7,9 +7,9 @@ import type {
import { import {
completeHardNavigation, completeHardNavigation,
navigate as navigateUsingSegmentCache, navigate as navigateUsingSegmentCache,
} from '../../segment-cache/navigation' } from '../../app-router-state'
import { getStaleTimeMs } from '../../segment-cache/cache' import { getStaleTimeMs } from '../../segment-cache/cache'
import { FreshnessPolicy } from '../ppr-navigations' import { FreshnessPolicy } from '../../render-tree'
// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`) // These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)
// and default to 5 minutes (static) / 0 seconds (dynamic) // and default to 5 minutes (static) / 0 seconds (dynamic)
......
...@@ -4,14 +4,14 @@ import type { ...@@ -4,14 +4,14 @@ import type {
RefreshAction, RefreshAction,
} from '../router-reducer-types' } from '../router-reducer-types'
import { ScrollBehavior } from '../router-reducer-types' import { ScrollBehavior } from '../router-reducer-types'
import { navigateToKnownRoute } from '../../segment-cache/navigation' import { navigateToKnownRoute } from '../../app-router-state'
import { createNavigationSeed } from '../../segment-cache/decode-server-response' import { createNavigationSeed } from '../../segment-cache/decode-server-response'
import { import {
invalidateSegmentCacheEntries, invalidateSegmentCacheEntries,
segmentCacheMap, segmentCacheMap,
} from '../../segment-cache/cache' } from '../../segment-cache/cache'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree' import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations' import { FreshnessPolicy, getCurrentNavigationLock } from '../../render-tree'
import { import {
invalidateBfCache, invalidateBfCache,
UnknownDynamicStaleTime, UnknownDynamicStaleTime,
......
...@@ -10,12 +10,12 @@ import { ...@@ -10,12 +10,12 @@ import {
spawnDynamicRequests, spawnDynamicRequests,
startPPRNavigation, startPPRNavigation,
type NavigationRequestAccumulation, type NavigationRequestAccumulation,
} from '../ppr-navigations' } from '../../render-tree'
import type { FlightRouterState } from '../../../../shared/lib/app-router-types' import type { FlightRouterState } from '../../../../shared/lib/app-router-types'
import { import {
completeHardNavigation, completeHardNavigation,
completeTraverseNavigation, completeTraverseNavigation,
} from '../../segment-cache/navigation' } from '../../app-router-state'
import { createNavigationSeed } from '../../segment-cache/decode-server-response' import { createNavigationSeed } from '../../segment-cache/decode-server-response'
import { segmentCacheMap } from '../../segment-cache/cache' import { segmentCacheMap } from '../../segment-cache/cache'
import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache' import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'
......
...@@ -56,7 +56,7 @@ import { ...@@ -56,7 +56,7 @@ import {
completeHardNavigation, completeHardNavigation,
navigateToKnownRoute, navigateToKnownRoute,
navigate, navigate,
} from '../../segment-cache/navigation' } from '../../app-router-state'
import { createNavigationSeed } from '../../segment-cache/decode-server-response' import { createNavigationSeed } from '../../segment-cache/decode-server-response'
import { discoverKnownRoute } from '../../segment-cache/optimistic-routes' import { discoverKnownRoute } from '../../segment-cache/optimistic-routes'
import type { NormalizedSearch } from '../../segment-cache/cache-key' import type { NormalizedSearch } from '../../segment-cache/cache-key'
...@@ -67,7 +67,7 @@ import { ...@@ -67,7 +67,7 @@ import {
type ActionRevalidationKind, type ActionRevalidationKind,
} from '../../../../shared/lib/action-revalidation-kind' } from '../../../../shared/lib/action-revalidation-kind'
import { isExternalURL } from '../../app-router-utils' import { isExternalURL } from '../../app-router-utils'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations' import { FreshnessPolicy, getCurrentNavigationLock } from '../../render-tree'
import { processFetch } from '../fetch-server-response' import { processFetch } from '../fetch-server-response'
import { import {
invalidateBfCache, invalidateBfCache,
......
...@@ -9,10 +9,10 @@ import { ...@@ -9,10 +9,10 @@ import {
import { import {
completeHardNavigation, completeHardNavigation,
navigateToKnownRoute, navigateToKnownRoute,
} from '../../segment-cache/navigation' } from '../../app-router-state'
import { segmentCacheMap } from '../../segment-cache/cache' import { segmentCacheMap } from '../../segment-cache/cache'
import { refreshReducer } from './refresh-reducer' import { refreshReducer } from './refresh-reducer'
import { getCurrentNavigationLock } from '../ppr-navigations' import { getCurrentNavigationLock } from '../../render-tree'
export function serverPatchReducer( export function serverPatchReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
......
...@@ -2,7 +2,7 @@ import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types' ...@@ -2,7 +2,7 @@ import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'
import type { FlightRouterState } from '../../../shared/lib/app-router-types' import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import type { NavigationSeed } from '../segment-cache/decode-server-response' import type { NavigationSeed } from '../segment-cache/decode-server-response'
import type { FetchServerResponseResult } from './fetch-server-response' import type { FetchServerResponseResult } from './fetch-server-response'
import type { FreshnessPolicy } from './ppr-navigations' import type { FreshnessPolicy } from '../render-tree'
export const ACTION_REFRESH = 'refresh' export const ACTION_REFRESH = 'refresh'
export const ACTION_NAVIGATE = 'navigate' export const ACTION_NAVIGATE = 'navigate'
......
...@@ -5477,7 +5477,7 @@ async function streamStagedRenderInDev({ ...@@ -5477,7 +5477,7 @@ async function streamStagedRenderInDev({
// earlier on a cache miss). When streaming live (a client navigation), it's // earlier on a cache miss). When streaming live (a client navigation), it's
// surfaced through the Flight payload as `_revealAfter`: the client decodes // surfaced through the Flight payload as `_revealAfter`: the client decodes
// it and defers resolving the response's deferred RSCs on it (see // it and defers resolving the response's deferred RSCs on it (see
// `ppr-navigations`), so a Suspense boundary's children aren't revealed // `render-tree`), so a Suspense boundary's children aren't revealed
// before their row has been decoded, which would flush a premature fallback. // before their row has been decoded, which would flush a premature fallback.
// React serializes the promise as a pending row whose resolution row is // React serializes the promise as a pending row whose resolution row is
// emitted only when we resolve it here, and that row follows the children's // emitted only when we resolve it here, and that row follows the children's
......
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