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
......@@ -527,6 +527,14 @@ impl AppPageLoaderTree {
true
}
fn contains_catchall_page(&self) -> bool {
(&*self.segment == "__PAGE__" && self.page.is_catchall())
|| self
.parallel_routes
.values()
.any(AppPageLoaderTree::contains_catchall_page)
}
fn is_builtin_not_found_default(&self, builtin_default: &FileSystemPath) -> bool {
&*self.segment == "__DEFAULT__"
&& self.modules.default.as_ref().is_some_and(|default| {
......@@ -562,6 +570,62 @@ impl AppPageLoaderTree {
})
}
fn collect_builtin_not_found_defaults(
&self,
builtin_default: &FileSystemPath,
declared_slots: &FxIndexMap<FileSystemPath, FxIndexSet<RcStr>>,
parent_layout: Option<&FileSystemPath>,
missing_slots: &mut FxIndexMap<FileSystemPath, FxIndexSet<RcStr>>,
) {
let owner_layout = self.modules.layout.as_ref().or(parent_layout);
for (slot, tree) in &self.parallel_routes {
if tree.is_builtin_not_found_default(builtin_default) {
if let Some(owner_layout) = owner_layout
&& declared_slots
.get(owner_layout)
.is_some_and(|slots| slots.contains(slot))
{
missing_slots
.entry(owner_layout.clone())
.or_default()
.insert(slot.clone());
}
} else {
tree.collect_builtin_not_found_defaults(
builtin_default,
declared_slots,
owner_layout,
missing_slots,
);
}
}
}
/// Returns true when one slot matches through a catch-all while a different slot at the same
/// level can only render Next.js' built-in not-found default.
fn has_unmatched_parallel_route(
&self,
builtin_default: &FileSystemPath,
declared_slots: &FxIndexMap<FileSystemPath, FxIndexSet<RcStr>>,
parent_layout: Option<&FileSystemPath>,
) -> bool {
let owner_layout = self.modules.layout.as_ref().or(parent_layout);
let slots_at_level = owner_layout.and_then(|layout| declared_slots.get(layout));
self.parallel_routes.iter().any(|(catchall_key, tree)| {
slots_at_level.is_some_and(|slots| slots.contains(catchall_key))
&& tree.contains_catchall_page()
&& self.parallel_routes.iter().any(|(default_key, tree)| {
default_key != catchall_key
&& slots_at_level.is_some_and(|slots| slots.contains(default_key))
&& tree.is_builtin_not_found_default(builtin_default)
})
}) || self.parallel_routes.values().any(|tree| {
tree.has_unmatched_parallel_route(builtin_default, declared_slots, owner_layout)
})
}
/// Returns true if this loader tree contains an intercepting route match.
pub fn is_intercepting(&self) -> bool {
if self.page.is_intercepting() && self.has_page() {
......@@ -948,26 +1012,77 @@ async fn directory_tree_to_entrypoints(
let plain_tree = directory_tree.into_plain().await?;
let mut declared_slots = FxIndexMap::default();
collect_declared_parallel_route_slots(&plain_tree, &mut declared_slots);
let mut retained_entrypoints = FxIndexMap::default();
let mut candidate_entrypoints = FxIndexMap::default();
// Loader trees built while walking a subtree may still contain temporary synthesized
// defaults that disappear when sibling pages are combined. Prune only the finalized root
// entrypoints so complete routes are never discarded based on an intermediate tree.
// defaults that disappear when sibling pages are combined. Inspect only the finalized root
// entrypoints so complete routes are never discarded based on an intermediate tree. This
// layer retains incomplete static matchers long enough to report their exact slot topology;
// incomplete catch-all matchers preserve the pruning behavior from the lower layer.
for (app_path, entrypoint) in entrypoints_ref.iter() {
let is_incomplete = match entrypoint {
Entrypoint::AppPage { loader_tree, .. } => loader_tree
.await?
.contains_declared_builtin_not_found_default(
&builtin_default,
&declared_slots,
None,
),
.has_unmatched_parallel_route(&builtin_default, &declared_slots, None),
_ => false,
};
if !is_incomplete {
candidate_entrypoints.insert(app_path.clone(), entrypoint.clone());
}
}
let mut incompatible_parallel_route_slots = Vec::new();
let mut retained_entrypoints = FxIndexMap::default();
// Report incomplete static matchers from their finalized loader trees, but still prune them
// from the matcher set. Interception routes intentionally use synthetic retain markers and
// therefore follow different reporting rules.
for (app_path, entrypoint) in &candidate_entrypoints {
let Entrypoint::AppPage { loader_tree, .. } = entrypoint else {
retained_entrypoints.insert(app_path.clone(), entrypoint.clone());
continue;
};
let loader_tree = loader_tree.await?;
if !loader_tree.contains_declared_builtin_not_found_default(
&builtin_default,
&declared_slots,
None,
) {
retained_entrypoints.insert(app_path.clone(), entrypoint.clone());
continue;
}
if app_path.intercepted_path().is_some() {
continue;
}
let mut missing_slots = FxIndexMap::default();
loader_tree.collect_builtin_not_found_defaults(
&builtin_default,
&declared_slots,
None,
&mut missing_slots,
);
if missing_slots.is_empty() {
bail!(
"Invariant: strict route matching retained the incomplete route matcher \
`{app_path}`"
);
}
incompatible_parallel_route_slots.extend(
missing_slots
.into_iter()
.map(|(layout, slots)| (layout, app_path.clone(), slots.into_iter().collect())),
);
}
if !incompatible_parallel_route_slots.is_empty() {
IncompatibleParallelRouteSlotsIssue {
app_dir: app_dir.clone(),
routes: incompatible_parallel_route_slots,
}
.resolved_cell()
.emit();
}
// This assertion is intentionally separate from the filtering condition above. It guards
......@@ -1063,6 +1178,93 @@ struct MissingCanonicalInterceptionRoutesIssue {
routes: Vec<(AppPath, AppPath, FileSystemPath)>,
}
#[turbo_tasks::value]
struct IncompatibleParallelRouteSlotsIssue {
app_dir: FileSystemPath,
routes: Vec<(FileSystemPath, AppPath, Vec<RcStr>)>,
}
#[async_trait]
#[turbo_tasks::value_impl]
impl Issue for IncompatibleParallelRouteSlotsIssue {
async fn file_path(&self) -> Result<FileSystemPath> {
Ok(self.routes[0].0.clone())
}
fn stage(&self) -> IssueStage {
IssueStage::AppStructure
}
fn severity(&self) -> IssueSeverity {
IssueSeverity::Error
}
async fn title(&self) -> Result<StyledString> {
Ok(StyledString::Text(rcstr!(
"Parallel route slots cannot render the same URLs"
)))
}
async fn description(&self) -> Result<Option<StyledString>> {
let mut routes_by_layout = FxIndexMap::<FileSystemPath, Vec<_>>::default();
for (layout, route, missing_slots) in &self.routes {
routes_by_layout
.entry(layout.clone())
.or_default()
.push((route.clone(), missing_slots.clone()));
}
let mut layouts = routes_by_layout
.into_iter()
.map(|(layout, mut routes)| {
routes.sort_by_cached_key(|(route, _)| route.to_string());
let layout_path = self
.app_dir
.get_path_to(&layout)
.expect("parallel route layout should be within the app directory")
.to_string();
let routes = routes
.into_iter()
.map(|(route, missing_slots)| {
let missing_slots = missing_slots
.iter()
.map(|slot| {
if &**slot == "children" {
slot.to_string()
} else {
format!("@{slot}")
}
})
.collect::<Vec<_>>()
.join(", ");
format!(
"- {route} is missing a matching page or default.tsx in \
{missing_slots}"
)
})
.collect::<Vec<_>>()
.join("\n");
(layout_path, routes)
})
.collect::<Vec<_>>();
layouts.sort_by(|a, b| a.0.cmp(&b.0));
let layouts = layouts
.into_iter()
.map(|(layout_path, routes)| format!("app/{layout_path}\n{routes}"))
.collect::<Vec<_>>()
.join("\n\n");
Ok(Some(StyledString::Text(
format!(
"The following layouts have parallel route slots that cannot render the same \
URLs:\n{layouts}\n\nEvery URL matched by one slot must have a matching page or \
default.tsx in every sibling slot."
)
.into(),
)))
}
}
#[async_trait]
#[turbo_tasks::value_impl]
impl Issue for MissingCanonicalInterceptionRoutesIssue {
......@@ -1449,7 +1651,6 @@ async fn directory_tree_to_loader_tree(
let plain_tree_vc = directory_tree.into_plain();
let plain_tree = &*plain_tree_vc.await?;
let strict_route_matching = *strict_route_matching.await?;
let mut missing_defaults = Vec::new();
let tree = directory_tree_to_loader_tree_internal(
app_dir.clone(),
......
......@@ -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)
}
......@@ -5,7 +5,9 @@ import {
isInterceptionRouteAppPath,
} from '../../../shared/lib/router/utils/interception-routes'
import {
UNDERSCORE_GLOBAL_ERROR_ROUTE,
UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../../../shared/lib/entry-constants'
......@@ -18,12 +20,28 @@ export type NormalizeCatchAllRoutesOptions = {
defaultAppPaths?: Iterable<string>
}
export type IncompatibleParallelRouteSlots = {
layoutPath: string
route: string
missingSlots: string[]
}
export type NormalizeCatchAllRoutesResult = {
unmatchedAppPages: string[]
incompatibleParallelRouteSlots: IncompatibleParallelRouteSlots[]
}
type ParallelRouteLevel = {
parentSegments: string[]
namedSlots: Set<string>
hasChildrenSlot: boolean
}
type ParallelRouteTopology = {
allAppPaths: Set<string>
levelsByParent: Map<string, ParallelRouteLevel>
}
const defaultNormalizer: AppPathNormalizer = {
normalize(pathname: string): string {
return normalizeAppPath(pathname).replace(/%5F/g, '_')
......@@ -36,7 +54,8 @@ const defaultNormalizer: AppPathNormalizer = {
* the catch-all. If it finds a match, it will add the catch-all to the parallel route's list of possible routes.
*
* @param appPaths The appPaths to transform
* @returns Page app paths that are not present in any retained matcher.
* @returns Page app paths that are not present in any retained matcher and
* incompatible static matchers found before they were pruned.
*/
export function normalizeCatchAllRoutes(
appPaths: Record<string, string[]>,
......@@ -45,13 +64,9 @@ export function normalizeCatchAllRoutes(
strictRouteMatching = false,
defaultAppPaths = [],
}: NormalizeCatchAllRoutesOptions = {}
): string[] {
): NormalizeCatchAllRoutesResult {
const pageAppPaths = strictRouteMatching
? new Set(
Object.values(appPaths)
.flat()
.filter((appPath) => appPath.endsWith('/page'))
)
? new Set(Object.values(appPaths).flat().filter(isUserAppPageRoute))
: undefined
const catchAllRoutes = [
...new Set(
......@@ -102,35 +117,248 @@ export function normalizeCatchAllRoutes(
}
if (strictRouteMatching) {
pruneUnrenderableRoutes(appPaths, defaultAppPaths)
const topology = createParallelRouteTopology(appPaths, defaultAppPaths)
pruneUnrenderableCatchAllRoutes(appPaths, topology)
const incompatibleParallelRouteSlots =
findIncompatibleParallelRouteSlotsWithTopology(appPaths, topology)
pruneUnrenderableRoutes(appPaths, topology)
const matchedAppPaths = new Set(Object.values(appPaths).flat())
return [...pageAppPaths!]
.filter((appPath) => !matchedAppPaths.has(appPath))
.sort()
return {
unmatchedAppPages: [...pageAppPaths!]
.filter((appPath) => !matchedAppPaths.has(appPath))
.sort(),
incompatibleParallelRouteSlots,
}
}
return {
unmatchedAppPages: [],
incompatibleParallelRouteSlots: [],
}
}
/**
* Finds ordinary route matchers that cannot construct every slot owned by a
* layout. Interception routes are partial updates and intentionally use
* different matching semantics.
*/
export function findIncompatibleParallelRouteSlots(
appPaths: Record<string, string[]>,
defaultAppPaths: Iterable<string> = []
): IncompatibleParallelRouteSlots[] {
return findIncompatibleParallelRouteSlotsWithTopology(
appPaths,
createParallelRouteTopology(appPaths, defaultAppPaths)
)
}
function findIncompatibleParallelRouteSlotsWithTopology(
appPaths: Record<string, string[]>,
{ allAppPaths, levelsByParent }: ParallelRouteTopology
): IncompatibleParallelRouteSlots[] {
const incompatibleRoutes: IncompatibleParallelRouteSlots[] = []
for (const [route, matchedAppPaths] of Object.entries(appPaths)) {
if (isBuiltin(route) || isInterceptionRouteAppPath(route)) continue
// Interception branches can be carried alongside an ordinary matcher, but
// they retain state instead of satisfying a hard-navigation slot.
const ordinaryAppPaths = matchedAppPaths.filter(
(appPath) =>
isUserAppPageRoute(appPath) && !isInterceptionRouteAppPath(appPath)
)
if (ordinaryAppPaths.length === 0) continue
for (const {
parentSegments,
namedSlots,
hasChildrenSlot,
} of levelsByParent.values()) {
if (
!ordinaryAppPaths.some((appPath) =>
hasPathPrefix(splitAppPath(appPath), parentSegments)
)
) {
continue
}
const siblingSlots = [
...(hasChildrenSlot ? ['children'] : []),
...namedSlots,
]
const missingSlots = siblingSlots.filter((slot) => {
const hasMatchedPage = ordinaryAppPaths.some((appPath) =>
isPathInSlot(appPath, parentSegments, slot)
)
const hasDefault = allAppPaths.has(
getDefaultAppPath(parentSegments, slot)
)
return !hasMatchedPage && !hasDefault
})
if (missingSlots.length > 0) {
incompatibleRoutes.push({
layoutPath: `/${parentSegments.join('/')}`,
route,
missingSlots: missingSlots.sort(),
})
}
}
}
return []
return incompatibleRoutes.sort((a, b) =>
a.layoutPath === b.layoutPath
? a.route.localeCompare(b.route)
: a.layoutPath.localeCompare(b.layoutPath)
)
}
function isBuiltin(appPath: string): boolean {
return (
appPath === UNDERSCORE_NOT_FOUND_ROUTE ||
appPath === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY ||
appPath === UNDERSCORE_GLOBAL_ERROR_ROUTE ||
appPath === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY
)
}
/**
* Removes routes that can never render because a declared slot at a matching
* layout level has neither a matching page nor an explicit default.
* Removes catch-all-derived routes that can never render because another slot
* at the same 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 pruneUnrenderableCatchAllRoutes(
appPaths: Record<string, string[]>,
{ allAppPaths, levelsByParent }: ParallelRouteTopology
) {
for (const [route, matchedAppPaths] of Object.entries(appPaths)) {
const catchAllAppPaths = matchedAppPaths.filter(
(appPath) => isUserAppPageRoute(appPath) && isCatchAll(appPath)
)
if (
catchAllAppPaths.some((catchAllAppPath) => {
const catchAllSegments = splitAppPath(catchAllAppPath).slice(0, -1)
const interceptionMarkerIndex = catchAllSegments.findIndex((segment) =>
INTERCEPTION_ROUTE_MARKERS.some((marker) =>
segment.startsWith(marker)
)
)
for (const {
parentSegments,
namedSlots,
hasChildrenSlot,
} of levelsByParent.values()) {
if (!hasPathPrefix(catchAllSegments, parentSegments)) continue
const catchAllSlot = getSlotAtParent(catchAllSegments, parentSegments)
const siblingSlots = [
...(hasChildrenSlot ? ['children'] : []),
...namedSlots,
]
// 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 =
interceptionMarkerIndex !== -1 &&
parentSegments.length <= interceptionMarkerIndex
for (const siblingSlot of siblingSlots) {
if (siblingSlot === catchAllSlot) continue
const hasMatchedPage = matchedAppPaths.some((appPath) =>
isPathInSlot(appPath, parentSegments, siblingSlot)
)
const hasDefault = allAppPaths.has(
getDefaultAppPath(parentSegments, siblingSlot)
)
if (
!hasMatchedPage &&
!hasDefault &&
!retainsInterceptionSiblings
) {
return true
}
}
}
return false
})
) {
const nonPageAppPaths = matchedAppPaths.filter(
(appPath) => !isUserAppPageRoute(appPath)
)
if (nonPageAppPaths.length === 0) {
delete appPaths[route]
} else {
appPaths[route] = nonPageAppPaths
}
}
}
}
/**
* Removes every route that cannot construct all slots at a matching layout
* level. Catch-all-derived routes are removed by the earlier pass so the
* caller can report only incompatible static matchers between the two passes.
*/
function pruneUnrenderableRoutes(
appPaths: Record<string, string[]>,
defaultAppPaths: Iterable<string>
{ allAppPaths, levelsByParent }: ParallelRouteTopology
) {
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 createParallelRouteTopology(
appPaths: Record<string, string[]>,
defaultAppPaths: Iterable<string>
): ParallelRouteTopology {
const allAppPaths = new Set([
...Object.values(appPaths).flat().filter(isUserAppPageRoute),
...Object.entries(appPaths)
.filter(([route]) => !isBuiltin(route))
.flatMap(([, matchedAppPaths]) => matchedAppPaths)
.filter(isUserAppPageRoute),
...[...defaultAppPaths].filter(
(appPath) => !isBuiltinAppPageEntry(appPath)
),
])
return {
allAppPaths,
levelsByParent: collectParallelRouteLevels(allAppPaths),
}
}
function collectParallelRouteLevels(
allAppPaths: Iterable<string>
): Map<string, ParallelRouteLevel> {
const levelsByParent = new Map<string, ParallelRouteLevel>()
for (const appPath of allAppPaths) {
......@@ -163,27 +391,7 @@ function pruneUnrenderableRoutes(
}
}
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
}
}
}
return levelsByParent
}
function isUserAppPageRoute(appPath: string): boolean {
......
......@@ -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