Skip to content

Commit

Permalink
Turbopack build: Implement app/global-error.tsx (#67803)
Browse files Browse the repository at this point in the history
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 #

-->
  • Loading branch information
timneutkens authored and ForsakenHarmony committed Aug 14, 2024
1 parent e52aee0 commit 54cf395
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 37 deletions.
1 change: 1 addition & 0 deletions packages/next-swc/crates/napi/src/app_structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ async fn prepare_components_for_js(
page,
layout,
error,
global_error: _,
loading,
template,
not_found,
Expand Down
4 changes: 4 additions & 0 deletions packages/next-swc/crates/next-core/src/app_structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ pub struct Components {
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<Vc<FileSystemPath>>,
#[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>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<Vc<FileSystemPath>>,
Expand All @@ -63,6 +65,7 @@ impl Components {
page: None,
layout: self.layout,
error: self.error,
global_error: self.global_error,
loading: self.loading,
template: self.template,
not_found: self.not_found,
Expand Down Expand Up @@ -333,6 +336,7 @@ async fn get_directory_tree_internal(
"page" => components.page = Some(file),
"layout" => components.layout = Some(file),
"error" => components.error = Some(file),
"global-error" => components.global_error = Some(file),
"loading" => components.loading = Some(file),
"template" => components.template = Some(file),
"not-found" => components.not_found = Some(file),
Expand Down
40 changes: 31 additions & 9 deletions packages/next-swc/crates/next-core/src/loader_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,8 @@ impl LoaderTreeBuilder {
let i = self.unique_number();
let identifier = magic_identifier::mangle(&format!("{name} #{i}"));

let source = Vc::upcast(FileSource::new(component));
let reference_ty = Value::new(ReferenceType::EcmaScriptModules(
EcmaScriptModulesReferenceSubType::Undefined,
));
let module = self
.server_component_transition
.process(source, self.context, reference_ty)
.module();
let module =
process_module(&self.context, &self.server_component_transition, component);

writeln!(
self.loader_tree_code,
Expand All @@ -126,7 +120,7 @@ impl LoaderTreeBuilder {
self.imports.push(
formatdoc!(
r#"
import {} from "COMPONENT_{}";
import * as {} from "COMPONENT_{}";
"#,
identifier,
i
Expand Down Expand Up @@ -381,6 +375,7 @@ impl LoaderTreeBuilder {
page,
default,
error,
global_error: _,
layout,
loading,
template,
Expand Down Expand Up @@ -426,6 +421,16 @@ impl LoaderTreeBuilder {
}

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?;
Ok(LoaderTreeModule {
imports: self.imports,
Expand Down Expand Up @@ -455,3 +460,20 @@ impl LoaderTreeModule {
.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()
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use turbopack_binding::{
use super::app_entry::AppEntry;
use crate::{
app_structure::LoaderTree,
loader_tree::LoaderTreeModule,
loader_tree::{LoaderTreeModule, GLOBAL_ERROR},
next_app::{AppPage, AppPath},
next_config::NextConfig,
next_edge::entry::wrap_edge_entry,
Expand Down Expand Up @@ -81,8 +81,11 @@ pub async fn get_app_page_entry(
indexmap! {
"VAR_DEFINITION_PAGE" => page.to_string().into(),
"VAR_DEFINITION_PATHNAME" => pathname.clone(),
// TODO(alexkirsz) Support custom global error.
"VAR_MODULE_GLOBAL_ERROR" => "next/dist/client/components/error-boundary".into(),
"VAR_MODULE_GLOBAL_ERROR" => if inner_assets.contains_key(GLOBAL_ERROR) {
GLOBAL_ERROR.into()
} else {
"next/dist/client/components/error-boundary".into()
},
},
indexmap! {
"tree" => loader_tree_code,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::collections::BTreeMap;

use anyhow::{bail, Result};
use indoc::formatdoc;
use turbo_tasks::{RcStr, Vc};
Expand All @@ -12,10 +10,7 @@ use turbopack_binding::turbopack::{
module::Module,
reference::ModuleReferences,
},
ecmascript::{
chunk::EcmascriptChunkType,
references::esm::{EsmExport, EsmExports},
},
ecmascript::{chunk::EcmascriptChunkType, references::esm::EsmExports},
turbopack::ecmascript::{
chunk::{
EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable,
Expand Down Expand Up @@ -95,17 +90,14 @@ impl ChunkableModule for NextServerComponentModule {
impl EcmascriptChunkPlaceable for NextServerComponentModule {
#[turbo_tasks::function]
fn get_exports(&self) -> Vc<EcmascriptExports> {
let exports = BTreeMap::from([(
"default".into(),
EsmExport::ImportedNamespace(Vc::upcast(NextServerComponentModuleReference::new(
Vc::upcast(self.module),
))),
)]);
let module_reference = Vc::upcast(NextServerComponentModuleReference::new(Vc::upcast(
self.module,
)));

EcmascriptExports::EsmExports(
EsmExports {
exports,
star_exports: Default::default(),
exports: Default::default(),
star_exports: vec![module_reference],
}
.cell(),
)
Expand Down Expand Up @@ -139,9 +131,7 @@ impl EcmascriptChunkItem for BuildServerComponentChunkItem {
Ok(EcmascriptChunkItemContent {
inner_code: formatdoc!(
r#"
__turbopack_esm__({{
default: () => __turbopack_import__({}),
}});
__turbopack_export_namespace__(__turbopack_import__({}));
"#,
StringifyJs(&module_id),
)
Expand Down
14 changes: 6 additions & 8 deletions test/turbopack-build-tests-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -1648,36 +1648,34 @@
},
"test/e2e/app-dir/global-error/basic/index.test.ts": {
"passed": [
"app dir - global error should catch metadata error in error boundary if presented"
],
"failed": [
"app dir - global error should catch metadata error in error boundary if 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 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 trigger error component when an error happens during rendering"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/e2e/app-dir/global-error/catch-all/index.test.ts": {
"passed": [
"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"
],
"failed": [
"app dir - global error - with catch-all route should render catch-all route correctly",
"app dir - global error - with catch-all route should render global error correctly"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/e2e/app-dir/global-error/layout-error/index.test.ts": {
"passed": [],
"failed": [
"passed": [
"app dir - global error - layout error should render global error for error in server components"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
Expand Down

0 comments on commit 54cf395

Please sign in to comment.