Unverified Commit c6dd32c2 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Turbopack: Add `--debug-build-paths` support to filter routes (#88655)

Add support for the `--debug-build-paths` flag in Turbopack builds. Previously this flag only affected which routes were prerendered (statically generated), but the bundler still compiled all routes.

Now routes are filtered early in `Project::entrypoints()`, so excluded routes are never compiled by Turbopack. Framework routes like `/_not-found` and `/_error` are always included to ensure the runtime works correctly.

This significantly reduces build times in large apps when building individual routes for debugging purposes. It also allows us to exclude building incompatible paths in end-to-end tests depending on whether `__NEXT_CACHE_COMPONENTS` is defined or not (see upstack PR).
parent d56ed7bb
......@@ -48,6 +48,7 @@ export default globalIgnores([
'examples/with-typescript-graphql/lib/gql/',
'test/development/basic/hmr/components/parse-error.js',
'test/development/mcp-server/fixtures/default-template/app/build-error/page.tsx',
'test/production/debug-build-path/fixtures/with-compile-error/app/broken/page.tsx',
'packages/next-swc/docs/assets/**/*',
'test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/sourcemapped.js',
'test/e2e/app-dir/server-source-maps/fixtures/default/external-pkg/sourcemapped.js',
......
......@@ -43,6 +43,7 @@ packages/next-env/**/*.d.ts
test/**/out/**
test/development/basic/hmr/components/parse-error.js
test/production/debug-build-path/fixtures/with-compile-error/app/broken/page.tsx
bench/nested-deps/pages/**/*
bench/nested-deps/components/**/*
......
......@@ -18,8 +18,8 @@ use next_api::{
RouteOperation,
},
project::{
DefineEnv, DraftModeOptions, PartialProjectOptions, Project, ProjectContainer,
ProjectOptions, WatchOptions,
DebugBuildPaths, DefineEnv, DraftModeOptions, PartialProjectOptions, Project,
ProjectContainer, ProjectOptions, WatchOptions,
},
route::Endpoint,
routes_hashes_manifest::routes_hashes_manifest_asset_if_enabled,
......@@ -186,6 +186,10 @@ pub struct NapiProjectOptions {
/// The version of Node.js that is available/currently running.
pub current_node_js_version: RcStr,
/// Debug build paths for selective builds.
/// When set, only routes matching these paths will be included in the build.
pub debug_build_paths: Option<NapiDebugBuildPaths>,
}
/// [NapiProjectOptions] with all fields optional.
......@@ -291,6 +295,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
no_mangling,
write_routes_hashes_manifest,
current_node_js_version,
debug_build_paths,
} = val;
ProjectOptions {
root_path,
......@@ -307,6 +312,10 @@ impl From<NapiProjectOptions> for ProjectOptions {
no_mangling,
write_routes_hashes_manifest,
current_node_js_version,
debug_build_paths: debug_build_paths.map(|p| DebugBuildPaths {
app: p.app,
pages: p.pages,
}),
}
}
}
......@@ -342,6 +351,7 @@ impl From<NapiPartialProjectOptions> for PartialProjectOptions {
browserslist_query,
no_mangling,
write_routes_hashes_manifest,
debug_build_paths: None,
}
}
}
......@@ -968,6 +978,13 @@ struct AllWrittenEntrypointsWithIssues {
effects: Arc<Effects>,
}
#[napi(object)]
#[derive(Clone, Debug)]
pub struct NapiDebugBuildPaths {
pub app: Vec<RcStr>,
pub pages: Vec<RcStr>,
}
#[tracing::instrument(level = "info", name = "write all entrypoints to disk", skip_all)]
#[napi]
pub async fn project_write_all_entrypoints_to_disk(
......
......@@ -25,7 +25,7 @@ use next_core::{
segment_config::ParseSegmentMode,
util::{NextRuntime, OptionEnvMap},
};
use rustc_hash::FxHashMap;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use tracing::{Instrument, field::Empty};
use turbo_rcstr::{RcStr, rcstr};
......@@ -144,6 +144,69 @@ pub struct WatchOptions {
pub poll_interval: Option<Duration>,
}
#[derive(
Debug,
Default,
Serialize,
Deserialize,
Clone,
TaskInput,
PartialEq,
Eq,
Hash,
TraceRawVcs,
NonLocalValue,
OperationValue,
Encode,
Decode,
)]
#[serde(rename_all = "camelCase")]
pub struct DebugBuildPaths {
pub app: Vec<RcStr>,
pub pages: Vec<RcStr>,
}
/// Pre-converted route keys from debug build paths for O(1) lookups.
struct DebugBuildPathsRouteKeys {
app: FxHashSet<RcStr>,
pages: FxHashSet<RcStr>,
}
impl DebugBuildPathsRouteKeys {
fn from_debug_build_paths(paths: &DebugBuildPaths) -> Self {
Self {
app: paths
.app
.iter()
.map(|path| {
// App router: "/blog/[slug]/page.tsx" -> "/blog/[slug]"
if let Some(last_slash_idx) = path.rfind('/') {
if last_slash_idx == 0 {
"/".into() // Root: "/page.tsx" -> "/"
} else {
path[..last_slash_idx].into()
}
} else {
path.clone()
}
})
.collect(),
pages: paths
.pages
.iter()
.map(|path| {
// Pages router: "/foo.tsx" -> "/foo"
if let Some(dot_idx) = path.rfind('.') {
path[..dot_idx].into()
} else {
path.clone()
}
})
.collect(),
}
}
}
#[derive(
Debug,
Serialize,
......@@ -208,6 +271,10 @@ pub struct ProjectOptions {
/// The version of Node.js that is available/currently running.
pub current_node_js_version: RcStr,
/// Debug build paths for selective builds.
/// When set, only routes matching these paths will be included in the build.
pub debug_build_paths: Option<DebugBuildPaths>,
}
pub struct PartialProjectOptions {
......@@ -253,6 +320,10 @@ pub struct PartialProjectOptions {
/// Whether to write the route hashes manifest.
pub write_routes_hashes_manifest: Option<bool>,
/// Debug build paths for selective builds.
/// When set, only routes matching these paths will be included in the build.
pub debug_build_paths: Option<DebugBuildPaths>,
}
#[derive(
......@@ -405,6 +476,24 @@ fn define_env_diff_report(old: &DefineEnv, new: &DefineEnv) -> String {
report
}
/// Checks if an app router route should be included based on pre-converted route keys.
fn should_include_app_route(route_key: &RcStr, route_keys: &FxHashSet<RcStr>) -> bool {
// Special app router framework routes
if matches!(route_key.as_str(), "/_not-found" | "/_global-error") {
return true;
}
route_keys.contains(route_key)
}
/// Checks if a pages router route should be included based on pre-converted route keys.
fn should_include_pages_route(route_key: &RcStr, route_keys: &FxHashSet<RcStr>) -> bool {
// Special pages router framework routes
if matches!(route_key.as_str(), "/_error" | "/_document" | "/_app") {
return true;
}
route_keys.contains(route_key)
}
impl ProjectContainer {
pub async fn initialize(self: ResolvedVc<Self>, options: ProjectOptions) -> Result<()> {
let span = tracing::info_span!(
......@@ -467,6 +556,7 @@ impl ProjectContainer {
browserslist_query,
no_mangling,
write_routes_hashes_manifest,
debug_build_paths,
} = options;
let resolved_self = self.to_resolved().await?;
......@@ -517,6 +607,9 @@ impl ProjectContainer {
if let Some(write_routes_hashes_manifest) = write_routes_hashes_manifest {
new_options.write_routes_hashes_manifest = write_routes_hashes_manifest;
}
if let Some(debug_build_paths) = debug_build_paths {
new_options.debug_build_paths = Some(debug_build_paths);
}
// TODO: Handle mode switch, should prevent mode being switched.
let watch = new_options.watch;
......@@ -583,6 +676,7 @@ impl ProjectContainer {
let no_mangling;
let write_routes_hashes_manifest;
let current_node_js_version;
let debug_build_paths;
{
let options = self.options_state.get();
let options = options
......@@ -607,6 +701,7 @@ impl ProjectContainer {
no_mangling = options.no_mangling;
write_routes_hashes_manifest = options.write_routes_hashes_manifest;
current_node_js_version = options.current_node_js_version.clone();
debug_build_paths = options.debug_build_paths.clone();
}
let dist_dir = next_config.dist_dir().owned().await?;
......@@ -633,6 +728,7 @@ impl ProjectContainer {
no_mangling,
write_routes_hashes_manifest,
current_node_js_version,
debug_build_paths,
}
.cell())
}
......@@ -723,6 +819,10 @@ pub struct Project {
write_routes_hashes_manifest: bool,
current_node_js_version: RcStr,
/// Debug build paths for selective builds.
/// When set, only routes matching these paths will be included in the build.
debug_build_paths: Option<DebugBuildPaths>,
}
#[turbo_tasks::value]
......@@ -1445,21 +1545,37 @@ impl Project {
pub async fn entrypoints(self: Vc<Self>) -> Result<Vc<Entrypoints>> {
self.collect_project_feature_telemetry().await?;
let this = self.await?;
let mut routes = FxIndexMap::default();
let app_project = self.app_project();
let pages_project = self.pages_project();
// Convert debug build paths to route keys once for O(1) lookups
let debug_build_paths_route_keys = this
.debug_build_paths
.as_ref()
.map(DebugBuildPathsRouteKeys::from_debug_build_paths);
if let Some(app_project) = &*app_project.await? {
let app_routes = app_project.routes();
routes.extend(
app_routes
.await?
.iter()
.filter(|(k, _)| {
debug_build_paths_route_keys
.as_ref()
.is_none_or(|keys| should_include_app_route(k, &keys.app))
})
.map(|(k, v)| (k.clone(), v.clone())),
);
}
for (pathname, page_route) in pages_project.routes().await?.iter() {
for (pathname, page_route) in pages_project.routes().await?.iter().filter(|(k, _)| {
debug_build_paths_route_keys
.as_ref()
.is_none_or(|keys| should_include_pages_route(k, &keys.pages))
}) {
match routes.entry(pathname.clone()) {
Entry::Occupied(mut entry) => {
ConflictIssue {
......
......@@ -184,6 +184,7 @@ fn main() {
no_mangling: false,
write_routes_hashes_manifest: false,
current_node_js_version: rcstr!("18.0.0"),
debug_build_paths: None,
};
let json = serde_json::to_string_pretty(&options).unwrap();
......
......@@ -96,4 +96,8 @@ export const NextBuildContext: Partial<{
isCompileMode?: boolean
debugPrerender: boolean
analyze: boolean
debugBuildPaths?: {
app: string[]
pages: string[]
}
}> = {}
......@@ -912,8 +912,7 @@ export default async function build(
bundler = Bundler.Turbopack,
experimentalBuildMode: 'default' | 'compile' | 'generate' | 'generate-env',
traceUploadUrl: string | undefined,
debugBuildAppPaths?: string[],
debugBuildPagePaths?: string[]
debugBuildPaths: { app: string[]; pages: string[] } | undefined
): Promise<void> {
const isCompileMode = experimentalBuildMode === 'compile'
const isGenerateMode = experimentalBuildMode === 'generate'
......@@ -936,6 +935,7 @@ export default async function build(
NextBuildContext.reactProductionProfiling = reactProductionProfiling
NextBuildContext.noMangling = noMangling
NextBuildContext.debugPrerender = debugPrerender
NextBuildContext.debugBuildPaths = debugBuildPaths
await nextBuildSpan.traceAsyncFn(async () => {
// attempt to load global env values so they are available in next.config.js
......@@ -1159,10 +1159,7 @@ export default async function build(
nextBuildSpan,
config,
cacheDir,
debugBuildPaths:
debugBuildAppPaths !== undefined || debugBuildPagePaths !== undefined
? { app: debugBuildAppPaths, pages: debugBuildPagePaths }
: undefined,
debugBuildPaths,
}
if (appDir && 'exportPathMap' in config) {
......@@ -1191,10 +1188,9 @@ export default async function build(
: []
// Apply debug build paths filter if specified
// If debugBuildPagePaths is defined (even if empty), only build specified pages
if (debugBuildPagePaths !== undefined) {
if (debugBuildPagePaths.length > 0) {
const debugPathsSet = new Set(debugBuildPagePaths)
if (debugBuildPaths) {
if (debugBuildPaths.pages.length > 0) {
const debugPathsSet = new Set(debugBuildPaths.pages)
pagesPaths = pagesPaths.filter((pagePath) =>
debugPathsSet.has(pagePath)
)
......@@ -1328,10 +1324,9 @@ export default async function build(
layoutPaths = result.layoutPaths
// Apply debug build paths filter if specified
// If debugBuildAppPaths is defined (even if empty), only build specified app paths
if (debugBuildAppPaths !== undefined) {
if (debugBuildAppPaths.length > 0) {
const debugPathsSet = new Set(debugBuildAppPaths)
if (debugBuildPaths) {
if (debugBuildPaths.app.length > 0) {
const debugPathsSet = new Set(debugBuildPaths.app)
appPaths = appPaths.filter((appPath) =>
debugPathsSet.has(appPath)
)
......
......@@ -159,6 +159,11 @@ export interface NapiProjectOptions {
writeRoutesHashesManifest: boolean
/** The version of Node.js that is available/currently running. */
currentNodeJsVersion: RcStr
/**
* Debug build paths for selective builds.
* When set, only routes matching these paths will be included in the build.
*/
debugBuildPaths?: NapiDebugBuildPaths
}
/** [NapiProjectOptions] with all fields optional. */
export interface NapiPartialProjectOptions {
......@@ -291,6 +296,10 @@ export interface NapiEntrypoints {
pagesAppEndpoint: ExternalObject<ExternalEndpoint>
pagesErrorEndpoint: ExternalObject<ExternalEndpoint>
}
export interface NapiDebugBuildPaths {
app: Array<RcStr>
pages: Array<RcStr>
}
export declare function projectWriteAllEntrypointsToDisk(
project: { __napiType: 'Project' },
appDirOnly: boolean
......
......@@ -84,6 +84,7 @@ export async function turbopackBuild(): Promise<{
writeRoutesHashesManifest:
!!process.env.NEXT_TURBOPACK_WRITE_ROUTES_HASHES_MANIFEST,
currentNodeJsVersion,
debugBuildPaths: NextBuildContext.debugBuildPaths,
},
{
persistentCaching,
......
......@@ -32,7 +32,7 @@ function verifyTypeScriptSetup(
isolatedDevBuild: boolean | undefined,
appDir: string | undefined,
pagesDir: string | undefined,
debugBuildPaths: { app?: string[]; pages?: string[] } | undefined
debugBuildPaths: { app: string[]; pages: string[] } | undefined
) {
const typeCheckWorker = new Worker(
require.resolve('../lib/verify-typescript-setup'),
......@@ -93,7 +93,7 @@ export async function startTypeChecking({
pagesDir?: string
telemetry: Telemetry
appDir?: string
debugBuildPaths?: { app?: string[]; pages?: string[] }
debugBuildPaths: { app: string[]; pages: string[] } | undefined
}) {
const ignoreTypeScriptErrors = Boolean(config.typescript.ignoreBuildErrors)
......
......@@ -103,8 +103,7 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
}
// Resolve selective build paths
let resolvedAppPaths: string[] | undefined
let resolvedPagePaths: string[] | undefined
let resolvedBuildPaths: { app: string[]; pages: string[] } | undefined
if (debugBuildPaths) {
try {
......@@ -112,9 +111,10 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
if (patterns.length > 0) {
const resolved = await resolveBuildPaths(patterns, dir)
// Pass empty arrays to indicate "build nothing" vs undefined for "build everything"
resolvedAppPaths = resolved.appPaths
resolvedPagePaths = resolved.pagePaths
resolvedBuildPaths = {
app: resolved.appPaths,
pages: resolved.pagePaths,
}
}
} catch (err) {
printAndExit(
......@@ -134,8 +134,7 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
bundler,
experimentalBuildMode,
traceUploadUrl,
resolvedAppPaths,
resolvedPagePaths
resolvedBuildPaths
)
.catch((err) => {
if (experimentalDebugMemoryUsage) {
......
......@@ -96,9 +96,11 @@ export async function resolveBuildPaths(
/**
* Categorizes a file path to either app or pages router based on its prefix.
* For app router, only route-defining files (page.*, route.*) are included.
*
* Examples:
* - "app/page.tsx" → appPaths.add("/page.tsx")
* - "app/layout.tsx" → skipped (not a route file)
* - "pages/index.tsx" → pagePaths.add("/index.tsx")
*/
function categorizeAndAddPath(
......@@ -109,7 +111,10 @@ function categorizeAndAddPath(
const normalized = filePath.replace(/\\/g, '/')
if (normalized.startsWith('app/')) {
appPaths.add('/' + normalized.slice(4))
// Only include route-defining files (page.* or route.*)
if (/\/(page|route)\.[^/]+$/.test(normalized)) {
appPaths.add('/' + normalized.slice(4))
}
} else if (normalized.startsWith('pages/')) {
pagePaths.add('/' + normalized.slice(6))
}
......
// This file has an intentional syntax error that will fail compilation
export default function BrokenPage() {
// Missing closing brace and invalid syntax
return <div>Broken {
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export default function ValidPage() {
return <div>Valid Page</div>
}
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