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
//! `AppContext` & `NvSdkRoot` resolution for `nv build` / `nv run` / `nv dev`.

use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
use std::env;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use super::sdk::{default_sdk_cache_dir, SdkManifest, CLI_VERSION, SDK_MANIFEST_FILENAME};
use super::{
    absolutize_path_from, find_package, load_full_cargo_metadata_in, select_cdylib_package,
    CargoMetadata, CargoPackageInfo,
};

const DEFAULT_ROOT_WORKSPACE_APP: &str = "nativeview-studio-workspace";

/// Selector identifying which NV app crate to build, run, or watch.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct AppSelector {
    pub app_path: Option<PathBuf>,
    pub package: Option<String>,
}

/// Resolved NV SDK root (either a packaged read-only SDK containing `sdk-manifest.json` or a
/// local monorepo checkout containing `hosts/` and `packages/core/abi`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NvSdkRoot(pub PathBuf);

impl NvSdkRoot {
    pub fn path(&self) -> &Path {
        &self.0
    }

    /// Returns `true` when this root is a packaged read-only SDK tarball (`sdk-manifest.json`).
    pub fn is_packaged_sdk(&self) -> bool {
        self.0.join(SDK_MANIFEST_FILENAME).is_file()
    }

    /// Loads `sdk-manifest.json` when present (packaged SDK), returning `Ok(None)` for checkouts.
    pub fn manifest(&self) -> Result<Option<SdkManifest>, String> {
        SdkManifest::load_from_dir(&self.0)
    }

    /// Returns `true` when `sdk-manifest.json` exists and declares `prebuilt_codegen: true`.
    pub fn has_prebuilt_codegen(&self) -> bool {
        self.manifest()
            .ok()
            .flatten()
            .is_some_and(|m| m.prebuilt_codegen)
    }
}

/// Resolved NV app crate metadata including transitive `[package.metadata.nativeview] host_module` names
/// and transitive non-dev path-dependency package directories.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppContext {
    pub manifest_path: PathBuf,
    pub manifest_dir: PathBuf,
    pub workspace_root: PathBuf,
    pub target_directory: PathBuf,
    pub package_id: String,
    pub package_name: String,
    pub package_version: String,
    pub lib_name: String,
    pub has_web_feature: bool,
    pub has_lockfile: bool,
    pub host_modules: Vec<String>,
    pub path_deps: Vec<PathBuf>,
}

impl AppContext {
    pub fn manifest_app_info(&self) -> crate::manifest::ManifestAppInfo {
        crate::manifest::ManifestAppInfo {
            package_name: self.package_name.clone(),
            package_version: self.package_version.clone(),
            lib_name: self.lib_name.clone(),
        }
    }

    /// Root directory used for worktree-scoped `nv dev` session discovery (`session.json`):
    /// shares `sdk_root` for in-SDK apps (including standalone `[workspace]` examples) so
    /// `nv dev wait` / `nv dev status` find the session from either the repo root or example dir,
    /// while external user projects stay scoped to their own `workspace_root`.
    pub fn dev_session_root(&self, sdk_root: Option<&NvSdkRoot>) -> PathBuf {
        if let Some(sdk) = sdk_root
            && !sdk.is_packaged_sdk()
            && path_starts_with_or_canonical(&self.manifest_dir, sdk.path())
        {
            sdk.path().to_path_buf()
        } else {
            self.workspace_root.clone()
        }
    }
}

