Unverified Commit 1cf1198c authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

interception routes: re-implementation (#48027)

The first implementation had limitation wrt to static routes so this is
a "simpler" approach to making interception work. This also fixes a few
bugs.

In this PR:
- changed the computation of the referrer route to now live on the
client state, since it's the only place where you can accurately keep
track of that. One router state was not sufficient, we needed a delta of
two states to guess which route had changed when having parallel routes
in the tree.
- uses rewrites as the basis for interception now instead of route
handlers, this means that we have to do some sketchy logic to make the
rules work since they only handle regexes whereas we have
`path/like/[this]`
- dev server now reloads rewrites as well when needed

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation or adding/fixing Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent dec037a4
......@@ -137,6 +137,7 @@ import { isAppRouteRoute } from '../lib/is-app-route-route'
import { createClientRouterFilter } from '../lib/create-client-router-filter'
import { createValidFileMatcher } from '../server/lib/find-page-file'
import { startTypeChecking } from './type-check'
import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites'
export type SsgRoute = {
initialRevalidateSeconds: number | false
......@@ -519,6 +520,12 @@ export default async function build(
appPageKeys.push(normalizedAppPageKey)
}
}
// Interception routes are modelled as beforeFiles rewrites
rewrites.beforeFiles.unshift(
...generateInterceptionRoutesRewrites(appPageKeys)
)
const totalAppPagesCount = appPageKeys.length
const pageKeys = {
......
......@@ -240,6 +240,7 @@ export function hydrate() {
apply: false,
hashFragment: null,
},
nextUrl: null,
}}
>
<HotReload
......
......@@ -3,6 +3,7 @@ export const ACTION = 'Next-Action' as const
export const NEXT_ROUTER_STATE_TREE = 'Next-Router-State-Tree' as const
export const NEXT_ROUTER_PREFETCH = 'Next-Router-Prefetch' as const
export const NEXT_URL = 'Next-Url' as const
export const FETCH_CACHE_HEADER = 'x-vercel-sc-headers' as const
export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const
export const RSC_VARY_HEADER =
......
......@@ -110,7 +110,15 @@ function Router({
[children, initialCanonicalUrl, initialTree, initialHead]
)
const [
{ tree, cache, prefetchCache, pushRef, focusAndScrollRef, canonicalUrl },
{
tree,
cache,
prefetchCache,
pushRef,
focusAndScrollRef,
canonicalUrl,
nextUrl,
},
dispatch,
sync,
] = useReducerWithReduxDevtools(reducer, initialState)
......@@ -370,6 +378,7 @@ function Router({
changeByServerResponse,
tree,
focusAndScrollRef,
nextUrl,
}}
>
<AppRouterContext.Provider value={appRouter}>
......
......@@ -298,7 +298,11 @@ function InnerLayoutRouter({
*/
childNodes.set(cacheKey, {
status: CacheStates.DATA_FETCH,
data: fetchServerResponse(new URL(url, location.origin), refetchTree),
data: fetchServerResponse(
new URL(url, location.origin),
refetchTree,
context.nextUrl
),
subTreeData: null,
head:
childNode && childNode.status === CacheStates.LAZY_INITIALIZED
......
import { IncomingHttpHeaders } from 'http'
import { NEXT_ROUTER_STATE_TREE } from '../../client/components/app-router-headers'
import { parseAndValidateFlightRouterState } from '../app-render/parse-and-validate-flight-router-state'
import { FlightRouterState } from '../app-render/types'
import { INTERCEPTION_ROUTE_MARKERS } from '../future/helpers/interception-routes'
import { FlightRouterState, Segment } from '../../../server/app-render/types'
import { INTERCEPTION_ROUTE_MARKERS } from '../../../server/future/helpers/interception-routes'
import { matchSegment } from '../match-segments'
const segmentToPathname = (segment: Segment): string => {
if (typeof segment === 'string') {
return segment
}
return segment[1]
}
export function extractPathFromFlightRouterState(
flightRouterState: FlightRouterState
......@@ -47,13 +53,44 @@ export function extractPathFromFlightRouterState(
return finalPath.endsWith('/') ? finalPath.slice(0, -1) : finalPath
}
export function parseNextReferrerFromHeaders(
headers: IncomingHttpHeaders
): string | undefined {
const flightRouterState = parseAndValidateFlightRouterState(
headers[NEXT_ROUTER_STATE_TREE.toLowerCase()]
)
export function computeChangedPath(
treeA: FlightRouterState,
treeB: FlightRouterState
): string | null {
const [segmentA, parallelRoutesA] = treeA
const [segmentB, parallelRoutesB] = treeB
const normalizedSegmentA = segmentToPathname(segmentA)
const normalizedSegmentB = segmentToPathname(segmentB)
if (
INTERCEPTION_ROUTE_MARKERS.some(
(m) =>
normalizedSegmentA.startsWith(m) || normalizedSegmentB.startsWith(m)
)
) {
return ''
}
if (!matchSegment(segmentA, segmentB)) {
// once we find where the tree changed, we compute the rest of the path by traversing the tree
return extractPathFromFlightRouterState(treeB) ?? ''
}
for (const parallelRouterKey in parallelRoutesA) {
if (parallelRoutesB[parallelRouterKey]) {
const changedPath = computeChangedPath(
parallelRoutesA[parallelRouterKey],
parallelRoutesB[parallelRouterKey]
)
if (changedPath !== null) {
if (changedPath === '') {
return segmentToPathname(segmentB)
}
return `${segmentToPathname(segmentB)}/${changedPath}`
}
}
}
if (!flightRouterState) return undefined
return extractPathFromFlightRouterState(flightRouterState)
return null
}
......@@ -95,6 +95,7 @@ describe('createInitialRouterState', () => {
pushRef: { pendingPush: false, mpaNavigation: false },
focusAndScrollRef: { apply: false, hashFragment: null },
cache: expectedCache,
nextUrl: '/linking',
}
expect(state).toMatchObject(expected)
......
......@@ -51,5 +51,6 @@ export function createInitialRouterState({
? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.
createHrefFromUrl(location)
: initialCanonicalUrl,
nextUrl: location?.pathname ?? null,
}
}
......@@ -8,6 +8,7 @@ import type {
import {
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_STATE_TREE,
NEXT_URL,
RSC,
RSC_CONTENT_TYPE_HEADER,
} from '../app-router-headers'
......@@ -21,11 +22,13 @@ import { callServer } from '../../app-call-server'
export async function fetchServerResponse(
url: URL,
flightRouterState: FlightRouterState,
nextUrl: string | null,
prefetch?: true
): Promise<[FlightData: FlightData, canonicalUrlOverride: URL | undefined]> {
const headers: {
[RSC]: '1'
[NEXT_ROUTER_STATE_TREE]: string
[NEXT_URL]?: string
[NEXT_ROUTER_PREFETCH]?: '1'
} = {
// Enable flight response
......@@ -38,6 +41,10 @@ export async function fetchServerResponse(
headers[NEXT_ROUTER_PREFETCH] = '1'
}
if (nextUrl) {
headers[NEXT_URL] = nextUrl
}
try {
let fetchUrl = url
if (process.env.NODE_ENV === 'production') {
......
import { computeChangedPath } from './compute-changed-path'
import {
Mutable,
ReadonlyReducerState,
......@@ -50,5 +51,10 @@ export function handleMutable(
typeof mutable.patchedTree !== 'undefined'
? mutable.patchedTree
: state.tree,
nextUrl:
typeof mutable.patchedTree !== 'undefined'
? computeChangedPath(state.tree, mutable.patchedTree) ??
state.canonicalUrl
: state.nextUrl,
}
}
......@@ -32,12 +32,11 @@ function fastRefreshReducerImpl(
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.data = createRecordFromThenable(
fetchServerResponse(new URL(href, origin), [
state.tree[0],
state.tree[1],
state.tree[2],
'refetch',
])
fetchServerResponse(
new URL(href, origin),
[state.tree[0], state.tree[1], state.tree[2], 'refetch'],
state.nextUrl
)
)
}
const [flightData, canonicalUrlOverride] = readRecordValue(cache.data!)
......
......@@ -195,6 +195,7 @@ describe('navigateReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking/about',
nextUrl: '/linking/about',
cache: {
status: CacheStates.READY,
data: null,
......@@ -378,6 +379,7 @@ describe('navigateReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking/about',
nextUrl: '/linking/about',
cache: {
status: CacheStates.READY,
data: null,
......@@ -564,6 +566,7 @@ describe('navigateReducer', () => {
hashFragment: null,
},
canonicalUrl: 'https://example.vercel.sh/',
nextUrl: '/linking',
cache: {
status: CacheStates.READY,
data: null,
......@@ -721,6 +724,7 @@ describe('navigateReducer', () => {
hashFragment: null,
},
canonicalUrl: 'https://example.vercel.sh/',
nextUrl: '/linking',
cache: {
status: CacheStates.READY,
data: null,
......@@ -875,6 +879,7 @@ describe('navigateReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking/about',
nextUrl: '/linking/about',
cache: {
status: CacheStates.READY,
data: null,
......@@ -1098,6 +1103,7 @@ describe('navigateReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking/about',
nextUrl: '/linking/about',
cache: {
status: CacheStates.READY,
data: null,
......@@ -1325,6 +1331,7 @@ describe('navigateReducer', () => {
hashFragment: null,
},
canonicalUrl: '/parallel-tab-bar/demographics',
nextUrl: '/parallel-tab-bar/demographics',
cache: {
status: CacheStates.READY,
data: null,
......
......@@ -169,7 +169,7 @@ export function navigateReducer(
state.cache,
// TODO-APP: segments.slice(1) strips '', we can get rid of '' altogether.
segments.slice(1),
() => fetchServerResponse(url, optimisticTree)
() => fetchServerResponse(url, optimisticTree, state.nextUrl)
)
// If optimistic fetch couldn't happen it falls back to the non-optimistic case.
......@@ -190,7 +190,9 @@ export function navigateReducer(
// If no in-flight fetch at the top, start it.
if (!cache.data) {
cache.data = createRecordFromThenable(fetchServerResponse(url, state.tree))
cache.data = createRecordFromThenable(
fetchServerResponse(url, state.tree, state.nextUrl)
)
}
// Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves.
......
......@@ -124,7 +124,12 @@ describe('prefetchReducer', () => {
})
const url = new URL('/linking/about', 'https://localhost')
const serverResponse = await fetchServerResponse(url, initialTree, true)
const serverResponse = await fetchServerResponse(
url,
initialTree,
null,
true
)
const action: PrefetchAction = {
type: ACTION_PREFETCH,
url,
......@@ -195,6 +200,7 @@ describe('prefetchReducer', () => {
undefined,
true,
],
nextUrl: '/linking',
}
expect(newState).toMatchObject(expectedState)
......@@ -262,7 +268,12 @@ describe('prefetchReducer', () => {
})
const url = new URL('/linking/about', 'https://localhost')
const serverResponse = await fetchServerResponse(url, initialTree, true)
const serverResponse = await fetchServerResponse(
url,
initialTree,
null,
true
)
const action: PrefetchAction = {
type: ACTION_PREFETCH,
url,
......@@ -335,6 +346,7 @@ describe('prefetchReducer', () => {
undefined,
true,
],
nextUrl: '/linking',
}
expect(newState).toMatchObject(expectedState)
......
......@@ -29,6 +29,7 @@ export function prefetchReducer(
url,
// initialTree is used when history.state.tree is missing because the history state is set in `useEffect` below, it being missing means this is the hydration case.
state.tree,
state.nextUrl,
true
)
)
......
......@@ -154,6 +154,7 @@ describe('refreshReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking',
nextUrl: '/linking',
cache: {
status: CacheStates.READY,
data: null,
......@@ -311,6 +312,7 @@ describe('refreshReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking',
nextUrl: '/linking',
cache: {
status: CacheStates.READY,
data: null,
......@@ -492,6 +494,7 @@ describe('refreshReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking',
nextUrl: '/linking',
cache: {
status: CacheStates.READY,
data: null,
......@@ -722,6 +725,7 @@ describe('refreshReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking',
nextUrl: '/linking',
cache: {
status: CacheStates.READY,
data: null,
......
......@@ -32,12 +32,11 @@ export function refreshReducer(
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.data = createRecordFromThenable(
fetchServerResponse(new URL(href, origin), [
state.tree[0],
state.tree[1],
state.tree[2],
'refetch',
])
fetchServerResponse(
new URL(href, origin),
[state.tree[0], state.tree[1], state.tree[2], 'refetch'],
state.nextUrl
)
)
}
const [flightData, canonicalUrlOverride] = readRecordValue(cache.data!)
......
......@@ -126,6 +126,7 @@ describe('serverPatchReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking/about',
nextUrl: '/linking/about',
cache: {
status: CacheStates.READY,
data: null,
......@@ -287,6 +288,7 @@ describe('serverPatchReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking/about',
nextUrl: '/linking/about',
cache: {
status: CacheStates.READY,
data: null,
......
......@@ -21,5 +21,6 @@ export function restoreReducer(
prefetchCache: state.prefetchCache,
// Restore provided tree
tree: tree,
nextUrl: url.pathname,
}
}
......@@ -189,6 +189,7 @@ describe('serverPatchReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking/about',
nextUrl: '/linking/somewhere-else',
cache: {
status: CacheStates.READY,
data: null,
......@@ -383,6 +384,7 @@ describe('serverPatchReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking/about',
nextUrl: '/linking/about',
cache: {
status: CacheStates.READY,
data: null,
......@@ -556,6 +558,7 @@ describe('serverPatchReducer', () => {
hashFragment: null,
},
canonicalUrl: '/linking/about',
nextUrl: '/linking/somewhere-else',
cache: {
status: CacheStates.READY,
data: null,
......
......@@ -188,6 +188,10 @@ export type AppRouterState = {
* - This is the url you see in the browser.
*/
canonicalUrl: string
/**
* The underlying "url" representing the UI state, which is used for intercepting routes.
*/
nextUrl: string | null
}
export type ReadonlyReducerState = Readonly<AppRouterState>
......
import { pathToRegexp } from 'next/dist/compiled/path-to-regexp'
import { NEXT_URL } from '../client/components/app-router-headers'
import {
extractInterceptionRouteInformation,
isInterceptionRouteAppPath,
} from '../server/future/helpers/interception-routes'
import { Rewrite } from './load-custom-routes'
// a function that converts normalised paths (e.g. /foo/[bar]/[baz]) to the format expected by pathToRegexp (e.g. /foo/:bar/:baz)
function toPathToRegexpPath(path: string): string {
return path.replace(/\[([^\]]+)\]/g, ':$1')
}
export function generateInterceptionRoutesRewrites(
appPaths: string[]
): Rewrite[] {
const rewrites: Rewrite[] = []
for (const appPath of appPaths) {
if (isInterceptionRouteAppPath(appPath)) {
const { interceptingRoute, interceptedRoute } =
extractInterceptionRouteInformation(appPath)
const normalizedInterceptingRoute = `${toPathToRegexpPath(
interceptingRoute
)}/(.*)?`
const normalizedInterceptedRoute = toPathToRegexpPath(interceptedRoute)
const normalizedAppPath = toPathToRegexpPath(appPath)
// pathToRegexp returns a regex that matches the path, but we need to
// convert it to a string that can be used in a header value
// to the format that Next/the proxy expects
let interceptingRouteRegex = pathToRegexp(normalizedInterceptingRoute)
.toString()
.slice(2, -3)
rewrites.push({
source: normalizedInterceptedRoute,
destination: normalizedAppPath,
has: [
{
type: 'header',
key: NEXT_URL,
value: interceptingRouteRegex,
},
],
})
}
}
return rewrites
}
......@@ -307,6 +307,11 @@ export async function renderToHTMLOrFlight(
let value = pathParams[key]
// this is a special marker that will be present for interception routes
if (value === '__NEXT_EMPTY_PARAM__') {
value = undefined
}
if (Array.isArray(value)) {
value = value.map((i) => encodeURIComponent(i))
} else if (typeof value === 'string') {
......
......@@ -99,7 +99,6 @@ import { I18NProvider } from './future/helpers/i18n-provider'
import { sendResponse } from './send-response'
import { RouteKind } from './future/route-kind'
import { handleInternalServerErrorResponse } from './future/route-modules/helpers/response-handlers'
import { parseNextReferrerFromHeaders } from './lib/parse-next-referrer'
import { fromNodeHeaders, toNodeHeaders } from './web/utils'
import { NEXT_QUERY_PARAM_PREFIX } from '../lib/constants'
......@@ -745,7 +744,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
let srcPathname = matchedPath
const match = await this.matchers.match(matchedPath, {
i18n: localeAnalysisResult,
referrer: parseNextReferrerFromHeaders(req.headers),
})
// Update the source pathname to the matched page's pathname.
......@@ -2094,14 +2092,13 @@ export default abstract class Server<ServerOptions extends Options = Options> {
private async renderToResponseImpl(
ctx: RequestContext
): Promise<ResponsePayload | null> {
const { res, query, pathname, req } = ctx
const { res, query, pathname } = ctx
let page = pathname
const bubbleNoFallback = !!query._nextBubbleNoFallback
delete query._nextBubbleNoFallback
const options: MatchOptions = {
i18n: this.i18nProvider?.fromQuery(pathname, query),
referrer: parseNextReferrerFromHeaders(req.headers),
}
try {
......
......@@ -103,6 +103,7 @@ import LRUCache from 'next/dist/compiled/lru-cache'
import { NextUrlWithParsedQuery } from '../request-meta'
import { deserializeErr, errorToJSON } from '../render'
import { invokeRequest } from '../lib/server-ipc'
import { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'
// Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: FunctionComponent
......@@ -789,6 +790,23 @@ export default class DevServer extends Server {
}
: undefined
this.customRoutes = await loadCustomRoutes(this.nextConfig)
this.customRoutes.rewrites.beforeFiles.unshift(
...generateInterceptionRoutesRewrites(Object.keys(appPaths))
)
const { rewrites } = this.customRoutes
if (
rewrites.beforeFiles.length ||
rewrites.afterFiles.length ||
rewrites.fallback.length
) {
this.router.setRewrites(
this.generateRewrites({
restrictedRedirectPaths: [],
})
)
}
try {
// we serve a separate manifest with all pages for the client in
// dev mode so that we can match a page after a rewrite on the client
......
import {
extractInterceptionRouteInformation,
isIntersectionRouteAppPath,
isInterceptionRouteAppPath,
} from './interception-routes'
describe('Interception Route helper', () => {
describe('isIntersectionRouteAppPath', () => {
describe('isInterceptionRouteAppPath', () => {
it('should validate correct paths', () => {
expect(isIntersectionRouteAppPath('/foo/(..)/bar')).toBe(true)
expect(isIntersectionRouteAppPath('/foo/(...)/bar')).toBe(true)
expect(isIntersectionRouteAppPath('/foo/(..)(..)/bar')).toBe(true)
expect(isInterceptionRouteAppPath('/foo/(..)/bar')).toBe(true)
expect(isInterceptionRouteAppPath('/foo/(...)/bar')).toBe(true)
expect(isInterceptionRouteAppPath('/foo/(..)(..)/bar')).toBe(true)
})
it('should not validate incorrect paths', () => {
expect(isIntersectionRouteAppPath('/foo/(..')).toBe(false)
expect(isIntersectionRouteAppPath('/foo/..)/bar')).toBe(false)
expect(isIntersectionRouteAppPath('/foo')).toBe(false)
expect(isInterceptionRouteAppPath('/foo/(..')).toBe(false)
expect(isInterceptionRouteAppPath('/foo/..)/bar')).toBe(false)
expect(isInterceptionRouteAppPath('/foo')).toBe(false)
})
})
describe('extractInterceptionRouteInformation', () => {
......
......@@ -3,7 +3,7 @@ import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths'
// order matters here, the first match will be used
export const INTERCEPTION_ROUTE_MARKERS = ['(..)(..)', '(..)', '(...)'] as const
export function isIntersectionRouteAppPath(path: string): boolean {
export function isInterceptionRouteAppPath(path: string): boolean {
// TODO-APP: add more serious validation
return (
path
......
......@@ -10,7 +10,6 @@ import { MatchOptions, RouteMatcherManager } from './route-matcher-manager'
import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { LocaleRouteMatcher } from '../route-matchers/locale-route-matcher'
import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash'
import { AppPageInterceptingRouteMatcher } from '../route-matchers/app-intercepting-route-matcher'
interface RouteMatchers {
static: ReadonlyArray<RouteMatcher>
......@@ -164,19 +163,7 @@ export class DefaultRouteMatcherManager implements RouteMatcherManager {
throw new Error('Invariant: expected to find identity in indexes map')
}
// Sort the dynamic matches by the type of matcher. This ensures that
// intercepting matchers are always first for each pathname.
const dynamicMatches = indexes
.map((index) => dynamic[index])
.sort((a, b) => {
if (a instanceof AppPageInterceptingRouteMatcher) {
return -1
}
if (b instanceof AppPageInterceptingRouteMatcher) {
return 1
}
return 0
})
const dynamicMatches = indexes.map((index) => dynamic[index])
sortedDynamicMatchers.push(...dynamicMatches)
}
......@@ -239,10 +226,7 @@ export class DefaultRouteMatcherManager implements RouteMatcherManager {
matcher: RouteMatcher,
options: MatchOptions
): RouteMatch | null {
if (
matcher instanceof LocaleRouteMatcher ||
matcher instanceof AppPageInterceptingRouteMatcher
) {
if (matcher instanceof LocaleRouteMatcher) {
return matcher.match(pathname, options)
}
......
......@@ -5,11 +5,6 @@ import type { LocaleAnalysisResult } from '../helpers/i18n-provider'
export type MatchOptions = {
skipDynamic?: boolean
/**
* If defined, this will be used as the referrer for the matching potential intercepting routes.
*/
referrer?: string | undefined
/**
* If defined, this indicates to the matcher that the request should be
* treated as locale-aware. If this is undefined, it means that this
......
import { isAppPageRoute } from '../../../lib/is-app-page-route'
import {
extractInterceptionRouteInformation,
isIntersectionRouteAppPath,
} from '../helpers/interception-routes'
import { APP_PATHS_MANIFEST } from '../../../shared/lib/constants'
import { AppNormalizers } from '../normalizers/built/app'
import { RouteKind } from '../route-kind'
import { AppPageInterceptingRouteMatcher } from '../route-matchers/app-intercepting-route-matcher'
import { AppPageRouteMatcher } from '../route-matchers/app-page-route-matcher'
import {
Manifest,
......@@ -48,33 +43,16 @@ export class AppPageRouteMatcherProvider extends ManifestRouteMatcherProvider<Ap
const filename = this.normalizers.filename.normalize(manifest[page])
const bundlePath = this.normalizers.bundlePath.normalize(page)
if (isIntersectionRouteAppPath(pathname)) {
const { interceptingRoute, interceptedRoute } =
extractInterceptionRouteInformation(pathname)
matchers.push(
new AppPageInterceptingRouteMatcher({
kind: RouteKind.APP_PAGE,
pathname: interceptedRoute,
page,
bundlePath,
filename,
appPaths,
interceptingRoute: interceptingRoute,
pathnameOverride: pathname,
})
)
} else {
matchers.push(
new AppPageRouteMatcher({
kind: RouteKind.APP_PAGE,
pathname,
page,
bundlePath,
filename,
appPaths,
})
)
}
matchers.push(
new AppPageRouteMatcher({
kind: RouteKind.APP_PAGE,
pathname,
page,
bundlePath,
filename,
appPaths,
})
)
}
return matchers
......
......@@ -2,11 +2,7 @@ import { FileReader } from './helpers/file-reader/file-reader'
import { AppPageRouteMatcher } from '../../route-matchers/app-page-route-matcher'
import { RouteKind } from '../../route-kind'
import { FileCacheRouteMatcherProvider } from './file-cache-route-matcher-provider'
import {
extractInterceptionRouteInformation,
isIntersectionRouteAppPath,
} from '../../helpers/interception-routes'
import { AppPageInterceptingRouteMatcher } from '../../route-matchers/app-intercepting-route-matcher'
import { DevAppNormalizers } from '../../normalizers/built/app'
export class DevAppPageRouteMatcherProvider extends FileCacheRouteMatcherProvider<AppPageRouteMatcher> {
......@@ -69,33 +65,16 @@ export class DevAppPageRouteMatcherProvider extends FileCacheRouteMatcherProvide
}
const { pathname, page, bundlePath } = cached
if (isIntersectionRouteAppPath(pathname)) {
const { interceptingRoute, interceptedRoute } =
extractInterceptionRouteInformation(pathname)
matchers.push(
new AppPageInterceptingRouteMatcher({
kind: RouteKind.APP_PAGE,
pathname: interceptedRoute,
page,
bundlePath,
filename,
appPaths: appPaths[pathname],
interceptingRoute: interceptingRoute,
pathnameOverride: pathname,
})
)
} else {
matchers.push(
new AppPageRouteMatcher({
kind: RouteKind.APP_PAGE,
pathname,
page,
bundlePath,
filename,
appPaths: appPaths[pathname],
})
)
}
matchers.push(
new AppPageRouteMatcher({
kind: RouteKind.APP_PAGE,
pathname,
page,
bundlePath,
filename,
appPaths: appPaths[pathname],
})
)
}
return matchers
}
......
import type { AppPageInterceptingRouteDefinition } from '../route-definitions/app-page-route-definition'
import type { AppPageInterceptingRouteMatch } from '../route-matches/app-page-route-match'
import { RouteMatcher } from './route-matcher'
export type AppPageInterceptingRouteMatcherMatchOptions = {
/**
* If provided, this is used for intercepting routes to resolve.
*/
referrer?: string
}
export class AppPageInterceptingRouteMatcher extends RouteMatcher<AppPageInterceptingRouteDefinition> {
private readonly interceptingRouteMatcher: RouteMatcher<AppPageInterceptingRouteDefinition>
constructor(definition: AppPageInterceptingRouteDefinition) {
super(definition)
this.interceptingRouteMatcher =
new RouteMatcher<AppPageInterceptingRouteDefinition>({
...definition,
pathname: definition.interceptingRoute,
})
}
public get identity(): string {
// TODO: probably include other details about the entrypoint
return `${this.definition.pathname}?__nextPage=${this.definition.page}`
}
/**
* Match will attempt to match the given pathname against this route while
* also taking into account the referrer information.
*
* @param pathname The pathname to match against.
* @param options The options to use when matching.
* @returns The match result, or `null` if there was no match.
*/
public match(
pathname: string,
options?: AppPageInterceptingRouteMatcherMatchOptions
): AppPageInterceptingRouteMatch | null {
// This is like the parent `match` method but instead this injects the
// additional `options` into the
const result = this.test(pathname, options)
if (!result) return null
return {
definition: this.definition,
params: result.params,
}
}
/**
* Test will attempt to match the given pathname against this route while
* also taking into account the referrer information.
*
* @param pathname The pathname to match against.
* @param options The options to use when matching.
* @returns The match result, or `null` if there was no match.
*/
public test(
pathname: string,
options?: AppPageInterceptingRouteMatcherMatchOptions
) {
// If this route does not have referrer information, then we can't match.
if (!options?.referrer) {
return null
}
// If the intercepting route match does not match, then this route does not
// match.
if (!this.interceptingRouteMatcher.test(options.referrer)) {
return null
}
// Perform the underlying test with the intercepted route definition.
return super.test(pathname)
}
}
import { extractPathFromFlightRouterState } from './parse-next-referrer'
describe('extractPathFromFlightRouterState', () => {
it('should return the correct referrer for a simple router state', () => {
expect(
extractPathFromFlightRouterState([
'',
{
children: [
'parallel-tab-bar',
{
views: ['impressions', { children: ['__PAGE__', {}] }],
children: ['__DEFAULT__', {}],
audience: ['__DEFAULT__', {}],
},
],
},
null,
null,
true,
])
).toBe('/parallel-tab-bar/impressions')
})
it('should return the correct referrer for a router state with an interception', () => {
expect(
extractPathFromFlightRouterState([
'',
{
children: [
'intercepting-parallel-modal',
{
children: [
['username', 'jim', 'd'],
{
children: ['__PAGE__', {}],
modal: [
'(..)photo',
{
children: [
['id', '0', 'd'],
{ children: ['__PAGE__', {}] },
],
},
null,
'refetch',
],
},
],
},
],
},
])
).toBe('/intercepting-parallel-modal/jim')
})
it('should return the correct referrer for a router state with a nested interception', () => {
expect(
extractPathFromFlightRouterState([
'',
{
children: [
'intercepting-parallel-modal',
{
children: [
['username', 'jim', 'd'],
{
children: ['__PAGE__', {}],
modal: [
'(..)photo',
{
children: [
['id', '0', 'd'],
{ children: ['__PAGE__', {}] },
],
},
],
},
],
},
],
},
null,
null,
true,
])
).toBe('/intercepting-parallel-modal/jim')
})
it('should return the correct referrer for a router state with a default children', () => {
expect(
extractPathFromFlightRouterState([
'',
{
children: [
'parallel-tab-bar',
{
audience: ['subscribers', { children: ['__PAGE__', {}] }],
children: ['__DEFAULT__', {}],
views: ['__DEFAULT__', {}],
},
],
},
null,
null,
true,
])
).toBe('/parallel-tab-bar/subscribers')
})
})
......@@ -100,7 +100,6 @@ import { NextNodeServerSpan } from './lib/trace/constants'
import { nodeFs } from './lib/node-fs-methods'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'
import { parseNextReferrerFromHeaders } from './lib/parse-next-referrer'
import { addPathPrefix } from '../shared/lib/router/utils/add-path-prefix'
import { pathHasPrefix } from '../shared/lib/router/utils/path-has-prefix'
import { filterReqHeaders, invokeRequest } from './lib/server-ipc'
......@@ -1363,7 +1362,6 @@ export default class NextNodeServer extends BaseServer {
const options: MatchOptions = {
i18n: this.i18nProvider?.fromQuery(pathname, query),
referrer: parseNextReferrerFromHeaders(req.headers),
}
const match = await this.matchers.match(pathname, options)
......@@ -2078,7 +2076,6 @@ export default class NextNodeServer extends BaseServer {
const options: MatchOptions = {
i18n: this.i18nProvider?.analyze(normalizedPathname),
referrer: parseNextReferrerFromHeaders(params.request.headers),
}
if (this.nextConfig.skipMiddlewareUrlNormalize) {
......
......@@ -27,7 +27,6 @@ import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-
import type { I18NProvider } from './future/helpers/i18n-provider'
import { getTracer } from './lib/trace/tracer'
import { RouterSpan } from './lib/trace/constants'
import { parseNextReferrerFromHeaders } from './lib/parse-next-referrer'
type RouteResult = {
finished: boolean
......@@ -84,7 +83,7 @@ export default class Router {
private readonly headers: ReadonlyArray<Route>
private readonly fsRoutes: Route[]
private readonly redirects: ReadonlyArray<Route>
private readonly rewrites: {
private rewrites: {
beforeFiles: ReadonlyArray<Route>
afterFiles: ReadonlyArray<Route>
fallback: ReadonlyArray<Route>
......@@ -145,6 +144,11 @@ export default class Router {
this.needsRecompilation = true
}
public setRewrites(rewrites: RouterOptions['rewrites']) {
this.rewrites = rewrites
this.needsRecompilation = true
}
public addFsRoute(fsRoute: Route) {
// We use unshift so that we're sure the routes is defined before Next's
// default routes.
......@@ -200,7 +204,6 @@ export default class Router {
// not include dynamic matches.
skipDynamic: true,
i18n: this.i18nProvider?.analyze(pathname),
referrer: parseNextReferrerFromHeaders(req.headers),
}
// If the locale was inferred from the default, we should mark
......
......@@ -113,6 +113,7 @@ export const GlobalLayoutRouterContext = React.createContext<{
overrideCanonicalUrl: URL | undefined
) => void
focusAndScrollRef: FocusAndScrollRef
nextUrl: string | null
}>(null as any)
export const TemplateContext = React.createContext<React.ReactNode>(null as any)
......
......@@ -8,6 +8,10 @@ import type { BaseNextRequest } from '../../../../server/base-http'
import { compile, pathToRegexp } from 'next/dist/compiled/path-to-regexp'
import { escapeStringRegexp } from '../../escape-regexp'
import { parseUrl } from './parse-url'
import {
INTERCEPTION_ROUTE_MARKERS,
isInterceptionRouteAppPath,
} from '../../../../server/future/helpers/interception-routes'
/**
* Ensure only a-zA-Z are used for param names for proper interpolating
......@@ -227,6 +231,27 @@ export function prepareDestination(args: {
let newUrl
// for interception routes we don't have access to the dynamic segments from the
// referrer route so we mark them as noop for the app renderer so that it
// can retrieve them from the router state later on. This also allows us to
// compile the route properly with path-to-regexp, otherwise it will throw
// The compiler also thinks that the interception route marker is an unnamed param, hence '0',
// so we need to add it to the params object.
if (isInterceptionRouteAppPath(destPath)) {
main: for (const segment of destPath.split('/')) {
for (const marker of INTERCEPTION_ROUTE_MARKERS) {
if (segment.startsWith(marker)) {
args.params['0'] = marker
break main
}
}
if (segment.startsWith(':')) {
const param = segment.slice(1)
args.params[param] = '__NEXT_EMPTY_PARAM__'
}
}
}
try {
newUrl = destPathCompiler(args.params)
......
import Link from 'next/link'
export default function Page() {
return (
<>
<h1 id="feed-page">Feed</h1>
<ul>
{Array.from({ length: 10 }).map((_, i) => (
<li key={i}>
<Link href={`/intercepting-routes/photos/${i}`}>Link {i}</Link>
</li>
))}
</ul>
</>
)
}
......@@ -225,6 +225,43 @@ createNextDescribe(
)
})
it('should render intercepted route from a nested route', async () => {
const browser = await next.browser('/intercepting-routes/feed/nested')
// Check if navigation to modal route works.
await check(
() =>
browser
.elementByCss('[href="/intercepting-routes/photos/1"]')
.click()
.waitForElementByCss('#photo-intercepted-1')
.text(),
'Photo INTERCEPTED 1'
)
// Check if intercepted route was rendered while existing page content was removed.
// Content would only be preserved when combined with parallel routes.
// await check(() => browser.elementByCss('#feed-page').text()).not.toBe('Feed')
// Check if url matches even though it was intercepted.
await check(
() => browser.url(),
next.url + '/intercepting-routes/photos/1'
)
// Trigger a refresh, this should load the normal page, not the modal.
await check(
() => browser.refresh().waitForElementByCss('#photo-page-1').text(),
'Photo PAGE 1'
)
// Check if the url matches still.
await check(
() => browser.url(),
next.url + '/intercepting-routes/photos/1'
)
})
it('should render modal when paired with parallel routes', async () => {
const browser = await next.browser(
'/intercepting-parallel-modal/vercel'
......
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