use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command as ProcessCommand;
use std::sync::atomic::{AtomicU64, Ordering};
use nativeview_abi::xxh64;
use crate::cargo_env;
const WASM_TARGET: &str = "wasm32-unknown-unknown";
const HASH_SEED: u64 = 0x4E56_4557_4542_3031;
static STAGE_SEQ: AtomicU64 = AtomicU64::new(1);
#[derive(Debug, Clone)]
pub(crate) struct WebShellToolchain {
pub(crate) wasm_bindgen: String,
}
#[derive(Debug)]
pub(crate) struct StagedWebShellBundle {
stage_dir: Option<PathBuf>,
hash: String,
}
impl StagedWebShellBundle {
pub(crate) fn hash(&self) -> &str {
&self.hash
}
#[cfg(test)]
pub(crate) fn from_existing_stage_dir(stage_dir: PathBuf) -> Result<Self, String> {
let guard = StageDirGuard(Some(stage_dir));
let hash = hash_staged_bundle_dir(guard.path())?;
Ok(Self {
stage_dir: guard.disarm(),
hash,
})
}
}
impl Drop for StagedWebShellBundle {
fn drop(&mut self) {
if let Some(dir) = self.stage_dir.take() {
let _ = fs::remove_dir_all(dir);
}
}
}
struct StageDirGuard(Option<PathBuf>);
impl StageDirGuard {
fn path(&self) -> &Path {
self.0.as_deref().unwrap_or_else(|| Path::new(""))
}
fn disarm(mut self) -> Option<PathBuf> {
self.0.take()
}
}
impl Drop for StageDirGuard {
fn drop(&mut self) {
if let Some(dir) = self.0.take() {
let _ = fs::remove_dir_all(dir);
}
}
}
pub(crate) fn parse_cargo_lock_version(lock_content: &str, crate_name: &str) -> Option<String> {
let needle = format!("name = \"{crate_name}\"");
let mut lines = lock_content.lines();
while let Some(line) = lines.next() {
if line.trim() == needle {
for next_line in lines.by_ref() {
let trimmed = next_line.trim();
if trimmed.is_empty() || trimmed.starts_with("[[") {
break;
}
if let Some(rest) = trimmed.strip_prefix("version = \"")
&& let Some(ver) = rest.strip_suffix('"')
{
return Some(ver.to_owned());
}
}
}
}
None
}
pub(crate) fn parse_wasm_bindgen_version(stdout: &str) -> Option<String> {
stdout.split_whitespace().nth(1).map(str::to_owned)
}
pub(crate) fn verify_wasm_bindgen_for(app_workspace_root: &Path, sdk_root: &Path) -> Result<String, String> {
let bin = env::var("WASM_BINDGEN")
.ok()
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "wasm-bindgen".to_owned());
let lock_path = {
let app_lock = app_workspace_root.join("Cargo.lock");
if app_lock.is_file() { app_lock } else { sdk_root.join("Cargo.lock") }
};
let locked_ver = fs::read_to_string(&lock_path)
.ok()
.and_then(|s| parse_cargo_lock_version(&s, "wasm-bindgen"));
let run_dir = if app_workspace_root.is_dir() { app_workspace_root } else { sdk_root };
let out = ProcessCommand::new(&bin)
.current_dir(run_dir)
.arg("--version")
.output()
.map_err(|e| match locked_ver.as_deref() {
Some(ver) => format!(
"'{bin}' not found ({e}). Install with: cargo install --locked wasm-bindgen-cli --version {ver}"
),
None => {
format!("'{bin}' not found ({e}). Install with: cargo install wasm-bindgen-cli")
}
})?;
if !out.status.success() {
return Err(format!("'{bin} --version' failed with {}", out.status));
}
let stdout = String::from_utf8_lossy(&out.stdout);
let cli_ver = parse_wasm_bindgen_version(&stdout).ok_or_else(|| {
format!(
"could not parse version from '{bin} --version' output: '{}'",
stdout.trim()
)
})?;
if let Some(locked) = locked_ver
&& cli_ver != locked
{
return Err(format!(
"wasm-bindgen CLI version ({cli_ver}) != Cargo.lock wasm-bindgen ({locked}). Fix with: cargo install -f --locked wasm-bindgen-cli --version {locked}"
));
}
Ok(bin)
}
pub(crate) fn verify_wasm_bindgen(repo_root: &Path) -> Result<String, String> {
verify_wasm_bindgen_for(repo_root, repo_root)
}
pub(crate) fn ensure_rustup_target(dir: &Path, target: &str) -> Result<(), String> {
let Ok(out) = ProcessCommand::new("rustup")
.current_dir(dir)
.args(["target", "list", "--installed"])
.output()
else {
return Ok(());
};
if !out.status.success() {
return Ok(());
}
let installed = String::from_utf8_lossy(&out.stdout)
.lines()
.any(|line| line.trim() == target);
if installed {
return Ok(());
}
let status = ProcessCommand::new("rustup")
.current_dir(dir)
.args(["target", "add", target])
.status()
.map_err(|e| format!("failed to run `rustup target add {target}`: {e}"))?;
if !status.success() {
return Err(format!(
"Rust target '{target}' is missing and `rustup target add {target}` failed with {status}; run `rustup target add {target}`"
));
}
Ok(())
}
pub(crate) fn ensure_wasm32_target(repo_root: &Path) -> Result<(), String> {
ensure_rustup_target(repo_root, WASM_TARGET)
}
pub(crate) fn run_wasm_bindgen(wasm_bindgen_bin: &str, wasm_input: &Path, out_dir: &Path) -> Result<(), String> {
let status = ProcessCommand::new(wasm_bindgen_bin)
.args(["--target", "web", "--no-typescript", "--out-dir"])
.arg(out_dir)
.arg(wasm_input)
.status()
.map_err(|e| format!("failed to run '{wasm_bindgen_bin}': {e}"))?;
if !status.success() {
return Err(format!("'{wasm_bindgen_bin}' failed with {status}"));
}
Ok(())
}
pub(crate) fn prepare_web_shell_toolchain(repo_root: &Path) -> Result<WebShellToolchain, String> {
let wasm_bindgen = verify_wasm_bindgen(repo_root)?;
ensure_wasm32_target(repo_root)?;
Ok(WebShellToolchain { wasm_bindgen })
}
pub(crate) fn hash_staged_bundle_dir(stage_dir: &Path) -> Result<String, String> {
let mut rel_files = Vec::new();
collect_files_sorted(stage_dir, stage_dir, &mut rel_files)?;
rel_files.sort();
let mut summary = Vec::with_capacity(rel_files.len() * 48);
for (rel, full_path) in rel_files {
let bytes = fs::read(&full_path)
.map_err(|e| format!("failed to read staged file '{}': {e}", full_path.display()))?;
let file_hash = xxh64(&bytes, HASH_SEED);
summary.extend_from_slice(&(rel.len() as u64).to_le_bytes());
summary.extend_from_slice(rel.as_bytes());
summary.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
summary.extend_from_slice(&file_hash.to_le_bytes());
}
let digest = xxh64(&summary, HASH_SEED);
Ok(format!("{digest:016x}"))
}
fn collect_files_sorted(
root: &Path,
dir: &Path,
out: &mut Vec<(String, PathBuf)>,
) -> Result<(), String> {
let entries =
fs::read_dir(dir).map_err(|e| format!("failed to read '{}': {e}", dir.display()))?;
for entry in entries {
let entry = entry.map_err(|e| format!("failed to iterate '{}': {e}", dir.display()))?;
let path = entry.path();
if path.is_dir() {
collect_files_sorted(root, &path, out)?;
} else if path.is_file() {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
if ext.eq_ignore_ascii_case("br") || ext.eq_ignore_ascii_case("gz") {
continue;
}
let rel = path
.strip_prefix(root)
.unwrap_or(&path)
.to_string_lossy()
.replace('\\', "/");
out.push((rel, path));
}
}
Ok(())
}
pub(crate) fn stage_web_shell_dev_bundle(
repo_root: &Path,
target_dir: &Path,
out_dir: &Path,
toolchain: &WebShellToolchain,
extra_features: &[String],
) -> Result<StagedWebShellBundle, String> {
let web_shell_dir = repo_root.join("hosts").join("web-shell");
if !web_shell_dir.join("Cargo.toml").is_file() {
return Err(format!(
"hosts/web-shell/Cargo.toml not found under '{}'",
repo_root.display()
));
}
let mut cmd = ProcessCommand::new("cargo");
cmd.current_dir(repo_root)
.env("CARGO_TARGET_DIR", target_dir)
.arg("rustc");
if repo_root.join("Cargo.lock").is_file() {
cmd.arg("--locked");
}
cmd.args([
"-p",
"nativeview-web-shell",
"--lib",
"--crate-type",
"cdylib",
"--target",
WASM_TARGET,
]);
if !extra_features.is_empty() {
cmd.args(["--features", &extra_features.join(",")]);
}
let stdout = cargo_env::run_cargo_json_command(&mut cmd, "cargo rustc -p nativeview-web-shell")?;
let wasm_input =
cargo_env::parse_cdylib_artifact_from_json(&stdout, "", "nativeview_web_shell", ".wasm")?;
if !wasm_input.is_file() {
return Err(format!(
"expected compiled WASM artifact at '{}'",
wasm_input.display()
));
}
let stage_parent = out_dir.parent().unwrap_or(out_dir);
fs::create_dir_all(stage_parent)
.map_err(|e| format!("failed to create '{}': {e}", stage_parent.display()))?;
let seq = STAGE_SEQ.fetch_add(1, Ordering::Relaxed);
let stage_dir = stage_parent.join(format!(".dev.staging-{}-{seq}", std::process::id()));
if stage_dir.exists() {
fs::remove_dir_all(&stage_dir)
.map_err(|e| format!("failed to clean '{}': {e}", stage_dir.display()))?;
}
fs::create_dir_all(&stage_dir)
.map_err(|e| format!("failed to create '{}': {e}", stage_dir.display()))?;
let stage_guard = StageDirGuard(Some(stage_dir));
run_wasm_bindgen(&toolchain.wasm_bindgen, &wasm_input, stage_guard.path())?;
let hash = hash_staged_bundle_dir(stage_guard.path())?;
Ok(StagedWebShellBundle {
stage_dir: stage_guard.disarm(),
hash,
})
}
pub(crate) fn atomic_replace_file(src: &Path, dst: &Path) -> Result<(), String> {
if let Err(first_err) = fs::rename(src, dst) {
#[cfg(windows)]
if dst.exists() {
let _ = fs::remove_file(dst);
if fs::rename(src, dst).is_ok() {
return Ok(());
}
}
let _ = fs::remove_file(src);
return Err(format!(
"failed to replace '{}' with '{}': {first_err}",
dst.display(),
src.display()
));
}
Ok(())
}
pub(crate) fn publish_staged_bundle(
mut staged: StagedWebShellBundle,
out_dir: &Path,
) -> Result<PathBuf, String> {
let stage_dir = staged
.stage_dir
.take()
.ok_or_else(|| "staged web-shell bundle already consumed".to_owned())?;
let stage_guard = StageDirGuard(Some(stage_dir));
fs::create_dir_all(out_dir)
.map_err(|e| format!("failed to create '{}': {e}", out_dir.display()))?;
let dest = out_dir.join(&staged.hash);
if !dest.exists() {
let src = stage_guard.path();
fs::rename(src, &dest).map_err(|e| {
format!(
"failed to publish staged bundle '{}' -> '{}': {e}",
src.display(),
dest.display()
)
})?;
let _ = stage_guard.disarm();
} else {
drop(stage_guard);
}
let manifest = format!(
"{{\"js\":\"{}/nativeview_web_shell.js\",\"wasm\":\"{}/nativeview_web_shell_bg.wasm\"}}\n",
staged.hash, staged.hash
);
let seq = STAGE_SEQ.fetch_add(1, Ordering::Relaxed);
let manifest_tmp = out_dir.join(format!(".manifest.json.tmp-{}-{seq}", std::process::id()));
fs::write(&manifest_tmp, manifest)
.map_err(|e| format!("failed to write '{}': {e}", manifest_tmp.display()))?;
let manifest_path = out_dir.join("manifest.json");
atomic_replace_file(&manifest_tmp, &manifest_path)?;
if let Ok(entries) = fs::read_dir(out_dir) {
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
let name = entry.file_name();
let Some(name_str) = name.to_str() else {
continue;
};
if name_str == staged.hash || name_str.starts_with('.') {
continue;
}
let _ = fs::remove_dir_all(path);
}
}
Ok(dest)
}
#[cfg(test)]
mod tests;