Unverified Commit 6d6228c0 authored by Josh Story's avatar Josh Story Committed by GitHub

Prune incomplete parallel route matchers (#97108)

## Summary

This adds an experimental `strictRouteMatching` flag that leaves a
matcher out when its finalized loader tree contains a synthesized
default that will always call `notFound()` for a slot actually declared
by the owning layout. Adding a `default.tsx` keeps the matcher, and
structural router-state branches that are not real slots of that layout
do not make it incomplete. The flag defaults to `false` so matcher
pruning can roll out independently from the preceding loader-tree
correction.

The main goal is to make `children` and named slots behave the same way.
If a URL cannot construct a complete route tree on its own, it should be
treated as an unmatched URL instead of sometimes showing a slot 404 and
sometimes producing a missing page or default error.

## Semantics

For example:

```text
app/split-matcher/
├── layout.tsx
├── foo/page.tsx
├── bar/page.tsx
└── @slot/[...parts]/page.tsx
```

With strict route matching disabled, Next.js emits matchers for
`/split-matcher/foo`, `/split-matcher/bar`, and the broad
`/split-matcher/[...parts]`. The broad matcher can match any URL, but
its `children` branch has neither a matching page nor a default, so it
can only construct a permanent 404 tree. With strict route matching
enabled, that broad matcher is omitted while `/foo` and `/bar` remain
because each combines a real `children` page with the named-slot
catchall. Adding `app/split-matcher/default.tsx` deliberately makes the
broad matcher complete and keeps it.

The same rule applies without a catchall:

```text
app/disagreeing-slots/
├── layout.tsx
├── @first/foo/page.tsx
└── @second/bar/page.tsx
```

`/foo` is incomplete because `@second` has no matching page or default,
and `/bar` is incomplete for the corresponding reason in `@first`, so
neither matcher is emitted. A later PR in this stack reports the
now-unreachable page files as a project misconfiguration.

A declared `children` route is treated like any named slot:

```text
app/declared-children/
├── layout.tsx
├── page.tsx
└── @panel/
    ├── default.tsx
    └── details/page.tsx
```

`/declared-children` is complete because `children` uses `page.tsx` and
`@panel` uses its default. `/declared-children/details` is incomplete
because `@panel` matches its page while the declared `children` slot has
no matching page or default at `/details`, so that matcher is pruned.

A route composed entirely from declared named slots is also complete:

```text
app/named-only/
├── layout.tsx
├── @left/[...slug]/page.tsx
└── @right/[...slug]/page.tsx
```

The preceding PR's default-on `explicitParallelRouteChildren` behavior
means this loader tree contains only `left` and `right`. Strict matching
keeps `/named-only/[...slug]` because both declared slots match; it does
not invent `children` and then prune the route for failing to satisfy
that nonexistent slot.

We got here incrementally.
[#47872](https://github.com/vercel/next.js/pull/47872) introduced the
404 fallback for unmatched parallel slots,
[#60186](https://github.com/vercel/next.js/pull/60186) added a
development warning because this was confusing in practice and linked
[#51805](https://github.com/vercel/next.js/issues/51805) and
[#49569](https://github.com/vercel/next.js/issues/49569), and
[#84702](https://github.com/vercel/next.js/pull/84702) later made a
missing default a build error for named slots while leaving `children`
on the old fallback for backwards compatibility. Strict matching takes
the next step and treats a matcher that can only construct a permanent
404 tree as unmatched.

This changes soft navigations that only worked by preserving a
previously active slot even though the URL could not be loaded directly,
which is why matcher pruning remains behind its own experimental flag.
The interception retention markers backed by `default-null`, including
named host slots from the first PR in this stack, are complete route
patches and are not pruned. This change however is well motivated
because if you did client nav to a route that only matches a named slot
and then hard refresh you will end up getting a 404. This is a sign our
current semantics are actually broken.

If you want to preserve the perma 404 behavior of the
slot-without-default you can just add a default and make it call
`notFound()` unconditionally.

## Verification

- `pnpm build-all`
- Focused `normalize-catchall-routes` unit coverage
- Production and development e2e coverage on Turbopack and Webpack
- The pruning e2e matrix with Cache Components enabled

<!-- NEXT_JS_LLM -->
parent 3243c970
......@@ -171,6 +171,7 @@ impl AppProject {
conf.page_extensions(),
conf.is_global_not_found_enabled(),
conf.explicit_parallel_route_children(),
conf.strict_route_matching(),
self.project.next_mode(),
)
}
......
This diff is collapsed.
......@@ -1433,6 +1433,9 @@ pub struct ExperimentalConfig {
global_not_found: Option<bool>,
/// Only include children in a parallel route layout when ordinary route content declares it.
explicit_parallel_route_children: Option<bool>,
/// Omit catch-all-derived route matchers whose loader trees contain an unmatched parallel
/// route.
strict_route_matching: Option<bool>,
/// Experimental Rust React compiler (Turbopack only); requires `reactCompiler`.
turbopack_rust_react_compiler: Option<bool>,
/// Defaults to false in development mode, true in production mode.
......@@ -2028,6 +2031,11 @@ impl NextConfig {
)
}
#[turbo_tasks::function]
pub fn strict_route_matching(&self) -> Vc<bool> {
Vc::cell(self.experimental.strict_route_matching.unwrap_or_default())
}
#[turbo_tasks::function]
pub fn transpile_packages(&self) -> Vc<Vec<RcStr>> {
Vc::cell(self.transpile_packages.clone().unwrap_or_default())
......
......@@ -75,6 +75,7 @@ export const NextBuildContext: Partial<{
previewProps: __ApiPreviewProps
mappedPages: MappedPages | undefined
mappedAppPages: MappedPages | undefined
mappedAppDefaults: MappedPages | undefined
mappedRootPaths: MappedPages
hasInstrumentationHook: boolean
......
......@@ -42,6 +42,7 @@ import type { ServerRuntime } from '../types'
import {
normalizeAppPath,
compareAppPaths,
selectAppPageEntry,
} from '../shared/lib/router/utils/app-paths'
import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
import type { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader'
......@@ -100,6 +101,7 @@ export interface CreateEntrypointsParams {
rootPaths?: MappedPages
appDir?: string
appPaths?: MappedPages
appDefaultPaths?: MappedPages
pageExtensions: PageExtensions
hasInstrumentationHook?: boolean
/**
......@@ -393,6 +395,7 @@ export async function createEntrypoints(
rootPaths,
appDir,
appPaths,
appDefaultPaths,
pageExtensions,
deferredEntriesFilter,
} = params
......@@ -419,7 +422,10 @@ export async function createEntrypoints(
}
// TODO: find a better place to do this
normalizeCatchAllRoutes(appPathsPerRoute)
normalizeCatchAllRoutes(appPathsPerRoute, {
strictRouteMatching: config.experimental.strictRouteMatching,
defaultAppPaths: Object.keys(appDefaultPaths ?? {}),
})
// Make sure to sort parallel routes to make the result deterministic.
appPathsPerRoute = Object.fromEntries(
......@@ -433,6 +439,14 @@ export async function createEntrypoints(
const getEntryHandler =
(mappings: MappedPages, pagesType: PAGE_TYPES): ((page: string) => void) =>
async (page) => {
if (
pagesType === PAGE_TYPES.APP &&
config.experimental.strictRouteMatching &&
!(normalizeAppPath(page) in appPathsPerRoute)
) {
return
}
// Apply deferred entries filter if specified
if (deferredEntriesFilter) {
const isDeferred = isDeferredEntry(page, deferredEntries)
......@@ -497,6 +511,19 @@ export async function createEntrypoints(
const isInstrumentation =
isInstrumentationHookFile(page) && pagesType === PAGE_TYPES.ROOT
const matchedAppPaths =
pagesType === PAGE_TYPES.APP
? (appPathsPerRoute[normalizeAppPath(page)] ?? null)
: null
const normalizedAppPage = normalizeAppPath(page)
const isFinalRouteMatcher =
config.experimental.strictRouteMatching &&
matchedAppPaths?.length &&
matchedAppPaths.some(
(appPath) => normalizeAppPath(appPath) === normalizedAppPage
) &&
selectAppPageEntry(normalizedAppPage, matchedAppPaths) === page
runDependingOnPageType({
page,
pageRuntime: staticInfo.runtime,
......@@ -514,7 +541,6 @@ export async function createEntrypoints(
},
onServer: () => {
if (pagesType === 'app' && appDir) {
const matchedAppPaths = appPathsPerRoute[normalizeAppPath(page)]
server[serverBundlePath] = getAppEntry({
page,
name: serverBundlePath,
......@@ -535,6 +561,10 @@ export async function createEntrypoints(
.explicitParallelRouteChildren
? true
: undefined,
strictRouteMatching: config.experimental.strictRouteMatching
? true
: undefined,
isFinalRouteMatcher: isFinalRouteMatcher ? true : undefined,
})
} else if (isInstrumentation) {
server[serverBundlePath.replace('src/', '')] =
......@@ -597,7 +627,6 @@ export async function createEntrypoints(
})
} else {
if (pagesType === 'app') {
const matchedAppPaths = appPathsPerRoute[normalizeAppPath(page)]
appDirLoader = getAppEntry({
name: serverBundlePath,
page,
......@@ -622,6 +651,10 @@ export async function createEntrypoints(
.explicitParallelRouteChildren
? true
: undefined,
strictRouteMatching: config.experimental.strictRouteMatching
? true
: undefined,
isFinalRouteMatcher: isFinalRouteMatcher ? true : undefined,
}).import
}
edgeServer[serverBundlePath] = getEdgeServerEntry({
......
......@@ -1473,6 +1473,7 @@ export default async function build(
NextBuildContext.mappedPages = discovery.mappedPages || {}
NextBuildContext.mappedAppPages = discovery.mappedAppPages
NextBuildContext.mappedAppDefaults = discovery.mappedAppDefaults
NextBuildContext.mappedRootPaths = await nextBuildSpan
.traceChild('create-root-mapping')
.traceAsyncFn(() =>
......@@ -2218,6 +2219,18 @@ export default async function build(
}
}
if (config.experimental.strictRouteMatching && pageKeys.app) {
const emittedAppPaths = new Set(
emittedAppPageKeys?.map((appPageKey) =>
normalizeAppPath(appPageKey)
)
)
const retainedAppPaths = pageKeys.app.filter((appPath) =>
emittedAppPaths.has(appPath)
)
pageKeys.app = retainedAppPaths.length ? retainedAppPaths : undefined
}
await writeManifest(
path.join(distDir, APP_PATH_ROUTES_MANIFEST),
appPathRoutes
......
......@@ -219,4 +219,292 @@ describe('normalizeCatchallRoutes', () => {
// ensure values are correct after normalizing
expect(appPaths).toMatchObject(initialAppPaths)
})
describe('strictRouteMatching pruning', () => {
it('does not require an implicit children slot with no routes', () => {
const appPaths = {
'/[...slug]': ['/@catchall/[...slug]/page'],
'/foo': ['/@specific/foo/page'],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual({
'/foo': ['/@specific/foo/page', '/@catchall/[...slug]/page'],
})
})
it('keeps a named-only matcher when every declared slot matches', () => {
const appPaths = {
'/[...slug]': ['/@left/[...slug]/page', '/@right/[...slug]/page'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual(expected)
})
it('does not infer children from built-in routes', () => {
const appPaths = {
'/_not-found': ['/built-in/global-not-found'],
'/_global-error': ['/built-in/app-error'],
'/[case]': ['/@slot/[case]/page'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
defaultAppPaths: [
'/_not-found/page',
'/_global-error/page',
'/@slot/default',
],
})
expect(appPaths).toEqual(expected)
})
it('does not apply page completeness to route handlers', () => {
const appPaths = {
'/': ['/page', '/@slot/page'],
'/icon.png': ['/@slot/icon/route'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual(expected)
})
it('prunes only the incomplete catch-all matcher', () => {
const appPaths = {
'/foo': ['/foo/page'],
'/bar': ['/bar/page'],
'/[...parts]': ['/@slot/[...parts]/page'],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual({
'/foo': ['/foo/page', '/@slot/[...parts]/page'],
'/bar': ['/bar/page', '/@slot/[...parts]/page'],
})
})
it('prunes a children catch-all when a named slot is missing', () => {
const appPaths = {
'/[...slug]': ['/[...slug]/page'],
'/foo': ['/@first/foo/page'],
'/bar': ['/@second/bar/page'],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual({})
})
it('prunes an optional children catch-all when a named slot is missing', () => {
const appPaths = {
'/[[...slug]]': ['/[[...slug]]/page'],
'/specific': ['/specific/page', '/@slot/specific/page'],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual({
'/specific': ['/specific/page', '/@slot/specific/page'],
})
})
it('prunes a catch-all with an incomplete nested parallel route', () => {
const appPaths = {
'/nested/[...slug]': [
'/nested/[...slug]/page',
'/nested/@outer/[...slug]/page',
],
'/nested/specific': [
'/nested/specific/page',
'/nested/@outer/specific/page',
'/nested/@outer/@inner/specific/page',
],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual({
'/nested/specific': [
'/nested/specific/page',
'/nested/@outer/specific/page',
'/nested/@outer/@inner/specific/page',
],
})
})
it('prunes an incomplete catch-all through a route group', () => {
const appPaths = {
'/grouped/[...slug]': ['/(pruning-group)/grouped/[...slug]/page'],
'/grouped/specific': [
'/(pruning-group)/grouped/specific/page',
'/(pruning-group)/grouped/@slot/specific/page',
],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual({
'/grouped/specific': [
'/(pruning-group)/grouped/specific/page',
'/(pruning-group)/grouped/@slot/specific/page',
],
})
})
it('keeps a catch-all matcher when every slot has catch-all coverage', () => {
const appPaths = {
'/[...slug]': ['/[...slug]/page', '/@slot/[...slug]/page'],
'/specific': ['/specific/page', '/@slot/specific/page'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual(expected)
})
it('keeps catch-all routes when missing siblings have defaults', () => {
const appPaths = {
'/[...slug]': ['/[...slug]/page'],
'/specific': ['/@slot/specific/page'],
}
normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
defaultAppPaths: ['/default', '/@slot/default'],
})
expect(appPaths).toEqual({
'/[...slug]': ['/[...slug]/page'],
'/specific': ['/@slot/specific/page', '/[...slug]/page'],
})
})
it('prunes a static matcher when a real children slot is unmatched', () => {
const appPaths = {
'/': ['/page'],
'/details': ['/@panel/details/page'],
}
normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
defaultAppPaths: ['/@panel/default'],
})
expect(appPaths).toEqual({
'/': ['/page'],
})
})
it('keeps a static matcher when every declared slot matches', () => {
const appPaths = {
'/foo': ['/@first/foo/page', '/@second/foo/page'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual(expected)
})
it('prunes static matchers with incompatible named slots', () => {
const appPaths = {
'/foo': ['/@first/foo/page'],
'/bar': ['/@second/bar/page'],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual({})
})
it('keeps an interception catch-all when host slots are retained', () => {
const appPaths = {
'/': ['/@content/page', '/@secondary/page'],
'/photo/[...slug]': ['/@modal/(.)photo/[...slug]/page'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
defaultAppPaths: ['/@modal/default'],
})
expect(appPaths).toEqual(expected)
})
it('keeps real children and named slots at an interception host', () => {
const appPaths = {
'/': ['/page', '/@sidebar/page'],
'/photo/[...slug]': ['/@modal/(.)photo/[...slug]/page'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
defaultAppPaths: ['/@modal/default'],
})
expect(appPaths).toEqual(expected)
})
it('keeps named slots when children contains the interception catch-all', () => {
const appPaths = {
'/': ['/page', '/@sidebar/page'],
'/photo/[...slug]': ['/(.)photo/[...slug]/page'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual(expected)
})
it('keeps slots owned by the immediate interception host through a route group', () => {
const appPaths = {
'/': ['/(host)/@modal/page', '/(host)/@modal/@sidebar/page'],
'/photo/[...slug]': ['/(host)/@modal/(.)photo/[...slug]/page'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual(expected)
})
it('keeps an optional interception catch-all when host slots are retained', () => {
const appPaths = {
'/': ['/page', '/@sidebar/page'],
'/photo/[[...slug]]': ['/@modal/(.)photo/[[...slug]]/page'],
}
const expected = structuredClone(appPaths)
normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
defaultAppPaths: ['/@modal/default'],
})
expect(appPaths).toEqual(expected)
})
it('prunes every incomplete matcher inside an interception subtree', () => {
const appPaths = {
'/photo/[...slug]': ['/@modal/(.)photo/@catchall/[...slug]/page'],
'/photo/specific': ['/@modal/(.)photo/@specific/specific/page'],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
expect(appPaths).toEqual({})
})
})
})
export { normalizeCatchAllRoutes } from '../server/lib/router-utils/normalize-catchall-routes'
import {
normalizeCatchAllRoutes as normalizeCatchAllRoutesInternal,
type NormalizeCatchAllRoutesOptions,
} from '../server/lib/router-utils/normalize-catchall-routes'
export function normalizeCatchAllRoutes(
appPaths: Record<string, string[]>,
options: NormalizeCatchAllRoutesOptions = {}
) {
return normalizeCatchAllRoutesInternal(appPaths, undefined, options)
}
......@@ -408,6 +408,7 @@ export interface RouteDiscoveryResult {
pageApiRoutes: RouteInfo[]
mappedAppPages?: MappedPages
mappedAppLayouts?: MappedPages
mappedAppDefaults?: MappedPages
mappedPages?: MappedPages
/** Raw page file paths (post-filtering), useful for telemetry */
pagesPaths: string[]
......@@ -514,6 +515,7 @@ export async function discoverRoutes(
let slots: SlotInfo[] = []
let mappedAppPages: MappedPages | undefined
let mappedAppLayouts: MappedPages | undefined
let mappedAppDefaults: MappedPages | undefined
if (appDir) {
let appPaths: string[]
......@@ -537,19 +539,16 @@ export async function discoverRoutes(
}
// Map all app file types in parallel
let mappedDefaultFiles: MappedPages
;[mappedAppPages, mappedAppLayouts, mappedDefaultFiles] = await Promise.all(
[
mapPaths(appPaths, PAGE_TYPES.APP),
mapPaths(layoutPaths, PAGE_TYPES.APP),
mapPaths(defaultPaths, PAGE_TYPES.APP),
]
)
;[mappedAppPages, mappedAppLayouts, mappedAppDefaults] = await Promise.all([
mapPaths(appPaths, PAGE_TYPES.APP),
mapPaths(layoutPaths, PAGE_TYPES.APP),
mapPaths(defaultPaths, PAGE_TYPES.APP),
])
// Extract slots from pages and default files
slots = combineSlots(
extractSlotsFromRoutes(mappedAppPages, SKIP_ROUTES),
extractSlotsFromRoutes(mappedDefaultFiles)
extractSlotsFromRoutes(mappedAppDefaults)
)
// Process routes
......@@ -571,6 +570,7 @@ export async function discoverRoutes(
pageApiRoutes,
mappedAppPages,
mappedAppLayouts,
mappedAppDefaults,
mappedPages,
pagesPaths,
appDirOnly,
......
......@@ -110,6 +110,7 @@ export async function webpackBuildImpl(
appDir: NextBuildContext.appDir!,
pages: NextBuildContext.mappedPages!,
appPaths: NextBuildContext.mappedAppPages!,
appDefaultPaths: NextBuildContext.mappedAppDefaults,
previewMode: NextBuildContext.previewProps!,
rootPaths: NextBuildContext.mappedRootPaths!,
hasInstrumentationHook: NextBuildContext.hasInstrumentationHook!,
......@@ -133,6 +134,7 @@ export async function webpackBuildImpl(
appDir: NextBuildContext.appDir!,
pages: NextBuildContext.mappedPages!,
appPaths: NextBuildContext.mappedAppPages!,
appDefaultPaths: NextBuildContext.mappedAppDefaults,
previewMode: NextBuildContext.previewProps!,
rootPaths: NextBuildContext.mappedRootPaths!,
hasInstrumentationHook: NextBuildContext.hasInstrumentationHook!,
......
......@@ -65,6 +65,8 @@ export type AppLoaderOptions = {
middlewareConfig: string
isGlobalNotFoundEnabled: true | undefined
explicitParallelRouteChildren: true | undefined
strictRouteMatching: true | undefined
isFinalRouteMatcher: true | undefined
}
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
......@@ -166,6 +168,8 @@ async function createTreeCodeFromPath(
collectedDeclarations,
isGlobalNotFoundEnabled,
explicitParallelRouteChildren,
strictRouteMatching,
isFinalRouteMatcher,
isDev,
}: {
page: string
......@@ -183,6 +187,8 @@ async function createTreeCodeFromPath(
collectedDeclarations: [string, string][]
isGlobalNotFoundEnabled: boolean
explicitParallelRouteChildren: boolean
strictRouteMatching: boolean
isFinalRouteMatcher: boolean
isDev: boolean
}
): Promise<{
......@@ -356,12 +362,14 @@ async function createTreeCodeFromPath(
): Promise<{
treeCode: string
containsInterception: boolean
containsBuiltinNotFoundDefault: boolean
}> {
const segmentPath = segments.join('/')
// Existing tree are the children of the current segment
const props: Record<string, string> = {}
const interceptingParallelKeys = new Set<string>()
let containsBuiltinNotFoundDefault = false
// Root layer could be 1st layer of normal routes
const isRootLayer = segments.length === 0
const isRootLayoutOrRootPage = segments.length <= 1
......@@ -677,12 +685,14 @@ async function createTreeCodeFromPath(
const {
treeCode: pageSubtreeCode,
containsInterception: subtreeContainsInterception,
containsBuiltinNotFoundDefault: subtreeContainsBuiltinNotFoundDefault,
} = await createSubtreePropsFromSegmentPath(
subSegmentPath,
nestedCollectedDeclarations
)
subtreeCode = pageSubtreeCode
containsBuiltinNotFoundDefault ||= subtreeContainsBuiltinNotFoundDefault
if (subtreeContainsInterception) {
interceptingParallelKeys.add(normalizedParallelKey)
}
......@@ -712,6 +722,10 @@ async function createTreeCodeFromPath(
interceptingParallelKeys.size > 0
function setSyntheticDefault(key: string, defaultPath: string) {
if (defaultPath === PARALLEL_ROUTE_DEFAULT_PATH) {
containsBuiltinNotFoundDefault = true
}
const varName = `default${nestedCollectedDeclarations.length}`
nestedCollectedDeclarations.push([varName, defaultPath])
props[key] = `[
......@@ -806,13 +820,28 @@ async function createTreeCodeFromPath(
containsInterception:
isInterceptionRouteAppPath(segmentPath) ||
interceptingParallelKeys.size > 0,
containsBuiltinNotFoundDefault,
}
}
const { treeCode } = await createSubtreePropsFromSegmentPath(
[],
collectedDeclarations
)
const { treeCode, containsBuiltinNotFoundDefault } =
await createSubtreePropsFromSegmentPath([], collectedDeclarations)
if (
strictRouteMatching &&
isFinalRouteMatcher &&
!isInterceptionRouteAppPath(page) &&
containsBuiltinNotFoundDefault &&
!isNotFoundRoute &&
!isAppErrorRoute
) {
// A retained ordinary matcher must be able to construct its complete
// route tree. An interception tree is a partial update and may
// intentionally contain synthetic slots.
throw new Error(
`Invariant: strict route matching retained the incomplete route matcher ${page}`
)
}
return {
treeCode: `${treeCode}.children;`,
......@@ -861,6 +890,8 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const isGlobalNotFoundEnabled = !!loaderOptions.isGlobalNotFoundEnabled
const explicitParallelRouteChildren =
!!loaderOptions.explicitParallelRouteChildren
const strictRouteMatching = !!loaderOptions.strictRouteMatching
const isFinalRouteMatcher = !!loaderOptions.isFinalRouteMatcher
// Update FILE_TYPES on the very top-level of the loader
if (!isGlobalNotFoundEnabled) {
......@@ -896,7 +927,6 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const normalizedAppPaths =
typeof appPaths === 'string' ? [appPaths] : appPaths || []
// All normalized app paths for computing static siblings across route groups
const allNormalizedAppPaths = allNormalizedAppPathsOption ?? []
......@@ -1195,6 +1225,8 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
collectedDeclarations,
isGlobalNotFoundEnabled,
explicitParallelRouteChildren,
strictRouteMatching,
isFinalRouteMatcher,
isDev: !!isDev,
})
......@@ -1256,6 +1288,8 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
collectedDeclarations,
isGlobalNotFoundEnabled,
explicitParallelRouteChildren,
strictRouteMatching,
isFinalRouteMatcher,
isDev: !!isDev,
})
}
......
......@@ -476,6 +476,7 @@ export const experimentalSchema = {
.optional(),
globalNotFound: z.boolean().optional(),
explicitParallelRouteChildren: z.boolean().optional(),
strictRouteMatching: z.boolean().optional(),
turbopackRustReactCompiler: z.boolean().optional(),
browserDebugInfoInTerminal: z
.union([
......
......@@ -1411,6 +1411,14 @@ export interface ExperimentalConfig {
*/
explicitParallelRouteChildren?: boolean
/**
* Omits catch-all-derived App Router matchers that cannot construct a
* complete parallel route tree for their URL. This requires
* `explicitParallelRouteChildren`; setting that option to `false` also
* disables strict route matching.
*/
strictRouteMatching?: boolean
/**
* @experimental Use the Rust port of the React compiler (Turbopack only).
* Requires `reactCompiler` to be enabled.
......@@ -2350,6 +2358,7 @@ export const defaultConfig = Object.freeze({
slowModuleDetection: undefined,
globalNotFound: false,
explicitParallelRouteChildren: true,
strictRouteMatching: false,
browserDebugInfoInTerminal: 'warn',
lockDistDir: true,
disableResumeDataCacheCompression: false,
......
......@@ -193,6 +193,36 @@ describe('loadConfig', () => {
})
})
describe('parallel route matching flags', () => {
it('allows explicit children detection without strict route matching', async () => {
const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
explicitParallelRouteChildren: true,
strictRouteMatching: false,
},
},
})
expect(result.experimental.explicitParallelRouteChildren).toBe(true)
expect(result.experimental.strictRouteMatching).toBe(false)
})
it('disables strict route matching when explicit children detection is disabled', async () => {
const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
explicitParallelRouteChildren: false,
strictRouteMatching: true,
},
},
})
expect(result.experimental.explicitParallelRouteChildren).toBe(false)
expect(result.experimental.strictRouteMatching).toBe(false)
})
})
describe('cacheHandlers validation', () => {
it('should reject invalid keys', async () => {
const invalidKeys = [
......
......@@ -454,6 +454,13 @@ function assignDefaultsAndValidate(
},
}
// Pruning assumes that children only exists when it is backed by an
// ordinary route branch. Restoring the legacy implicit children slot must
// therefore also restore the legacy matcher behavior.
if (!result.experimental.explicitParallelRouteChildren) {
result.experimental.strictRouteMatching = false
}
// Normalize prefetchInlining: true | { maxSize?, maxBundleSize? } into a
// resolved object with concrete defaults, so consumers don't have to
// resolve the values themselves.
......
......@@ -998,6 +998,13 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
const isInstrumentation =
isInstrumentationHookFile(page) && pageType === PAGE_TYPES.ROOT
const entryAppPaths =
'appPaths' in entryData ? entryData.appPaths : null
const isFinalRouteMatcher =
pageType === PAGE_TYPES.APP &&
this.config.experimental.strictRouteMatching &&
!!entryAppPaths?.length
let pageRuntime = staticInfo?.runtime
runDependingOnPageType({
......@@ -1057,6 +1064,13 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
.explicitParallelRouteChildren
? true
: undefined,
strictRouteMatching: this.config.experimental
.strictRouteMatching
? true
: undefined,
isFinalRouteMatcher: isFinalRouteMatcher
? true
: undefined,
}).import
: undefined
......@@ -1185,6 +1199,11 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
.explicitParallelRouteChildren
? true
: undefined,
strictRouteMatching: this.config.experimental
.strictRouteMatching
? true
: undefined,
isFinalRouteMatcher: isFinalRouteMatcher ? true : undefined,
})
} else if (isAPIRoute(page)) {
value = getRouteLoaderEntry({
......
import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths'
import { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/interception-routes'
import { isAppPageRoute } from '../../../lib/is-app-page-route'
import {
INTERCEPTION_ROUTE_MARKERS,
isInterceptionRouteAppPath,
} from '../../../shared/lib/router/utils/interception-routes'
import {
UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../../../shared/lib/entry-constants'
type AppPathNormalizer = {
normalize(pathname: string): string
}
export type NormalizeCatchAllRoutesOptions = {
strictRouteMatching?: boolean
defaultAppPaths?: Iterable<string>
}
type ParallelRouteLevel = {
parentSegments: string[]
namedSlots: Set<string>
hasChildrenSlot: boolean
}
const defaultNormalizer: AppPathNormalizer = {
normalize(pathname: string): string {
return normalizeAppPath(pathname).replace(/%5F/g, '_')
......@@ -20,7 +39,11 @@ const defaultNormalizer: AppPathNormalizer = {
*/
export function normalizeCatchAllRoutes(
appPaths: Record<string, string[]>,
normalizer: AppPathNormalizer = defaultNormalizer
normalizer: AppPathNormalizer = defaultNormalizer,
{
strictRouteMatching = false,
defaultAppPaths = [],
}: NormalizeCatchAllRoutesOptions = {}
) {
const catchAllRoutes = [
...new Set(
......@@ -69,6 +92,174 @@ export function normalizeCatchAllRoutes(
}
}
}
if (strictRouteMatching) {
pruneUnrenderableRoutes(appPaths, defaultAppPaths)
}
}
/**
* Removes routes that can never render because a declared slot at a matching
* layout level has neither a matching page nor an explicit default.
*
* The built-in default for such a slot always calls `notFound()`. Keeping the
* route in the matcher set would therefore retain a matcher that can never
* construct a complete loader tree.
*/
function pruneUnrenderableRoutes(
appPaths: Record<string, string[]>,
defaultAppPaths: Iterable<string>
) {
const allAppPaths = new Set([
...Object.values(appPaths).flat().filter(isUserAppPageRoute),
...[...defaultAppPaths].filter(
(appPath) => !isBuiltinAppPageEntry(appPath)
),
])
const levelsByParent = new Map<string, ParallelRouteLevel>()
for (const appPath of allAppPaths) {
const segments = splitAppPath(appPath)
for (let i = 0; i < segments.length - 1; i++) {
const segment = segments[i]
if (!isMatchableSlot(segment)) continue
const parentSegments = segments.slice(0, i)
const parentKey = JSON.stringify(parentSegments)
let level = levelsByParent.get(parentKey)
if (!level) {
level = {
parentSegments,
namedSlots: new Set(),
hasChildrenSlot: false,
}
levelsByParent.set(parentKey, level)
}
level.namedSlots.add(segment)
}
}
for (const appPath of allAppPaths) {
for (const level of levelsByParent.values()) {
if (isPathInSlot(appPath, level.parentSegments, 'children')) {
level.hasChildrenSlot = true
}
}
}
for (const [route, matchedAppPaths] of Object.entries(appPaths)) {
const matchedPageAppPaths = matchedAppPaths.filter(isUserAppPageRoute)
if (matchedPageAppPaths.length === 0) continue
if (
hasIncompleteParallelRoute(
matchedPageAppPaths,
levelsByParent.values(),
allAppPaths
)
) {
const nonPageAppPaths = matchedAppPaths.filter(
(appPath) => !isUserAppPageRoute(appPath)
)
if (nonPageAppPaths.length === 0) {
delete appPaths[route]
} else {
appPaths[route] = nonPageAppPaths
}
}
}
}
function isUserAppPageRoute(appPath: string): boolean {
return isAppPageRoute(appPath) && !isBuiltinAppPageEntry(appPath)
}
function isBuiltinAppPageEntry(appPath: string): boolean {
return (
appPath === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY ||
appPath === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY
)
}
function hasIncompleteParallelRoute(
matchedAppPaths: string[],
levels: Iterable<ParallelRouteLevel>,
allAppPaths: Set<string>
): boolean {
const matchedSegments = matchedAppPaths.map((appPath) =>
splitAppPath(appPath).slice(0, -1)
)
for (const { parentSegments, namedSlots, hasChildrenSlot } of levels) {
const pathsAtLevel = matchedSegments.filter((segments) =>
hasPathPrefix(segments, parentSegments)
)
if (pathsAtLevel.length === 0) continue
// An interception response replaces one slot while retaining every
// sibling owned by layouts up to the interception marker. Those siblings
// use the null retain marker rather than a page or default. Slots inside
// the newly selected subtree still match normally.
const retainsInterceptionSiblings = pathsAtLevel.some((segments) => {
const interceptionMarkerIndex = segments.findIndex((segment) =>
INTERCEPTION_ROUTE_MARKERS.some((marker) => segment.startsWith(marker))
)
return (
interceptionMarkerIndex !== -1 &&
parentSegments.length <= interceptionMarkerIndex
)
})
const slots = [...(hasChildrenSlot ? ['children'] : []), ...namedSlots]
for (const slot of slots) {
const hasMatchedPage = matchedAppPaths.some((appPath) =>
isPathInSlot(appPath, parentSegments, slot)
)
const hasDefault = allAppPaths.has(
getDefaultAppPath(parentSegments, slot)
)
if (!hasMatchedPage && !hasDefault && !retainsInterceptionSiblings) {
return true
}
}
}
return false
}
function splitAppPath(appPath: string): string[] {
return appPath.split('/').filter(Boolean)
}
function hasPathPrefix(path: string[], prefix: string[]): boolean {
return prefix.every((segment, index) => path[index] === segment)
}
function getSlotAtParent(path: string[], parent: string[]): string {
const segment = path[parent.length]
return segment?.startsWith('@') && segment !== '@children'
? segment
: 'children'
}
function isPathInSlot(
appPath: string,
parent: string[],
slot: string
): boolean {
const segments = splitAppPath(appPath)
return (
hasPathPrefix(segments, parent) &&
getSlotAtParent(segments, parent) === slot
)
}
function getDefaultAppPath(parent: string[], slot: string): string {
const segments =
slot === 'children' ? [...parent, 'default'] : [...parent, slot, 'default']
return `/${segments.join('/')}`
}
function hasMatchedSlots(path1: string, path2: string): boolean {
......
......@@ -464,6 +464,7 @@ async function startWatcher(
const routedPages: string[] = []
const knownFiles = wp.getTimeInfoEntries()
const appPaths: Record<string, string[]> = {}
const defaultAppPaths = new Set<string>()
const pageNameSet = new Set<string>()
const conflictingAppPagePaths = new Set<string>()
const duplicatePagePaths = new Set<string>()
......@@ -723,6 +724,11 @@ async function startWatcher(
continue
}
if (validFileMatcher.isAppDefaultPage(fileName)) {
defaultAppPaths.add(normalizedPageName.replace(/%5F/g, '_'))
continue
}
// Skip non-router pages (loading.tsx, error.tsx, etc.)
if (!validFileMatcher.isAppRouterPage(fileName)) continue
......@@ -1049,7 +1055,10 @@ async function startWatcher(
}
}
normalizeCatchAllRoutes(appPagePaths)
normalizeCatchAllRoutes(appPagePaths, undefined, {
strictRouteMatching: nextConfig.experimental.strictRouteMatching,
defaultAppPaths,
})
for (const pageAppPaths of Object.values(appPagePaths)) {
pageAppPaths.sort(compareAppPaths)
}
......
export default function Page() {
return <p id="named-canonical-page">Named canonical slot</p>
}
......@@ -6,6 +6,7 @@ export default function Page() {
<p>Named content slot</p>
<RetainedCounter />
<LinkAccordion href="/named-target" />
<LinkAccordion href="/named-host/named-catchall-target/photo" />
</div>
)
}
export default function Page() {
return (
<p id="named-host-catchall-modal">Intercepted named catch-all target</p>
)
}
export default function Layout({
canonical,
content,
modal,
secondary,
}: {
canonical: React.ReactNode
content: React.ReactNode
modal: React.ReactNode
secondary: React.ReactNode
}) {
return (
<main id="named-host">
<section id="named-host-canonical">{canonical}</section>
<section id="named-host-content">{content}</section>
<section id="named-host-secondary">{secondary}</section>
<section id="named-host-modal">{modal}</section>
......
import { notFound } from 'next/navigation'
// The children slot intentionally 404s at /regular-route. Make that behavior
// explicit so strict route matching can distinguish it from a synthesized
// fallback left behind by an incomplete matcher.
export default function Default() {
notFound()
}
......@@ -157,6 +157,34 @@ describe('interception-dynamic-segment', () => {
})
}
if (isNextDev) {
it('should retain named host slots for an interception catch-all in development', async () => {
const { act, browser } = await createBrowserWithRouterAct('/named-host')
await browser.elementById('retained-counter').click()
await act(async () => {
await navigate(browser, '/named-host/named-catchall-target/photo')
})
expect(
await browser.elementById('named-host-catchall-modal').text()
).toBe('Intercepted named catch-all target')
expect(await browser.elementById('named-host-content').text()).toContain(
'Named content slot'
)
expect(
await browser.elementById('named-host-secondary').text()
).toContain('Named secondary slot without a default')
expect(await browser.elementById('named-host-canonical').text()).toBe(
'Named canonical slot'
)
expect(await browser.elementById('retained-counter').text()).toBe(
'Retained count: 1'
)
})
}
if (!isNextDev) {
/**
* Test Case Validation: Ensure NO 404s occur during interception navigation
......@@ -292,6 +320,32 @@ describe('interception-dynamic-segment', () => {
expect(await browser.hasElementByCss('#named-host')).toBe(false)
})
it('should retain named host slots for an interception catch-all', async () => {
const { act, browser } = await createBrowserWithRouterAct('/named-host')
await browser.elementById('retained-counter').click()
await act(async () => {
await navigate(browser, '/named-host/named-catchall-target/photo')
})
expect(
await browser.elementById('named-host-catchall-modal').text()
).toBe('Intercepted named catch-all target')
expect(
await browser.elementById('named-host-content').text()
).toContain('Named content slot')
expect(
await browser.elementById('named-host-secondary').text()
).toContain('Named secondary slot without a default')
expect(await browser.elementById('named-host-canonical').text()).toBe(
'Named canonical slot'
)
expect(await browser.elementById('retained-counter').text()).toBe(
'Retained count: 1'
)
})
it('should send and render a real default for a newly entered slot owner', async () => {
const { act, browser } = await createBrowserWithRouterAct('/')
......
......@@ -7,6 +7,10 @@ const nextConfig = {
// intercepted layouts omit children, while a real children branch still
// uses the marker needed to preserve its active state during navigation.
explicitParallelRouteChildren: true,
// Interception catch-alls retain every sibling owned by the host layout.
// Strict matching must not mistake those retained slots for incomplete
// route coverage and prune the interception matcher.
strictRouteMatching: true,
},
}
......
export default function Layout({
children,
content,
modal,
}: {
children: React.ReactNode
content: React.ReactNode
modal: React.ReactNode
}) {
return (
<main>
<section id="children">{children}</section>
<section id="content">{content}</section>
<section id="modal">{modal}</section>
</main>
)
}
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
// This fixture exercises the legacy missing-default validation directly.
// Keep that coverage if strict route matching becomes the default; once
// strict matching is the only mode, this fixture can be removed.
strictRouteMatching: false,
},
}
module.exports = nextConfig
......@@ -75,4 +75,17 @@ describe('parallel-routes-leaf-segments-no-build-error', () => {
expect($('#children').text()).toBe('No Children Default')
})
})
describe('interception host with a matching sibling route', () => {
it('should not require a default for the matched sibling slot', async () => {
// @content has no default, but it has a matching page for every ordinary
// child route. The interception matcher retains @content during a soft
// navigation, so compiling that matcher must not report a missing default.
const $ = await next.render$('/interception-host/dashboard')
expect($('#children').text()).toBe('Dashboard page')
expect($('#content').text()).toBe('Dashboard content')
expect($('#modal').text()).toBe('No modal')
})
})
})
export default function GroupedSlotPage() {
return <p id="grouped-slot-page">grouped slot page</p>
}
export default function GroupedCatchallPage() {
return <p id="grouped-catchall-page">grouped catch-all page</p>
}
import type { ReactNode } from 'react'
/**
* The route group must not affect completeness. The broad children catch-all
* lacks @slot coverage and is pruned, while /grouped/specific has both pages
* and remains in the matcher set.
*/
export default function GroupedLayout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<div id="grouped-layout">
{children}
{slot}
</div>
)
}
export default function GroupedSpecificPage() {
return <p id="grouped-specific-page">grouped specific page</p>
}
export default function FirstSlot() {
return <p id="first-slot-page">first slot</p>
}
export default function SecondSlot() {
return <p id="second-slot-page">second slot</p>
}
export default function ChildrenCatchall() {
return <p id="children-catchall-page">children catch-all</p>
}
import type { ReactNode } from 'react'
/**
* `children` matches every non-empty path, but @first only matches /foo and
* @second only matches /bar. Every candidate therefore synthesizes a
* not-found default for at least one named slot, so this route emits no
* matchers when pruning is enabled.
*/
export default function ChildrenCatchallLayout({
children,
first,
second,
}: {
children: ReactNode
first: ReactNode
second: ReactNode
}) {
return (
<div id="children-catchall-layout">
{children}
{first}
{second}
</div>
)
}
export default function ChildrenDefaultSlotCatchall() {
return <p id="children-default-slot-catchall">slot catch-all</p>
}
export default function ChildrenDefault() {
return <p id="children-default">children default</p>
}
import type { ReactNode } from 'react'
/**
* The explicit default declares coverage for the implicit children slot, so
* the named catch-all produces a complete broad matcher that must be retained.
*/
export default function ChildrenDefaultLayout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<div id="children-default-layout">
{children}
{slot}
</div>
)
}
'use client'
import { useRouter } from 'next/navigation'
export function ClientNavigation({ paths }: { paths: string[] }) {
const router = useRouter()
return paths.map((path) => (
<button
key={path}
data-router-push={path}
onClick={() => router.push(path)}
>
Navigate to {path}
</button>
))
}
export default function CompleteSlotCatchall() {
return <p id="complete-slot-catchall">slot catch-all</p>
}
export default function CompleteChildrenCatchall() {
return <p id="complete-children-catchall">children catch-all</p>
}
import type { ReactNode } from 'react'
/**
* Both children and @slot cover the same catch-all, so the broad matcher can
* construct a complete loader tree and must be retained when pruning is on.
*/
export default function CompleteCatchallsLayout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<div id="complete-catchalls-layout">
{children}
{slot}
</div>
)
}
import { notFound } from 'next/navigation'
export default function DefaultNotFoundSlot() {
notFound()
}
export default function DefaultNotFoundCatchall() {
return <p id="default-not-found-catchall">default not-found catch-all</p>
}
import type { ReactNode } from 'react'
/**
* @slot has a user-authored default, so the broad children catch-all remains
* in the matcher set. That default deliberately calls notFound(), proving an
* explicit default can preserve the old perma-404 behavior.
*/
export default function DefaultNotFoundLayout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<div id="default-not-found-layout">
{children}
{slot}
</div>
)
}
import type { ReactNode } from 'react'
/**
* Pruned URLs fall through to the root not-found UI without rendering any of
* the route-level layouts below. Their tests use those layout IDs to verify
* that an incomplete matcher was omitted instead of selected.
*/
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<div id="root-layout">root layout</div>
{children}
</body>
</html>
)
}
export default function NamedCatchall() {
return <p id="named-catchall-page">named catch-all</p>
}
export default function NamedSpecific() {
return <p id="named-specific-page">named specific page</p>
}
import type { ReactNode } from 'react'
/**
* This layout intentionally has no children slot. /foo is retained because
* both declared named slots match it, while the broader catch-all is pruned
* because @specific has no matching page or default for other URLs. Strict
* matching does not synthesize a children slot at this level.
*/
export default function NamedCatchallLayout({
catchall,
specific,
}: {
catchall: ReactNode
specific: ReactNode
}) {
return (
<div id="named-catchall-layout">
{catchall}
{specific}
</div>
)
}
export default function NamedOnlyLeftCatchall() {
return <p id="named-only-left-catchall">left catch-all</p>
}
export default function NamedOnlyRightCatchall() {
return <p id="named-only-right-catchall">right catch-all</p>
}
import type { ReactNode } from 'react'
/**
* Both named slots cover the catch-all and this layout intentionally has no
* children slot. The broad matcher is complete, and strict matching represents
* this level using only the declared left and right slots.
*/
export default function NamedOnlyCatchallsLayout({
left,
right,
}: {
left: ReactNode
right: ReactNode
}) {
return (
<div id="named-only-catchalls-layout">
{left}
{right}
</div>
)
}
export default function NestedInnerSpecificPage() {
return <p id="nested-inner-specific-page">nested inner specific page</p>
}
export default function NestedOuterCatchallPage() {
return <p id="nested-outer-catchall-page">nested outer catch-all page</p>
}
import type { ReactNode } from 'react'
/**
* @inner only has a /specific page. The outer children catch-all therefore
* makes every other URL incomplete at this nested parallel-route level.
*/
export default function NestedOuterLayout({
children,
inner,
}: {
children: ReactNode
inner: ReactNode
}) {
return (
<div id="nested-outer-layout">
{children}
{inner}
</div>
)
}
export default function NestedOuterSpecificPage() {
return <p id="nested-outer-specific-page">nested outer specific page</p>
}
export default function NestedCatchallPage() {
return <p id="nested-catchall-page">nested catch-all page</p>
}
import type { ReactNode } from 'react'
/**
* Both top-level slots have catch-all coverage, but @outer contains another
* parallel level that is incomplete for the broad matcher. Pruning must find
* that nested synthesized default; only /specific has a complete tree.
*/
export default function NestedParallelLayout({
children,
outer,
}: {
children: ReactNode
outer: ReactNode
}) {
return (
<div id="nested-parallel-layout">
{children}
{outer}
</div>
)
}
export default function NestedSpecificPage() {
return <p id="nested-specific-page">nested specific page</p>
}
export default function NotFound() {
return <p id="root-not-found">root not found</p>
}
export default function OptionalSlotPage() {
return <p id="optional-slot-page">optional slot page</p>
}
export default function OptionalCatchallPage() {
return <p id="optional-catchall-page">optional catch-all page</p>
}
/**
* The optional children catch-all can match the segment root or any suffix,
* while @slot only matches /specific. The broad optional matcher is pruned,
* but /specific remains because both slots have an exact page for that URL.
*/
export default function OptionalChildrenCatchallLayout({
children,
slot,
}: {
children: React.ReactNode
slot: React.ReactNode
}) {
return (
<main id="optional-children-catchall-layout">
{children}
{slot}
</main>
)
}
export default function OptionalSpecificPage() {
return <p id="optional-specific-page">optional specific page</p>
}
import { ClientNavigation } from './client-navigation'
const navigationPaths = [
'/named-catchall/anything',
'/named-only-catchalls/anything',
'/children-catchall/foo',
'/children-catchall/bar',
'/optional-children-catchall',
'/optional-children-catchall/anything',
'/split-matcher/anything',
'/nested-parallel/anything',
'/grouped/anything',
]
export default function Page() {
return (
<>
<p id="home">home</p>
<ClientNavigation paths={navigationPaths} />
</>
)
}
export default function SplitSlotCatchall() {
return <p id="split-slot-catchall">split slot catch-all</p>
}
export default function BarPage() {
return <p id="split-bar-page">bar page</p>
}
export default function FooPage() {
return <p id="split-foo-page">foo page</p>
}
import type { ReactNode } from 'react'
/**
* The @slot catch-all is combined with the concrete children pages for /foo
* and /bar, so those complete matchers remain. Its standalone broad matcher
* has no children page or default and is pruned.
*/
export default function SplitMatcherLayout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<div id="split-matcher-layout">
{children}
{slot}
</div>
)
}
export default function SlotDefault() {
return <p id="valid-slot-default">valid slot default</p>
}
export default function SlotPage() {
return <p id="valid-slot-page">valid slot page</p>
}
export default function ValidCatchall() {
return <p id="valid-catchall-page">valid catch-all</p>
}
import type { ReactNode } from 'react'
/**
* This is the retained control case. @slot/default covers the broad children
* catch-all, and @slot/special covers the concrete /special matcher, so both
* matcher shapes can construct a complete loader tree.
*/
export default function ValidLayout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<div id="valid-layout">
{children}
{slot}
</div>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
strictRouteMatching: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
import cheerio from 'cheerio'
import stripAnsi from 'strip-ansi'
const prunedRoutes: Array<[path: string, layoutId: string]> = [
['/named-catchall/anything', 'named-catchall-layout'],
['/children-catchall/foo', 'children-catchall-layout'],
['/children-catchall/bar', 'children-catchall-layout'],
['/optional-children-catchall', 'optional-children-catchall-layout'],
['/optional-children-catchall/anything', 'optional-children-catchall-layout'],
['/split-matcher/anything', 'split-matcher-layout'],
['/nested-parallel/anything', 'nested-parallel-layout'],
['/grouped/anything', 'grouped-layout'],
]
function getAppRoutes(cliOutput: string): string[] {
const routes: string[] = []
let inAppRoutes = false
for (const line of stripAnsi(cliOutput).split('\n')) {
if (line.startsWith('Route (app)')) {
inAppRoutes = true
continue
}
if (!inAppRoutes) continue
const match = line.match(/^[┌├└] +(?:\S+ +)?(\/\S+)/)
if (match) routes.push(match[1])
if (line.startsWith('└')) break
}
return routes
}
describe('parallel-routes-pruned-matchers', () => {
const { next, isNextStart } = nextTestSetup({
files: __dirname,
})
it.each(prunedRoutes)(
'omits the permanently-not-found matcher for %s',
async (path, layoutId) => {
const response = await next.fetch(path)
const $ = cheerio.load(await response.text())
expect(response.status).toBe(404)
expect($.root().text()).toContain('root not found')
expect($(`#${layoutId}`).length).toBe(0)
}
)
it.each(prunedRoutes)(
'renders the same 404 after client navigation to %s',
async (path, layoutId) => {
let act: ReturnType<typeof createRouterAct>
const responseStatuses: number[] = []
const browser = await next.browser('/', {
beforePageLoad(page) {
page.on('response', (response) => {
if (new URL(response.url()).pathname === path) {
responseStatuses.push(response.status())
}
})
act = createRouterAct(page, { allowErrorStatusCodes: [404] })
},
})
await act!(async () => {
await browser.elementByCss(`button[data-router-push="${path}"]`).click()
})
await browser.waitForElementByCss('#root-not-found')
expect(await browser.elementById('root-not-found').text()).toBe(
'root not found'
)
expect(await browser.hasElementByCss(`#${layoutId}`)).toBe(false)
expect(responseStatuses).toContain(404)
}
)
it('keeps a named-only matcher when every declared slot matches', async () => {
const $ = await next.render$('/named-catchall/foo')
expect($('#named-catchall-page').text()).toBe('named catch-all')
expect($('#named-specific-page').text()).toBe('named specific page')
})
it('keeps a broad matcher composed entirely from named slots', async () => {
const browser = await next.browser('/named-only-catchalls/anything')
expect(await browser.elementById('named-only-left-catchall').text()).toBe(
'left catch-all'
)
expect(await browser.elementById('named-only-right-catchall').text()).toBe(
'right catch-all'
)
})
it('renders a route with only named slots after client navigation', async () => {
let act: ReturnType<typeof createRouterAct>
const path = '/named-only-catchalls/anything'
const browser = await next.browser('/', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
await act!(async () => {
await browser.elementByCss(`button[data-router-push="${path}"]`).click()
})
await browser.waitForElementByCss('#named-only-catchalls-layout')
expect(await browser.elementById('named-only-left-catchall').text()).toBe(
'left catch-all'
)
expect(await browser.elementById('named-only-right-catchall').text()).toBe(
'right catch-all'
)
})
it('keeps a named catch-all when children has an explicit default', async () => {
const $ = await next.render$('/children-default/anything')
expect($('#children-default').text()).toBe('children default')
expect($('#children-default-slot-catchall').text()).toBe('slot catch-all')
})
it('keeps a catch-all matcher when every slot has catch-all coverage', async () => {
const $ = await next.render$('/complete-catchalls/anything')
expect($('#complete-children-catchall').text()).toBe('children catch-all')
expect($('#complete-slot-catchall').text()).toBe('slot catch-all')
})
it('keeps a catch-all matcher when the sibling slot has a default', async () => {
const $ = await next.render$('/valid/foo')
expect($('#valid-catchall-page').text()).toBe('valid catch-all')
expect($('#valid-slot-default').text()).toBe('valid slot default')
})
it('keeps a catch-all matcher when every sibling slot matches', async () => {
const $ = await next.render$('/valid/special')
expect($('#valid-catchall-page').text()).toBe('valid catch-all')
expect($('#valid-slot-page').text()).toBe('valid slot page')
})
it('keeps the specific sibling of a pruned optional catch-all', async () => {
const $ = await next.render$('/optional-children-catchall/specific')
expect($('#optional-specific-page').text()).toBe('optional specific page')
expect($('#optional-slot-page').text()).toBe('optional slot page')
})
it.each(['foo', 'bar'])(
'keeps /split-matcher/%s while pruning the broader matcher',
async (segment) => {
const $ = await next.render$(`/split-matcher/${segment}`)
expect($(`#split-${segment}-page`).text()).toBe(`${segment} page`)
expect($('#split-slot-catchall').text()).toBe('split slot catch-all')
}
)
it('keeps a matcher when an explicit default calls notFound', async () => {
const response = await next.fetch('/default-not-found/anything')
expect(response.status).toBe(404)
})
it('prunes a matcher with an incomplete nested parallel route', async () => {
const $ = await next.render$('/nested-parallel/specific')
expect($('#nested-specific-page').text()).toBe('nested specific page')
expect($('#nested-outer-specific-page').text()).toBe(
'nested outer specific page'
)
expect($('#nested-inner-specific-page').text()).toBe(
'nested inner specific page'
)
})
it('keeps the specific sibling of a pruned route-group matcher', async () => {
const $ = await next.render$('/grouped/specific')
expect($('#grouped-specific-page').text()).toBe('grouped specific page')
expect($('#grouped-slot-page').text()).toBe('grouped slot page')
})
if (isNextStart) {
it('lists only retained routes in the build output', () => {
const appRoutes = getAppRoutes(next.cliOutput)
const omittedRoutes = [
'/named-catchall/[...slug]',
'/children-catchall/[...slug]',
'/optional-children-catchall/[[...slug]]',
'/split-matcher/[...parts]',
'/nested-parallel/[...slug]',
'/grouped/[...slug]',
]
expect(
appRoutes.filter((route) => omittedRoutes.includes(route))
).toEqual([])
expect(appRoutes).toEqual(
expect.arrayContaining([
'/named-catchall/foo',
'/named-only-catchalls/[...slug]',
'/children-default/[...slug]',
'/complete-catchalls/[...slug]',
'/valid/[...slug]',
'/valid/special',
'/optional-children-catchall/specific',
'/split-matcher/foo',
'/split-matcher/bar',
'/default-not-found/[...slug]',
'/nested-parallel/specific',
'/grouped/specific',
])
)
})
}
})
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