|
|
use std::{collections::BTreeMap, io::Write}; |
|
|
|
|
|
use anyhow::{Context, Result, bail}; |
|
|
use next_core::{ |
|
|
next_manifests::{ |
|
|
ActionLayer, ActionManifestModuleId, ActionManifestWorkerEntry, ServerReferenceManifest, |
|
|
}, |
|
|
util::NextRuntime, |
|
|
}; |
|
|
use swc_core::{ |
|
|
atoms::Atom, |
|
|
common::comments::Comments, |
|
|
ecma::{ |
|
|
ast::{ |
|
|
Decl, ExportSpecifier, Id, ModuleDecl, ModuleItem, ObjectLit, Program, |
|
|
PropOrSpread::Prop, |
|
|
}, |
|
|
utils::find_pat_ids, |
|
|
}, |
|
|
}; |
|
|
use turbo_rcstr::{RcStr, rcstr}; |
|
|
use turbo_tasks::{FxIndexMap, ResolvedVc, TryFlatJoinIterExt, ValueToString, Vc}; |
|
|
use turbo_tasks_fs::{self, File, FileSystemPath, rope::RopeBuilder}; |
|
|
use turbopack_core::{ |
|
|
asset::AssetContent, |
|
|
chunk::{ChunkItem, ChunkItemExt, ChunkableModule, ChunkingContext, EvaluatableAsset}, |
|
|
context::AssetContext, |
|
|
file_source::FileSource, |
|
|
ident::AssetIdent, |
|
|
module::Module, |
|
|
module_graph::{ |
|
|
ModuleGraph, SingleModuleGraph, SingleModuleGraphModuleNode, |
|
|
async_module_info::AsyncModulesInfo, |
|
|
}, |
|
|
output::OutputAsset, |
|
|
reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType}, |
|
|
resolve::ModulePart, |
|
|
virtual_output::VirtualOutputAsset, |
|
|
virtual_source::VirtualSource, |
|
|
}; |
|
|
use turbopack_ecmascript::{ |
|
|
EcmascriptParsable, chunk::EcmascriptChunkPlaceable, parse::ParseResult, |
|
|
tree_shake::asset::EcmascriptModulePartAsset, |
|
|
}; |
|
|
|
|
|
#[turbo_tasks::value] |
|
|
pub(crate) struct ServerActionsManifest { |
|
|
pub loader: ResolvedVc<Box<dyn EvaluatableAsset>>, |
|
|
pub manifest: ResolvedVc<Box<dyn OutputAsset>>, |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#[turbo_tasks::function] |
|
|
pub(crate) async fn create_server_actions_manifest( |
|
|
actions: Vc<AllActions>, |
|
|
project_path: FileSystemPath, |
|
|
node_root: FileSystemPath, |
|
|
page_name: RcStr, |
|
|
runtime: NextRuntime, |
|
|
rsc_asset_context: Vc<Box<dyn AssetContext>>, |
|
|
module_graph: Vc<ModuleGraph>, |
|
|
chunking_context: Vc<Box<dyn ChunkingContext>>, |
|
|
) -> Result<Vc<ServerActionsManifest>> { |
|
|
let loader = |
|
|
build_server_actions_loader(project_path, page_name.clone(), actions, rsc_asset_context); |
|
|
let evaluable = Vc::try_resolve_sidecast::<Box<dyn EvaluatableAsset>>(loader) |
|
|
.await? |
|
|
.context("loader module must be evaluatable")? |
|
|
.to_resolved() |
|
|
.await?; |
|
|
|
|
|
let chunk_item = loader.as_chunk_item(module_graph, Vc::upcast(chunking_context)); |
|
|
let manifest = build_manifest( |
|
|
node_root, |
|
|
page_name, |
|
|
runtime, |
|
|
actions, |
|
|
chunk_item, |
|
|
module_graph.async_module_info(), |
|
|
) |
|
|
.await?; |
|
|
Ok(ServerActionsManifest { |
|
|
loader: evaluable, |
|
|
manifest, |
|
|
} |
|
|
.cell()) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#[turbo_tasks::function] |
|
|
pub(crate) async fn build_server_actions_loader( |
|
|
project_path: FileSystemPath, |
|
|
page_name: RcStr, |
|
|
actions: Vc<AllActions>, |
|
|
asset_context: Vc<Box<dyn AssetContext>>, |
|
|
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> { |
|
|
let actions = actions.await?; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let mut contents = RopeBuilder::from(""); |
|
|
let mut import_map = FxIndexMap::default(); |
|
|
for (hash_id, (_layer, name, module)) in actions.iter() { |
|
|
let index = import_map.len(); |
|
|
let module_name = import_map |
|
|
.entry(*module) |
|
|
.or_insert_with(|| format!("ACTIONS_MODULE{index}").into()); |
|
|
writeln!( |
|
|
contents, |
|
|
"export {{{name} as '{hash_id}'}} from '{module_name}'" |
|
|
)?; |
|
|
} |
|
|
|
|
|
let path = project_path.join(&format!(".next-internal/server/app{page_name}/actions.js"))?; |
|
|
let file = File::from(contents.build()); |
|
|
let source = VirtualSource::new_with_ident( |
|
|
AssetIdent::from_path(path).with_modifier(rcstr!("server actions loader")), |
|
|
AssetContent::file(file.into()), |
|
|
); |
|
|
let import_map = import_map.into_iter().map(|(k, v)| (v, k)).collect(); |
|
|
let module = asset_context |
|
|
.process( |
|
|
Vc::upcast(source), |
|
|
ReferenceType::Internal(ResolvedVc::cell(import_map)), |
|
|
) |
|
|
.module(); |
|
|
|
|
|
let Some(placeable) = |
|
|
Vc::try_resolve_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(module).await? |
|
|
else { |
|
|
bail!("internal module must be evaluatable"); |
|
|
}; |
|
|
|
|
|
Ok(placeable) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
async fn build_manifest( |
|
|
node_root: FileSystemPath, |
|
|
page_name: RcStr, |
|
|
runtime: NextRuntime, |
|
|
actions: Vc<AllActions>, |
|
|
chunk_item: Vc<Box<dyn ChunkItem>>, |
|
|
async_module_info: Vc<AsyncModulesInfo>, |
|
|
) -> Result<ResolvedVc<Box<dyn OutputAsset>>> { |
|
|
let manifest_path_prefix = &page_name; |
|
|
let manifest_path = node_root.join(&format!( |
|
|
"server/app{manifest_path_prefix}/server-reference-manifest.json", |
|
|
))?; |
|
|
let mut manifest = ServerReferenceManifest { |
|
|
..Default::default() |
|
|
}; |
|
|
|
|
|
let key = format!("app{page_name}"); |
|
|
|
|
|
let actions_value = actions.await?; |
|
|
let loader_id = chunk_item.id().to_string().await?; |
|
|
let mapping = match runtime { |
|
|
NextRuntime::Edge => &mut manifest.edge, |
|
|
NextRuntime::NodeJs => &mut manifest.node, |
|
|
}; |
|
|
|
|
|
for (hash_id, (layer, _name, _module)) in actions_value { |
|
|
let entry = mapping.entry(hash_id.as_str()).or_default(); |
|
|
entry.workers.insert( |
|
|
&key, |
|
|
ActionManifestWorkerEntry { |
|
|
module_id: ActionManifestModuleId::String(loader_id.as_str()), |
|
|
is_async: *async_module_info.is_async(chunk_item.module()).await?, |
|
|
}, |
|
|
); |
|
|
entry.layer.insert(&key, *layer); |
|
|
} |
|
|
|
|
|
Ok(ResolvedVc::upcast( |
|
|
VirtualOutputAsset::new( |
|
|
manifest_path, |
|
|
AssetContent::file(File::from(serde_json::to_string_pretty(&manifest)?).into()), |
|
|
) |
|
|
.to_resolved() |
|
|
.await?, |
|
|
)) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
pub async fn to_rsc_context( |
|
|
client_module: Vc<Box<dyn Module>>, |
|
|
entry_path: &str, |
|
|
entry_query: &str, |
|
|
asset_context: Vc<Box<dyn AssetContext>>, |
|
|
) -> Result<ResolvedVc<Box<dyn Module>>> { |
|
|
|
|
|
|
|
|
|
|
|
let source = FileSource::new_with_query( |
|
|
client_module |
|
|
.ident() |
|
|
.path() |
|
|
.await? |
|
|
.root() |
|
|
.await? |
|
|
.join(entry_path)?, |
|
|
entry_query.into(), |
|
|
); |
|
|
let module = asset_context |
|
|
.process( |
|
|
Vc::upcast(source), |
|
|
ReferenceType::EcmaScriptModules(EcmaScriptModulesReferenceSubType::Undefined), |
|
|
) |
|
|
.module() |
|
|
.to_resolved() |
|
|
.await?; |
|
|
Ok(module) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pub fn parse_server_actions( |
|
|
program: &Program, |
|
|
comments: &dyn Comments, |
|
|
) -> Option<(BTreeMap<String, String>, String, String)> { |
|
|
let byte_pos = match program { |
|
|
Program::Module(m) => m.span.lo, |
|
|
Program::Script(s) => s.span.lo, |
|
|
}; |
|
|
comments.get_leading(byte_pos).and_then(|comments| { |
|
|
comments.iter().find_map(|c| { |
|
|
c.text |
|
|
.split_once("__next_internal_action_entry_do_not_use__") |
|
|
.and_then(|(_, actions)| serde_json::from_str(actions).ok()) |
|
|
}) |
|
|
}) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
#[turbo_tasks::function] |
|
|
async fn parse_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<OptionActionMap>> { |
|
|
let Some(ecmascript_asset) = |
|
|
Vc::try_resolve_sidecast::<Box<dyn EcmascriptParsable>>(module).await? |
|
|
else { |
|
|
return Ok(Vc::cell(None)); |
|
|
}; |
|
|
|
|
|
if let Some(module) = Vc::try_resolve_downcast_type::<EcmascriptModulePartAsset>(module).await? |
|
|
&& matches!( |
|
|
module.await?.part, |
|
|
ModulePart::Evaluation | ModulePart::Facade |
|
|
) |
|
|
{ |
|
|
return Ok(Vc::cell(None)); |
|
|
} |
|
|
|
|
|
let original_parsed = ecmascript_asset.parse_original().resolve().await?; |
|
|
|
|
|
let ParseResult::Ok { |
|
|
program: original, |
|
|
comments, |
|
|
.. |
|
|
} = &*original_parsed.await? |
|
|
else { |
|
|
|
|
|
return Ok(Vc::cell(None)); |
|
|
}; |
|
|
|
|
|
let Some((mut actions, entry_path, entry_query)) = parse_server_actions(original, comments) |
|
|
else { |
|
|
return Ok(Vc::cell(None)); |
|
|
}; |
|
|
|
|
|
let fragment = ecmascript_asset.failsafe_parse().resolve().await?; |
|
|
|
|
|
if fragment != original_parsed { |
|
|
let ParseResult::Ok { |
|
|
program: fragment, .. |
|
|
} = &*fragment.await? |
|
|
else { |
|
|
|
|
|
return Ok(Vc::cell(None)); |
|
|
}; |
|
|
|
|
|
let all_exports = all_export_names(fragment); |
|
|
actions.retain(|_, name| all_exports.iter().any(|export| export == name)); |
|
|
} |
|
|
|
|
|
let mut actions = FxIndexMap::from_iter(actions.into_iter()); |
|
|
actions.sort_keys(); |
|
|
Ok(Vc::cell(Some( |
|
|
ActionMap { |
|
|
actions, |
|
|
entry_path, |
|
|
entry_query, |
|
|
} |
|
|
.resolved_cell(), |
|
|
))) |
|
|
} |
|
|
|
|
|
fn all_export_names(program: &Program) -> Vec<Atom> { |
|
|
match program { |
|
|
Program::Module(m) => { |
|
|
let mut exports = Vec::new(); |
|
|
for item in m.body.iter() { |
|
|
match item { |
|
|
ModuleItem::ModuleDecl( |
|
|
ModuleDecl::ExportDefaultExpr(..) | ModuleDecl::ExportDefaultDecl(..), |
|
|
) => { |
|
|
exports.push("default".into()); |
|
|
} |
|
|
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(decl)) => match &decl.decl { |
|
|
Decl::Class(c) => { |
|
|
exports.push(c.ident.sym.clone()); |
|
|
} |
|
|
Decl::Fn(f) => { |
|
|
exports.push(f.ident.sym.clone()); |
|
|
} |
|
|
Decl::Var(v) => { |
|
|
let ids: Vec<Id> = find_pat_ids(v); |
|
|
exports.extend(ids.into_iter().map(|id| id.0)); |
|
|
} |
|
|
_ => {} |
|
|
}, |
|
|
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(decl)) => { |
|
|
if is_turbopack_internal_var(&decl.with) { |
|
|
continue; |
|
|
} |
|
|
|
|
|
for s in decl.specifiers.iter() { |
|
|
match s { |
|
|
ExportSpecifier::Named(named) => { |
|
|
exports.push( |
|
|
named |
|
|
.exported |
|
|
.as_ref() |
|
|
.unwrap_or(&named.orig) |
|
|
.atom() |
|
|
.clone(), |
|
|
); |
|
|
} |
|
|
ExportSpecifier::Default(_) => { |
|
|
exports.push("default".into()); |
|
|
} |
|
|
ExportSpecifier::Namespace(e) => { |
|
|
exports.push(e.name.atom().clone()); |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
_ => {} |
|
|
} |
|
|
} |
|
|
exports |
|
|
} |
|
|
|
|
|
_ => { |
|
|
vec![] |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
fn is_turbopack_internal_var(with: &Option<Box<ObjectLit>>) -> bool { |
|
|
with.as_deref() |
|
|
.and_then(|v| { |
|
|
v.props.iter().find_map(|p| match p { |
|
|
Prop(prop) => match &**prop { |
|
|
swc_core::ecma::ast::Prop::KeyValue(key_value_prop) => { |
|
|
if key_value_prop.key.as_ident()?.sym == "__turbopack_var__" { |
|
|
Some(key_value_prop.value.as_lit()?.as_bool()?.value) |
|
|
} else { |
|
|
None |
|
|
} |
|
|
} |
|
|
_ => None, |
|
|
}, |
|
|
_ => None, |
|
|
}) |
|
|
}) |
|
|
.unwrap_or(false) |
|
|
} |
|
|
|
|
|
type HashToLayerNameModule = FxIndexMap<String, (ActionLayer, String, ResolvedVc<Box<dyn Module>>)>; |
|
|
|
|
|
|
|
|
|
|
|
#[turbo_tasks::value(transparent)] |
|
|
pub struct AllActions(HashToLayerNameModule); |
|
|
|
|
|
#[turbo_tasks::value_impl] |
|
|
impl AllActions { |
|
|
#[turbo_tasks::function] |
|
|
pub fn empty() -> Vc<Self> { |
|
|
Vc::cell(FxIndexMap::default()) |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
#[turbo_tasks::value] |
|
|
#[derive(Debug)] |
|
|
pub struct ActionMap { |
|
|
pub actions: FxIndexMap<String, String>, |
|
|
pub entry_path: String, |
|
|
pub entry_query: String, |
|
|
} |
|
|
|
|
|
|
|
|
#[turbo_tasks::value(transparent)] |
|
|
struct OptionActionMap(Option<ResolvedVc<ActionMap>>); |
|
|
|
|
|
type LayerAndActions = (ActionLayer, ResolvedVc<ActionMap>); |
|
|
|
|
|
#[turbo_tasks::value(transparent)] |
|
|
pub struct AllModuleActions(FxIndexMap<ResolvedVc<Box<dyn Module>>, LayerAndActions>); |
|
|
|
|
|
#[turbo_tasks::function] |
|
|
pub async fn map_server_actions(graph: Vc<SingleModuleGraph>) -> Result<Vc<AllModuleActions>> { |
|
|
let actions = graph |
|
|
.await? |
|
|
.iter_nodes() |
|
|
.map(|node| { |
|
|
async move { |
|
|
let SingleModuleGraphModuleNode { module } = node; |
|
|
|
|
|
let layer = match module.ident().await?.layer.as_ref() { |
|
|
Some(layer) if layer.name() == "app-rsc" || layer.name() == "app-edge-rsc" => { |
|
|
ActionLayer::Rsc |
|
|
} |
|
|
Some(layer) if layer.name() == "app-client" => ActionLayer::ActionBrowser, |
|
|
|
|
|
_ => return Ok(None), |
|
|
}; |
|
|
|
|
|
|
|
|
Ok(parse_actions(**module) |
|
|
.await? |
|
|
.map(|action_map| (*module, (layer, action_map)))) |
|
|
} |
|
|
}) |
|
|
.try_flat_join() |
|
|
.await?; |
|
|
Ok(Vc::cell(actions.into_iter().collect())) |
|
|
} |
|
|
|