/// Walks non-dev `path_deps` transitively from `root_manifest_dir` across `meta.packages` and
/// returns canonicalized dependency package directories (excluding `root_manifest_dir` itself).
pub fn collect_transitive_path_deps(
    meta: &CargoMetadata,
    root_manifest_dir: &Path,
) -> Vec<PathBuf> {
    let mut by_manifest_dir: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
    for pkg in &meta.packages {
        let Some(dir) = pkg.manifest_dir() else {
            continue;
        };
        let canon_dir = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
        let dep_dirs: Vec<PathBuf> = pkg
            .path_deps
            .iter()
            .map(|dp| std::fs::canonicalize(dp).unwrap_or_else(|_| dp.clone()))
            .collect();
        by_manifest_dir.insert(canon_dir, dep_dirs);
    }

    let start = std::fs::canonicalize(root_manifest_dir)
        .unwrap_or_else(|_| root_manifest_dir.to_path_buf());
    let mut visited = HashSet::new();
    let mut queue = VecDeque::new();
    visited.insert(start.clone());
    queue.push_back(start.clone());

    let mut deps = Vec::new();
    while let Some(dir) = queue.pop_front() {
        if dir != start {
            deps.push(dir.clone());
        }
        if let Some(children) = by_manifest_dir.get(&dir) {
            for child in children {
                if visited.insert(child.clone()) {
                    queue.push_back(child.clone());
                }
            }
        }
    }
    deps
}

/// Returns `true` when `dir` looks like a valid NV SDK root (either a packaged SDK containing
/// `sdk-manifest.json` or a local monorepo checkout containing `hosts/` and `packages/core/abi`).
pub fn is_nv_sdk_root(dir: &Path) -> bool {
    dir.join(SDK_MANIFEST_FILENAME).is_file()
        || (dir.join("hosts").is_dir() && dir.join("packages").join("core").join("abi").is_dir())
}

fn find_sdk_ancestor(start: &Path) -> Option<PathBuf> {
    start.ancestors().find(|d| is_nv_sdk_root(d)).map(Path::to_path_buf)
}

/// Walks the resolved Cargo dependency graph from `root_pkg_id` and collects all unique sorted
/// `[package.metadata.nativeview] host_module` tokens across reachable packages.
pub fn collect_host_modules(meta: &CargoMetadata, root_pkg_id: &str) -> Vec<String> {
    let by_id: HashMap<&str, &CargoPackageInfo> =
        meta.packages.iter().map(|p| (p.id.as_str(), p)).collect();
    let mut visited = HashSet::new();
    let mut queue = VecDeque::new();
    let mut modules = BTreeSet::new();

    if visited.insert(root_pkg_id) {
        queue.push_back(root_pkg_id);
    }
    while let Some(id) = queue.pop_front() {
        if let Some(pkg) = by_id.get(id)
            && let Some(m) = pkg.host_module.as_deref()
        {
            let normalized: String = m.chars().map(|c| c.to_ascii_lowercase()).collect();
            modules.insert(normalized);
        }
        if let Some(deps) = meta.resolve_deps.get(id) {
            for dep in deps {
                if visited.insert(dep.as_str()) {
                    queue.push_back(dep.as_str());
                }
            }
        }
    }
    modules.into_iter().collect()
}

/// Resolves `NvSdkRoot` via precedence:
/// 1. Explicit `--sdk-root`
/// 2. `$NV_SDK_ROOT`
/// 3. Ancestor of resolved `nativeview-abi` dependency's `manifest_path`
/// 4. Ancestor walk from `app_manifest_dir` (monorepo checkout)
/// 5. Version-pinned read-only SDK cache (`$XDG_CACHE_HOME/nativeview/sdk/vX.Y.Z/`)
/// 6. Compile-time `CARGO_MANIFEST_DIR/../../..` if valid on disk
/// 7. Actionable error pointing to `nv sdk install`
pub fn resolve_sdk_root(
    sdk_override: Option<&Path>,
    env_sdk_root: Option<&str>,
    meta: &CargoMetadata,
    app_manifest_dir: &Path,
    cwd: &Path,
) -> Result<NvSdkRoot, String> {
    if let Some(explicit) = sdk_override {
        let abs = absolutize_path_from(explicit, cwd);
        return if is_nv_sdk_root(&abs) {
            Ok(NvSdkRoot(abs))
        } else {
            Err(format!(
                "--sdk-root '{}' is not a valid NV SDK root (expected sdk-manifest.json or hosts/ + packages/core/abi)",
                abs.display()
            ))
        };
    }
    if let Some(env_val) = env_sdk_root.map(str::trim).filter(|s| !s.is_empty()) {
        let abs = absolutize_path_from(Path::new(env_val), cwd);
        return if is_nv_sdk_root(&abs) {
            Ok(NvSdkRoot(abs))
        } else {
            Err(format!(
                "NV_SDK_ROOT '{}' is not a valid NV SDK root (expected sdk-manifest.json or hosts/ + packages/core/abi)",
                abs.display()
            ))
        };
    }
    if let Some(abi_pkg) = meta.packages.iter().find(|p| p.name == "nativeview-abi")
        && let Some(root) = find_sdk_ancestor(&abi_pkg.manifest_path)
    {
        return Ok(NvSdkRoot(root));
    }
    if let Some(root) = find_sdk_ancestor(app_manifest_dir) {
        return Ok(NvSdkRoot(root));
    }
    let cached = default_sdk_cache_dir(CLI_VERSION);
    if is_nv_sdk_root(&cached) {
        return Ok(NvSdkRoot(cached));
    }
    let compile_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..").join("..").join("..");
    if let Ok(canon) = std::fs::canonicalize(&compile_root)
        && is_nv_sdk_root(&canon)
    {
        return Ok(NvSdkRoot(canon));
    }
    Err(
        "could not locate NV SDK root; run `nv sdk install`, pass --sdk-root <DIR>, or set NV_SDK_ROOT"
            .to_owned(),
    )
}

