Unverified Commit 80340422 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add compiler error for conflicting App Router and Pages Router in Turbopack (#62531)

## What?

Working on fixing `test/e2e/conflicting-app-page-error`, this adds a
compiler error for the case where App Router routes conflict with Pages
Router routes. It's not 1:1 the same error as in webpack because in the
webpack version we hijacked the App Router resolving logic to assume
there's a certain set of paths, where Turbopack has the full route to
route tree resolving implementation which doesn't assume there's a
single page that can be resolved.

The tests are updated to reflect this change.


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

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

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

### Fixing a bug

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

### Adding a feature

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


## For Maintainers

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

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Closes NEXT-2592
parent d12693e7
...@@ -40,6 +40,7 @@ use turbopack_binding::{ ...@@ -40,6 +40,7 @@ use turbopack_binding::{
context::AssetContext, context::AssetContext,
diagnostics::DiagnosticExt, diagnostics::DiagnosticExt,
file_source::FileSource, file_source::FileSource,
issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString},
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
resolve::{find_context_file, FindContextFileResult}, resolve::{find_context_file, FindContextFileResult},
source::Source, source::Source,
...@@ -347,6 +348,42 @@ impl ProjectDefineEnv { ...@@ -347,6 +348,42 @@ impl ProjectDefineEnv {
} }
} }
#[turbo_tasks::value(shared)]
struct ConflictIssue {
path: Vc<FileSystemPath>,
title: Vc<StyledString>,
description: Vc<StyledString>,
severity: Vc<IssueSeverity>,
}
#[turbo_tasks::value_impl]
impl Issue for ConflictIssue {
#[turbo_tasks::function]
fn stage(&self) -> Vc<IssueStage> {
IssueStage::AppStructure.cell()
}
#[turbo_tasks::function]
fn severity(&self) -> Vc<IssueSeverity> {
self.severity
}
#[turbo_tasks::function]
fn file_path(&self) -> Vc<FileSystemPath> {
self.path
}
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
self.title
}
#[turbo_tasks::function]
fn description(&self) -> Vc<OptionStyledString> {
Vc::cell(Some(self.description))
}
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Project { impl Project {
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -639,6 +676,24 @@ impl Project { ...@@ -639,6 +676,24 @@ impl Project {
for (pathname, page_route) in pages_project.routes().await?.iter() { for (pathname, page_route) in pages_project.routes().await?.iter() {
match routes.entry(pathname.clone()) { match routes.entry(pathname.clone()) {
Entry::Occupied(mut entry) => { Entry::Occupied(mut entry) => {
ConflictIssue {
path: self.project_path(),
title: StyledString::Text(
format!("App Router and Pages Router both match path: {}", pathname)
.to_string(),
)
.cell(),
description: StyledString::Text(
"Next.js does not support having both App Router and Pages Router \
routes matching the same path. Please remove one of the conflicting \
routes."
.to_string(),
)
.cell(),
severity: IssueSeverity::Error.cell(),
}
.cell()
.emit();
*entry.get_mut() = Route::Conflict; *entry.get_mut() = Route::Conflict;
} }
Entry::Vacant(entry) => { Entry::Vacant(entry) => {
......
...@@ -1017,18 +1017,21 @@ export default async function build( ...@@ -1017,18 +1017,21 @@ export default async function build(
app: appPaths.length > 0 ? appPaths : undefined, app: appPaths.length > 0 ? appPaths : undefined,
} }
const numConflictingAppPaths = conflictingAppPagePaths.length // Turbopack already handles conflicting app and page routes.
if (mappedAppPages && numConflictingAppPaths > 0) { if (!IS_TURBOPACK_BUILD) {
Log.error( const numConflictingAppPaths = conflictingAppPagePaths.length
`Conflicting app and page file${ if (mappedAppPages && numConflictingAppPaths > 0) {
numConflictingAppPaths === 1 ? ' was' : 's were' Log.error(
} found, please remove the conflicting files to continue:` `Conflicting app and page file${
) numConflictingAppPaths === 1 ? ' was' : 's were'
for (const [pagePath, appPath] of conflictingAppPagePaths) { } found, please remove the conflicting files to continue:`
Log.error(` "${pagePath}" - "${appPath}"`) )
for (const [pagePath, appPath] of conflictingAppPagePaths) {
Log.error(` "${pagePath}" - "${appPath}"`)
}
await telemetry.flush()
process.exit(1)
} }
await telemetry.flush()
process.exit(1)
} }
const conflictingPublicFiles: string[] = [] const conflictingPublicFiles: string[] = []
...@@ -1335,8 +1338,6 @@ export default async function build( ...@@ -1335,8 +1338,6 @@ export default async function build(
throw new Error("next build doesn't support turbopack yet") throw new Error("next build doesn't support turbopack yet")
} }
// TODO: Without NODE_ENV=development React will error that the RSC payload was rendered using development React while renderToHTML is called on the production React.
// This is caused by Turbopack not having the production build option yet.
const startTime = process.hrtime() const startTime = process.hrtime()
const bindings = await loadBindings(config?.experimental?.useWasmBinary) const bindings = await loadBindings(config?.experimental?.useWasmBinary)
const dev = false const dev = false
...@@ -1353,7 +1354,6 @@ export default async function build( ...@@ -1353,7 +1354,6 @@ export default async function build(
allowedRevalidateHeaderKeys: undefined, allowedRevalidateHeaderKeys: undefined,
clientRouterFilters: undefined, clientRouterFilters: undefined,
config, config,
// When passing `false` you get `react.jsxDEV is not a function`
dev, dev,
distDir, distDir,
fetchCacheKeyPrefix: undefined, fetchCacheKeyPrefix: undefined,
......
import { import {
getRedboxHeader, getRedboxHeader,
hasRedbox, hasRedbox,
check,
getRedboxSource, getRedboxSource,
retry,
} from 'next-test-utils' } from 'next-test-utils'
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
...@@ -17,15 +17,24 @@ createNextDescribe( ...@@ -17,15 +17,24 @@ createNextDescribe(
if (isNextStart) { if (isNextStart) {
it('should print error for conflicting app/page', async () => { it('should print error for conflicting app/page', async () => {
const { cliOutput } = await next.build() const { cliOutput } = await next.build()
expect(cliOutput).toMatch( if (process.env.TURBOPACK) {
/Conflicting app and page files? (were|was) found/ expect(cliOutput).toContain(
) 'App Router and Pages Router both match path: /'
)
for (const [pagePath, appPath] of [ expect(cliOutput).toContain(
['pages/index.js', 'app/page.js'], 'App Router and Pages Router both match path: /another'
['pages/another.js', 'app/another/page.js'], )
]) { } else {
expect(cliOutput).toContain(`"${pagePath}" - "${appPath}"`) expect(cliOutput).toMatch(
/Conflicting app and page files? (were|was) found/
)
for (const [pagePath, appPath] of [
['pages/index.js', 'app/page.js'],
['pages/another.js', 'app/another/page.js'],
]) {
expect(cliOutput).toContain(`"${pagePath}" - "${appPath}"`)
}
} }
expect(cliOutput).not.toContain('/non-conflict-pages') expect(cliOutput).not.toContain('/non-conflict-pages')
...@@ -34,19 +43,21 @@ createNextDescribe( ...@@ -34,19 +43,21 @@ createNextDescribe(
} }
async function containConflictsError(browser, conflicts) { async function containConflictsError(browser, conflicts) {
await check(async () => { await retry(async () => {
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
const redboxSource = await getRedboxSource(browser) const redboxSource = await getRedboxSource(browser)
expect(redboxSource).toMatch( if (process.env.TURBOPACK) {
/Conflicting app and page files? (were|was) found, please remove the conflicting files to continue:/ expect(redboxSource).toContain(
) 'App Router and Pages Router both match path:'
)
for (const pair of conflicts) {
expect(redboxSource).toContain(`"${pair[0]}" - "${pair[1]}"`)
} }
return 'success' if (!process.env.TURBOPACK) {
}, /success/) for (const pair of conflicts) {
expect(redboxSource).toContain(`"${pair[0]}" - "${pair[1]}"`)
}
}
})
} }
if (isNextDev) { if (isNextDev) {
......
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