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
431
432
433
434
435
436
437
438
//! Turnkey embeddable package builders (`nv build --target web-pkg | rn-pkg | nitro-ui-pkg`).

pub(crate) mod kit_runtime;
pub(crate) mod manifests;
pub(crate) mod native_libs;
pub(crate) mod native_pkg;
pub(crate) mod web_pkg;
#[cfg(test)]
mod tests;

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use nativeview_cli::manifest::NvManifest;
use nativeview_codegen::{export_lib_stem, HybridFileSpec};

use super::pipeline::{BuildTarget, ResolvedBuildPlan};
use crate::cargo_env::{AppContext, NvSdkRoot};

/// Optional native host modules bundled out of the box by shared mobile kits (`@nativeview/rn`,
/// `@nativeview/nitro-ui`) and accepted by component export targets (`rn-pkg`, `nitro-ui-pkg`).
pub(super) const SUPPORTED_EXPORT_HOST_MODULES: &[&str] = &["canvas", "svg"];

/// Supported Android NDK ABIs for `rn-pkg` and `nitro-ui-pkg` native `.so` packaging.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum AndroidAbi {
    Arm64V8a,
    X86_64,
    ArmeabiV7a,
    X86,
}

impl AndroidAbi {
    pub(crate) const fn jni_dir(self) -> &'static str {
        match self {
            Self::Arm64V8a => "arm64-v8a",
            Self::X86_64 => "x86_64",
            Self::ArmeabiV7a => "armeabi-v7a",
            Self::X86 => "x86",
        }
    }

    pub(crate) const fn rust_triple(self) -> &'static str {
        match self {
            Self::Arm64V8a => "aarch64-linux-android",
            Self::X86_64 => "x86_64-linux-android",
            Self::ArmeabiV7a => "armv7-linux-androideabi",
            Self::X86 => "i686-linux-android",
        }
    }

    pub(crate) const fn cargo_env_triple(self) -> &'static str {
        match self {
            Self::Arm64V8a => "AARCH64_LINUX_ANDROID",
            Self::X86_64 => "X86_64_LINUX_ANDROID",
            Self::ArmeabiV7a => "ARMV7_LINUX_ANDROIDEABI",
            Self::X86 => "I686_LINUX_ANDROID",
        }
    }

    pub(crate) const fn ndk_clang_prefix(self) -> &'static str {
        match self {
            Self::Arm64V8a => "aarch64-linux-android",
            Self::X86_64 => "x86_64-linux-android",
            Self::ArmeabiV7a => "armv7a-linux-androideabi",
            Self::X86 => "i686-linux-android",
        }
    }
}

/// Selected mobile native library slices for `rn-pkg` and `nitro-ui-pkg`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ExportPlatformSelection {
    pub ios_sim: bool,
    pub ios_device: bool,
    pub android_abis: Vec<AndroidAbi>,
    pub explicit: bool,
}

impl ExportPlatformSelection {
    /// Host-OS + release-aware defaults when `--platforms` is omitted.
    pub(crate) fn defaults_for(host_os: &str, release: bool) -> Self {
        let is_mac = host_os == "macos";
        let android_abis = if release {
            vec![AndroidAbi::Arm64V8a, AndroidAbi::X86_64]
        } else {
            vec![AndroidAbi::Arm64V8a]
        };
        Self {
            ios_sim: is_mac,
            ios_device: is_mac && release,
            android_abis,
            explicit: false,
        }
    }