fn paths_equal_or_canonical(a: &Path, b: &Path) -> bool {
    a == b
        || match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
            (Ok(ca), Ok(cb)) => ca == cb,
            _ => false,
        }
}

fn path_starts_with_or_canonical(child: &Path, parent: &Path) -> bool {
    child.starts_with(parent)
        || match (std::fs::canonicalize(child), std::fs::canonicalize(parent)) {
            (Ok(cc), Ok(cp)) => cc.starts_with(cp),
            _ => false,
        }
}

/// Resolves the effective Cargo `target_directory` for an app:
/// - Honors explicit non-blank `CARGO_TARGET_DIR` (already resolved into `meta_target_dir` by Cargo).
/// - NEVER writes `target/` inside a packaged read-only SDK (`sdk-manifest.json`).
/// - Shares `<sdk_root>/target` ONLY for in-SDK standalone workspaces (`manifest_dir` inside
///   a monorepo checkout `sdk_root`) whose `meta_target_dir` is still the default `<workspace_root>/target`.
pub fn resolve_app_target_directory(
    meta_target_dir: &Path,
    meta_workspace_root: &Path,
    manifest_dir: &Path,
    sdk_root: &Path,
    env_cargo_target_dir: Option<&OsStr>,
) -> PathBuf {
    let has_env = env_cargo_target_dir.is_some_and(|v| {
        v.to_str().map(|s| !s.trim().is_empty()).unwrap_or(!v.is_empty())
    });
    let is_packaged = sdk_root.join(SDK_MANIFEST_FILENAME).is_file();
    if !has_env
        && !is_packaged
        && path_starts_with_or_canonical(manifest_dir, sdk_root)
        && paths_equal_or_canonical(meta_target_dir, &meta_workspace_root.join("target"))
    {
        return sdk_root.join("target");
    }
    meta_target_dir.to_path_buf()
}

fn resolve_manifest_path_from_app_path(app_path: &Path, cwd: &Path) -> Result<PathBuf, String> {
    let abs = absolutize_path_from(app_path, cwd);
    if abs.is_dir() {
        let manifest = abs.join("Cargo.toml");
        if manifest.is_file() {
            return Ok(manifest);
        }
        return Err(format!("no Cargo.toml found in '{}'", abs.display()));
    }
    if abs.is_file() {
        return Ok(abs);
    }
    Err(format!("app path does not exist: '{}'", app_path.display()))
}

