Unverified Commit cb1dbfb8 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

refactor: consume global-error from loader tree (#88437)

parent e78d35b3
......@@ -419,15 +419,6 @@ impl AppPageLoaderTreeBuilder {
let loader_tree = &*loader_tree.await?;
let modules = &loader_tree.modules;
// load global-error module
if let Some(global_error) = &modules.global_error {
let module = self
.base
.process_source(Vc::upcast(FileSource::new(global_error.clone())))
.to_resolved()
.await?;
self.base.inner_assets.insert(GLOBAL_ERROR.into(), module);
};
// load global-not-found module
if let Some(global_not_found) = &modules.global_not_found {
let module = self
......@@ -468,5 +459,4 @@ impl AppPageLoaderTreeModule {
}
}
pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR_MODULE";
pub const GLOBAL_NOT_FOUND: &str = "GLOBAL_NOT_FOUND_MODULE";
......@@ -1742,6 +1742,13 @@ async fn directory_tree_to_entrypoints_internal_untraced(
.join("dist/client/components/builtin/unauthorized.js")?,
);
}
if modules.global_error.is_none() {
modules.global_error = Some(
get_next_package(app_dir.clone())
.await?
.join("dist/client/components/builtin/global-error.js")?,
);
}
// Next.js has this logic in "collect-app-paths", where the root not-found page
// is considered as its own entry point.
......@@ -1843,7 +1850,9 @@ async fn directory_tree_to_entrypoints_internal_untraced(
// the build isn't app-only. If the build is app-only (no user pages/api), we should still
// expose the app global error so runtime errors render, but we shouldn't emit it otherwise.
if matches!(*next_mode.await?, NextMode::Build) {
// Use built-in global-error.js to create a `_global-error/page` route.
// Create a `_global-error/page` route using user's global-error.js or built-in
// fallback.
let next_package = get_next_package(app_dir.clone()).await?;
let global_error_tree = AppPageLoaderTree {
page: app_page.clone(),
segment: directory_name.clone(),
......@@ -1853,8 +1862,7 @@ async fn directory_tree_to_entrypoints_internal_untraced(
segment: rcstr!("__PAGE__"),
parallel_routes: FxIndexMap::default(),
modules: AppDirModules {
page: Some(get_next_package(app_dir.clone())
.await?
page: Some(next_package
.join("dist/client/components/builtin/app-error.js")?),
..Default::default()
},
......@@ -1862,7 +1870,12 @@ async fn directory_tree_to_entrypoints_internal_untraced(
static_siblings: Vec::new(),
}
},
modules: AppDirModules::default(),
// global-error is needed for getGlobalErrorStyles to work during rendering.
// Use user's custom global-error if defined, otherwise builtin fallback.
modules: AppDirModules {
global_error: modules.global_error.clone(),
..Default::default()
},
global_metadata,
static_siblings: Vec::new(),
}
......
......@@ -16,7 +16,7 @@ use turbopack_core::{
use turbopack_ecmascript::runtime_functions::{TURBOPACK_LOAD, TURBOPACK_REQUIRE};
use crate::{
app_page_loader_tree::{AppPageLoaderTreeModule, GLOBAL_ERROR},
app_page_loader_tree::AppPageLoaderTreeModule,
app_structure::AppPageLoaderTree,
next_app::{AppPage, AppPath, app_entry::AppEntry},
next_config::NextConfig,
......@@ -78,14 +78,6 @@ pub async fn get_app_page_entry(
[
("VAR_DEFINITION_PAGE", &*page.to_string()),
("VAR_DEFINITION_PATHNAME", &pathname),
(
"VAR_MODULE_GLOBAL_ERROR",
if inner_assets.contains_key(GLOBAL_ERROR) {
GLOBAL_ERROR
} else {
"next/dist/client/components/builtin/global-error"
},
),
],
[
("tree", &*loader_tree_code),
......
......@@ -980,5 +980,6 @@
"979": "invariant: expected %s bytes of postponed state but only received %s bytes",
"980": "Failed to load client middleware manifest",
"981": "resolvedPathname must be set in request metadata",
"982": "`serializeResumeDataCache` should not be called in edge runtime."
"982": "`serializeResumeDataCache` should not be called in edge runtime.",
"983": "Invariant: global-error module is required but not found in loader tree"
}
......@@ -75,10 +75,6 @@ import {
*/
declare const tree: LoaderTree
// TODO this should ideally be read from the loader tree instead, where it's always inserted already anyway.
import GlobalError from 'VAR_MODULE_GLOBAL_ERROR' with { 'turbopack-transition': 'next-server-component' }
export { GlobalError }
// These are injected by the loader afterwards.
declare const __next_app_require__: (id: string | number) => unknown
declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown>
......@@ -86,7 +82,6 @@ declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown>
// We inject the tree and pages here so that we can use them in the route
// module.
// INJECT:tree
// INJECT:__next_app_require__
// INJECT:__next_app_load_chunk__
......@@ -491,7 +486,6 @@ export async function handler(
const ComponentMod = {
...entryBase,
tree,
GlobalError,
handler,
routeModule,
__next_app__,
......
......@@ -333,7 +333,7 @@ async function createTreeCodeFromPath(
filePathEntries
)
// Only resolve global-* convention files at the root layer
// Resolve global-* convention files at the root layer
if (isRootLayer) {
const resolvedGlobalErrorPath = await resolver(
`${appDirPrefix}/${GLOBAL_ERROR_FILE_TYPE}`
......@@ -341,9 +341,6 @@ async function createTreeCodeFromPath(
if (resolvedGlobalErrorPath) {
globalError = resolvedGlobalErrorPath
}
// Add global-error to root layer's filePaths, so that it's always available,
// by default it's the built-in global-error.js
filePaths.set(GLOBAL_ERROR_FILE_TYPE, globalError)
// TODO(global-not-found): remove this flag assertion condition
// once global-not-found is stable
......@@ -360,6 +357,10 @@ async function createTreeCodeFromPath(
}
}
// Add global-error to ALL layers' filePaths, so that it's always available.
// By default it's the built-in global-error.js, or user's custom one if defined.
filePaths.set(GLOBAL_ERROR_FILE_TYPE, globalError)
let definedFilePaths = Array.from(filePaths.entries()).filter(
([, filePath]) => filePath !== undefined
) as [ValueOf<typeof FILE_TYPES>, string][]
......@@ -1103,7 +1104,6 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
{
VAR_DEFINITION_PAGE: page,
VAR_DEFINITION_PATHNAME: pathname,
VAR_MODULE_GLOBAL_ERROR: treeCodeResult.globalError,
},
{
tree: treeCodeResult.treeCode,
......
......@@ -388,8 +388,12 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
{
children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents, null],
},
// When global-not-found is present, skip layout from components
hasGlobalNotFound ? components : {},
// Always include global-error so that getGlobalErrorStyles can access it.
// When global-not-found is present, use full components.
// Otherwise, only include global-error module.
hasGlobalNotFound
? components
: { 'global-error': components['global-error'] },
null, // staticSiblings
]
}
......@@ -5538,26 +5542,29 @@ const getGlobalErrorStyles = async (
GlobalError: GlobalErrorComponent
styles: ReactNode | undefined
}> => {
const {
modules: { 'global-error': globalErrorModule },
} = parseLoaderTree(tree)
const globalErrorModule = parseLoaderTree(tree).modules['global-error']
if (!globalErrorModule) {
throw new Error(
'Invariant: global-error module is required but not found in loader tree'
)
}
const {
componentMod: { createElement },
} = ctx
const GlobalErrorComponent: GlobalErrorComponent =
ctx.componentMod.GlobalError
let globalErrorStyles
if (globalErrorModule) {
const [, styles] = await createComponentStylesAndScripts({
// Get the GlobalError component and styles from the loader tree
const [GlobalErrorComponent, styles] = await createComponentStylesAndScripts({
ctx,
filePath: globalErrorModule[1],
getComponent: globalErrorModule[0],
injectedCSS: new Set(),
injectedJS: new Set(),
})
globalErrorStyles = styles
}
let globalErrorStyles: ReactNode = styles
if (ctx.renderOpts.dev) {
const dir =
(process.env.NEXT_RUNTIME === 'edge'
......@@ -5566,7 +5573,7 @@ const getGlobalErrorStyles = async (
const globalErrorModulePath = normalizeConventionFilePath(
dir,
globalErrorModule?.[1]
globalErrorModule[1]
)
if (globalErrorModulePath) {
const SegmentViewNode = ctx.componentMod.SegmentViewNode
......
......@@ -170,7 +170,7 @@ describe('opentelemetry', () => {
},
{
attributes: {
'next.clientComponentLoadCount': isNextDev ? 7 : 6,
'next.clientComponentLoadCount': isNextDev ? 8 : 7,
'next.span_type':
'NextNodeServer.clientComponentLoading',
},
......@@ -578,7 +578,7 @@ describe('opentelemetry', () => {
},
{
attributes: {
'next.clientComponentLoadCount': isNextDev ? 10 : 8,
'next.clientComponentLoadCount': isNextDev ? 12 : 10,
'next.span_type':
'NextNodeServer.clientComponentLoading',
},
......@@ -701,7 +701,7 @@ describe('opentelemetry', () => {
},
{
attributes: {
'next.clientComponentLoadCount': isNextDev ? 8 : 7,
'next.clientComponentLoadCount': isNextDev ? 9 : 8,
'next.span_type':
'NextNodeServer.clientComponentLoading',
},
......@@ -1380,7 +1380,7 @@ describe('opentelemetry with custom server', () => {
},
{
attributes: {
'next.clientComponentLoadCount': isNextDev ? 7 : 6,
'next.clientComponentLoadCount': isNextDev ? 8 : 7,
'next.span_type': 'NextNodeServer.clientComponentLoading',
},
kind: 0,
......
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