Unverified Commit 58166a87 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Turbopack build: Implement app/global-error.tsx (#67803)

Implements global-error.tsx for Turbopack, this feature was missing.

While adding this @sokra and I found that the
server_component_transition was incorrectly wrapping a module around the
server component, this is now refactored to re-export the server
component instead, making the transition behave as expected.

<!-- 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 #

-->
parent 489d5ac6
...@@ -153,6 +153,7 @@ async fn prepare_components_for_js( ...@@ -153,6 +153,7 @@ async fn prepare_components_for_js(
page, page,
layout, layout,
error, error,
global_error: _,
loading, loading,
template, template,
not_found, not_found,
......
...@@ -44,6 +44,8 @@ pub struct Components { ...@@ -44,6 +44,8 @@ pub struct Components {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<Vc<FileSystemPath>>, pub error: Option<Vc<FileSystemPath>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub global_error: Option<Vc<FileSystemPath>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub loading: Option<Vc<FileSystemPath>>, pub loading: Option<Vc<FileSystemPath>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<Vc<FileSystemPath>>, pub template: Option<Vc<FileSystemPath>>,
...@@ -63,6 +65,7 @@ impl Components { ...@@ -63,6 +65,7 @@ impl Components {
page: None, page: None,
layout: self.layout, layout: self.layout,
error: self.error, error: self.error,
global_error: self.global_error,
loading: self.loading, loading: self.loading,
template: self.template, template: self.template,
not_found: self.not_found, not_found: self.not_found,
...@@ -333,6 +336,7 @@ async fn get_directory_tree_internal( ...@@ -333,6 +336,7 @@ async fn get_directory_tree_internal(
"page" => components.page = Some(file), "page" => components.page = Some(file),
"layout" => components.layout = Some(file), "layout" => components.layout = Some(file),
"error" => components.error = Some(file), "error" => components.error = Some(file),
"global-error" => components.global_error = Some(file),
"loading" => components.loading = Some(file), "loading" => components.loading = Some(file),
"template" => components.template = Some(file), "template" => components.template = Some(file),
"not-found" => components.not_found = Some(file), "not-found" => components.not_found = Some(file),
......
...@@ -107,14 +107,8 @@ impl LoaderTreeBuilder { ...@@ -107,14 +107,8 @@ impl LoaderTreeBuilder {
let i = self.unique_number(); let i = self.unique_number();
let identifier = magic_identifier::mangle(&format!("{name} #{i}")); let identifier = magic_identifier::mangle(&format!("{name} #{i}"));
let source = Vc::upcast(FileSource::new(component)); let module =
let reference_ty = Value::new(ReferenceType::EcmaScriptModules( process_module(&self.context, &self.server_component_transition, component);
EcmaScriptModulesReferenceSubType::Undefined,
));
let module = self
.server_component_transition
.process(source, self.context, reference_ty)
.module();
writeln!( writeln!(
self.loader_tree_code, self.loader_tree_code,
...@@ -126,7 +120,7 @@ impl LoaderTreeBuilder { ...@@ -126,7 +120,7 @@ impl LoaderTreeBuilder {
self.imports.push( self.imports.push(
formatdoc!( formatdoc!(
r#" r#"
import {} from "COMPONENT_{}"; import * as {} from "COMPONENT_{}";
"#, "#,
identifier, identifier,
i i
...@@ -381,6 +375,7 @@ impl LoaderTreeBuilder { ...@@ -381,6 +375,7 @@ impl LoaderTreeBuilder {
page, page,
default, default,
error, error,
global_error: _,
layout, layout,
loading, loading,
template, template,
...@@ -426,6 +421,16 @@ impl LoaderTreeBuilder { ...@@ -426,6 +421,16 @@ impl LoaderTreeBuilder {
} }
async fn build(mut self, loader_tree: Vc<LoaderTree>) -> Result<LoaderTreeModule> { async fn build(mut self, loader_tree: Vc<LoaderTree>) -> Result<LoaderTreeModule> {
let components = loader_tree.await?.components.await?;
if let Some(global_error) = components.global_error {
let module = process_module(
&self.context,
&self.server_component_transition,
global_error,
);
self.inner_assets.insert(GLOBAL_ERROR.into(), module);
};
self.walk_tree(loader_tree, true).await?; self.walk_tree(loader_tree, true).await?;
Ok(LoaderTreeModule { Ok(LoaderTreeModule {
imports: self.imports, imports: self.imports,
...@@ -455,3 +460,20 @@ impl LoaderTreeModule { ...@@ -455,3 +460,20 @@ impl LoaderTreeModule {
.await .await
} }
} }
pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR_MODULE";
fn process_module(
&context: &Vc<ModuleAssetContext>,
&server_component_transition: &Vc<Box<dyn Transition>>,
component: Vc<FileSystemPath>,
) -> Vc<Box<dyn Module>> {
let source = Vc::upcast(FileSource::new(component));
let reference_ty = Value::new(ReferenceType::EcmaScriptModules(
EcmaScriptModulesReferenceSubType::Undefined,
));
server_component_transition
.process(source, context, reference_ty)
.module()
}
...@@ -22,7 +22,7 @@ use turbopack_binding::{ ...@@ -22,7 +22,7 @@ use turbopack_binding::{
use super::app_entry::AppEntry; use super::app_entry::AppEntry;
use crate::{ use crate::{
app_structure::LoaderTree, app_structure::LoaderTree,
loader_tree::LoaderTreeModule, loader_tree::{LoaderTreeModule, GLOBAL_ERROR},
next_app::{AppPage, AppPath}, next_app::{AppPage, AppPath},
next_config::NextConfig, next_config::NextConfig,
next_edge::entry::wrap_edge_entry, next_edge::entry::wrap_edge_entry,
...@@ -81,8 +81,11 @@ pub async fn get_app_page_entry( ...@@ -81,8 +81,11 @@ pub async fn get_app_page_entry(
indexmap! { indexmap! {
"VAR_DEFINITION_PAGE" => page.to_string().into(), "VAR_DEFINITION_PAGE" => page.to_string().into(),
"VAR_DEFINITION_PATHNAME" => pathname.clone(), "VAR_DEFINITION_PATHNAME" => pathname.clone(),
// TODO(alexkirsz) Support custom global error. "VAR_MODULE_GLOBAL_ERROR" => if inner_assets.contains_key(GLOBAL_ERROR) {
"VAR_MODULE_GLOBAL_ERROR" => "next/dist/client/components/error-boundary".into(), GLOBAL_ERROR.into()
} else {
"next/dist/client/components/error-boundary".into()
},
}, },
indexmap! { indexmap! {
"tree" => loader_tree_code, "tree" => loader_tree_code,
......
use std::collections::BTreeMap;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use indoc::formatdoc; use indoc::formatdoc;
use turbo_tasks::{RcStr, Vc}; use turbo_tasks::{RcStr, Vc};
...@@ -12,10 +10,7 @@ use turbopack_binding::turbopack::{ ...@@ -12,10 +10,7 @@ use turbopack_binding::turbopack::{
module::Module, module::Module,
reference::ModuleReferences, reference::ModuleReferences,
}, },
ecmascript::{ ecmascript::{chunk::EcmascriptChunkType, references::esm::EsmExports},
chunk::EcmascriptChunkType,
references::esm::{EsmExport, EsmExports},
},
turbopack::ecmascript::{ turbopack::ecmascript::{
chunk::{ chunk::{
EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable,
...@@ -95,17 +90,14 @@ impl ChunkableModule for NextServerComponentModule { ...@@ -95,17 +90,14 @@ impl ChunkableModule for NextServerComponentModule {
impl EcmascriptChunkPlaceable for NextServerComponentModule { impl EcmascriptChunkPlaceable for NextServerComponentModule {
#[turbo_tasks::function] #[turbo_tasks::function]
fn get_exports(&self) -> Vc<EcmascriptExports> { fn get_exports(&self) -> Vc<EcmascriptExports> {
let exports = BTreeMap::from([( let module_reference = Vc::upcast(NextServerComponentModuleReference::new(Vc::upcast(
"default".into(), self.module,
EsmExport::ImportedNamespace(Vc::upcast(NextServerComponentModuleReference::new( )));
Vc::upcast(self.module),
))),
)]);
EcmascriptExports::EsmExports( EcmascriptExports::EsmExports(
EsmExports { EsmExports {
exports, exports: Default::default(),
star_exports: Default::default(), star_exports: vec![module_reference],
} }
.cell(), .cell(),
) )
...@@ -139,9 +131,7 @@ impl EcmascriptChunkItem for BuildServerComponentChunkItem { ...@@ -139,9 +131,7 @@ impl EcmascriptChunkItem for BuildServerComponentChunkItem {
Ok(EcmascriptChunkItemContent { Ok(EcmascriptChunkItemContent {
inner_code: formatdoc!( inner_code: formatdoc!(
r#" r#"
__turbopack_esm__({{ __turbopack_export_namespace__(__turbopack_import__({}));
default: () => __turbopack_import__({}),
}});
"#, "#,
StringifyJs(&module_id), StringifyJs(&module_id),
) )
......
...@@ -1793,15 +1793,14 @@ ...@@ -1793,15 +1793,14 @@
}, },
"test/e2e/app-dir/global-error/basic/index.test.ts": { "test/e2e/app-dir/global-error/basic/index.test.ts": {
"passed": [ "passed": [
"app dir - global error should catch metadata error in error boundary if presented" "app dir - global error should catch metadata error in error boundary if presented",
],
"failed": [
"app dir - global error should catch metadata error in global-error if no error boundary is presented", "app dir - global error should catch metadata error in global-error if no error boundary is presented",
"app dir - global error should catch the client error thrown in the nested routes", "app dir - global error should catch the client error thrown in the nested routes",
"app dir - global error should render global error for error in client components", "app dir - global error should render global error for error in client components",
"app dir - global error should render global error for error in server components", "app dir - global error should render global error for error in server components",
"app dir - global error should trigger error component when an error happens during rendering" "app dir - global error should trigger error component when an error happens during rendering"
], ],
"failed": [],
"pending": [], "pending": [],
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
...@@ -1809,20 +1808,19 @@ ...@@ -1809,20 +1808,19 @@
"test/e2e/app-dir/global-error/catch-all/index.test.ts": { "test/e2e/app-dir/global-error/catch-all/index.test.ts": {
"passed": [ "passed": [
"app dir - global error - with catch-all route should render 404 page correctly", "app dir - global error - with catch-all route should render 404 page correctly",
"app dir - global error - with catch-all route should render catch-all route correctly" "app dir - global error - with catch-all route should render catch-all route correctly",
],
"failed": [
"app dir - global error - with catch-all route should render global error correctly" "app dir - global error - with catch-all route should render global error correctly"
], ],
"failed": [],
"pending": [], "pending": [],
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/e2e/app-dir/global-error/layout-error/index.test.ts": { "test/e2e/app-dir/global-error/layout-error/index.test.ts": {
"passed": [], "passed": [
"failed": [
"app dir - global error - layout error should render global error for error in server components" "app dir - global error - layout error should render global error for error in server components"
], ],
"failed": [],
"pending": [], "pending": [],
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
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