    /// Parses a comma-separated `--platforms` list (`ios-sim`, `ios`, `ios-device`, `android`,
    /// `android-arm64`, `android-x86_64`, `android-armv7`, `android-x86`, `all`, `none`).
    pub(crate) fn parse(raw: Option<&str>, host_os: &str, release: bool) -> Result<Self, String> {
        let Some(raw) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
            return Ok(Self::defaults_for(host_os, release));
        };
        let mut ios_sim = false;
        let mut ios_device = false;
        let mut android_abis = Vec::new();
        for token in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
            if token.eq_ignore_ascii_case("none")
                || token.eq_ignore_ascii_case("js-only")
                || token.eq_ignore_ascii_case("skip-native")
            {
                ios_sim = false;
                ios_device = false;
                android_abis.clear();
            } else if token.eq_ignore_ascii_case("ios-sim") {
                ios_sim = true;
            } else if token.eq_ignore_ascii_case("ios-device") {
                ios_device = true;
            } else if token.eq_ignore_ascii_case("ios") {
                ios_sim = true;
                ios_device = true;
            } else if token.eq_ignore_ascii_case("android") {
                push_unique_abi(&mut android_abis, AndroidAbi::Arm64V8a);
                if release {
                    push_unique_abi(&mut android_abis, AndroidAbi::X86_64);
                }
            } else if token.eq_ignore_ascii_case("android-arm64")
                || token.eq_ignore_ascii_case("arm64-v8a")
            {
                push_unique_abi(&mut android_abis, AndroidAbi::Arm64V8a);
            } else if token.eq_ignore_ascii_case("android-x86_64")
                || token.eq_ignore_ascii_case("x86_64")
            {
                push_unique_abi(&mut android_abis, AndroidAbi::X86_64);
            } else if token.eq_ignore_ascii_case("android-armv7")
                || token.eq_ignore_ascii_case("armeabi-v7a")
            {
                push_unique_abi(&mut android_abis, AndroidAbi::ArmeabiV7a);
            } else if token.eq_ignore_ascii_case("android-x86")
                || token.eq_ignore_ascii_case("x86")
            {
                push_unique_abi(&mut android_abis, AndroidAbi::X86);
            } else if token.eq_ignore_ascii_case("all") {
                ios_sim = true;
                ios_device = true;
                push_unique_abi(&mut android_abis, AndroidAbi::Arm64V8a);
                push_unique_abi(&mut android_abis, AndroidAbi::X86_64);
                push_unique_abi(&mut android_abis, AndroidAbi::ArmeabiV7a);
                push_unique_abi(&mut android_abis, AndroidAbi::X86);
            } else {
                return Err(format!(
                    "unknown --platforms token '{token}' (expected: ios-sim, ios-device, ios, android, android-arm64, android-x86_64, android-armv7, android-x86, all, none)"
                ));
            }
        }
        Ok(Self { ios_sim, ios_device, android_abis, explicit: true })
    }

    pub(crate) fn has_ios(&self) -> bool {
        self.ios_sim || self.ios_device
    }
}

fn push_unique_abi(list: &mut Vec<AndroidAbi>, abi: AndroidAbi) {
    if !list.contains(&abi) {
        list.push(abi);
    }
}

impl ExportPlatformSelection {

    pub(crate) fn summary_label(&self) -> String {
        let mut parts = Vec::new();
        if self.ios_sim {
            parts.push("ios-sim".to_owned());
        }
        if self.ios_device {
            parts.push("ios-device".to_owned());
        }
        for abi in &self.android_abis {
            parts.push(format!("android:{}", abi.jni_dir()));
        }
        if parts.is_empty() { "none (source/manifests only)".to_owned() } else { parts.join(", ") }
    }
}

/// Resolved export metadata derived from `Cargo.toml`, `nativeview.toml [export]`, and the parsed
/// `#[nativeview_hybrid_spec]` file.
#[derive(Debug, Clone)]
pub(crate) struct ExportContext {
    pub spec_path: PathBuf,
    pub spec: HybridFileSpec,
    pub npm_package_name: String,
    pub version: String,
    pub android_package: String,
    pub ios_module_name: String,
    pub primary_view_name: String,
    pub crate_lib_stem: String,
}

