//! Embeds the authorization pages' build, `web/dist` (`spec/OAUTH-PAGES.md`, //! "How the pages are built"): every file Vite wrote under `web/dist/assets`, //! by name, with its content type, and the `` tags that name the //! entry's stylesheets and script and the pages' icon, read from Vite's //! manifest; and `web/dist/email.html`, the emails' HTML part //! (`spec/EMAIL.md`, "The message"). A build without `web/dist` fails, //! saying to build `web/` first. #![forbid(unsafe_code)] use serde_json::Value as Json; use std::{env, fmt::Write, fs, path::Path}; const BUILD_WEB: &str = "build the pages first: `just web`, or `cd web && npm ci && npm run build`"; /// The content type a file of the build is served with, by its extension. fn content_type(name: &str) -> &'static str { match name.rsplit_once('.').map(|(_, ext)| ext) { Some("js") => "text/javascript", Some("css") => "text/css", Some("svg") => "image/svg+xml", Some("woff2") => "font/woff2", Some("png") => "image/png", _ => panic!( "web/dist/assets/{name}: the pages serve no file of this kind (spec/OAUTH-PAGES.md, \"Assets\")" ), } } fn main() { let dist = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../web/dist"); println!("cargo:rerun-if-changed={}", dist.display()); let manifest_path = dist.join(".vite/manifest.json"); let manifest: Json = match fs::read_to_string(&manifest_path) { Ok(text) => serde_json::from_str(&text) .unwrap_or_else(|e| panic!("{}: {e}; {BUILD_WEB}", manifest_path.display())), Err(e) => panic!("{}: {e}; {BUILD_WEB}", manifest_path.display()), }; let mut assets: Vec<(String, std::path::PathBuf)> = fs::read_dir(dist.join("assets")) .unwrap_or_else(|e| panic!("web/dist/assets: {e}; {BUILD_WEB}")) .map(|e| e.unwrap()) .filter(|e| e.file_type().unwrap().is_file()) .map(|e| (e.file_name().into_string().unwrap(), e.path())) .collect(); assets.sort(); // A file the manifest names, as its name under `assets/`, which must be one of the build's. let asset = |file: &Json| -> String { let file = file.as_str().expect("a manifest file is a string"); let name = file .strip_prefix("assets/") .unwrap_or_else(|| panic!("web/dist/{file} is not under assets/; {BUILD_WEB}")); assert!( assets.iter().any(|(n, _)| n == name), "web/dist/{file}, which the manifest names, is missing; {BUILD_WEB}" ); name.to_string() }; let chunks = manifest.as_object().expect("the manifest is an object"); let entry = chunks .values() .find(|c| c["isEntry"] == Json::Bool(true)) .unwrap_or_else(|| panic!("the manifest names no entry; {BUILD_WEB}")); // The entry's stylesheets: those it lists, or, as one stylesheet is // built for the whole app (`cssCodeSplit: false`), the build's. let mut stylesheets: Vec = entry["css"] .as_array() .into_iter() .flatten() .map(asset) .collect(); if stylesheets.is_empty() { stylesheets = chunks .values() .filter(|c| c["file"].as_str().is_some_and(|f| f.ends_with(".css"))) .map(|c| asset(&c["file"])) .collect(); } let script = asset(&entry["file"]); let icon = asset( &chunks .get("src/assets/icon.svg") .unwrap_or_else(|| panic!("the manifest names no src/assets/icon.svg; {BUILD_WEB}"))["file"], ); let mut head = format!(""); for s in &stylesheets { write!(head, "").unwrap(); } write!( head, "" ) .unwrap(); let mut out = String::from( "/// The build's files under `web/dist/assets`, by name: its content type and bytes.\n\ pub(super) static ASSETS: &[(&str, &str, &[u8])] = &[\n", ); for (name, path) in &assets { let path = path.canonicalize().unwrap(); writeln!( out, " ({name:?}, {:?}, include_bytes!({:?})),", content_type(name), path.display().to_string() ) .unwrap(); } out.push_str("];\n\n"); writeln!( out, "/// The pages' `` tags naming the build's icon, its entry's stylesheets and its script.\n\ pub(super) const HEAD: &str = {head:?};" ) .unwrap(); let to = Path::new(&env::var("OUT_DIR").unwrap()).join("web.rs"); fs::write(to, out).unwrap(); let email = dist .join("email.html") .canonicalize() .unwrap_or_else(|e| panic!("web/dist/email.html: {e}; {BUILD_WEB}")); let to = Path::new(&env::var("OUT_DIR").unwrap()).join("email.rs"); fs::write( to, format!( "/// The emails' HTML part, as `web/` builds it, its values still to fill in.\n\ const TEMPLATE: &str = include_str!({:?});\n", email.display().to_string() ), ) .unwrap(); }