use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use serde::Deserialize;
use crate::view::Raw;
pub const BUILD_DIR: &str = "build";
const MANIFEST: &str = "public/build/.vite/manifest.json";
const DEV_SERVER: &str = "GLACIER_VITE";
#[derive(Debug, Clone, Deserialize)]
struct Chunk {
file: String,
#[serde(default)]
css: Vec<String>,
#[serde(default)]
imports: Vec<String>,
}
type Manifest = HashMap<String, Chunk>;
static EMBEDDED: OnceLock<&'static str> = OnceLock::new();
#[doc(hidden)]
pub fn embed_manifest(json: &'static str) {
let _ = EMBEDDED.set(json);
}
pub fn vite(entries: impl Entries) -> Raw {
let entries = entries.list();
let tags = match std::env::var(DEV_SERVER) {
Ok(server) if cfg!(debug_assertions) && !server.is_empty() => {
dev_tags(server.trim_end_matches('/'), &entries)
}
_ => match manifest() {
Ok(manifest) => build_tags(&manifest, &entries),
Err(message) => {
tracing::error!(target: "glacier::vite", "{message}");
format!("<!-- vite: {} -->", crate::html::escape(&message))
}
},
};
Raw(tags)
}
pub trait Entries {
fn list(self) -> Vec<String>;
}
impl Entries for &str {
fn list(self) -> Vec<String> {
vec![self.to_owned()]
}
}
impl Entries for String {
fn list(self) -> Vec<String> {
vec![self]
}
}
impl<const N: usize> Entries for [&str; N] {
fn list(self) -> Vec<String> {
self.iter().map(|e| (*e).to_owned()).collect()
}
}
impl Entries for &[&str] {
fn list(self) -> Vec<String> {
self.iter().map(|e| (*e).to_owned()).collect()
}
}
fn is_css(path: &str) -> bool {
[".css", ".scss", ".sass", ".less", ".styl", ".pcss"]
.iter()
.any(|ext| path.ends_with(ext))
}
fn attr(value: &str) -> String {
crate::html::escape(value).to_string()
}
fn dev_tags(server: &str, entries: &[String]) -> String {
let mut tags = format!(
r#"<script type="module" src="{}/@vite/client"></script>"#,
attr(server)
);
for entry in entries {
let url = attr(&format!("{server}/{}", entry.trim_start_matches('/')));
if is_css(entry) {
tags.push_str(&format!(r#"<link rel="stylesheet" href="{url}">"#));
} else {
tags.push_str(&format!(r#"<script type="module" src="{url}"></script>"#));
}
}
tags
}
fn url(file: &str) -> String {
attr(&format!("/{BUILD_DIR}/{file}"))
}
fn build_tags(manifest: &Manifest, entries: &[String]) -> String {
let mut styles = Vec::new();
let mut preloads = Vec::new();
let mut scripts = Vec::new();
for entry in entries {
let key = entry.trim_start_matches('/');
let Some(chunk) = manifest.get(key) else {
tracing::error!(
target: "glacier::vite",
"`{key}` isn't in Vite's manifest; is it in vite.config.js's `input`?"
);
scripts.push(format!("<!-- vite: no entry {} -->", attr(key)));
continue;
};
if is_css(&chunk.file) {
push_unique(&mut styles, url(&chunk.file));
} else {
push_unique(&mut scripts, url(&chunk.file));
}
let mut seen = Vec::new();
let mut stack = vec![chunk];
while let Some(chunk) = stack.pop() {
for css in &chunk.css {
push_unique(&mut styles, url(css));
}
for import in &chunk.imports {
if seen.contains(import) {
continue;
}
seen.push(import.clone());
if let Some(imported) = manifest.get(import) {
push_unique(&mut preloads, url(&imported.file));
stack.push(imported);
}
}
}
}
let mut tags = String::new();
for href in styles {
tags.push_str(&format!(r#"<link rel="stylesheet" href="{href}">"#));
}
for href in preloads {
tags.push_str(&format!(r#"<link rel="modulepreload" href="{href}">"#));
}
for src in scripts {
if src.starts_with("<!--") {
tags.push_str(&src);
} else {
tags.push_str(&format!(r#"<script type="module" src="{src}"></script>"#));
}
}
tags
}
fn push_unique(list: &mut Vec<String>, item: String) {
if !list.contains(&item) {
list.push(item);
}
}
fn manifest() -> Result<Manifest, String> {
if let Some(json) = EMBEDDED.get() {
return parse(json);
}
static CACHE: OnceLock<Mutex<Option<(std::time::SystemTime, Manifest)>>> = OnceLock::new();
let modified = std::fs::metadata(MANIFEST)
.and_then(|m| m.modified())
.map_err(|_| {
format!(
"no {MANIFEST}: run `vite build` (a release build does), or `glacier server` \
for the dev server"
)
})?;
let mut cache = CACHE
.get_or_init(Default::default)
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some((at, manifest)) = cache.as_ref()
&& *at == modified
{
return Ok(manifest.clone());
}
let json = std::fs::read_to_string(MANIFEST).map_err(|e| format!("reading {MANIFEST}: {e}"))?;
let manifest = parse(&json)?;
*cache = Some((modified, manifest.clone()));
Ok(manifest)
}
fn parse(json: &str) -> Result<Manifest, String> {
serde_json::from_str(json).map_err(|e| format!("reading Vite's manifest: {e}"))
}
#[cfg(test)]
mod tests {
use super::*;
const MANIFEST_JSON: &str = r#"{
"assets/js/app.js": {
"file": "assets/app-4ed993c7.js",
"src": "assets/js/app.js",
"isEntry": true,
"imports": ["_shared-B7PI925R.js"],
"css": ["assets/app-5UjPuW-k.css"]
},
"_shared-B7PI925R.js": {
"file": "assets/shared-B7PI925R.js",
"css": ["assets/shared-ChJ_j-JJ.css"]
},
"assets/css/print.css": {
"file": "assets/print-1a2b3c.css",
"src": "assets/css/print.css",
"isEntry": true
}
}"#;
#[test]
fn a_build_links_hashed_files_with_their_css_and_preloads() {
let manifest = parse(MANIFEST_JSON).unwrap();
let tags = build_tags(
&manifest,
&[
"assets/js/app.js".to_owned(),
"assets/css/print.css".to_owned(),
],
);
assert_eq!(
tags,
concat!(
r#"<link rel="stylesheet" href="/build/assets/app-5UjPuW-k.css">"#,
r#"<link rel="stylesheet" href="/build/assets/shared-ChJ_j-JJ.css">"#,
r#"<link rel="stylesheet" href="/build/assets/print-1a2b3c.css">"#,
r#"<link rel="modulepreload" href="/build/assets/shared-B7PI925R.js">"#,
r#"<script type="module" src="/build/assets/app-4ed993c7.js"></script>"#,
)
);
}
#[test]
fn an_unknown_entry_is_a_comment() {
let manifest = parse(MANIFEST_JSON).unwrap();
assert_eq!(
build_tags(&manifest, &["assets/js/admin.js".to_owned()]),
"<!-- vite: no entry assets/js/admin.js -->"
);
}
#[test]
fn the_dev_server_serves_entries_and_its_client() {
assert_eq!(
dev_tags(
"http://localhost:5173",
&[
"assets/js/app.js".to_owned(),
"assets/css/app.css".to_owned()
]
),
concat!(
r#"<script type="module" src="http://localhost:5173/@vite/client"></script>"#,
r#"<script type="module" src="http://localhost:5173/assets/js/app.js"></script>"#,
r#"<link rel="stylesheet" href="http://localhost:5173/assets/css/app.css">"#,
)
);
}
}