File size: 8,260 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 |
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<Box<dyn ChunkableModule>>,
pub module_graph: ResolvedVc<ModuleGraph>,
pub chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
pub runtime_entries: Option<ResolvedVc<EvaluatableAssets>>,
}
/// 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<DevHtmlEntry>,
body: Option<RcStr>,
}
#[turbo_tasks::value_impl]
impl OutputAsset for DevHtmlAsset {
#[turbo_tasks::function]
fn path(&self) -> Vc<FileSystemPath> {
self.path.clone().cell()
}
#[turbo_tasks::function]
fn references(self: Vc<Self>) -> Vc<OutputAssets> {
self.chunks()
}
}
#[turbo_tasks::value_impl]
impl Asset for DevHtmlAsset {
#[turbo_tasks::function]
fn content(self: Vc<Self>) -> Vc<AssetContent> {
self.html_content().content()
}
#[turbo_tasks::function]
fn versioned_content(self: Vc<Self>) -> Vc<Box<dyn VersionedContent>> {
Vc::upcast(self.html_content())
}
}
impl DevHtmlAsset {
/// Create a new dev HTML asset.
pub fn new(path: FileSystemPath, entries: Vec<DevHtmlEntry>) -> Vc<Self> {
DevHtmlAsset {
path,
entries,
body: None,
}
.cell()
}
/// Create a new dev HTML asset.
pub fn new_with_body(
path: FileSystemPath,
entries: Vec<DevHtmlEntry>,
body: RcStr,
) -> Vc<Self> {
DevHtmlAsset {
path,
entries,
body: Some(body),
}
.cell()
}
}
#[turbo_tasks::value_impl]
impl DevHtmlAsset {
#[turbo_tasks::function]
pub async fn with_path(self: Vc<Self>, path: FileSystemPath) -> Result<Vc<Self>> {
let mut html: DevHtmlAsset = self.owned().await?;
html.path = path;
Ok(html.cell())
}
#[turbo_tasks::function]
pub async fn with_body(self: Vc<Self>, body: RcStr) -> Result<Vc<Self>> {
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<Self>) -> Result<Vc<DevHtmlAssetContent>> {
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<Vc<OutputAssets>> {
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<RcStr>,
body: Option<RcStr>,
}
impl DevHtmlAssetContent {
fn new(chunk_paths: Vec<RcStr>, body: Option<RcStr>) -> Vc<Self> {
DevHtmlAssetContent { chunk_paths, body }.cell()
}
}
#[turbo_tasks::value_impl]
impl DevHtmlAssetContent {
#[turbo_tasks::function]
fn content(&self) -> Result<Vc<AssetContent>> {
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!("<script src=\"{relative_path}\"></script>"));
} else if relative_path.ends_with(".css") {
stylesheets.push(format!(
"<link data-turbopack rel=\"stylesheet\" href=\"{relative_path}\">"
));
} 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!(
"<!DOCTYPE html>\n<html>\n<head>\n{}\n</head>\n<body>\n{}\n{}\n</body>\n</html>",
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<Self>) -> Result<Vc<DevHtmlAssetVersion>> {
let this = self.await?;
Ok(DevHtmlAssetVersion { content: this }.cell())
}
}
#[turbo_tasks::value_impl]
impl VersionedContent for DevHtmlAssetContent {
#[turbo_tasks::function]
fn content(self: Vc<Self>) -> Vc<AssetContent> {
self.content()
}
#[turbo_tasks::function]
fn version(self: Vc<Self>) -> Vc<Box<dyn Version>> {
Vc::upcast(self.version())
}
}
#[turbo_tasks::value(operation)]
struct DevHtmlAssetVersion {
content: ReadRef<DevHtmlAssetContent>,
}
#[turbo_tasks::value_impl]
impl Version for DevHtmlAssetVersion {
#[turbo_tasks::function]
fn id(&self) -> Vc<RcStr> {
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())
}
}
|