nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
Documentation
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Portable cross-platform Rust builder for `hosts/web-shell` WASM dev bundles.
//!
//! Replaces Unix-only `./hosts/web-shell/build.sh --dev` spawning inside `nv dev` with direct
//! `cargo rustc --target wasm32-unknown-unknown --message-format=json-render-diagnostics` +
//! `wasm-bindgen` + lock-free content-hashed staging + atomic `manifest.json` publishing so
//! Windows, macOS, and Linux behave identically without `bash`, `awk`, `find`, `xargs`, or
//! `shasum`, and HTTP readers are never blocked across `cargo rustc` / `wasm-bindgen`.

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);

/// Verified `wasm-bindgen` + `wasm32-unknown-unknown` toolchain state prepared once at startup.
#[derive(Debug, Clone)]
pub(crate) struct WebShellToolchain {
    pub(crate) wasm_bindgen: String,
}

/// Content-hashed staging directory ready for atomic publication into `<out_dir>/<hash>/`.
///
/// Dropping an unpublished bundle automatically removes its temporary staging directory so build
/// or publish failures never leave orphaned staging directories or touch the live bundle.
#[derive(Debug)]
pub(crate) struct StagedWebShellBundle {
    stage_dir: Option<PathBuf>,
    hash: String,
}

impl StagedWebShellBundle {
    /// Deterministic 16-hex content hash of the staged bundle.
    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);
        }
    }
}

/// Extracts the locked version of `crate_name` from a `Cargo.lock` document.
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
}

/// Parses the semver token from `wasm-bindgen --version` output (e.g. `"wasm-bindgen 0.2.130"`).
pub(crate) fn parse_wasm_bindgen_version(stdout: &str) -> Option<String> {
    stdout.split_whitespace().nth(1).map(str::to_owned)
}

/// Resolves the `wasm-bindgen` executable name (honoring `WASM_BINDGEN` env var) and checks it
/// against `app_workspace_root/Cargo.lock` (falling back to `sdk_root/Cargo.lock`).
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)
}

/// Resolves the `wasm-bindgen` executable name and checks it against `repo_root/Cargo.lock`.
pub(crate) fn verify_wasm_bindgen(repo_root: &Path) -> Result<String, String> {
    verify_wasm_bindgen_for(repo_root, repo_root)
}

/// Ensures `target` is installed for `dir`'s active rustup toolchain (sets `.current_dir(dir)`
/// so `rust-toolchain.toml` is honored).
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 {
        // Systems without rustup (e.g. Nix/distro toolchains) may already provide the target.
        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(())
}

/// Ensures the `wasm32-unknown-unknown` rustc target is installed for `repo_root`'s active
/// toolchain (sets `.current_dir(repo_root)` so `rust-toolchain.toml` is honored).
pub(crate) fn ensure_wasm32_target(repo_root: &Path) -> Result<(), String> {
    ensure_rustup_target(repo_root, WASM_TARGET)
}

/// Runs `wasm-bindgen --target web --no-typescript --out-dir <out_dir> <wasm_input>`.
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(())
}

/// Performs one-time toolchain validation (`wasm-bindgen` + `wasm32-unknown-unknown` target) so
/// Tier-2 rebuilds do not repeatedly spawn `rustup` or `wasm-bindgen --version`.
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 })
}

/// Computes a deterministic 16-hex content hash over every non-precompressed file under `stage_dir`.
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(())
}

/// Lock-free stage phase: compiles `nativeview-web-shell` (`dev` bundle) to `wasm32-unknown-unknown`,
/// runs `wasm-bindgen` into a unique sibling staging directory under `out_dir.parent()`, and
/// hashes the staged bundle. Never touches live files under `out_dir`.
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(())
}

/// Non-destructive atomic publish phase (intended to run under the short HTTP `web_lock.write()`):
/// 1. Moves `<stage_dir>` into `<out_dir>/<hash>` alongside any existing live bundle.
/// 2. Atomically swaps `<out_dir>/manifest.json` via temp file + rename.
/// 3. Prunes stale hash directories AFTER `manifest.json` is live.
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()
            )
        })?;
        // Rename succeeded; disarm so Drop does not touch anything.
        let _ = stage_guard.disarm();
    } else {
        // Identical content hash already exists live; drop `stage_guard` to clean up staging dir.
        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)?;

    // Prune stale hash directories strictly AFTER `manifest.json` is live.
    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;