impl ExportContext {
    /// Parses `[export].spec` and resolves all export metadata, applying `[export].android_package`
    /// onto `spec.namespace` so every downstream generator emits matching Android package names.
    pub(crate) fn resolve(app: &AppContext, manifest: &NvManifest) -> Result<Self, String> {
        let rel_spec = manifest.resolved_export_spec();
        let spec_path = app.manifest_dir.join(rel_spec);
        if !spec_path.is_file() {
            return Err(format!(
                "export spec file not found at '{}' (configure `[export] spec = \"...\"` in nativeview.toml)",
                spec_path.display()
            ));
        }
        let mut spec = nativeview_codegen::parse_hybrid_rust_spec_file(&spec_path)
            .map_err(|e| format!("failed to parse export spec '{}': {e}", spec_path.display()))?;
        if spec.views.is_empty() {
            return Err(format!(
                "export spec '{}' declares no #[nv_hybrid_view] traits",
                spec_path.display()
            ));
        }
        let default_android_pkg = spec.android_package();
        let android_package = manifest.resolved_export_android_package(&default_android_pkg);
        if spec.namespace.as_deref() != Some(android_package.as_str()) {
            spec.namespace = Some(android_package.clone());
        }
        let info = app.manifest_app_info();
        let primary_view_name = spec.views[0].name.clone();
        let crate_lib_stem = export_lib_stem(&spec);
        let npm_package_name = manifest.resolved_export_package_name(&info);
        let version = manifest.resolved_export_version(&info);
        let ios_module_name =
            manifest.resolved_export_ios_module_name(Some(&primary_view_name), &info);
        Ok(Self {
            spec_path,
            spec,
            npm_package_name,
            version,
            android_package,
            ios_module_name,
            primary_view_name,
            crate_lib_stem,
        })
    }

    pub(crate) fn view_names(&self) -> Vec<&str> {
        self.spec.views.iter().map(|v| v.name.as_str()).collect()
    }
}

/// Summary of an emitted embeddable package returned by [`build_export_package`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BuiltExportPackage {
    pub target: BuildTarget,
    pub out_dir: PathBuf,
    pub package_name: String,
    pub version: String,
    pub views: Vec<String>,
    pub notes: Vec<String>,
}

impl BuiltExportPackage {
    pub(crate) fn format_summary(&self) -> String {
        let mut summary = format!(
            "==> Export package ({}) complete:\n    package: {}@{}\n    views:   {}\n    out_dir: {}\n",
            self.target.as_str(),
            self.package_name,
            self.version,
            self.views.join(", "),
            self.out_dir.display(),
        );
        for note in &self.notes {
            summary.push_str(&format!("    {note}\n"));
        }
        summary
    }
}

pub(crate) fn write_text_file(path: &Path, content: &str) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;
    }
    fs::write(path, content).map_err(|e| format!("failed to write '{}': {e}", path.display()))
}

fn normalize_for_safety(path: &Path) -> Result<PathBuf, String> {
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        env::current_dir()
            .map_err(|e| format!("failed to read current working directory: {e}"))?
            .join(path)
    };
    if abs.exists() {
        return abs
            .canonicalize()
            .map_err(|e| format!("failed to canonicalize '{}': {e}", abs.display()));
    }
    let mut normalized = PathBuf::new();
    for comp in abs.components() {
        match comp {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                normalized.pop();
            }
            other => normalized.push(other.as_os_str()),
        }
    }
    Ok(normalized)
}

/// Validates `out_dir` is safe to wipe and recreate (refuses filesystem roots, `.`, `..`,
/// `manifest_dir`, `workspace_root`, `sdk_root`, or any ancestor of them).
pub(crate) fn prepare_clean_out_dir(
    out_dir: &Path,
    app: &AppContext,
    sdk_root: &NvSdkRoot,
) -> Result<(), String> {
    let raw_str = out_dir.as_os_str();
    if raw_str.is_empty() || raw_str == "." || raw_str == ".." {
        return Err(format!(
            "refusing to wipe unsafe --out directory '{}'; choose a dedicated output subdirectory",
            out_dir.display()
        ));
    }
    let target = normalize_for_safety(out_dir)?;
    if target.parent().is_none() {
        return Err(format!("refusing to wipe filesystem root '{}'", target.display()));
    }
    for protected in [&app.manifest_dir, &app.workspace_root, sdk_root.path()] {
        let prot = normalize_for_safety(protected)?;
        if target == prot || prot.starts_with(&target) {
            return Err(format!(
                "refusing to wipe --out '{}' because it equals or contains protected workspace directory '{}'",
                target.display(),
                prot.display()
            ));
        }
    }
    if target.exists() {
        fs::remove_dir_all(&target)
            .map_err(|e| format!("failed to clean '{}': {e}", target.display()))?;
    }
    fs::create_dir_all(&target)
        .map_err(|e| format!("failed to create '{}': {e}", target.display()))
}

