Unverified Commit 96f545ae authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: don't inherit API route config from parent layouts (#100243)

Basically reverts https://github.com/vercel/next.js/pull/63683

API routes don't have "parent layouts" and shouldn't inherit their
config from anywhere
parent 7525c5d3
...@@ -32,8 +32,6 @@ use next_core::{ ...@@ -32,8 +32,6 @@ use next_core::{
}, },
next_server_component::NextServerComponentTransition, next_server_component::NextServerComponentTransition,
next_server_utility::{NEXT_SERVER_UTILITY_MERGE_TAG, NextServerUtilityTransition}, next_server_utility::{NEXT_SERVER_UTILITY_MERGE_TAG, NextServerUtilityTransition},
parse_segment_config_from_source,
segment_config::{NextSegmentConfig, ParseSegmentMode},
util::{NextRuntime, app_function_name, module_styles_rule_condition, styles_rule_condition}, util::{NextRuntime, app_function_name, module_styles_rule_condition, styles_rule_condition},
}; };
use smallvec::smallvec; use smallvec::smallvec;
...@@ -1079,16 +1077,11 @@ pub fn app_entry_point_to_route( ...@@ -1079,16 +1077,11 @@ pub fn app_entry_point_to_route(
}) })
.collect(), .collect(),
), ),
AppEntrypoint::AppRoute { AppEntrypoint::AppRoute { page, path, .. } => Route::AppRoute {
page,
path,
root_layouts,
..
} => Route::AppRoute {
original_name: page.to_string().into(), original_name: page.to_string().into(),
endpoint: ResolvedVc::upcast( endpoint: ResolvedVc::upcast(
AppEndpoint { AppEndpoint {
ty: AppEndpointType::Route { path, root_layouts }, ty: AppEndpointType::Route { path },
app_project, app_project,
page, page,
} }
...@@ -1129,7 +1122,6 @@ enum AppEndpointType { ...@@ -1129,7 +1122,6 @@ enum AppEndpointType {
}, },
Route { Route {
path: FileSystemPath, path: FileSystemPath,
root_layouts: ResolvedVc<FileSystemPathVec>,
}, },
Metadata { Metadata {
metadata: MetadataItem, metadata: MetadataItem,
...@@ -1161,31 +1153,16 @@ impl AppEndpoint { ...@@ -1161,31 +1153,16 @@ impl AppEndpoint {
async fn app_route_entry( async fn app_route_entry(
&self, &self,
path: FileSystemPath, path: FileSystemPath,
root_layouts: Vc<FileSystemPathVec>,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
) -> Result<Vc<AppEntry>> { ) -> Result<Vc<AppEntry>> {
let root_layouts = root_layouts.await?;
let config = if root_layouts.is_empty() {
None
} else {
let mut config = NextSegmentConfig::default();
for layout in root_layouts.iter().rev() {
let source = Vc::upcast(FileSource::new(layout.clone()));
let layout_config = parse_segment_config_from_source(source, ParseSegmentMode::App);
config.apply_parent_config(&*layout_config.await?);
}
Some(config.cell())
};
Ok(get_app_route_entry( Ok(get_app_route_entry(
self.app_project.route_module_context(), self.app_project.route_module_context(),
self.app_project.edge_route_module_context(), self.app_project.edge_route_module_context(),
Vc::upcast(FileSource::new(path)), Vc::upcast(FileSource::new(path)),
self.page.clone(), self.page.clone(),
self.app_project.project().project_path().owned().await?, self.app_project.project().project_path().owned().await?,
config, // Route Handlers only use their own exports, not ancestor layout configuration.
None,
next_config, next_config,
)) ))
} }
...@@ -1214,9 +1191,7 @@ impl AppEndpoint { ...@@ -1214,9 +1191,7 @@ impl AppEndpoint {
let next_config = self.await?.app_project.project().next_config(); let next_config = self.await?.app_project.project().next_config();
let app_entry = match &this.ty { let app_entry = match &this.ty {
AppEndpointType::Page { loader_tree, .. } => self.app_page_entry(**loader_tree), AppEndpointType::Page { loader_tree, .. } => self.app_page_entry(**loader_tree),
AppEndpointType::Route { path, root_layouts } => { AppEndpointType::Route { path } => self.app_route_entry(path.clone(), next_config),
self.app_route_entry(path.clone(), **root_layouts, next_config)
}
AppEndpointType::Metadata { metadata } => { AppEndpointType::Metadata { metadata } => {
self.app_metadata_entry(metadata.clone(), next_config) self.app_metadata_entry(metadata.clone(), next_config)
} }
......
...@@ -693,7 +693,6 @@ pub enum Entrypoint { ...@@ -693,7 +693,6 @@ pub enum Entrypoint {
AppRoute { AppRoute {
page: AppPage, page: AppPage,
path: FileSystemPath, path: FileSystemPath,
root_layouts: ResolvedVc<FileSystemPathVec>,
root_params: ResolvedVc<RootParamVecOption>, root_params: ResolvedVc<RootParamVecOption>,
}, },
AppMetadata { AppMetadata {
...@@ -854,7 +853,6 @@ fn add_app_route( ...@@ -854,7 +853,6 @@ fn add_app_route(
result: &mut FxIndexMap<AppPath, Entrypoint>, result: &mut FxIndexMap<AppPath, Entrypoint>,
page: AppPage, page: AppPage,
path: FileSystemPath, path: FileSystemPath,
root_layouts: ResolvedVc<FileSystemPathVec>,
root_params: ResolvedVc<RootParamVecOption>, root_params: ResolvedVc<RootParamVecOption>,
) { ) {
let e = match result.entry(page.clone().into()) { let e = match result.entry(page.clone().into()) {
...@@ -863,7 +861,6 @@ fn add_app_route( ...@@ -863,7 +861,6 @@ fn add_app_route(
e.insert(Entrypoint::AppRoute { e.insert(Entrypoint::AppRoute {
page, page,
path, path,
root_layouts,
root_params, root_params,
}); });
return; return;
...@@ -2266,7 +2263,6 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -2266,7 +2263,6 @@ async fn directory_tree_to_entrypoints_internal_untraced(
&mut result, &mut result,
app_page.complete(PageType::Route)?, app_page.complete(PageType::Route)?,
route.clone(), route.clone(),
root_layouts,
root_params, root_params,
); );
} }
...@@ -2609,7 +2605,6 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -2609,7 +2605,6 @@ async fn directory_tree_to_entrypoints_internal_untraced(
Entrypoint::AppRoute { Entrypoint::AppRoute {
page, page,
path, path,
root_layouts,
root_params, root_params,
} => { } => {
add_app_route( add_app_route(
...@@ -2617,7 +2612,6 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -2617,7 +2612,6 @@ async fn directory_tree_to_entrypoints_internal_untraced(
&mut result, &mut result,
page.clone(), page.clone(),
path.clone(), path.clone(),
*root_layouts,
*root_params, *root_params,
); );
} }
......
...@@ -106,6 +106,7 @@ ...@@ -106,6 +106,7 @@
"test/e2e/app-dir/actions/app-action-size-limit-invalid-node-middleware.test.ts", "test/e2e/app-dir/actions/app-action-size-limit-invalid-node-middleware.test.ts",
"test/e2e/app-dir/actions/app-action-size-limit-invalid.test.ts", "test/e2e/app-dir/actions/app-action-size-limit-invalid.test.ts",
"test/e2e/app-dir/actions/app-action.test.ts", "test/e2e/app-dir/actions/app-action.test.ts",
"test/e2e/app-dir/adapter-dynamic-metadata-runtime/adapter-dynamic-metadata-runtime.test.ts",
"test/e2e/app-dir/app-a11y/index.test.ts", "test/e2e/app-dir/app-a11y/index.test.ts",
"test/e2e/app-dir/app-catch-all-optional/app-catch-all-optional.test.ts", "test/e2e/app-dir/app-catch-all-optional/app-catch-all-optional.test.ts",
"test/e2e/app-dir/app-client-cache/client-cache.defaults.test.ts", "test/e2e/app-dir/app-client-cache/client-cache.defaults.test.ts",
......
import type { NextAdapter } from 'next'
import { nextTestSetup } from 'e2e-utils'
describe('adapter-dynamic-metadata-runtime', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// The custom adapter's build output is only available in local production mode.
// @force-gate start
it('should preserve runtime from the original metadata source', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
expect(
outputs.appRoutes.find((item) => item.pathname === '/robots.txt')
).toMatchObject({ runtime: 'edge' })
expect(
outputs.appRoutes.find((item) => item.pathname === '/sitemap.xml')
).toMatchObject({ runtime: 'nodejs' })
})
it('should serve dynamic metadata routes with explicit runtimes', async () => {
const robots = await next.fetch('/robots.txt')
expect(robots.status).toBe(200)
expect(robots.headers.get('content-type')).toContain('text/plain')
expect(await robots.text()).toContain('User-Agent: *')
const sitemap = await next.fetch('/sitemap.xml')
expect(sitemap.status).toBe(200)
expect(sitemap.headers.get('content-type')).toBe('application/xml')
expect(await sitemap.text()).toContain('<urlset')
})
})
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import type { MetadataRoute } from 'next'
import { connection } from 'next/server'
export const runtime = 'edge'
export default async function robots(): Promise<MetadataRoute.Robots> {
await connection()
return {
rules: {
userAgent: '*',
allow: '/',
},
sitemap: 'https://example.com/sitemap.xml',
}
}
import type { MetadataRoute } from 'next'
import { connection } from 'next/server'
export const runtime = 'nodejs'
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
await connection()
return [
{
url: 'https://example.com',
},
]
}
import fs from 'fs'
/** @type {import('next').NextAdapter} */
const adapter = {
name: 'adapter-dynamic-metadata-runtime',
onBuildComplete: async (ctx) => {
await fs.promises.writeFile(
'build-complete.json',
JSON.stringify(ctx, null, 2)
)
},
}
export default adapter
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
if (!process.env.NEXT_ADAPTER_PATH && process.env.NEXT_ENABLE_ADAPTER !== '0') {
nextConfig.adapterPath = require.resolve('./my-adapter.mjs')
}
module.exports = nextConfig
...@@ -39,6 +39,21 @@ describe('adapter-dynamic-metadata', () => { ...@@ -39,6 +39,21 @@ describe('adapter-dynamic-metadata', () => {
expect(appRoute?.runtime).toBe('nodejs') expect(appRoute?.runtime).toBe('nodejs')
} }
}) })
it('should preserve segment config from the original metadata source', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
expect(
outputs.appRoutes.find((item) => item.pathname === '/sitemap.xml')
).toMatchObject({
runtime: 'nodejs',
config: {
maxDuration: 42,
preferredRegion: ['iad1', 'sfo1'],
},
})
})
} }
it('should serve dynamic metadata routes', async () => { it('should serve dynamic metadata routes', async () => {
......
import type { MetadataRoute } from 'next' import type { MetadataRoute } from 'next'
import { connection } from 'next/server' import { connection } from 'next/server'
export const maxDuration = 42
export const preferredRegion = ['iad1', 'sfo1']
export default async function sitemap(): Promise<MetadataRoute.Sitemap> { export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
await connection() await connection()
......
...@@ -239,9 +239,6 @@ describe('segment-config-precedence', () => { ...@@ -239,9 +239,6 @@ describe('segment-config-precedence', () => {
runtime: 'nodejs', runtime: 'nodejs',
config: { regions: ['sfo1'], maxDuration: 0 }, config: { regions: ['sfo1'], maxDuration: 0 },
}, },
// TODO: Stop Turbopack inheriting route handler runtime and regions from layouts.
...(!process.env.IS_TURBOPACK_TEST
? [
{ {
route: '/config-handler/undefined', route: '/config-handler/undefined',
runtime: 'nodejs', runtime: 'nodejs',
...@@ -257,8 +254,6 @@ describe('segment-config-precedence', () => { ...@@ -257,8 +254,6 @@ describe('segment-config-precedence', () => {
runtime: 'edge', runtime: 'edge',
config: {}, config: {},
}, },
]
: []),
])( ])(
'uses route handler exports without inheriting page layouts: $route', 'uses route handler exports without inheriting page layouts: $route',
async ({ route, runtime, config }) => { async ({ route, runtime, config }) => {
......
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