use std::path::{Path, PathBuf};
use std::process::Command;
use super::{dist_dir, tool_missing};
use crate::runner::cli::{Target, WebRenderer};
use crate::runner::config::{TelarSection, resolve_package, split_android_flag};
const BUNDLE: &str = "app";
pub(crate) const WASM_TARGET: &str = "wasm32-unknown-unknown";
const WEB_PROFILE: &str = "web";
pub(crate) fn build_web(
cargo_args: Vec<String>,
config: TelarSection,
release: bool,
renderer: Option<WebRenderer>,
) -> ! {
let out = match build_web_bundle(cargo_args, config, release, renderer) {
Ok(out) => out,
Err(e) => {
eprintln!("[cargo-telar] {e}");
std::process::exit(1);
}
};
eprintln!("[cargo-telar] Packaged web build at {}", out.display());
std::process::exit(0);
}
pub(crate) fn build_web_bundle(
cargo_args: Vec<String>,
_config: TelarSection,
release: bool,
renderer: Option<WebRenderer>,
) -> Result<PathBuf, String> {
let (_android, rest) = split_android_flag(cargo_args);
let resolved = resolve_package(&rest);
let mut build_args = vec![
"build".to_string(),
"--target".to_string(),
WASM_TARGET.to_string(),
"--lib".to_string(),
];
build_args.extend(rest.iter().filter(|a| *a != "--release").cloned());
if release {
build_args.push("--profile".to_string());
build_args.push(WEB_PROFILE.to_string());
}
resolved
.frontend_feature(Target::Web.feature(renderer))
.push_to(&mut build_args);
eprintln!("[cargo-telar] Building the wasm module...");
let status = Command::new("cargo")
.args(&build_args)
.status()
.map_err(|e| format!("failed to invoke cargo: {e}"))?;
if !status.success() {
return Err("the wasm build failed".to_string());
}
let profile = if release { WEB_PROFILE } else { "debug" };
let module = resolved
.workspace_root
.join(format!("target/{WASM_TARGET}"))
.join(profile)
.join(format!("{}.wasm", resolved.name().replace('-', "_")));
if !module.exists() {
return Err(format!(
"the build produced no wasm module at {}. Does this package have a `[lib]` target?",
module.display()
));
}
let out = dist_dir(&resolved.workspace_root).join("web");
std::fs::create_dir_all(&out)
.map_err(|e| format!("could not create {}: {e}", out.display()))?;
run_wasm_bindgen(&module, &out)?;
optimise(&out.join(format!("{BUNDLE}_bg.wasm")), release);
let wasm = fingerprint(&out, release)?;
write_page(&out, &resolved.name(), renderer, &wasm)?;
precompress(&out, release);
Ok(out)
}
const COMPRESS_FLOOR: u64 = 1024;
fn precompress(out: &Path, release: bool) {
if let Ok(entries) = std::fs::read_dir(out) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if name.ends_with(".br") || name.ends_with(".gz") {
let _ = std::fs::remove_file(entry.path());
}
}
}
if !release {
return;
}
let Ok(entries) = std::fs::read_dir(out) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if entry.metadata().is_ok_and(|m| m.len() < COMPRESS_FLOOR) {
continue;
}
let Ok(bytes) = std::fs::read(entry.path()) else {
continue;
};
if let Some(encoded) = brotli(&bytes) {
let _ = std::fs::write(out.join(format!("{name}.br")), encoded);
}
if let Some(encoded) = gzip(&bytes) {
let _ = std::fs::write(out.join(format!("{name}.gz")), encoded);
}
}
}
fn brotli(bytes: &[u8]) -> Option<Vec<u8>> {
let params = brotli::enc::BrotliEncoderParams {
quality: 11,
lgwin: 22,
..Default::default()
};
let mut encoded = Vec::new();
brotli::BrotliCompress(&mut std::io::Cursor::new(bytes), &mut encoded, ¶ms).ok()?;
Some(encoded)
}
fn gzip(bytes: &[u8]) -> Option<Vec<u8>> {
use std::io::Write;
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
encoder.write_all(bytes).ok()?;
encoder.finish().ok()
}
fn fingerprint(out: &Path, release: bool) -> Result<String, String> {
let plain = format!("{BUNDLE}_bg.wasm");
let module = out.join(&plain);
let named = match release {
true => {
let bytes = std::fs::read(&module)
.map_err(|e| format!("could not read {}: {e}", module.display()))?;
Some(format!("{BUNDLE}-{}_bg.wasm", short_hash(&bytes)))
}
false => None,
};
if let Ok(entries) = std::fs::read_dir(out) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let base = name
.strip_suffix(".br")
.or_else(|| name.strip_suffix(".gz"))
.unwrap_or(&name);
if base.starts_with(&format!("{BUNDLE}-"))
&& base.ends_with("_bg.wasm")
&& Some(base) != named.as_deref()
{
let _ = std::fs::remove_file(entry.path());
}
}
}
let Some(named) = named else {
return Ok(plain);
};
std::fs::rename(&module, out.join(&named))
.map_err(|e| format!("could not rename {}: {e}", module.display()))?;
let glue = out.join(format!("{BUNDLE}.js"));
let source = std::fs::read_to_string(&glue)
.map_err(|e| format!("could not read {}: {e}", glue.display()))?;
let patched = source.replace(&format!("'{plain}'"), &format!("'{named}'"));
if patched == source {
return Err(format!(
"the generated glue does not name `{plain}`, so the renamed module would never be fetched"
));
}
std::fs::write(&glue, patched)
.map_err(|e| format!("could not write {}: {e}", glue.display()))?;
Ok(named)
}
fn short_hash(bytes: &[u8]) -> String {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in bytes {
hash ^= *byte as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
format!("{hash:016x}")[..12].to_string()
}
fn run_wasm_bindgen(module: &Path, out: &Path) -> Result<(), String> {
let status = Command::new("wasm-bindgen")
.arg("--target")
.arg("web")
.arg("--no-typescript")
.arg("--out-dir")
.arg(out)
.arg("--out-name")
.arg(BUNDLE)
.arg(module)
.status()
.map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
tool_missing(
"wasm-bindgen",
"cargo install wasm-bindgen-cli --version <the version in your Cargo.lock>",
)
} else {
format!("failed to invoke wasm-bindgen: {e}")
}
})?;
if !status.success() {
return Err("wasm-bindgen failed".to_string());
}
Ok(())
}
fn optimise(module: &Path, release: bool) {
if !release {
return;
}
let tmp = module.with_extension("opt.wasm");
let status = Command::new("wasm-opt")
.args([
"-Oz",
"--enable-bulk-memory",
"--enable-nontrapping-float-to-int",
])
.arg("-o")
.arg(&tmp)
.arg(module)
.status();
match status {
Ok(status) if status.success() => {
let _ = std::fs::rename(&tmp, module);
}
Ok(_) => {
let _ = std::fs::remove_file(&tmp);
eprintln!("[cargo-telar] wasm-opt failed; shipping the unoptimised module.");
}
Err(_) => eprintln!(
"[cargo-telar] wasm-opt is not installed, so the module is shipped unoptimised (install `binaryen` for a smaller one)."
),
}
}
fn write_page(
out: &Path,
app_name: &str,
renderer: Option<WebRenderer>,
wasm: &str,
) -> Result<(), String> {
let page = out.join("index.html");
let provided = Path::new("web").join("index.html");
if provided.exists() {
return std::fs::copy(&provided, &page)
.map(|_| ())
.map_err(|e| format!("could not copy {}: {e}", provided.display()));
}
std::fs::write(&page, default_page(app_name, renderer, wasm))
.map_err(|e| format!("could not write {}: {e}", page.display()))
}
fn default_page(app_name: &str, renderer: Option<WebRenderer>, wasm: &str) -> String {
let choice = renderer
.map(|r| format!(" data-telar-renderer=\"{}\"", r.as_str()))
.unwrap_or_default();
format!(
r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>{app_name}</title>
<meta name="description" content="{app_name}, a Telar application." />
<!-- Both start downloading with the page rather than one after the other. The module is only reached
through an import inside the glue, so without this the browser learns the wasm exists after it has
fetched and parsed the glue — two round trips in series before a pixel, on the largest file here. -->
<link rel="modulepreload" href="./{BUNDLE}.js" />
<link rel="preload" href="./{wasm}" as="fetch" type="application/wasm" crossorigin />
<style>
/* What the page is before the app has drawn anything, and what shows through an overscroll once it
has. Without it both are white on a system asking for dark. */
html {{ color-scheme: light dark; }}
html, body {{ margin: 0; height: 100%; overflow: hidden; }}
/* `100%` rather than `100vw`, which is the viewport including the space a scrollbar takes and so a
hair wider than the page on every desktop browser that reserves one. `dvh` rather than `vh` because
a mobile browser's `vh` is the viewport with the URL bar retracted, which it is not on arrival. */
#telar-root {{ width: 100%; height: 100dvh; }}
</style>
</head>
<body>
<div id="telar-root"{choice}></div>
<script type="module">
import init from './{BUNDLE}.js';
// `init` instantiates the module and returns its exports; `telar_start` is the entry `telar::app!` generates for this target.
const wasm = await init();
wasm.telar_start();
</script>
</body>
</html>
"#
)
}