const SKIP_COPY_DIRS: &[&str] = &[".git", "target", "node_modules", ".build", "build"];

pub(crate) fn copy_tree_filtered(
    src: &Path,
    dst: &Path,
    accept: &dyn Fn(&Path) -> bool,
) -> Result<(), String> {
    if !src.is_dir() {
        return Err(format!("required source directory not found: '{}'", src.display()));
    }
    let mut entries: Vec<PathBuf> = fs::read_dir(src)
        .map_err(|e| format!("failed to read '{}': {e}", src.display()))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| format!("failed to iterate '{}': {e}", src.display()))?
        .into_iter()
        .map(|e| e.path())
        .collect();
    entries.sort();
    for from in entries {
        let Some(name) = from.file_name() else {
            continue;
        };
        let to = dst.join(name);
        if from.is_dir() {
            let name_str = name.to_str().unwrap_or("");
            if SKIP_COPY_DIRS.contains(&name_str) || !accept(&from) {
                continue;
            }
            copy_tree_filtered(&from, &to, accept)?;
        } else if accept(&from) {
            if let Some(parent) = to.parent() {
                fs::create_dir_all(parent)
                    .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;
            }
            fs::copy(&from, &to).map_err(|e| {
                format!("failed to copy '{}' -> '{}': {e}", from.display(), to.display())
            })?;
        }
    }
    Ok(())
}

/// Formats a deterministic `--dry-run` plan for `web-pkg`, `rn-pkg`, or `nitro-ui-pkg`.
pub(crate) fn format_export_plan(
    app: &AppContext,
    sdk_root: &NvSdkRoot,
    manifest: &NvManifest,
    plan: &ResolvedBuildPlan,
    platforms_opt: Option<&str>,
) -> Result<String, String> {
    let ctx = ExportContext::resolve(app, manifest)?;
    let platforms = ExportPlatformSelection::parse(platforms_opt, env::consts::OS, plan.release)?;
    match plan.target {
        BuildTarget::WebPkg => Ok(web_pkg::format_web_pkg_plan(app, sdk_root, &ctx, plan)),
        BuildTarget::RnPkg => {
            Ok(native_pkg::format_rn_pkg_plan(app, sdk_root, manifest, &ctx, plan, &platforms))
        }
        BuildTarget::NitroUiPkg => {
            Ok(native_pkg::format_nitro_ui_pkg_plan(app, sdk_root, manifest, &ctx, plan, &platforms))
        }
        other => Err(format!("internal error: '{}' is not an export package target", other.as_str())),
    }
}

/// Executes a live turnkey export package build (`web-pkg`, `rn-pkg`, or `nitro-ui-pkg`).
pub(crate) fn build_export_package(
    app: &AppContext,
    sdk_root: &NvSdkRoot,
    manifest: &NvManifest,
    plan: &ResolvedBuildPlan,
    platforms_opt: Option<&str>,
) -> Result<BuiltExportPackage, String> {
    let ctx = ExportContext::resolve(app, manifest)?;
    let platforms = ExportPlatformSelection::parse(platforms_opt, env::consts::OS, plan.release)?;
    match plan.target {
        BuildTarget::WebPkg => web_pkg::build_web_pkg(app, sdk_root, &ctx, &plan.out_dir, plan.release),
        BuildTarget::RnPkg => {
            native_pkg::build_rn_pkg(app, sdk_root, manifest, &ctx, &plan.out_dir, plan.release, &platforms)
        }
        BuildTarget::NitroUiPkg => native_pkg::build_nitro_ui_pkg(
            app,
            sdk_root,
            manifest,
            &ctx,
            &plan.out_dir,
            plan.release,
            &platforms,
        ),
        other => Err(format!("internal error: '{}' is not an export package target", other.as_str())),
    }
}