Unverified Commit 84005941 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

add edge support for next.rs API (#52885)

### What?

adds edge pages, apis, app pages and app routes to next.rs api

### Why?

### How?
parent 8664ffe2
......@@ -8,16 +8,43 @@ use turbopack_binding::turbopack::core::error::PrettyPrintError;
use super::utils::{get_issues, subscribe, NapiIssue, RootTask, TurbopackResult, VcArc};
#[napi(object)]
#[derive(Default)]
pub struct NapiEndpointConfig {}
#[napi(object)]
#[derive(Default)]
pub struct NapiWrittenEndpoint {
pub server_entry_path: String,
pub server_paths: Vec<String>,
pub r#type: String,
pub entry_path: Option<String>,
pub server_paths: Option<Vec<String>>,
pub files: Option<Vec<String>>,
pub global_var_name: Option<String>,
pub config: NapiEndpointConfig,
}
impl From<&WrittenEndpoint> for NapiWrittenEndpoint {
fn from(written_endpoint: &WrittenEndpoint) -> Self {
Self {
server_entry_path: written_endpoint.server_entry_path.clone(),
server_paths: written_endpoint.server_paths.clone(),
match written_endpoint {
WrittenEndpoint::NodeJs {
server_entry_path,
server_paths,
} => Self {
r#type: "nodejs".to_string(),
entry_path: Some(server_entry_path.clone()),
server_paths: Some(server_paths.clone()),
..Default::default()
},
WrittenEndpoint::Edge {
files,
global_var_name,
server_paths,
} => Self {
r#type: "edge".to_string(),
files: Some(files.clone()),
server_paths: Some(server_paths.clone()),
global_var_name: Some(global_var_name.clone()),
..Default::default()
},
}
}
}
......
......@@ -4,7 +4,7 @@ use next_core::{
app_structure::{
get_entrypoints, Entrypoint as AppEntrypoint, Entrypoints as AppEntrypoints, LoaderTree,
},
emit_all_assets,
emit_all_assets, get_edge_resolve_options_context,
mode::NextMode,
next_app::{
get_app_client_references_chunks, get_app_client_shared_chunks, get_app_page_entry,
......@@ -12,7 +12,7 @@ use next_core::{
},
next_client::{
get_client_module_options_context, get_client_resolve_options_context,
get_client_runtime_entries, ClientContextType,
get_client_runtime_entries, ClientContextType, RuntimeEntries,
},
next_client_reference::{
ClientReferenceGraph, ClientReferenceType, NextEcmascriptClientReferenceTransition,
......@@ -25,6 +25,7 @@ use next_core::{
get_server_module_options_context, get_server_resolve_options_context,
get_server_runtime_entries, ServerContextType,
},
util::NextRuntime,
};
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, Completion, TryJoinIterExt, Value, Vc};
......@@ -37,7 +38,7 @@ use turbopack_binding::{
core::{
asset::AssetContent,
changed::any_content_changed_of_output_assets,
chunk::EvaluatableAssets,
chunk::{ChunkableModule, ChunkingContext, EvaluatableAssets},
file_source::FileSource,
output::{OutputAsset, OutputAssets},
virtual_output::VirtualOutputAsset,
......@@ -178,6 +179,18 @@ impl AppProject {
))
}
#[turbo_tasks::function]
async fn edge_rsc_resolve_options_context(self: Vc<Self>) -> Result<Vc<ResolveOptionsContext>> {
let this = self.await?;
Ok(get_edge_resolve_options_context(
self.project().project_path(),
Value::new(self.rsc_ty()),
this.mode,
self.project().next_config(),
self.project().execution_context(),
))
}
#[turbo_tasks::function]
fn rsc_module_context(self: Vc<Self>) -> Vc<ModuleAssetContext> {
let transitions = [
......@@ -203,6 +216,31 @@ impl AppProject {
)
}
#[turbo_tasks::function]
fn edge_rsc_module_context(self: Vc<Self>) -> Vc<ModuleAssetContext> {
let transitions = [
(
ECMASCRIPT_CLIENT_TRANSITION_NAME.to_string(),
Vc::upcast(NextEcmascriptClientReferenceTransition::new(
self.client_transition(),
self.ssr_transition(),
)),
),
(
"next-dynamic".to_string(),
Vc::upcast(NextDynamicTransition::new(self.client_transition())),
),
]
.into_iter()
.collect();
ModuleAssetContext::new(
Vc::cell(transitions),
self.project().edge_compile_time_info(),
self.rsc_module_options_context(),
self.edge_rsc_resolve_options_context(),
)
}
#[turbo_tasks::function]
fn client_module_context(self: Vc<Self>) -> Vc<ModuleAssetContext> {
ModuleAssetContext::new(
......@@ -247,7 +285,7 @@ impl AppProject {
}
#[turbo_tasks::function]
async fn rsc_runtime_entries(self: Vc<Self>) -> Result<Vc<EvaluatableAssets>> {
async fn runtime_entries(self: Vc<Self>) -> Result<Vc<RuntimeEntries>> {
let this = self.await?;
Ok(get_server_runtime_entries(
self.project().project_path(),
......@@ -257,8 +295,19 @@ impl AppProject {
Value::new(self.rsc_ty()),
this.mode,
self.project().next_config(),
)
.resolve_entries(Vc::upcast(self.rsc_module_context())))
))
}
#[turbo_tasks::function]
fn rsc_runtime_entries(self: Vc<Self>) -> Vc<EvaluatableAssets> {
self.runtime_entries()
.resolve_entries(Vc::upcast(self.rsc_module_context()))
}
#[turbo_tasks::function]
fn edge_rsc_runtime_entries(self: Vc<Self>) -> Vc<EvaluatableAssets> {
self.runtime_entries()
.resolve_entries(Vc::upcast(self.edge_rsc_module_context()))
}
#[turbo_tasks::function]
......@@ -387,6 +436,7 @@ impl AppEndpoint {
fn app_page_entry(&self, loader_tree: Vc<LoaderTree>) -> Vc<AppEntry> {
get_app_page_entry(
self.app_project.rsc_module_context(),
self.app_project.edge_rsc_module_context(),
loader_tree,
self.app_project.app_dir(),
self.pathname.clone(),
......@@ -398,6 +448,7 @@ impl AppEndpoint {
fn app_route_entry(&self, path: Vc<FileSystemPath>) -> Vc<AppEntry> {
get_app_route_entry(
self.app_project.rsc_module_context(),
self.app_project.edge_rsc_module_context(),
Vc::upcast(FileSource::new(path)),
self.pathname.clone(),
self.app_project.project().project_path(),
......@@ -475,20 +526,6 @@ impl AppEndpoint {
))
.await?;
let rsc_chunk = this
.app_project
.project()
.rsc_chunking_context()
.entry_chunk(
server_path.join(format!(
"app/{original_name}.js",
original_name = app_entry.original_name
)),
app_entry.rsc_entry,
this.app_project.rsc_runtime_entries(),
);
output_assets.push(rsc_chunk);
let app_entry_client_references = client_reference_graph
.entry(Vc::upcast(app_entry.rsc_entry))
.await?;
......@@ -547,32 +584,6 @@ impl AppEndpoint {
));
output_assets.push(app_build_manifest_output);
let app_paths_manifest = AppPathsManifest {
node_server_app_paths: PagesManifest {
pages: [(
app_entry.original_name.clone(),
server_path
.await?
.get_path_to(&*rsc_chunk.ident().path().await?)
.expect("RSC chunk path should be within app paths manifest directory")
.to_string(),
)]
.into_iter()
.collect(),
},
..Default::default()
};
let app_paths_manifest_output = Vc::upcast(VirtualOutputAsset::new(
node_root.join(format!(
"server/app{original_name}/app-paths-manifest.json",
original_name = app_entry.original_name
)),
AssetContent::file(
File::from(serde_json::to_string_pretty(&app_paths_manifest)?).into(),
),
));
output_assets.push(app_paths_manifest_output);
let build_manifest = BuildManifest {
root_main_files: client_shared_chunks_paths,
..Default::default()
......@@ -597,11 +608,72 @@ impl AppEndpoint {
);
output_assets.push(entry_manifest);
Ok(AppEndpointOutput {
rsc_chunk,
output_assets: Vc::cell(output_assets),
}
.cell())
let endpoint_output = match app_entry.config.await?.runtime.unwrap_or_default() {
NextRuntime::Edge => {
let chunking_context = this.app_project.project().edge_rsc_chunking_context();
let files = chunking_context.evaluated_chunk_group(
app_entry
.rsc_entry
.as_root_chunk(Vc::upcast(chunking_context)),
this.app_project.edge_rsc_runtime_entries(),
);
output_assets.extend(files.await?.iter().copied());
AppEndpointOutput::Edge {
files,
output_assets: Vc::cell(output_assets),
}
}
NextRuntime::NodeJs => {
let rsc_chunk = this
.app_project
.project()
.rsc_chunking_context()
.entry_chunk(
server_path.join(format!(
"app/{original_name}.js",
original_name = app_entry.original_name
)),
app_entry.rsc_entry,
this.app_project.rsc_runtime_entries(),
);
output_assets.push(rsc_chunk);
let app_paths_manifest = AppPathsManifest {
node_server_app_paths: PagesManifest {
pages: [(
app_entry.original_name.clone(),
server_path
.await?
.get_path_to(&*rsc_chunk.ident().path().await?)
.expect(
"RSC chunk path should be within app paths manifest directory",
)
.to_string(),
)]
.into_iter()
.collect(),
},
..Default::default()
};
let app_paths_manifest_output = Vc::upcast(VirtualOutputAsset::new(
node_root.join(format!(
"server/app{original_name}/app-paths-manifest.json",
original_name = app_entry.original_name
)),
AssetContent::file(
File::from(serde_json::to_string_pretty(&app_paths_manifest)?).into(),
),
));
output_assets.push(app_paths_manifest_output);
AppEndpointOutput::NodeJs {
rsc_chunk,
output_assets: Vc::cell(output_assets),
}
}
};
Ok(endpoint_output.cell())
}
}
......@@ -610,47 +682,91 @@ impl Endpoint for AppEndpoint {
#[turbo_tasks::function]
async fn write_to_disk(self: Vc<Self>) -> Result<Vc<WrittenEndpoint>> {
let output = self.output();
let output_assets = output.output_assets();
let this = self.await?;
let node_root = this.app_project.project().node_root();
let output = output.await?;
let node_root_ref = node_root.await?;
let node_root_ref = &node_root.await?;
let node_root = this.app_project.project().node_root();
emit_all_assets(
output.output_assets,
output_assets,
node_root,
self.client_relative_path(),
this.app_project.project().node_root(),
)
.await?;
let server_paths = all_server_paths(output.output_assets, node_root)
let server_paths = all_server_paths(output_assets, node_root)
.await?
.clone_value();
Ok(WrittenEndpoint {
server_entry_path: node_root_ref
.get_path_to(&*output.rsc_chunk.ident().path().await?)
.context("rsc chunk entry path must be inside the node root")?
.to_string(),
server_paths,
}
.cell())
let written_endpoint = match *output.await? {
AppEndpointOutput::NodeJs {
rsc_chunk,
output_assets: _,
} => WrittenEndpoint::NodeJs {
server_entry_path: node_root_ref
.get_path_to(&*rsc_chunk.ident().path().await?)
.context("rsc chunk entry path must be inside the node root")?
.to_string(),
server_paths,
},
AppEndpointOutput::Edge {
files,
output_assets: _,
} => WrittenEndpoint::Edge {
files: files
.await?
.iter()
.map(|&file| async move {
Ok(node_root_ref
.get_path_to(&*file.ident().path().await?)
.context("ssr chunk file path must be inside the node root")?
.to_string())
})
.try_join()
.await?,
global_var_name: "TODO".to_string(),
server_paths,
},
};
Ok(written_endpoint.cell())
}
#[turbo_tasks::function]
async fn changed(self: Vc<Self>) -> Result<Vc<Completion>> {
let output = self.output();
Ok(any_content_changed_of_output_assets(
output.await?.output_assets,
))
let output_assets = self.output().output_assets();
Ok(any_content_changed_of_output_assets(output_assets))
}
}
#[turbo_tasks::value]
struct AppEndpointOutput {
rsc_chunk: Vc<Box<dyn OutputAsset>>,
output_assets: Vc<OutputAssets>,
enum AppEndpointOutput {
NodeJs {
rsc_chunk: Vc<Box<dyn OutputAsset>>,
output_assets: Vc<OutputAssets>,
},
Edge {
files: Vc<OutputAssets>,
output_assets: Vc<OutputAssets>,
},
}
#[turbo_tasks::value_impl]
impl AppEndpointOutput {
#[turbo_tasks::function]
pub fn output_assets(&self) -> Vc<OutputAssets> {
match *self {
AppEndpointOutput::NodeJs {
rsc_chunk: _,
output_assets,
} => output_assets,
AppEndpointOutput::Edge {
files: _,
output_assets,
} => output_assets,
}
}
}
......@@ -2,11 +2,11 @@ use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use next_core::{
all_server_paths, create_page_loader_entry_module, emit_all_assets,
get_asset_path_from_pathname,
get_asset_path_from_pathname, get_edge_resolve_options_context,
mode::NextMode,
next_client::{
get_client_module_options_context, get_client_resolve_options_context,
get_client_runtime_entries, ClientContextType,
get_client_runtime_entries, ClientContextType, RuntimeEntries,
},
next_dynamic::NextDynamicTransition,
next_manifests::{BuildManifest, PagesManifest},
......@@ -17,12 +17,14 @@ use next_core::{
pages_structure::{
find_pages_structure, PagesDirectoryStructure, PagesStructure, PagesStructureItem,
},
util::{parse_config_from_source, NextRuntime},
};
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, Completion, TaskInput, TryJoinIterExt, Value, Vc};
use turbopack_binding::{
turbo::tasks_fs::{File, FileSystem, FileSystemPath, VirtualFileSystem},
turbopack::{
build::BuildChunkingContext,
core::{
asset::AssetContent,
changed::any_content_changed_of_output_assets,
......@@ -34,7 +36,7 @@ use turbopack_binding::{
source::Source,
virtual_output::VirtualOutputAsset,
},
ecmascript::EcmascriptModuleAsset,
ecmascript::{chunk::EcmascriptChunkingContext, EcmascriptModuleAsset},
turbopack::{
module_options::ModuleOptionsContext,
resolve_options_context::ResolveOptionsContext,
......@@ -221,23 +223,43 @@ impl PagesProject {
}
#[turbo_tasks::function]
pub(super) fn ssr_module_context(self: Vc<Self>) -> Vc<Box<dyn AssetContext>> {
Vc::upcast(ModuleAssetContext::new(
pub(super) fn ssr_module_context(self: Vc<Self>) -> Vc<ModuleAssetContext> {
ModuleAssetContext::new(
self.transitions(),
self.project().server_compile_time_info(),
self.ssr_module_options_context(),
self.ssr_resolve_options_context(),
))
)
}
#[turbo_tasks::function]
pub(super) fn ssr_data_module_context(self: Vc<Self>) -> Vc<Box<dyn AssetContext>> {
Vc::upcast(ModuleAssetContext::new(
pub(super) fn ssr_data_module_context(self: Vc<Self>) -> Vc<ModuleAssetContext> {
ModuleAssetContext::new(
self.transitions(),
self.project().server_compile_time_info(),
self.ssr_data_module_options_context(),
self.ssr_resolve_options_context(),
))
)
}
#[turbo_tasks::function]
pub(super) fn edge_ssr_module_context(self: Vc<Self>) -> Vc<ModuleAssetContext> {
ModuleAssetContext::new(
Default::default(),
self.project().edge_compile_time_info(),
self.ssr_module_options_context(),
self.edge_ssr_resolve_options_context(),
)
}
#[turbo_tasks::function]
pub(super) fn edge_ssr_data_module_context(self: Vc<Self>) -> Vc<ModuleAssetContext> {
ModuleAssetContext::new(
Default::default(),
self.project().edge_compile_time_info(),
self.ssr_data_module_options_context(),
self.edge_ssr_resolve_options_context(),
)
}
#[turbo_tasks::function]
......@@ -273,6 +295,26 @@ impl PagesProject {
let this = self.await?;
Ok(get_server_resolve_options_context(
self.project().project_path(),
// NOTE(alexkirsz) This could be `PagesData` for the data endpoint, but it doesn't
// matter (for now at least) because `get_server_resolve_options_context` doesn't
// differentiate between the two.
Value::new(ServerContextType::Pages {
pages_dir: self.pages_dir(),
}),
this.mode,
self.project().next_config(),
self.project().execution_context(),
))
}
#[turbo_tasks::function]
async fn edge_ssr_resolve_options_context(self: Vc<Self>) -> Result<Vc<ResolveOptionsContext>> {
let this = self.await?;
Ok(get_edge_resolve_options_context(
self.project().project_path(),
// NOTE(alexkirsz) This could be `PagesData` for the data endpoint, but it doesn't
// matter (for now at least) because `get_server_resolve_options_context` doesn't
// differentiate between the two.
Value::new(ServerContextType::Pages {
pages_dir: self.pages_dir(),
}),
......@@ -299,9 +341,9 @@ impl PagesProject {
}
#[turbo_tasks::function]
async fn ssr_runtime_entries(self: Vc<Self>) -> Result<Vc<EvaluatableAssets>> {
async fn runtime_entries(self: Vc<Self>) -> Result<Vc<RuntimeEntries>> {
let this = self.await?;
let ssr_runtime_entries = get_server_runtime_entries(
Ok(get_server_runtime_entries(
self.project().project_path(),
self.project().env(),
Value::new(ServerContextType::Pages {
......@@ -309,8 +351,45 @@ impl PagesProject {
}),
this.mode,
self.project().next_config(),
);
Ok(ssr_runtime_entries.resolve_entries(self.ssr_module_context()))
))
}
#[turbo_tasks::function]
async fn data_runtime_entries(self: Vc<Self>) -> Result<Vc<RuntimeEntries>> {
let this = self.await?;
Ok(get_server_runtime_entries(
self.project().project_path(),
self.project().env(),
Value::new(ServerContextType::PagesData {
pages_dir: self.pages_dir(),
}),
this.mode,
self.project().next_config(),
))
}
#[turbo_tasks::function]
fn ssr_runtime_entries(self: Vc<Self>) -> Vc<EvaluatableAssets> {
let ssr_runtime_entries = self.runtime_entries();
ssr_runtime_entries.resolve_entries(Vc::upcast(self.ssr_module_context()))
}
#[turbo_tasks::function]
fn ssr_data_runtime_entries(self: Vc<Self>) -> Vc<EvaluatableAssets> {
let ssr_data_runtime_entries = self.data_runtime_entries();
ssr_data_runtime_entries.resolve_entries(Vc::upcast(self.ssr_module_context()))
}
#[turbo_tasks::function]
fn edge_ssr_runtime_entries(self: Vc<Self>) -> Vc<EvaluatableAssets> {
let ssr_runtime_entries = self.runtime_entries();
ssr_runtime_entries.resolve_entries(Vc::upcast(self.edge_ssr_module_context()))
}
#[turbo_tasks::function]
fn edge_ssr_data_runtime_entries(self: Vc<Self>) -> Vc<EvaluatableAssets> {
let ssr_data_runtime_entries = self.data_runtime_entries();
ssr_data_runtime_entries.resolve_entries(Vc::upcast(self.edge_ssr_module_context()))
}
}
......@@ -387,114 +466,117 @@ impl PageEndpoint {
}
#[turbo_tasks::function]
async fn ssr_chunk(self: Vc<Self>) -> Result<Vc<Box<dyn OutputAsset>>> {
async fn internal_ssr_chunk(
self: Vc<Self>,
reference_type: Value<ReferenceType>,
node_path: Vc<FileSystemPath>,
module_context: Vc<ModuleAssetContext>,
edge_module_context: Vc<ModuleAssetContext>,
chunking_context: Vc<BuildChunkingContext>,
edge_chunking_context: Vc<Box<dyn EcmascriptChunkingContext>>,
runtime_entries: Vc<EvaluatableAssets>,
edge_runtime_entries: Vc<EvaluatableAssets>,
) -> Result<Vc<SsrChunk>> {
let this = self.await?;
let reference_type = Value::new(ReferenceType::Entry(EntryReferenceSubType::Page));
let ssr_module = this
.pages_project
.ssr_module_context()
.process(self.source(), reference_type.clone());
let ssr_module = module_context.process(self.source(), reference_type.clone());
let Some(ssr_module) =
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(ssr_module).await?
else {
bail!("expected an ECMAScript module asset");
};
let config = parse_config_from_source(ssr_module).await?;
let is_edge = matches!(config.runtime, NextRuntime::Edge);
let asset_path = get_asset_path_from_pathname(&this.pathname.await?, ".js");
let ssr_entry_chunk_path_string = format!("server/pages{asset_path}");
let ssr_entry_chunk_path = this
.pages_project
.project()
.node_root()
.join(ssr_entry_chunk_path_string);
let ssr_entry_chunk = this
.pages_project
.project()
.ssr_chunking_context()
.entry_chunk(
ssr_entry_chunk_path,
Vc::upcast(ssr_module),
this.pages_project.ssr_runtime_entries(),
);
if is_edge {
let ssr_module = edge_module_context.process(self.source(), reference_type.clone());
Ok(ssr_entry_chunk)
}
let Some(ssr_module) =
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(ssr_module).await?
else {
bail!("expected an ECMAScript module asset");
};
#[turbo_tasks::function]
async fn ssr_data_chunk(self: Vc<Self>) -> Result<Vc<Box<dyn OutputAsset>>> {
let this = self.await?;
let reference_type = Value::new(ReferenceType::Entry(EntryReferenceSubType::Page));
let edge_files = edge_chunking_context.evaluated_chunk_group(
ssr_module.as_root_chunk(Vc::upcast(edge_chunking_context)),
edge_runtime_entries,
);
let ssr_data_module = this
.pages_project
.ssr_data_module_context()
.process(self.source(), reference_type.clone());
Ok(SsrChunk::Edge { files: edge_files }.cell())
} else {
let Some(ssr_module) =
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(ssr_module).await?
else {
bail!("expected an ECMAScript module asset");
};
let Some(ssr_data_module) =
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(ssr_data_module).await?
else {
bail!("expected an ECMAScript module asset");
};
let asset_path = get_asset_path_from_pathname(&this.pathname.await?, ".js");
let asset_path = get_asset_path_from_pathname(&this.pathname.await?, ".js");
let ssr_data_entry_chunk_path_string = format!("server/pages-data/{asset_path}");
let ssr_data_entry_chunk_path = this
.pages_project
.project()
.node_root()
.join(ssr_data_entry_chunk_path_string);
let ssr_data_entry_chunk = this
.pages_project
.project()
.ssr_data_chunking_context()
.entry_chunk(
ssr_data_entry_chunk_path,
Vc::upcast(ssr_data_module),
this.pages_project.ssr_runtime_entries(),
let ssr_entry_chunk_path_string = format!("pages{asset_path}");
let ssr_entry_chunk_path = node_path.join(ssr_entry_chunk_path_string);
let ssr_entry_chunk = chunking_context.entry_chunk(
ssr_entry_chunk_path,
Vc::upcast(ssr_module),
runtime_entries,
);
Ok(ssr_data_entry_chunk)
Ok(SsrChunk::NodeJs {
entry: ssr_entry_chunk,
}
.cell())
}
}
#[turbo_tasks::function]
async fn api_chunk(self: Vc<Self>) -> Result<Vc<Box<dyn OutputAsset>>> {
async fn ssr_chunk(self: Vc<Self>) -> Result<Vc<SsrChunk>> {
let this = self.await?;
let reference_type = Value::new(ReferenceType::Entry(EntryReferenceSubType::PagesApi));
let api_module = this
.pages_project
.ssr_module_context()
.process(self.source(), reference_type.clone());
let Some(api_module) =
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(api_module).await?
else {
bail!("expected an ECMAScript module asset");
};
Ok(self.internal_ssr_chunk(
Value::new(ReferenceType::Entry(EntryReferenceSubType::Page)),
this.pages_project
.project()
.node_root()
.join("server".to_string()),
this.pages_project.ssr_module_context(),
this.pages_project.edge_ssr_module_context(),
this.pages_project.project().ssr_chunking_context(),
this.pages_project.project().edge_ssr_chunking_context(),
this.pages_project.ssr_runtime_entries(),
this.pages_project.edge_ssr_runtime_entries(),
))
}
let asset_path = get_asset_path_from_pathname(&this.pathname.await?, ".js");
let api_entry_chunk_path_string = format!("server/pages/{asset_path}");
let api_entry_chunk_path = this
.pages_project
.project()
.node_root()
.join(api_entry_chunk_path_string);
let api_entry_chunk = this
.pages_project
.project()
.ssr_chunking_context()
.entry_chunk(
api_entry_chunk_path,
Vc::upcast(api_module),
this.pages_project.ssr_runtime_entries(),
);
#[turbo_tasks::function]
async fn ssr_data_chunk(self: Vc<Self>) -> Result<Vc<SsrChunk>> {
let this = self.await?;
Ok(self.internal_ssr_chunk(
Value::new(ReferenceType::Entry(EntryReferenceSubType::Page)),
this.pages_project
.project()
.node_root()
.join("server-data".to_string()),
this.pages_project.ssr_data_module_context(),
this.pages_project.edge_ssr_data_module_context(),
this.pages_project.project().ssr_data_chunking_context(),
this.pages_project
.project()
.edge_ssr_data_chunking_context(),
this.pages_project.ssr_data_runtime_entries(),
this.pages_project.edge_ssr_data_runtime_entries(),
))
}
Ok(api_entry_chunk)
#[turbo_tasks::function]
async fn api_chunk(self: Vc<Self>) -> Result<Vc<SsrChunk>> {
let this = self.await?;
Ok(self.internal_ssr_chunk(
Value::new(ReferenceType::Entry(EntryReferenceSubType::PagesApi)),
this.pages_project
.project()
.node_root()
.join("server".to_string()),
this.pages_project.ssr_module_context(),
this.pages_project.edge_ssr_module_context(),
this.pages_project.project().ssr_chunking_context(),
this.pages_project.project().edge_ssr_chunking_context(),
this.pages_project.ssr_runtime_entries(),
this.pages_project.edge_ssr_runtime_entries(),
))
}
#[turbo_tasks::function]
......@@ -572,50 +654,40 @@ impl PageEndpoint {
async fn output(self: Vc<Self>) -> Result<Vc<PageEndpointOutput>> {
let this = self.await?;
match this.ty {
let mut output_assets = vec![];
let ssr_chunk = match this.ty {
PageEndpointType::Html => {
let client_chunks = self.client_chunks();
let ssr_chunk = self.ssr_chunk();
output_assets.extend(client_chunks.await?.iter().copied());
let build_manifest = self.build_manifest(client_chunks);
let pages_manifest = self.pages_manifest(ssr_chunk);
Ok(PageEndpointOutput {
entry_chunk: ssr_chunk,
output_assets: Vc::cell(
client_chunks
.await?
.iter()
.copied()
.chain([ssr_chunk, build_manifest, pages_manifest])
.collect(),
),
}
.cell())
output_assets.push(build_manifest);
self.ssr_chunk()
}
PageEndpointType::Data => {
let ssr_data_chunk = self.ssr_data_chunk();
PageEndpointType::Data => self.ssr_data_chunk(),
PageEndpointType::Api => self.api_chunk(),
};
let pages_manifest = self.pages_manifest(ssr_data_chunk);
let page_output = match *ssr_chunk.await? {
SsrChunk::NodeJs { entry } => {
let pages_manifest = self.pages_manifest(entry);
output_assets.push(pages_manifest);
output_assets.push(entry);
Ok(PageEndpointOutput {
entry_chunk: ssr_data_chunk,
output_assets: Vc::cell(vec![ssr_data_chunk, pages_manifest]),
PageEndpointOutput::NodeJs {
entry_chunk: entry,
output_assets: Vc::cell(output_assets),
}
.cell())
}
PageEndpointType::Api => {
let api_chunk = self.api_chunk();
let pages_manifest = self.pages_manifest(api_chunk);
Ok(PageEndpointOutput {
entry_chunk: api_chunk,
output_assets: Vc::cell(vec![api_chunk, pages_manifest]),
SsrChunk::Edge { files } => {
output_assets.extend(files.await?.iter().copied());
PageEndpointOutput::Edge {
files,
output_assets: Vc::cell(output_assets),
}
.cell())
}
}
};
Ok(page_output.cell())
}
}
......@@ -623,53 +695,99 @@ impl PageEndpoint {
impl Endpoint for PageEndpoint {
#[turbo_tasks::function]
async fn write_to_disk(self: Vc<Self>) -> Result<Vc<WrittenEndpoint>> {
let PageEndpointOutput {
entry_chunk,
output_assets,
} = &*self.output().await?;
let output = self.output();
let output_assets = output.output_assets();
let this = self.await?;
let node_root = this.pages_project.project().node_root();
emit_all_assets(
*output_assets,
output_assets,
node_root,
this.pages_project.project().client_relative_path(),
this.pages_project.project().node_root(),
)
.await?;
let server_paths = all_server_paths(*output_assets, node_root)
let server_paths = all_server_paths(output_assets, node_root)
.await?
.clone_value();
Ok(WrittenEndpoint {
server_entry_path: this
.pages_project
.project()
.node_root()
.await?
.get_path_to(&*entry_chunk.ident().path().await?)
.context("ssr chunk entry path must be inside the node root")?
.to_string(),
server_paths,
}
.cell())
let node_root = &this.pages_project.project().node_root().await?;
let written_endpoint = match *output.await? {
PageEndpointOutput::NodeJs {
entry_chunk,
output_assets: _,
} => WrittenEndpoint::NodeJs {
server_entry_path: node_root
.get_path_to(&*entry_chunk.ident().path().await?)
.context("ssr chunk entry path must be inside the node root")?
.to_string(),
server_paths,
},
PageEndpointOutput::Edge {
files,
output_assets: _,
} => WrittenEndpoint::Edge {
files: files
.await?
.iter()
.map(|&file| async move {
Ok(node_root
.get_path_to(&*file.ident().path().await?)
.context("ssr chunk file path must be inside the node root")?
.to_string())
})
.try_join()
.await?,
global_var_name: "TODO".to_string(),
server_paths,
},
};
Ok(written_endpoint.cell())
}
#[turbo_tasks::function]
async fn changed(self: Vc<Self>) -> Result<Vc<Completion>> {
let PageEndpointOutput {
entry_chunk: _,
output_assets,
} = &*self.output().await?;
let output = self.output();
let output_assets = output.output_assets();
Ok(any_content_changed_of_output_assets(output_assets))
}
}
#[turbo_tasks::value]
enum PageEndpointOutput {
NodeJs {
entry_chunk: Vc<Box<dyn OutputAsset>>,
output_assets: Vc<OutputAssets>,
},
Edge {
files: Vc<OutputAssets>,
output_assets: Vc<OutputAssets>,
},
}
Ok(any_content_changed_of_output_assets(*output_assets))
#[turbo_tasks::value_impl]
impl PageEndpointOutput {
#[turbo_tasks::function]
pub fn output_assets(&self) -> Vc<OutputAssets> {
match *self {
PageEndpointOutput::NodeJs {
entry_chunk: _,
output_assets,
} => output_assets,
PageEndpointOutput::Edge {
files: _,
output_assets,
} => output_assets,
}
}
}
#[turbo_tasks::value]
struct PageEndpointOutput {
entry_chunk: Vc<Box<dyn OutputAsset>>,
output_assets: Vc<OutputAssets>,
pub enum SsrChunk {
NodeJs { entry: Vc<Box<dyn OutputAsset>> },
Edge { files: Vc<OutputAssets> },
}
......@@ -4,6 +4,7 @@ use anyhow::Result;
use indexmap::{map::Entry, IndexMap};
use next_core::{
app_structure::find_app_dir,
get_edge_chunking_context, get_edge_compile_time_info,
mode::NextMode,
next_client::{get_client_chunking_context, get_client_compile_time_info},
next_config::NextConfig,
......@@ -262,6 +263,15 @@ impl Project {
))
}
#[turbo_tasks::function]
pub(super) fn edge_compile_time_info(self: Vc<Self>) -> Vc<CompileTimeInfo> {
get_edge_compile_time_info(
self.project_path(),
// TODO(alexkirsz) Fill this out.
ServerAddr::empty(),
)
}
#[turbo_tasks::function]
pub(super) async fn client_chunking_context(
self: Vc<Self>,
......@@ -276,31 +286,65 @@ impl Project {
}
#[turbo_tasks::function]
pub(super) fn server_chunking_context(self: Vc<Self>) -> Vc<BuildChunkingContext> {
fn server_chunking_context(self: Vc<Self>) -> Vc<BuildChunkingContext> {
get_server_chunking_context(
self.project_path(),
self.node_root(),
self.client_fs().root(),
self.client_root(),
self.server_compile_time_info().environment(),
)
}
#[turbo_tasks::function]
fn edge_chunking_context(self: Vc<Self>) -> Vc<Box<dyn EcmascriptChunkingContext>> {
get_edge_chunking_context(
self.project_path(),
self.node_root(),
self.client_root(),
self.edge_compile_time_info().environment(),
)
}
#[turbo_tasks::function]
pub(super) fn ssr_chunking_context(self: Vc<Self>) -> Vc<BuildChunkingContext> {
self.server_chunking_context().with_layer("ssr".to_string())
}
#[turbo_tasks::function]
pub(super) fn edge_ssr_chunking_context(
self: Vc<Self>,
) -> Vc<Box<dyn EcmascriptChunkingContext>> {
self.edge_chunking_context()
.with_layer("edge ssr".to_string())
}
#[turbo_tasks::function]
pub(super) fn ssr_data_chunking_context(self: Vc<Self>) -> Vc<BuildChunkingContext> {
self.server_chunking_context()
.with_layer("ssr data".to_string())
}
#[turbo_tasks::function]
pub(super) fn edge_ssr_data_chunking_context(
self: Vc<Self>,
) -> Vc<Box<dyn EcmascriptChunkingContext>> {
self.edge_chunking_context()
.with_layer("edge ssr data".to_string())
}
#[turbo_tasks::function]
pub(super) fn rsc_chunking_context(self: Vc<Self>) -> Vc<BuildChunkingContext> {
self.server_chunking_context().with_layer("rsc".to_string())
}
#[turbo_tasks::function]
pub(super) fn edge_rsc_chunking_context(
self: Vc<Self>,
) -> Vc<Box<dyn EcmascriptChunkingContext>> {
self.edge_chunking_context()
.with_layer("edge rsc".to_string())
}
/// Scans the app/pages directories for entry points files (matching the
/// provided page_extensions).
#[turbo_tasks::function]
......
......@@ -29,11 +29,20 @@ pub trait Endpoint {
#[turbo_tasks::value(shared)]
#[derive(Debug)]
pub struct WrittenEndpoint {
/// Relative to the root_path
pub server_entry_path: String,
/// Relative to the root_path
pub server_paths: Vec<String>,
pub enum WrittenEndpoint {
NodeJs {
/// Relative to the root_path
server_entry_path: String,
/// Relative to the root_path
server_paths: Vec<String>,
},
Edge {
/// Relative to the root_path
files: Vec<String>,
global_var_name: String,
/// Relative to the root_path
server_paths: Vec<String>,
},
}
/// The routes as map from pathname to route. (pathname includes the leading
......
......@@ -190,6 +190,8 @@ pub async fn get_app_entries(
.map(|(pathname, entrypoint)| async move {
Ok(match entrypoint {
Entrypoint::AppPage { loader_tree } => get_app_page_entry(
rsc_context,
// TODO add edge support
rsc_context,
*loader_tree,
app_dir,
......@@ -197,6 +199,8 @@ pub async fn get_app_entries(
project_root,
),
Entrypoint::AppRoute { path } => get_app_route_entry(
rsc_context,
// TODO add edge support
rsc_context,
Vc::upcast(FileSource::new(*path)),
pathname.clone(),
......@@ -212,6 +216,8 @@ pub async fn get_app_entries(
if let Some(favicon) = global_metadata.favicon {
entries.push(get_app_route_favicon_entry(
rsc_context,
// TODO add edge support
rsc_context,
favicon,
project_root,
......
......@@ -48,8 +48,14 @@ pub mod url_node;
pub mod util;
mod web_entry_source;
pub use app_segment_config::{
parse_segment_config_from_loader_tree, parse_segment_config_from_source,
};
pub use app_source::create_app_source;
pub use emit::{all_server_paths, emit_all_assets};
pub use next_edge::context::{
get_edge_chunking_context, get_edge_compile_time_info, get_edge_resolve_options_context,
};
pub use page_loader::create_page_loader_entry_module;
pub use page_source::create_page_source;
pub use turbopack_binding::{turbopack::node::source_map, *};
......
use turbo_tasks::Vc;
use turbopack_binding::turbopack::ecmascript::chunk::EcmascriptChunkPlaceable;
use crate::app_segment_config::NextSegmentConfig;
/// The entry module asset for a Next.js app route or page.
#[turbo_tasks::value(shared)]
pub struct AppEntry {
......@@ -11,4 +13,6 @@ pub struct AppEntry {
pub original_name: String,
/// The RSC module asset for the route or page.
pub rsc_entry: Vc<Box<dyn EcmascriptChunkPlaceable>>,
/// The source code config for this entry.
pub config: Vc<NextSegmentConfig>,
}
......@@ -19,14 +19,15 @@ use crate::{app_structure::MetadataItem, next_app::AppEntry};
/// Computes the entry for a Next.js favicon file.
#[turbo_tasks::function]
pub async fn get_app_route_favicon_entry(
rsc_context: Vc<ModuleAssetContext>,
nodejs_context: Vc<ModuleAssetContext>,
edge_context: Vc<ModuleAssetContext>,
favicon: MetadataItem,
project_root: Vc<FileSystemPath>,
) -> Result<Vc<AppEntry>> {
let path = match favicon {
// TODO(alexkirsz) Is there a difference here?
MetadataItem::Static { path } => path,
MetadataItem::Dynamic { path } => path,
MetadataItem::Dynamic { path: _ } => bail!("Dynamic metadata is not implemented yet"),
};
let mut code = RopeBuilder::default();
......@@ -79,7 +80,8 @@ pub async fn get_app_route_favicon_entry(
VirtualSource::new(project_root.join("todo.tsx".to_string()), AssetContent::file(file.into()));
Ok(get_app_route_entry(
rsc_context,
nodejs_context,
edge_context,
Vc::upcast(source),
// TODO(alexkirsz) Get this from the metadata?
"/favicon.ico".to_string(),
......
......@@ -22,17 +22,27 @@ use crate::{
mode::NextMode,
next_app::UnsupportedDynamicMetadataIssue,
next_server_component::NextServerComponentTransition,
parse_segment_config_from_loader_tree,
util::NextRuntime,
};
/// Computes the entry for a Next.js app page.
#[turbo_tasks::function]
pub async fn get_app_page_entry(
context: Vc<ModuleAssetContext>,
nodejs_context: Vc<ModuleAssetContext>,
edge_context: Vc<ModuleAssetContext>,
loader_tree: Vc<LoaderTree>,
app_dir: Vc<FileSystemPath>,
pathname: String,
project_root: Vc<FileSystemPath>,
) -> Result<Vc<AppEntry>> {
let config = parse_segment_config_from_loader_tree(loader_tree, Vc::upcast(nodejs_context));
let context = if matches!(config.await?.runtime, Some(NextRuntime::Edge)) {
nodejs_context
} else {
edge_context
};
let server_component_transition = Vc::upcast(NextServerComponentTransition::new());
let loader_tree = LoaderTreeModule::build(
......@@ -111,6 +121,7 @@ pub async fn get_app_page_entry(
pathname: pathname.to_string(),
original_name,
rsc_entry,
config,
}
.cell())
}
......
......@@ -11,7 +11,9 @@ use turbopack_binding::{
core::{
asset::AssetContent,
context::AssetContext,
reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
reference_type::{
EcmaScriptModulesReferenceSubType, EntryReferenceSubType, ReferenceType,
},
source::Source,
virtual_source::VirtualSource,
},
......@@ -20,16 +22,30 @@ use turbopack_binding::{
},
};
use crate::next_app::AppEntry;
use crate::{next_app::AppEntry, parse_segment_config_from_source, util::NextRuntime};
/// Computes the entry for a Next.js app route.
#[turbo_tasks::function]
pub async fn get_app_route_entry(
rsc_context: Vc<ModuleAssetContext>,
nodejs_context: Vc<ModuleAssetContext>,
edge_context: Vc<ModuleAssetContext>,
source: Vc<Box<dyn Source>>,
pathname: String,
project_root: Vc<FileSystemPath>,
) -> Result<Vc<AppEntry>> {
let config = parse_segment_config_from_source(
nodejs_context.process(
source,
Value::new(ReferenceType::Entry(EntryReferenceSubType::AppRoute)),
),
source,
);
let context = if matches!(config.await?.runtime, Some(NextRuntime::Edge)) {
nodejs_context
} else {
edge_context
};
let mut result = RopeBuilder::default();
let kind = "app-route";
......@@ -105,7 +121,7 @@ pub async fn get_app_route_entry(
AssetContent::file(file.into()),
);
let entry = rsc_context.process(
let entry = context.process(
source,
Value::new(ReferenceType::EcmaScriptModules(
EcmaScriptModulesReferenceSubType::Undefined,
......@@ -116,7 +132,7 @@ pub async fn get_app_route_entry(
"ENTRY".to_string() => entry
};
let rsc_entry = rsc_context.process(
let rsc_entry = context.process(
Vc::upcast(virtual_source),
Value::new(ReferenceType::Internal(Vc::cell(inner_assets))),
);
......@@ -131,6 +147,7 @@ pub async fn get_app_route_entry(
pathname: pathname.to_string(),
original_name,
rsc_entry,
config,
}
.cell())
}
......
......@@ -11,15 +11,17 @@ use turbopack_binding::{
environment::{EdgeWorkerEnvironment, Environment, ExecutionEnvironment, ServerAddr},
free_var_references,
},
node::execution_context::ExecutionContext,
dev::DevChunkingContext,
ecmascript::chunk::EcmascriptChunkingContext,
node::{debug::should_debug, execution_context::ExecutionContext},
turbopack::resolve_options_context::ResolveOptionsContext,
},
};
use crate::{
mode::NextMode, next_config::NextConfig, next_import_map::get_next_edge_import_map,
next_server::context::ServerContextType, next_shared::resolve::UnsupportedModulesResolvePlugin,
util::foreign_code_context_condition,
mode::NextMode, next_client::context::get_client_assets_path, next_config::NextConfig,
next_import_map::get_next_edge_import_map, next_server::context::ServerContextType,
next_shared::resolve::UnsupportedModulesResolvePlugin, util::foreign_code_context_condition,
};
fn defines() -> CompileTimeDefines {
......@@ -108,3 +110,23 @@ pub async fn get_edge_resolve_options_context(
}
.cell())
}
#[turbo_tasks::function]
pub fn get_edge_chunking_context(
project_path: Vc<FileSystemPath>,
node_root: Vc<FileSystemPath>,
client_root: Vc<FileSystemPath>,
environment: Vc<Environment>,
) -> Vc<Box<dyn EcmascriptChunkingContext>> {
Vc::upcast(
DevChunkingContext::builder(
project_path,
node_root.join("edge".to_string()),
node_root.join("edge/chunks".to_string()),
get_client_assets_path(client_root),
environment,
)
.reference_chunk_source_maps(should_debug("edge"))
.build(),
)
}
......@@ -96,7 +96,20 @@ pub async fn foreign_code_context_condition(
Ok(result)
}
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, TraceRawVcs, Serialize, Deserialize)]
#[derive(
Default,
PartialEq,
Eq,
Clone,
Copy,
Debug,
TraceRawVcs,
Serialize,
Deserialize,
Hash,
PartialOrd,
Ord,
)]
#[serde(rename_all = "lowercase")]
pub enum NextRuntime {
#[default]
......
......@@ -450,13 +450,23 @@ interface EndpointConfig {
preferredRegion?: string
}
interface WrittenEndpoint {
/** The entry path for the endpoint. */
entryPath: string
/** All paths that has been written for the endpoint. */
paths: string[]
config: EndpointConfig
}
type WrittenEndpoint =
| {
type: 'nodejs'
/** The entry path for the endpoint. */
entryPath: string
/** All server paths that has been written for the endpoint. */
serverPaths: string[]
config: EndpointConfig
}
| {
type: 'edge'
files: string[]
/** All server paths that has been written for the endpoint. */
serverPaths: string[]
globalVarName: string
config: EndpointConfig
}
// TODO(sokra) Support wasm option.
function bindingToApi(binding: any, _wasm: boolean) {
......
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