use anyhow::Result; use mime_guess::mime::TEXT_HTML_UTF_8; use serde::{Deserialize, Serialize}; use turbo_rcstr::RcStr; use turbo_tasks::{ NonLocalValue, ReadRef, ResolvedVc, TaskInput, TryJoinIterExt, Vc, trace::TraceRawVcs, }; use turbo_tasks_fs::{File, FileSystemPath}; use turbo_tasks_hash::{Xxh3Hash64Hasher, encode_hex}; use turbopack_core::{ asset::{Asset, AssetContent}, chunk::{ ChunkableModule, ChunkingContext, ChunkingContextExt, EvaluatableAssets, availability_info::AvailabilityInfo, }, module::Module, module_graph::{ModuleGraph, chunk_group_info::ChunkGroup}, output::{OutputAsset, OutputAssets}, version::{Version, VersionedContent}, }; #[derive( Clone, Debug, Deserialize, Eq, Hash, NonLocalValue, PartialEq, Serialize, TaskInput, TraceRawVcs, )] pub struct DevHtmlEntry { pub chunkable_module: ResolvedVc>, pub module_graph: ResolvedVc, pub chunking_context: ResolvedVc>, pub runtime_entries: Option>, } /// The HTML entry point of the dev server. /// /// Generates an HTML page that includes the ES and CSS chunks. #[turbo_tasks::value(shared)] #[derive(Clone)] pub struct DevHtmlAsset { path: FileSystemPath, entries: Vec, body: Option, } #[turbo_tasks::value_impl] impl OutputAsset for DevHtmlAsset { #[turbo_tasks::function] fn path(&self) -> Vc { self.path.clone().cell() } #[turbo_tasks::function] fn references(self: Vc) -> Vc { self.chunks() } } #[turbo_tasks::value_impl] impl Asset for DevHtmlAsset { #[turbo_tasks::function] fn content(self: Vc) -> Vc { self.html_content().content() } #[turbo_tasks::function] fn versioned_content(self: Vc) -> Vc> { Vc::upcast(self.html_content()) } } impl DevHtmlAsset { /// Create a new dev HTML asset. pub fn new(path: FileSystemPath, entries: Vec) -> Vc { DevHtmlAsset { path, entries, body: None, } .cell() } /// Create a new dev HTML asset. pub fn new_with_body( path: FileSystemPath, entries: Vec, body: RcStr, ) -> Vc { DevHtmlAsset { path, entries, body: Some(body), } .cell() } } #[turbo_tasks::value_impl] impl DevHtmlAsset { #[turbo_tasks::function] pub async fn with_path(self: Vc, path: FileSystemPath) -> Result> { let mut html: DevHtmlAsset = self.owned().await?; html.path = path; Ok(html.cell()) } #[turbo_tasks::function] pub async fn with_body(self: Vc, body: RcStr) -> Result> { let mut html: DevHtmlAsset = self.owned().await?; html.body = Some(body); Ok(html.cell()) } } #[turbo_tasks::value_impl] impl DevHtmlAsset { #[turbo_tasks::function] async fn html_content(self: Vc) -> Result> { let this = self.await?; let context_path = this.path.parent(); let mut chunk_paths = vec![]; for chunk in &*self.chunks().await? { let chunk_path = &*chunk.path().await?; if let Some(relative_path) = context_path.get_path_to(chunk_path) { chunk_paths.push(format!("/{relative_path}").into()); } } Ok(DevHtmlAssetContent::new(chunk_paths, this.body.clone())) } #[turbo_tasks::function] async fn chunks(&self) -> Result> { let all_assets = self .entries .iter() .map(|entry| async move { let &DevHtmlEntry { chunkable_module, chunking_context, module_graph, runtime_entries, } = entry; let assets = if let Some(runtime_entries) = runtime_entries { let runtime_entries = if let Some(evaluatable) = ResolvedVc::try_downcast(chunkable_module) { runtime_entries .with_entry(*evaluatable) .to_resolved() .await? } else { runtime_entries }; chunking_context.evaluated_chunk_group_assets( chunkable_module.ident(), ChunkGroup::Entry( runtime_entries .await? .iter() .map(|v| ResolvedVc::upcast(*v)) .collect(), ), *module_graph, AvailabilityInfo::Root, ) } else { chunking_context.root_chunk_group_assets( chunkable_module.ident(), ChunkGroup::Entry(vec![ResolvedVc::upcast(chunkable_module)]), *module_graph, ) }; assets.await }) .try_join() .await? .iter() .flatten() .copied() .collect(); Ok(Vc::cell(all_assets)) } } #[turbo_tasks::value(operation)] struct DevHtmlAssetContent { chunk_paths: Vec, body: Option, } impl DevHtmlAssetContent { fn new(chunk_paths: Vec, body: Option) -> Vc { DevHtmlAssetContent { chunk_paths, body }.cell() } } #[turbo_tasks::value_impl] impl DevHtmlAssetContent { #[turbo_tasks::function] fn content(&self) -> Result> { let mut scripts = Vec::new(); let mut stylesheets = Vec::new(); for relative_path in &*self.chunk_paths { if relative_path.ends_with(".js") { scripts.push(format!("")); } else if relative_path.ends_with(".css") { stylesheets.push(format!( "" )); } else { anyhow::bail!("chunk with unknown asset type: {}", relative_path) } } let body = match &self.body { Some(body) => body.as_str(), None => "", }; let html: RcStr = format!( "\n\n\n{}\n\n\n{}\n{}\n\n", stylesheets.join("\n"), body, scripts.join("\n"), ) .into(); Ok(AssetContent::file( File::from(html).with_content_type(TEXT_HTML_UTF_8).into(), )) } #[turbo_tasks::function] async fn version(self: Vc) -> Result> { let this = self.await?; Ok(DevHtmlAssetVersion { content: this }.cell()) } } #[turbo_tasks::value_impl] impl VersionedContent for DevHtmlAssetContent { #[turbo_tasks::function] fn content(self: Vc) -> Vc { self.content() } #[turbo_tasks::function] fn version(self: Vc) -> Vc> { Vc::upcast(self.version()) } } #[turbo_tasks::value(operation)] struct DevHtmlAssetVersion { content: ReadRef, } #[turbo_tasks::value_impl] impl Version for DevHtmlAssetVersion { #[turbo_tasks::function] fn id(&self) -> Vc { let mut hasher = Xxh3Hash64Hasher::new(); for relative_path in &*self.content.chunk_paths { hasher.write_ref(relative_path); } if let Some(body) = &self.content.body { hasher.write_ref(body); } let hash = hasher.finish(); let hex_hash = encode_hex(hash); Vc::cell(hex_hash.into()) } }