/// Resolves [`AppContext`] and an optional [`NvSdkRoot`] (never failing when no SDK is installed,
/// so standalone `[features] web` apps work with zero `NV_SDK_ROOT`).
pub fn resolve_app_and_optional_sdk(
    selector: &AppSelector,
    sdk_override: Option<&Path>,
    cwd: &Path,
    filter_platform: Option<&str>,
) -> Result<(AppContext, Option<NvSdkRoot>), String> {
    let explicit_manifest = match selector.app_path.as_deref() {
        Some(p) => Some(resolve_manifest_path_from_app_path(p, cwd)?),
        None => None,
    };

    let cwd_manifest = cwd.join("Cargo.toml");
    let query_manifest = explicit_manifest.as_deref().or_else(|| {
        cwd_manifest.is_file().then_some(cwd_manifest.as_path())
    });

    let meta = load_full_cargo_metadata_in(query_manifest, cwd, filter_platform)?;
    let pkg = select_app_package(&meta, selector.package.as_deref(), explicit_manifest.as_deref(), cwd)?;
    let manifest_dir = pkg
        .manifest_dir()
        .ok_or_else(|| format!("invalid manifest path '{}'", pkg.manifest_path.display()))?
        .to_path_buf();
    let lib_name = pkg
        .cdylib_name
        .clone()
        .ok_or_else(|| format!("package '{}' has no `cdylib` library target", pkg.name))?;

    let env_sdk = env::var("NV_SDK_ROOT").ok();
    let sdk_root = if sdk_override.is_some()
        || env_sdk.as_deref().is_some_and(|s| !s.trim().is_empty())
    {
        Some(resolve_sdk_root(sdk_override, env_sdk.as_deref(), &meta, &manifest_dir, cwd)?)
    } else {
        resolve_sdk_root(None, None, &meta, &manifest_dir, cwd).ok()
    };

    let env_target = env::var_os("CARGO_TARGET_DIR");
    let target_directory = match sdk_root.as_ref() {
        Some(sdk) => resolve_app_target_directory(
            &meta.target_directory,
            &meta.workspace_root,
            &manifest_dir,
            sdk.path(),
            env_target.as_deref(),
        ),
        None => meta.target_directory.clone(),
    };
    let host_modules = collect_host_modules(&meta, &pkg.id);
    let path_deps = collect_transitive_path_deps(&meta, &manifest_dir);
    let has_lockfile = meta.workspace_root.join("Cargo.lock").is_file();

    let ctx = AppContext {
        manifest_path: pkg.manifest_path.clone(),
        manifest_dir,
        workspace_root: meta.workspace_root.clone(),
        target_directory,
        package_id: pkg.id.clone(),
        package_name: pkg.name.clone(),
        package_version: pkg.version.clone(),
        lib_name,
        has_web_feature: pkg.has_feature("web"),
        has_lockfile,
        host_modules,
        path_deps,
    };
    Ok((ctx, sdk_root))
}

/// Resolves both [`AppContext`] and [`NvSdkRoot`] from CLI selector, optional `--sdk-root`, `cwd`,
/// and optional `--filter-platform` triple.
pub fn resolve_app_and_sdk(
    selector: &AppSelector,
    sdk_override: Option<&Path>,
    cwd: &Path,
    filter_platform: Option<&str>,
) -> Result<(AppContext, NvSdkRoot), String> {
    let (ctx, sdk_opt) = resolve_app_and_optional_sdk(selector, sdk_override, cwd, filter_platform)?;
    let sdk_root = sdk_opt.ok_or_else(|| {
        "could not locate NV SDK root; run `nv sdk install`, pass --sdk-root <DIR>, or set NV_SDK_ROOT"
            .to_owned()
    })?;
    Ok((ctx, sdk_root))
}

fn select_app_package<'a>(
    meta: &'a CargoMetadata,
    package: Option<&str>,
    explicit_manifest: Option<&Path>,
    cwd: &Path,
) -> Result<&'a CargoPackageInfo, String> {
    if package.is_some() || explicit_manifest.is_some() {
        return select_cdylib_package(meta, package, explicit_manifest);
    }
    let cwd_manifest = cwd.join("Cargo.toml");
    if cwd_manifest.is_file()
        && let Ok(pkg) = select_cdylib_package(meta, None, Some(&cwd_manifest))
    {
        return Ok(pkg);
    }
    if let Some(default_pkg) = find_package(meta, DEFAULT_ROOT_WORKSPACE_APP)
        && default_pkg.cdylib_name.is_some()
    {
        return Ok(default_pkg);
    }
    select_cdylib_package(meta, None, Some(&meta.workspace_root.join("Cargo.toml")))
}