File size: 16,025 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
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>>,
}
/// Scans the RSC entry point's full module graph looking for exported Server
/// Actions (identifiable by a magic comment in the transformed module's
/// output), and constructs a evaluatable "action loader" entry point and
/// manifest describing the found actions.
///
/// If Server Actions are not enabled, this returns an empty manifest and a None
/// loader.
#[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())
}
/// Builds the "action loader" entry point, which reexports every found action
/// behind a lazy dynamic import.
///
/// The actions are reexported under a hashed name (comprised of the exporting
/// file's name and the action name). This hash matches the id sent to the
/// client and present inside the paired manifest.
#[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?;
// Every module which exports an action (that is accessible starting from
// our app page entry point) will be present. We generate a single loader
// file which re-exports the respective module's action function using the
// hashed ID as export name.
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)
}
/// Builds a manifest containing every action's hashed id, with an internal
/// module id which exports a function using that hashed name.
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?,
))
}
/// The ActionBrowser layer's module is in the Client context, and we need to
/// bring it into the RSC context.
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>>> {
// TODO a cleaner solution would something similar to the EcmascriptClientReferenceModule, as
// opposed to the following hack to construct the RSC module corresponding to this client
// 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)
}
/// Parses the Server Actions comment for all exported action function names.
///
/// Action names are stored in a leading BlockComment prefixed by
/// `__next_internal_action_entry_do_not_use__`.
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())
})
})
}
/// Inspects the comments inside [Module] looking for the magic actions comment.
/// If found, we return the mapping of every action's hashed id to the name of
/// the exported action function. If not, we return a None.
#[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 {
// The file might be parse-able, but this is reported separately.
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 {
// The file might be be parse-able, but this is reported separately.
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>>)>;
/// A mapping of every module which exports a Server Action, with the hashed id
/// and exported name of each found action.
#[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())
}
}
/// Maps the hashed action id to the action's exported function name.
#[turbo_tasks::value]
#[derive(Debug)]
pub struct ActionMap {
pub actions: FxIndexMap<String, String>,
pub entry_path: String,
pub entry_query: String,
}
/// An Option wrapper around [ActionMap].
#[turbo_tasks::value(transparent)]
struct OptionActionMap(Option<ResolvedVc<ActionMap>>);
type LayerAndActions = (ActionLayer, ResolvedVc<ActionMap>);
/// A mapping of every module module containing Server Actions, mapping to its layer and actions.
#[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;
// TODO: compare module contexts instead?
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,
// TODO really ignore SSR?
_ => return Ok(None),
};
// TODO the old implementation did parse_actions(to_rsc_context(module))
// is that really necessary?
Ok(parse_actions(**module)
.await?
.map(|action_map| (*module, (layer, action_map))))
}
})
.try_flat_join()
.await?;
Ok(Vc::cell(actions.into_iter().collect()))
}
|