| 'use client' |
|
|
| import React, { |
| useEffect, |
| useMemo, |
| startTransition, |
| useInsertionEffect, |
| useDeferredValue, |
| } from 'react' |
| import { |
| AppRouterContext, |
| LayoutRouterContext, |
| GlobalLayoutRouterContext, |
| } from '../../shared/lib/app-router-context.shared-runtime' |
| import type { CacheNode } from '../../shared/lib/app-router-context.shared-runtime' |
| import { ACTION_RESTORE } from './router-reducer/router-reducer-types' |
| import type { AppRouterState } from './router-reducer/router-reducer-types' |
| import { createHrefFromUrl } from './router-reducer/create-href-from-url' |
| import { |
| SearchParamsContext, |
| PathnameContext, |
| PathParamsContext, |
| } from '../../shared/lib/hooks-client-context.shared-runtime' |
| import { dispatchAppRouterAction, useActionQueue } from './use-action-queue' |
| import { ErrorBoundary } from './error-boundary' |
| import DefaultGlobalError from './builtin/global-error' |
| import { isBot } from '../../shared/lib/router/utils/is-bot' |
| import { addBasePath } from '../add-base-path' |
| import { AppRouterAnnouncer } from './app-router-announcer' |
| import { RedirectBoundary } from './redirect-boundary' |
| import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache' |
| import { unresolvedThenable } from './unresolved-thenable' |
| import { removeBasePath } from '../remove-base-path' |
| import { hasBasePath } from '../has-base-path' |
| import { getSelectedParams } from './router-reducer/compute-changed-path' |
| import type { FlightRouterState } from '../../server/app-render/types' |
| import { useNavFailureHandler } from './nav-failure-handler' |
| import { |
| dispatchTraverseAction, |
| publicAppRouterInstance, |
| type AppRouterActionQueue, |
| type GlobalErrorState, |
| } from './app-router-instance' |
| import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect' |
| import { isRedirectError, RedirectType } from './redirect-error' |
| import { pingVisibleLinks } from './links' |
| import GracefulDegradeBoundary from './errors/graceful-degrade-boundary' |
|
|
| const globalMutable: { |
| pendingMpaPath?: string |
| } = {} |
|
|
| export function isExternalURL(url: URL) { |
| return url.origin !== window.location.origin |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| export function createPrefetchURL(href: string): URL | null { |
| |
| if (isBot(window.navigator.userAgent)) { |
| return null |
| } |
|
|
| let url: URL |
| try { |
| url = new URL(addBasePath(href), window.location.href) |
| } catch (_) { |
| |
| |
| throw new Error( |
| `Cannot prefetch '${href}' because it cannot be converted to a URL.` |
| ) |
| } |
|
|
| |
| if (process.env.NODE_ENV === 'development') { |
| return null |
| } |
|
|
| |
| if (isExternalURL(url)) { |
| return null |
| } |
|
|
| return url |
| } |
|
|
| function HistoryUpdater({ |
| appRouterState, |
| }: { |
| appRouterState: AppRouterState |
| }) { |
| useInsertionEffect(() => { |
| if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) { |
| |
| |
| window.next.__pendingUrl = undefined |
| } |
|
|
| const { tree, pushRef, canonicalUrl } = appRouterState |
| const historyState = { |
| ...(pushRef.preserveCustomHistoryState ? window.history.state : {}), |
| |
| |
| |
| __NA: true, |
| __PRIVATE_NEXTJS_INTERNALS_TREE: tree, |
| } |
| if ( |
| pushRef.pendingPush && |
| |
| |
| createHrefFromUrl(new URL(window.location.href)) !== canonicalUrl |
| ) { |
| |
| pushRef.pendingPush = false |
| window.history.pushState(historyState, '', canonicalUrl) |
| } else { |
| window.history.replaceState(historyState, '', canonicalUrl) |
| } |
| }, [appRouterState]) |
|
|
| useEffect(() => { |
| |
| |
| |
| |
| if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) { |
| pingVisibleLinks(appRouterState.nextUrl, appRouterState.tree) |
| } |
| }, [appRouterState.nextUrl, appRouterState.tree]) |
|
|
| return null |
| } |
|
|
| export function createEmptyCacheNode(): CacheNode { |
| return { |
| lazyData: null, |
| rsc: null, |
| prefetchRsc: null, |
| head: null, |
| prefetchHead: null, |
| parallelRoutes: new Map(), |
| loading: null, |
| navigatedAt: -1, |
| } |
| } |
|
|
| function copyNextJsInternalHistoryState(data: any) { |
| if (data == null) data = {} |
| const currentState = window.history.state |
| const __NA = currentState?.__NA |
| if (__NA) { |
| data.__NA = __NA |
| } |
| const __PRIVATE_NEXTJS_INTERNALS_TREE = |
| currentState?.__PRIVATE_NEXTJS_INTERNALS_TREE |
| if (__PRIVATE_NEXTJS_INTERNALS_TREE) { |
| data.__PRIVATE_NEXTJS_INTERNALS_TREE = __PRIVATE_NEXTJS_INTERNALS_TREE |
| } |
|
|
| return data |
| } |
|
|
| function Head({ |
| headCacheNode, |
| }: { |
| headCacheNode: CacheNode | null |
| }): React.ReactNode { |
| |
| |
| |
| const head = headCacheNode !== null ? headCacheNode.head : null |
| const prefetchHead = |
| headCacheNode !== null ? headCacheNode.prefetchHead : null |
|
|
| |
| const resolvedPrefetchRsc = prefetchHead !== null ? prefetchHead : head |
|
|
| |
| |
| |
| return useDeferredValue(head, resolvedPrefetchRsc) |
| } |
|
|
| |
| |
| |
| function Router({ |
| actionQueue, |
| assetPrefix, |
| globalError, |
| gracefullyDegrade, |
| }: { |
| actionQueue: AppRouterActionQueue |
| assetPrefix: string |
| globalError: GlobalErrorState |
| gracefullyDegrade: boolean |
| }) { |
| const state = useActionQueue(actionQueue) |
| const { canonicalUrl } = state |
| |
| const { searchParams, pathname } = useMemo(() => { |
| const url = new URL( |
| canonicalUrl, |
| typeof window === 'undefined' ? 'http://n' : window.location.href |
| ) |
|
|
| return { |
| |
| searchParams: url.searchParams, |
| pathname: hasBasePath(url.pathname) |
| ? removeBasePath(url.pathname) |
| : url.pathname, |
| } |
| }, [canonicalUrl]) |
|
|
| if (process.env.NODE_ENV !== 'production') { |
| |
| const { cache, prefetchCache, tree } = state |
|
|
| |
| |
| useEffect(() => { |
| |
| |
| |
| window.nd = { |
| router: publicAppRouterInstance, |
| cache, |
| prefetchCache, |
| tree, |
| } |
| }, [cache, prefetchCache, tree]) |
| } |
|
|
| useEffect(() => { |
| |
| |
| |
| |
| function handlePageShow(event: PageTransitionEvent) { |
| if ( |
| !event.persisted || |
| !window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE |
| ) { |
| return |
| } |
|
|
| |
| |
| |
| globalMutable.pendingMpaPath = undefined |
|
|
| dispatchAppRouterAction({ |
| type: ACTION_RESTORE, |
| url: new URL(window.location.href), |
| tree: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE, |
| }) |
| } |
|
|
| window.addEventListener('pageshow', handlePageShow) |
|
|
| return () => { |
| window.removeEventListener('pageshow', handlePageShow) |
| } |
| }, []) |
|
|
| useEffect(() => { |
| |
| |
| function handleUnhandledRedirect( |
| event: ErrorEvent | PromiseRejectionEvent |
| ) { |
| const error = 'reason' in event ? event.reason : event.error |
| if (isRedirectError(error)) { |
| event.preventDefault() |
| const url = getURLFromRedirectError(error) |
| const redirectType = getRedirectTypeFromError(error) |
| |
| |
| if (redirectType === RedirectType.push) { |
| publicAppRouterInstance.push(url, {}) |
| } else { |
| publicAppRouterInstance.replace(url, {}) |
| } |
| } |
| } |
| window.addEventListener('error', handleUnhandledRedirect) |
| window.addEventListener('unhandledrejection', handleUnhandledRedirect) |
|
|
| return () => { |
| window.removeEventListener('error', handleUnhandledRedirect) |
| window.removeEventListener('unhandledrejection', handleUnhandledRedirect) |
| } |
| }, []) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| const { pushRef } = state |
| if (pushRef.mpaNavigation) { |
| |
| if (globalMutable.pendingMpaPath !== canonicalUrl) { |
| const location = window.location |
| if (pushRef.pendingPush) { |
| location.assign(canonicalUrl) |
| } else { |
| location.replace(canonicalUrl) |
| } |
|
|
| globalMutable.pendingMpaPath = canonicalUrl |
| } |
| |
| |
| |
| |
| |
| |
| throw unresolvedThenable |
| } |
|
|
| useEffect(() => { |
| const originalPushState = window.history.pushState.bind(window.history) |
| const originalReplaceState = window.history.replaceState.bind( |
| window.history |
| ) |
|
|
| |
| const applyUrlFromHistoryPushReplace = ( |
| url: string | URL | null | undefined |
| ) => { |
| const href = window.location.href |
| const tree: FlightRouterState | undefined = |
| window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE |
|
|
| startTransition(() => { |
| dispatchAppRouterAction({ |
| type: ACTION_RESTORE, |
| url: new URL(url ?? href, href), |
| tree, |
| }) |
| }) |
| } |
|
|
| |
| |
| |
| |
| |
| window.history.pushState = function pushState( |
| data: any, |
| _unused: string, |
| url?: string | URL | null |
| ): void { |
| |
| if (data?.__NA || data?._N) { |
| return originalPushState(data, _unused, url) |
| } |
|
|
| data = copyNextJsInternalHistoryState(data) |
|
|
| if (url) { |
| applyUrlFromHistoryPushReplace(url) |
| } |
|
|
| return originalPushState(data, _unused, url) |
| } |
|
|
| |
| |
| |
| |
| |
| window.history.replaceState = function replaceState( |
| data: any, |
| _unused: string, |
| url?: string | URL | null |
| ): void { |
| |
| if (data?.__NA || data?._N) { |
| return originalReplaceState(data, _unused, url) |
| } |
| data = copyNextJsInternalHistoryState(data) |
|
|
| if (url) { |
| applyUrlFromHistoryPushReplace(url) |
| } |
| return originalReplaceState(data, _unused, url) |
| } |
|
|
| |
| |
| |
| |
| |
| const onPopState = (event: PopStateEvent) => { |
| if (!event.state) { |
| |
| return |
| } |
|
|
| |
| if (!event.state.__NA) { |
| window.location.reload() |
| return |
| } |
|
|
| |
| |
| startTransition(() => { |
| dispatchTraverseAction( |
| window.location.href, |
| event.state.__PRIVATE_NEXTJS_INTERNALS_TREE |
| ) |
| }) |
| } |
|
|
| |
| window.addEventListener('popstate', onPopState) |
| return () => { |
| window.history.pushState = originalPushState |
| window.history.replaceState = originalReplaceState |
| window.removeEventListener('popstate', onPopState) |
| } |
| }, []) |
|
|
| const { cache, tree, nextUrl, focusAndScrollRef } = state |
|
|
| const matchingHead = useMemo(() => { |
| return findHeadInCache(cache, tree[1]) |
| }, [cache, tree]) |
|
|
| |
| const pathParams = useMemo(() => { |
| return getSelectedParams(tree) |
| }, [tree]) |
|
|
| const layoutRouterContext = useMemo(() => { |
| return { |
| parentTree: tree, |
| parentCacheNode: cache, |
| parentSegmentPath: null, |
| |
| |
| url: canonicalUrl, |
| } |
| }, [tree, cache, canonicalUrl]) |
|
|
| const globalLayoutRouterContext = useMemo(() => { |
| return { |
| tree, |
| focusAndScrollRef, |
| nextUrl, |
| } |
| }, [tree, focusAndScrollRef, nextUrl]) |
|
|
| let head |
| if (matchingHead !== null) { |
| |
| |
| |
| |
| |
| |
| const [headCacheNode, headKey] = matchingHead |
| head = <Head key={headKey} headCacheNode={headCacheNode} /> |
| } else { |
| head = null |
| } |
|
|
| let content = ( |
| <RedirectBoundary> |
| {head} |
| {cache.rsc} |
| <AppRouterAnnouncer tree={tree} /> |
| </RedirectBoundary> |
| ) |
|
|
| if (process.env.NODE_ENV !== 'production') { |
| |
| |
| |
| |
| |
| |
| if (typeof window !== 'undefined') { |
| const { DevRootHTTPAccessFallbackBoundary } = |
| require('./dev-root-http-access-fallback-boundary') as typeof import('./dev-root-http-access-fallback-boundary') |
| content = ( |
| <DevRootHTTPAccessFallbackBoundary> |
| {content} |
| </DevRootHTTPAccessFallbackBoundary> |
| ) |
| } |
| const HotReloader: typeof import('../dev/hot-reloader/app/hot-reloader-app').default = |
| ( |
| require('../dev/hot-reloader/app/hot-reloader-app') as typeof import('../dev/hot-reloader/app/hot-reloader-app') |
| ).default |
|
|
| content = ( |
| <HotReloader assetPrefix={assetPrefix} globalError={globalError}> |
| {content} |
| </HotReloader> |
| ) |
| } else { |
| |
| |
| if (gracefullyDegrade) { |
| content = <GracefulDegradeBoundary>{content}</GracefulDegradeBoundary> |
| } else { |
| content = ( |
| <ErrorBoundary |
| errorComponent={globalError[0]} |
| errorStyles={globalError[1]} |
| > |
| {content} |
| </ErrorBoundary> |
| ) |
| } |
| } |
|
|
| return ( |
| <> |
| <HistoryUpdater appRouterState={state} /> |
| <RuntimeStyles /> |
| <PathParamsContext.Provider value={pathParams}> |
| <PathnameContext.Provider value={pathname}> |
| <SearchParamsContext.Provider value={searchParams}> |
| <GlobalLayoutRouterContext.Provider |
| value={globalLayoutRouterContext} |
| > |
| {/* TODO: We should be able to remove this context. useRouter |
| should import from app-router-instance instead. It's only |
| necessary because useRouter is shared between Pages and |
| App Router. We should fork that module, then remove this |
| context provider. */} |
| <AppRouterContext.Provider value={publicAppRouterInstance}> |
| <LayoutRouterContext.Provider value={layoutRouterContext}> |
| {content} |
| </LayoutRouterContext.Provider> |
| </AppRouterContext.Provider> |
| </GlobalLayoutRouterContext.Provider> |
| </SearchParamsContext.Provider> |
| </PathnameContext.Provider> |
| </PathParamsContext.Provider> |
| </> |
| ) |
| } |
|
|
| export default function AppRouter({ |
| actionQueue, |
| globalErrorState, |
| assetPrefix, |
| gracefullyDegrade, |
| }: { |
| actionQueue: AppRouterActionQueue |
| globalErrorState: GlobalErrorState |
| assetPrefix: string |
| gracefullyDegrade: boolean |
| }) { |
| useNavFailureHandler() |
|
|
| const router = ( |
| <Router |
| actionQueue={actionQueue} |
| assetPrefix={assetPrefix} |
| globalError={globalErrorState} |
| gracefullyDegrade={gracefullyDegrade} |
| /> |
| ) |
|
|
| if (gracefullyDegrade) { |
| return router |
| } else { |
| return ( |
| <ErrorBoundary |
| // At the very top level, use the default GlobalError component as the final fallback. |
| // When the app router itself fails, which means the framework itself fails, we show the default error. |
| errorComponent={DefaultGlobalError} |
| > |
| {router} |
| </ErrorBoundary> |
| ) |
| } |
| } |
|
|
| const runtimeStyles = new Set<string>() |
| let runtimeStyleChanged = new Set<() => void>() |
|
|
| globalThis._N_E_STYLE_LOAD = function (href: string) { |
| let len = runtimeStyles.size |
| runtimeStyles.add(href) |
| if (runtimeStyles.size !== len) { |
| runtimeStyleChanged.forEach((cb) => cb()) |
| } |
| |
| |
| return Promise.resolve() |
| } |
|
|
| function RuntimeStyles() { |
| const [, forceUpdate] = React.useState(0) |
| const renderedStylesSize = runtimeStyles.size |
| useEffect(() => { |
| const changed = () => forceUpdate((c) => c + 1) |
| runtimeStyleChanged.add(changed) |
| if (renderedStylesSize !== runtimeStyles.size) { |
| changed() |
| } |
| return () => { |
| runtimeStyleChanged.delete(changed) |
| } |
| }, [renderedStylesSize, forceUpdate]) |
|
|
| const dplId = process.env.NEXT_DEPLOYMENT_ID |
| ? `?dpl=${process.env.NEXT_DEPLOYMENT_ID}` |
| : '' |
| return [...runtimeStyles].map((href, i) => ( |
| <link |
| key={i} |
| rel="stylesheet" |
| href={`${href}${dplId}`} |
| // @ts-ignore |
| precedence="next" |
| // TODO figure out crossOrigin and nonce |
| // crossOrigin={TODO} |
| // nonce={TODO} |
| /> |
| )) |
| } |
|
|