Unverified Commit e674165f authored by Josh Story's avatar Josh Story Committed by GitHub

Report incompatible parallel route slots (#97430)

With strict route matching a layout can have sibling slots whose pages
can never form a complete route. For example:

```
app/
  layout.tsx
  @left/
    foo/
      page.tsx
  @right/
    bar/
      page.tsx
```

`/foo` is always missing `@right`, and `/bar` is always missing `@left`.
The pages were authored as route targets, but neither URL can construct
the complete slot tree owned by `app/layout.tsx`. Catchall pruning
removes broad matchers that cannot render and the unmatched-page
validation reports dangling files, but neither explains this
project-level mistake.

This validates the finalized ordinary matcher set and reports each
incomplete URL at the layout that owns the conflicting slots. Adding the
corresponding pages or an explicit `default.tsx` makes the topology
valid. Framework-owned defaults do not invent a `children` slot, and
interception matchers remain exempt because they intentionally describe
partial router state updates.

<!-- NEXT_JS_LLM -->
parent dea15ec6
This diff is collapsed.
......@@ -61,7 +61,9 @@ import type { MappedPages } from './build-context'
import { PAGE_TYPES } from '../lib/page-types'
import { UnmatchedAppPagesError } from '../shared/lib/errors/unmatched-app-pages-error'
import { MissingCanonicalInterceptionRoutesError } from '../shared/lib/errors/missing-canonical-interception-routes-error'
import { IncompatibleParallelRouteSlotsError } from '../shared/lib/errors/incompatible-parallel-route-slots-error'
import { findMissingCanonicalInterceptionRoutes } from '../shared/lib/router/utils/interception-routes'
import { findPageFile } from '../server/lib/find-page-file'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts'
......@@ -430,10 +432,11 @@ export async function createEntrypoints(
}
// TODO: find a better place to do this
const unmatchedAppPages = normalizeCatchAllRoutes(appPathsPerRoute, {
strictRouteMatching: config.experimental.strictRouteMatching,
defaultAppPaths: Object.keys(appDefaultPaths ?? {}),
})
const { unmatchedAppPages, incompatibleParallelRouteSlots } =
normalizeCatchAllRoutes(appPathsPerRoute, {
strictRouteMatching: config.experimental.strictRouteMatching,
defaultAppPaths: Object.keys(appDefaultPaths ?? {}),
})
// Only App Router pages can make an intercepted URL directly renderable.
// Route handlers and metadata routes may share the pathname, but they
// cannot provide the canonical page shown by an initial request.
......@@ -447,27 +450,70 @@ export async function createEntrypoints(
.strictRouteMatching
? findMissingCanonicalInterceptionRoutes(appPagePathsPerRoute)
: []
const routeMatchingErrors: Error[] = []
if (missingCanonicalInterceptionRoutes.length > 0) {
throw new MissingCanonicalInterceptionRoutesError(
missingCanonicalInterceptionRoutes
routeMatchingErrors.push(
new MissingCanonicalInterceptionRoutesError(
missingCanonicalInterceptionRoutes
)
)
}
if (unmatchedAppPages.length > 0) {
throw new UnmatchedAppPagesError(
unmatchedAppPages.map((appPath) => {
const absolutePagePath = appPageFiles.get(appPath)
if (!absolutePagePath) return appPath
return relative(
rootDir,
getPageFilePath({
absolutePagePath,
pagesDir,
appDir,
rootDir,
if (incompatibleParallelRouteSlots.length > 0) {
routeMatchingErrors.push(
new IncompatibleParallelRouteSlotsError(
await Promise.all(
incompatibleParallelRouteSlots.map(async (incompatibleRoute) => {
const layoutPagePath = posix.join(
incompatibleRoute.layoutPath,
'layout'
)
const layoutFile = await findPageFile(
appDir,
layoutPagePath,
pageExtensions,
true
)
return {
...incompatibleRoute,
layoutFile: relative(
rootDir,
layoutFile
? join(appDir, layoutFile)
: join(appDir, layoutPagePath)
),
}
})
)
})
)
)
}
if (unmatchedAppPages.length > 0) {
routeMatchingErrors.push(
new UnmatchedAppPagesError(
unmatchedAppPages.map((appPath) => {
const absolutePagePath = appPageFiles.get(appPath)
if (!absolutePagePath) return appPath
return relative(
rootDir,
getPageFilePath({
absolutePagePath,
pagesDir,
appDir,
rootDir,
})
)
})
)
)
}
if (routeMatchingErrors.length === 1) {
throw routeMatchingErrors[0]
}
if (routeMatchingErrors.length > 1) {
throw new Error(
routeMatchingErrors.map((error) => error.message).join('\n\n')
)
}
......
import { normalizeCatchAllRoutes } from './normalize-catchall-routes'
import {
findIncompatibleParallelRouteSlots,
normalizeCatchAllRoutes,
} from './normalize-catchall-routes'
describe('normalizeCatchallRoutes', () => {
it('should not add the catch-all to the interception route', () => {
......@@ -228,7 +231,7 @@ describe('normalizeCatchallRoutes', () => {
'/bar': ['/@second/bar/page'],
}
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths)
const { unmatchedAppPages } = normalizeCatchAllRoutes(appPaths)
expect(unmatchedAppPages).toEqual([])
})
......@@ -311,7 +314,7 @@ describe('normalizeCatchallRoutes', () => {
'/bar': ['/@second/bar/page'],
}
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths, {
const { unmatchedAppPages } = normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
})
......@@ -329,7 +332,7 @@ describe('normalizeCatchallRoutes', () => {
'/specific': ['/specific/page', '/@slot/specific/page'],
}
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths, {
const { unmatchedAppPages } = normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
})
......@@ -524,7 +527,7 @@ describe('normalizeCatchallRoutes', () => {
'/photo/specific': ['/@modal/(.)photo/@specific/specific/page'],
}
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths, {
const { unmatchedAppPages } = normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
})
......@@ -542,11 +545,144 @@ describe('normalizeCatchallRoutes', () => {
'/[...parts]': ['/@slot/[...parts]/page'],
}
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths, {
const { unmatchedAppPages } = normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
})
expect(unmatchedAppPages).toEqual([])
})
})
describe('incompatible parallel route slots', () => {
it('reports incompatible static matchers and still prunes them', () => {
const appPaths = {
'/foo': ['/@left/foo/page'],
'/bar': ['/@right/bar/page'],
}
const { incompatibleParallelRouteSlots } = normalizeCatchAllRoutes(
appPaths,
{ strictRouteMatching: true }
)
expect(incompatibleParallelRouteSlots).toEqual([
{
layoutPath: '/',
route: '/bar',
missingSlots: ['@left'],
},
{
layoutPath: '/',
route: '/foo',
missingSlots: ['@right'],
},
])
expect(appPaths).toEqual({})
})
it('does not report a broad catch-all matcher that can be pruned', () => {
const appPaths = {
'/foo': ['/foo/page'],
'/[...parts]': ['/@slot/[...parts]/page'],
}
const { incompatibleParallelRouteSlots } = normalizeCatchAllRoutes(
appPaths,
{ strictRouteMatching: true }
)
expect(incompatibleParallelRouteSlots).toEqual([])
expect(appPaths).toEqual({
'/foo': ['/foo/page', '/@slot/[...parts]/page'],
})
})
it('reports static pages in sibling slots that cannot render together', () => {
const incompatibleRoutes = findIncompatibleParallelRouteSlots({
'/foo': ['/@left/foo/page'],
'/bar': ['/@right/bar/page'],
})
expect(incompatibleRoutes).toEqual([
{
layoutPath: '/',
route: '/bar',
missingSlots: ['@left'],
},
{
layoutPath: '/',
route: '/foo',
missingSlots: ['@right'],
},
])
})
it('reports an incompatible children route at the nested owner', () => {
const incompatibleRoutes = findIncompatibleParallelRouteSlots({
'/dashboard/foo': ['/dashboard/foo/page'],
'/dashboard/bar': ['/dashboard/@panel/bar/page'],
})
expect(incompatibleRoutes).toEqual([
{
layoutPath: '/dashboard',
route: '/dashboard/bar',
missingSlots: ['children'],
},
{
layoutPath: '/dashboard',
route: '/dashboard/foo',
missingSlots: ['@panel'],
},
])
})
it('accepts explicit defaults for the missing sibling slots', () => {
const incompatibleRoutes = findIncompatibleParallelRouteSlots(
{
'/foo': ['/@left/foo/page'],
'/bar': ['/@right/bar/page'],
},
['/@left/default', '/@right/default']
)
expect(incompatibleRoutes).toEqual([])
})
it('does not infer children from framework-owned defaults', () => {
const incompatibleRoutes = findIncompatibleParallelRouteSlots(
{
'/foo': ['/@left/foo/page'],
'/bar': ['/@right/bar/page'],
'/_not-found': ['/next/dist/builtin/global-not-found/page'],
},
['/_global-error/page']
)
expect(incompatibleRoutes).toEqual([
{
layoutPath: '/',
route: '/bar',
missingSlots: ['@left'],
},
{
layoutPath: '/',
route: '/foo',
missingSlots: ['@right'],
},
])
})
it('does not apply ordinary matching requirements to interception routes', () => {
const incompatibleRoutes = findIncompatibleParallelRouteSlots(
{
'/': ['/@content/page'],
'/photo/(.)[id]': ['/@modal/(.)photo/[id]/page'],
},
['/@modal/default']
)
expect(incompatibleRoutes).toEqual([])
})
})
})
import {
findIncompatibleParallelRouteSlots,
normalizeCatchAllRoutes as normalizeCatchAllRoutesInternal,
type NormalizeCatchAllRoutesOptions,
} from '../server/lib/router-utils/normalize-catchall-routes'
export { findIncompatibleParallelRouteSlots }
export function normalizeCatchAllRoutes(
appPaths: Record<string, string[]>,
options: NormalizeCatchAllRoutesOptions = {}
): string[] {
) {
return normalizeCatchAllRoutesInternal(appPaths, undefined, options)
}
......@@ -100,6 +100,7 @@ import { isAppPageRoute } from '../../../lib/is-app-page-route'
import { isAppRouteRoute } from '../../../lib/is-app-route-route'
import { UnmatchedAppPagesError } from '../../../shared/lib/errors/unmatched-app-pages-error'
import { MissingCanonicalInterceptionRoutesError } from '../../../shared/lib/errors/missing-canonical-interception-routes-error'
import { IncompatibleParallelRouteSlotsError } from '../../../shared/lib/errors/incompatible-parallel-route-slots-error'
import { findMissingCanonicalInterceptionRoutes } from '../../../shared/lib/router/utils/interception-routes'
import {
createRouteTypesManifest,
......@@ -465,7 +466,7 @@ async function startWatcher(
let enabledTypeScript = await verifyTypeScript(opts)
let previousClientRouterFilters: any
let previousConflictingPagePaths: Set<string> = new Set()
let previousRouteMatchingError: string | null = null
let previousRouteMatchingErrors: string | null = null
let hadInitialScan = false
let previousDuplicatePagePaths: Set<string> = new Set()
......@@ -506,6 +507,7 @@ async function startWatcher(
const duplicatePagePaths = new Set<string>()
const appPageFilePaths = new Map<string, string>()
const appRouteFilePaths = new Map<string, string>()
const parallelRouteLayoutFiles = new Map<string, string>()
const pagesPageFilePaths = new Map<string, string>()
const appRouteHandlers: Array<RouteInfo & { page: string }> = []
const pageApiRoutes: RouteInfo[] = []
......@@ -753,6 +755,11 @@ async function startWatcher(
// Handle layouts separately - they don't get added to appPaths
if (validFileMatcher.isAppLayoutPage(fileName)) {
const layoutPath =
normalizedPageName
.replace(/%5F/g, '_')
.replace(/\/layout$/, '') || '/'
parallelRouteLayoutFiles.set(layoutPath, fileName)
const layoutRoute = ensureLeadingSlash(
normalizeAppPath(normalizedPageName).replace(/\/layout$/, '')
)
......@@ -1091,39 +1098,60 @@ async function startWatcher(
}
}
const unmatchedAppPages = normalizeCatchAllRoutes(
appPagePaths,
undefined,
{
const { unmatchedAppPages, incompatibleParallelRouteSlots } =
normalizeCatchAllRoutes(appPagePaths, undefined, {
strictRouteMatching: nextConfig.experimental.strictRouteMatching,
defaultAppPaths,
}
)
})
const missingCanonicalInterceptionRoutes = nextConfig.experimental
.strictRouteMatching
? findMissingCanonicalInterceptionRoutes(appPagePaths)
: []
const routeMatchingError =
missingCanonicalInterceptionRoutes.length > 0
? new MissingCanonicalInterceptionRoutesError(
missingCanonicalInterceptionRoutes
)
: unmatchedAppPages.length > 0
? new UnmatchedAppPagesError(
unmatchedAppPages.map((appPath) => {
const filePath = appRouteFilePaths.get(appPath)
return filePath
? normalizePathSep(path.relative(dir, filePath))
: appPath
})
)
: null
const routeMatchingErrors: Error[] = []
if (missingCanonicalInterceptionRoutes.length > 0) {
routeMatchingErrors.push(
new MissingCanonicalInterceptionRoutesError(
missingCanonicalInterceptionRoutes
)
)
}
if (incompatibleParallelRouteSlots.length > 0) {
routeMatchingErrors.push(
new IncompatibleParallelRouteSlotsError(
incompatibleParallelRouteSlots.map((incompatibleRoute) => ({
...incompatibleRoute,
layoutFile: path.relative(
dir,
parallelRouteLayoutFiles.get(incompatibleRoute.layoutPath) ??
path.join(appDir!, incompatibleRoute.layoutPath, 'layout')
),
}))
)
)
}
if (unmatchedAppPages.length > 0) {
routeMatchingErrors.push(
new UnmatchedAppPagesError(
unmatchedAppPages.map((appPath) => {
const filePath = appRouteFilePaths.get(appPath)
return filePath
? normalizePathSep(path.relative(dir, filePath))
: appPath
})
)
)
}
const routeMatchingError = routeMatchingErrors[0] ?? null
const routeMatchingErrorsKey =
routeMatchingErrors.map((error) => error.message).join('\n\n') || null
if (
numConflicting === 0 &&
routeMatchingError &&
routeMatchingError.message !== previousRouteMatchingError
routeMatchingErrorsKey !== null &&
routeMatchingErrorsKey !== previousRouteMatchingErrors
) {
Log.error(routeMatchingError.message)
for (const error of routeMatchingErrors) {
Log.error(error.message)
}
}
// Turbopack reports route-matching failures as app-structure issues.
// Webpack needs an HMR server error so dev can finish booting and surface
......@@ -1131,11 +1159,11 @@ async function startWatcher(
if (!opts.turbo) {
if (numConflicting === 0 && routeMatchingError) {
hotReloader.setHmrServerError(routeMatchingError)
} else if (numConflicting === 0 && previousRouteMatchingError) {
} else if (numConflicting === 0 && previousRouteMatchingErrors) {
hotReloader.clearHmrServerError()
}
}
previousRouteMatchingError = routeMatchingError?.message ?? null
previousRouteMatchingErrors = routeMatchingErrorsKey
for (const pageAppPaths of Object.values(appPagePaths)) {
pageAppPaths.sort(compareAppPaths)
}
......
export type IncompatibleParallelRouteSlots = {
layoutFile: string
route: string
missingSlots: readonly string[]
}
export class IncompatibleParallelRouteSlotsError extends Error {
constructor(routes: readonly IncompatibleParallelRouteSlots[]) {
const routesByLayout = new Map<string, IncompatibleParallelRouteSlots[]>()
for (const route of routes) {
const layoutRoutes = routesByLayout.get(route.layoutFile)
if (layoutRoutes) {
layoutRoutes.push(route)
} else {
routesByLayout.set(route.layoutFile, [route])
}
}
const formattedLayouts = [...routesByLayout]
.sort(([a], [b]) => a.localeCompare(b))
.map(([layoutFile, layoutRoutes]) => {
const formattedRoutes = layoutRoutes
.sort((a, b) => a.route.localeCompare(b.route))
.map(
({ route, missingSlots }) =>
`- ${route} is missing a matching page or default.tsx in ${missingSlots.join(', ')}`
)
.join('\n')
return `${layoutFile}\n${formattedRoutes}`
})
.join('\n\n')
super(
`The following layouts have parallel route slots that cannot render the same URLs:\n${formattedLayouts}\n\nEvery URL matched by one slot must have a matching page or default.tsx in every sibling slot.`
)
this.name = 'IncompatibleParallelRouteSlotsError'
this.stack = undefined
}
}
export default function LeftFoo() {
return <p>left foo</p>
}
export default function RightBar() {
return <p>right bar</p>
}
import type { ReactNode } from 'react'
export default function Root({
left,
right,
}: {
left: ReactNode
right: ReactNode
}) {
return (
<html>
<body>
{left}
{right}
</body>
</html>
)
}
import { nextTestSetup } from 'e2e-utils'
import stripAnsi from 'strip-ansi'
describe('incompatible-parallel-route-slots', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
it('reports the layout whose slots cannot render the same URLs', async () => {
if (isNextDev) {
await next.start()
const browser = await next.browser('/foo')
if (isTurbopack) {
await expect({ browser, next }).toDisplayRedbox(`
{
"description": "Parallel route slots cannot render the same URLs",
"environmentLabel": null,
"label": "Build Error",
"source": "./app/layout.tsx
Error: Parallel route slots cannot render the same URLs
The following layouts have parallel route slots that cannot render the same URLs:
app/layout.tsx
- /bar is missing a matching page or default.tsx in @left
- /foo is missing a matching page or default.tsx in @right
Every URL matched by one slot must have a matching page or default.tsx in every sibling slot.",
"stack": [],
}
`)
} else {
// Webpack and Rspack surface the filesystem-watcher error through the
// same HMR server-error path.
await expect({ browser, next }).toDisplayRedbox(`
{
"description": "app/layout.tsx",
"environmentLabel": null,
"label": "Build Error",
"source": "The following layouts have parallel route slots that cannot render the same URLs:
app/layout.tsx
- /bar is missing a matching page or default.tsx in @left
- /foo is missing a matching page or default.tsx in @right
Every URL matched by one slot must have a matching page or default.tsx in every sibling slot.",
"stack": [],
}
`)
}
const response = await (await next.fetch('/foo')).text()
expect(`${stripAnsi(next.cliOutput)}\n${response}`).not.toContain(
'strict route matching retained the incomplete route matcher'
)
} else {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(extractIncompatibleSlotsError(cliOutput)).toMatchInlineSnapshot(`
"The following layouts have parallel route slots that cannot render the same URLs:
app/layout.tsx
- /bar is missing a matching page or default.tsx in @left
- /foo is missing a matching page or default.tsx in @right
Every URL matched by one slot must have a matching page or default.tsx in every sibling slot."
`)
// The structural diagnostic should be emitted before the loader-tree
// invariant that guards the pruning implementation.
expect(stripAnsi(cliOutput)).not.toContain(
'strict route matching retained the incomplete route matcher'
)
}
})
})
function extractIncompatibleSlotsError(output: string): string {
const normalizedOutput = stripAnsi(output)
const start = normalizedOutput.indexOf(
'The following layouts have parallel route slots that cannot render the same URLs:'
)
const finalLine =
'Every URL matched by one slot must have a matching page or default.tsx in every sibling slot.'
const end = normalizedOutput.indexOf(finalLine, start)
expect(start).not.toBe(-1)
expect(end).not.toBe(-1)
return normalizedOutput.slice(start, end + finalLine.length)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
strictRouteMatching: true,
},
}
module.exports = nextConfig
......@@ -15,43 +15,34 @@ describe('unmatched-app-pages', () => {
await next.start()
const browser = await next.browser('/')
// This fixture also contains incompatible slot topology. Once that
// validation is enabled it is the more actionable primary dev error;
// production below still verifies that every unmatched page is reported.
if (isTurbopack) {
await expect({ browser, next }).toDisplayRedbox(`
{
"description": "Unmatched app pages",
"description": "Parallel route slots cannot render the same URLs",
"environmentLabel": null,
"label": "Build Error",
"source": "./app/(pruning-group)/grouped/[...slug]/page.tsx
Error: Unmatched app pages
The following page files do not match any complete route:
- app/(pruning-group)/grouped/[...slug]/page.tsx
- app/declared-children/@panel/details/page.tsx
- app/disagreeing-slots/@first/foo/page.tsx
- app/disagreeing-slots/@second/bar/page.tsx
- app/disagreeing-slots/[...slug]/page.tsx
- app/nested-parallel/@outer/[...slug]/page.tsx
- app/nested-parallel/[...slug]/page.tsx
- app/optional-catchall/[[...slug]]/page.tsx
Every page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages.",
"source": "./app/declared-children/layout.tsx
Error: Parallel route slots cannot render the same URLs
The following layouts have parallel route slots that cannot render the same URLs:
app/declared-children/layout.tsx
- /declared-children/details is missing a matching page or default.tsx in children
Every URL matched by one slot must have a matching page or default.tsx in every sibling slot.",
"stack": [],
}
`)
} else {
await expect({ browser, next }).toDisplayRedbox(`
{
"description": "- app/(pruning-group)/grouped/[...slug]/page.tsx",
"description": "app/declared-children/layout.tsx",
"environmentLabel": null,
"label": "Build Error",
"source": "The following page files do not match any complete route:
- app/(pruning-group)/grouped/[...slug]/page.tsx
- app/declared-children/@panel/details/page.tsx
- app/disagreeing-slots/@first/foo/page.tsx
- app/disagreeing-slots/@second/bar/page.tsx
- app/disagreeing-slots/[...slug]/page.tsx
- app/nested-parallel/@outer/[...slug]/page.tsx
- app/nested-parallel/[...slug]/page.tsx
- app/optional-catchall/[[...slug]]/page.tsx
Every page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages.",
"source": "The following layouts have parallel route slots that cannot render the same URLs:
app/declared-children/layout.tsx
- /declared-children/details is missing a matching page or default.tsx in children
Every URL matched by one slot must have a matching page or default.tsx in every sibling slot.",
"stack": [],
}
`)
......
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