File size: 10,233 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 |
#![feature(min_specialization)]
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
use std::{iter::once, thread::available_parallelism};
use anyhow::{Result, bail};
pub use node_entry::{NodeEntry, NodeRenderingEntries, NodeRenderingEntry};
use rustc_hash::FxHashMap;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexSet, ResolvedVc, TryJoinIterExt, Vc,
graph::{AdjacencyMap, GraphTraversal},
};
use turbo_tasks_env::ProcessEnv;
use turbo_tasks_fs::{File, FileSystemPath, to_sys_path};
use turbopack_core::{
asset::{Asset, AssetContent},
changed::content_changed,
chunk::{ChunkingContext, ChunkingContextExt, EvaluatableAsset, EvaluatableAssets},
module::Module,
module_graph::{ModuleGraph, chunk_group_info::ChunkGroupEntry},
output::{OutputAsset, OutputAssets, OutputAssetsSet},
source_map::GenerateSourceMap,
virtual_output::VirtualOutputAsset,
};
use self::{pool::NodeJsPool, source_map::StructuredError};
pub mod debug;
pub mod embed_js;
pub mod evaluate;
pub mod execution_context;
mod node_entry;
mod pool;
pub mod render;
pub mod route_matcher;
pub mod source_map;
pub mod transforms;
#[turbo_tasks::function]
async fn emit(
intermediate_asset: Vc<Box<dyn OutputAsset>>,
intermediate_output_path: FileSystemPath,
) -> Result<()> {
for asset in internal_assets(intermediate_asset, intermediate_output_path).await? {
let _ = asset
.content()
.write(asset.path().owned().await?)
.resolve()
.await?;
}
Ok(())
}
/// List of the all assets of the "internal" subgraph and a list of boundary
/// assets that are not considered "internal" ("external")
#[derive(Debug)]
#[turbo_tasks::value]
struct SeparatedAssets {
internal_assets: ResolvedVc<OutputAssetsSet>,
external_asset_entrypoints: ResolvedVc<OutputAssetsSet>,
}
/// Extracts the subgraph of "internal" assets (assets within the passes
/// directory). Also lists all boundary assets that are not part of the
/// "internal" subgraph.
#[turbo_tasks::function]
async fn internal_assets(
intermediate_asset: ResolvedVc<Box<dyn OutputAsset>>,
intermediate_output_path: FileSystemPath,
) -> Result<Vc<OutputAssetsSet>> {
Ok(
*separate_assets_operation(intermediate_asset, intermediate_output_path)
.read_strongly_consistent()
.await?
.internal_assets,
)
}
#[turbo_tasks::value(transparent)]
pub struct AssetsForSourceMapping(FxHashMap<String, ResolvedVc<Box<dyn GenerateSourceMap>>>);
/// Extracts a map of "internal" assets ([`internal_assets`]) which implement
/// the [GenerateSourceMap] trait.
#[turbo_tasks::function]
async fn internal_assets_for_source_mapping(
intermediate_asset: Vc<Box<dyn OutputAsset>>,
intermediate_output_path: FileSystemPath,
) -> Result<Vc<AssetsForSourceMapping>> {
let internal_assets =
internal_assets(intermediate_asset, intermediate_output_path.clone()).await?;
let intermediate_output_path = intermediate_output_path.clone();
let mut internal_assets_for_source_mapping = FxHashMap::default();
for asset in internal_assets.iter() {
if let Some(generate_source_map) =
ResolvedVc::try_sidecast::<Box<dyn GenerateSourceMap>>(*asset)
&& let Some(path) = intermediate_output_path.get_path_to(&*asset.path().await?)
{
internal_assets_for_source_mapping.insert(path.to_string(), generate_source_map);
}
}
Ok(Vc::cell(internal_assets_for_source_mapping))
}
/// Returns a set of "external" assets on the boundary of the "internal"
/// subgraph
#[turbo_tasks::function]
pub async fn external_asset_entrypoints(
module: Vc<Box<dyn EvaluatableAsset>>,
runtime_entries: Vc<EvaluatableAssets>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
intermediate_output_path: FileSystemPath,
) -> Result<Vc<OutputAssetsSet>> {
Ok(*separate_assets_operation(
get_intermediate_asset(chunking_context, module, runtime_entries)
.to_resolved()
.await?,
intermediate_output_path,
)
.read_strongly_consistent()
.await?
.external_asset_entrypoints)
}
/// Splits the asset graph into "internal" assets and boundaries to "external"
/// assets.
#[turbo_tasks::function(operation)]
async fn separate_assets_operation(
intermediate_asset: ResolvedVc<Box<dyn OutputAsset>>,
intermediate_output_path: FileSystemPath,
) -> Result<Vc<SeparatedAssets>> {
let intermediate_output_path = intermediate_output_path.clone();
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
enum Type {
Internal(ResolvedVc<Box<dyn OutputAsset>>),
External(ResolvedVc<Box<dyn OutputAsset>>),
}
let get_asset_children = |asset| {
let intermediate_output_path = intermediate_output_path.clone();
async move {
let Type::Internal(asset) = asset else {
return Ok(Vec::new());
};
asset
.references()
.await?
.iter()
.map(|asset| async {
// Assets within the output directory are considered as "internal" and all
// others as "external". We follow references on "internal" assets, but do not
// look into references of "external" assets, since there are no "internal"
// assets behind "externals"
if asset.path().await?.is_inside_ref(&intermediate_output_path) {
Ok(Type::Internal(*asset))
} else {
Ok(Type::External(*asset))
}
})
.try_join()
.await
}
};
let graph = AdjacencyMap::new()
.skip_duplicates()
.visit(once(Type::Internal(intermediate_asset)), get_asset_children)
.await
.completed()?
.into_inner();
let mut internal_assets = FxIndexSet::default();
let mut external_asset_entrypoints = FxIndexSet::default();
for item in graph.into_postorder_topological() {
match item {
Type::Internal(asset) => {
internal_assets.insert(asset);
}
Type::External(asset) => {
external_asset_entrypoints.insert(asset);
}
}
}
Ok(SeparatedAssets {
internal_assets: ResolvedVc::cell(internal_assets),
external_asset_entrypoints: ResolvedVc::cell(external_asset_entrypoints),
}
.cell())
}
/// Emit a basic package.json that sets the type of the package to commonjs.
/// Currently code generated for Node is CommonJS, while authored code may be
/// ESM, for example.
fn emit_package_json(dir: FileSystemPath) -> Result<Vc<()>> {
Ok(emit(
Vc::upcast(VirtualOutputAsset::new(
dir.join("package.json")?,
AssetContent::file(File::from("{\"type\": \"commonjs\"}").into()),
)),
dir,
))
}
/// Creates a node.js renderer pool for an entrypoint.
#[turbo_tasks::function(operation)]
pub async fn get_renderer_pool_operation(
cwd: FileSystemPath,
env: ResolvedVc<Box<dyn ProcessEnv>>,
intermediate_asset: ResolvedVc<Box<dyn OutputAsset>>,
intermediate_output_path: FileSystemPath,
output_root: FileSystemPath,
project_dir: FileSystemPath,
debug: bool,
) -> Result<Vc<NodeJsPool>> {
emit_package_json(intermediate_output_path.clone())?.await?;
emit(*intermediate_asset, output_root.clone())
.as_side_effect()
.await?;
let assets_for_source_mapping =
internal_assets_for_source_mapping(*intermediate_asset, output_root.clone());
let entrypoint = intermediate_asset.path().owned().await?;
let Some(cwd) = to_sys_path(cwd.clone()).await? else {
bail!(
"can only render from a disk filesystem, but `cwd = {}`",
cwd.value_to_string().await?
);
};
let Some(entrypoint) = to_sys_path(entrypoint.clone()).await? else {
bail!(
"can only render from a disk filesystem, but `entrypoint = {}`",
entrypoint.value_to_string().await?
);
};
// Invalidate pool when code content changes
content_changed(*ResolvedVc::upcast(intermediate_asset)).await?;
Ok(NodeJsPool::new(
cwd,
entrypoint,
env.read_all()
.await?
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
assets_for_source_mapping.to_resolved().await?,
output_root,
project_dir,
available_parallelism().map_or(1, |v| v.get()),
debug,
)
.cell())
}
/// Converts a module graph into node.js executable assets
#[turbo_tasks::function]
pub async fn get_intermediate_asset(
chunking_context: Vc<Box<dyn ChunkingContext>>,
main_entry: ResolvedVc<Box<dyn EvaluatableAsset>>,
other_entries: Vc<EvaluatableAssets>,
) -> Result<Vc<Box<dyn OutputAsset>>> {
Ok(Vc::upcast(
chunking_context.root_entry_chunk_group_asset(
chunking_context
.chunk_path(None, main_entry.ident(), None, rcstr!(".js"))
.owned()
.await?,
other_entries.with_entry(*main_entry),
ModuleGraph::from_modules(
Vc::cell(vec![ChunkGroupEntry::Entry(
other_entries
.await?
.into_iter()
.copied()
.chain(std::iter::once(main_entry))
.map(ResolvedVc::upcast)
.collect(),
)]),
false,
),
OutputAssets::empty(),
),
))
}
#[derive(Clone, Debug)]
#[turbo_tasks::value(shared)]
pub struct ResponseHeaders {
pub status: u16,
pub headers: Vec<(RcStr, RcStr)>,
}
pub fn register() {
turbo_tasks::register();
turbo_tasks_bytes::register();
turbo_tasks_fs::register();
turbopack_dev_server::register();
turbopack_ecmascript::register();
include!(concat!(env!("OUT_DIR"), "/register.rs"));
}
|