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
//! Thin, multi-component-safe mobile package builders & `--dry-run` planners for
//! `--target rn-pkg` (peer `@nativeview/rn`) and `--target nitro-ui-pkg` (peer `@nativeview/nitro-ui`).
//!
//! Component packages never vendor shared Apple/Android host runtimes or `libnv_android_shell.so`;
//! they emit only the component's wrappers, manifests, dynamic iOS `.framework` XCFramework
//! (`<Mod>Core.xcframework`), NitroUI export anchors, and Android `lib<crate>.so`.

use std::path::Path;

use nativeview_cli::manifest::NvManifest;
use nativeview_codegen::{ExportTarget, ios_core_framework_name};

use super::manifests::{
    emit_android_library_manifest_xml, emit_apple_export_anchor_h, emit_apple_export_anchor_m,
    emit_nitro_android_build_gradle, emit_nitro_package_swift, emit_nitro_pkg_index_ts,
    emit_nitro_pkg_package_json, emit_rn_android_build_gradle, emit_rn_pkg_index_ts,
    emit_rn_pkg_package_json, emit_rn_podspec,
};
use super::native_libs::{
    append_ios_xcframework_plan, build_component_mobile_native_libs, ios_xcf_staging_dir,
    ios_xcf_target_dir, DynamicFrameworkCrate,
};
use super::{
    prepare_clean_out_dir, write_text_file, BuiltExportPackage, ExportContext,
    ExportPlatformSelection, SUPPORTED_EXPORT_HOST_MODULES,
};
use crate::build::host_cache::modules_cache_key;
use crate::build::pipeline::{BuildTarget, ResolvedBuildPlan};
use crate::cargo_env::{AppContext, NvSdkRoot};

fn validate_export_host_modules(app: &AppContext, target: BuildTarget) -> Result<(), String> {
    let unsupported: Vec<&str> = app
        .host_modules
        .iter()
        .map(String::as_str)
        .filter(|m| !SUPPORTED_EXPORT_HOST_MODULES.contains(m))
        .collect();
    if !unsupported.is_empty() {
        return Err(format!(
            "--target {} does not yet support optional native host module(s): {} (supported: {})",
            target.as_str(),
            unsupported.join(", "),
            SUPPORTED_EXPORT_HOST_MODULES.join(", ")
        ));
    }
    Ok(())
}

/// Formats the deterministic `--dry-run` plan for `--target rn-pkg`.
pub(crate) fn format_rn_pkg_plan(
    app: &AppContext,
    sdk_root: &NvSdkRoot,
    manifest: &NvManifest,
    ctx: &ExportContext,
    plan: &ResolvedBuildPlan,
    platforms: &ExportPlatformSelection,
) -> String {
    format_mobile_pkg_plan(
        "rn-pkg (React Native Fabric, peer @nativeview/rn, zero Jetpack Compose)",
        "@nativeview/rn (NativeViewReactNative pod + :nativeview_react-native Gradle subproject)",
        app,
        sdk_root,
        manifest.apple.resolved_rn_min_ios(),
        ctx,
        plan,
        platforms,
        &[
            "src/<Name>NativeComponent.ts + src/index.ts".to_owned(),
            format!(
                "ios/<Name>ComponentView.generated.mm + {}.podspec (depends on NativeViewReactNative)",
                ctx.ios_module_name
            ),
            format!(
                "android/src/main/java/{}/<Name>{{ViewManager,ReactPackage}}.generated.kt + android/build.gradle (depends on :nativeview_react-native)",
                ctx.android_package.replace('.', "/")
            ),
            format!(
                "package.json (RN codegenConfig name={}, peer @nativeview/rn)",
                nativeview_codegen::rn_codegen_spec_name(&ctx.spec)
            ),
        ],
    )
}

/// Formats the deterministic `--dry-run` plan for `--target nitro-ui-pkg`.
pub(crate) fn format_nitro_ui_pkg_plan(
    app: &AppContext,
    sdk_root: &NvSdkRoot,
    manifest: &NvManifest,
    ctx: &ExportContext,
    plan: &ResolvedBuildPlan,
    platforms: &ExportPlatformSelection,
) -> String {
    let nitro_pkg = format!(
        "com.margelo.nitro.{}",
        ctx.android_package
            .strip_prefix("com.margelo.nitro.")
            .unwrap_or(&ctx.android_package)
    );
    format_mobile_pkg_plan(
        "nitro-ui-pkg (margelo/nitro-ui bare, peer @nativeview/nitro-ui, zero React Native, zero Compose)",
        "@nativeview/nitro-ui (../app-nvehost SwiftPM + :runtime Android host kit)",
        app,
        sdk_root,
        manifest.apple.resolved_nitro_min_ios(),
        ctx,
        plan,
        platforms,
        &[
            "src/specs/Native<Name>.nitro.ts + src/<Name>.ts + src/index.ts".to_owned(),
            "ios/HybridNative<Name>.swift + ios/anchor/NvExportAnchor.{h,m} + Package.swift (depends on ../app-nvehost)".to_owned(),
            format!(
                "android/src/main/java/{}/HybridNative<Name>.kt + android/build.gradle (jniLibs only)",
                nitro_pkg.replace('.', "/")
            ),
            "nitro.json (environment: bare) + package.json (#nitro/* imports, peer @nativeview/nitro-ui)".to_owned(),
        ],
    )
}

#[allow(clippy::too_many_arguments)]
fn format_mobile_pkg_plan(
    heading: &str,
    runtime_peer: &str,
    app: &AppContext,
    sdk_root: &NvSdkRoot,
    min_ios: &str,
    ctx: &ExportContext,
    plan: &ResolvedBuildPlan,
    platforms: &ExportPlatformSelection,
    codegen_outputs: &[String],
) -> String {
    let profile = if plan.release { "release" } else { "debug" };
    let mut out = format!(
        "Native View Engine — Export Package Plan ({heading})\n  app:        {} (lib={})\n  spec:       {}\n  views:      {}\n  package:    {}@{}\n  runtime:    {runtime_peer}\n  ios_module: {}\n  android:    {}\n  modules:    {}\n  platforms:  {}\n  sdk_root:   {}\n  profile:    {profile}\n  out_dir:    {}\n\n",
        app.package_name,
        app.lib_name,
        ctx.spec_path.display(),
        ctx.view_names().join(", "),
        ctx.npm_package_name,
        ctx.version,
        ctx.ios_module_name,
        ctx.android_package,
        modules_cache_key(&app.host_modules),
        platforms.summary_label(),
        sdk_root.path().display(),
        plan.out_dir.display(),
    );

    out.push_str("[1/3] Thin codegen, export anchors & package manifests (zero host vendoring)\n");
    for line in codegen_outputs {
        out.push_str(&format!("  emit {}/{line}\n", plan.out_dir.display()));
    }
    out.push('\n');

    out.push_str("[2/3] iOS dynamic .framework XCFramework (component cdylib only)\n");
    let framework_name = ios_core_framework_name(&ctx.ios_module_name);
    let xcf_target_dir = ios_xcf_target_dir(&app.target_directory, min_ios);
    let staging_root = ios_xcf_staging_dir(&app.target_directory, &framework_name, min_ios);
    let krate = DynamicFrameworkCrate {
        manifest_path: &app.manifest_path,
        working_dir: &app.manifest_dir,
        package: &app.package_name,
        package_id: &app.package_id,
        artifact_name: &app.lib_name,
        locked: app.has_lockfile,
        target_dir: &xcf_target_dir,
        workspace_root: &app.workspace_root,
    };
    append_ios_xcframework_plan(
        &mut out,
        &krate,
        &framework_name,
        &plan.out_dir,
        &staging_root,
        plan.release,
        platforms,
        min_ios,
    );

    out.push_str("[3/3] Android component cdylib (.so only; libnv_android_shell.so lives in kit)\n");
    if platforms.android_abis.is_empty() {
        out.push_str("  skip (Android not selected in --platforms)\n");
    } else {
        for &abi in &platforms.android_abis {
            out.push_str(&format!("  abi  {} ({})\n", abi.jni_dir(), abi.rust_triple()));
            out.push_str(&format!(
                "  cmd  cargo rustc -p {} --lib --crate-type cdylib --target {}{}\n",
                app.package_name,
                abi.rust_triple(),
                if plan.release { " --release -- -C strip=debuginfo" } else { "" }
            ));
            out.push_str(&format!(
                "  out  {}/android/src/main/jniLibs/{}/lib{}.so\n",
                plan.out_dir.display(),
                abi.jni_dir(),
                ctx.crate_lib_stem
            ));
        }
    }
    out
}

/// Executes a live `--target rn-pkg` build into `out_dir`.
pub(crate) fn build_rn_pkg(
    app: &AppContext,
    sdk_root: &NvSdkRoot,
    manifest: &NvManifest,
    ctx: &ExportContext,
    out_dir: &Path,
    release: bool,
    platforms: &ExportPlatformSelection,
) -> Result<BuiltExportPackage, String> {
    validate_export_host_modules(app, BuildTarget::RnPkg)?;
    prepare_clean_out_dir(out_dir, app, sdk_root)?;

    println!("==> Generating thin React Native Fabric wrappers...");
    let pkg_path = ctx.android_package.replace('.', "/");
    let android_java = out_dir.join("android/src/main/java").join(&pkg_path);
    for view in &ctx.spec.views {
        let out = nativeview_codegen::generate_export_rn_with_ios_module(
            &ctx.spec,
            view,
            Some(&ctx.ios_module_name),
        )
        .map_err(|e| format!("export_rn failed for '{}': {e}", view.name))?;
        // `react-native-codegen` matches strictly `^.*NativeComponent\.(ts|tsx|js|jsx)$`.
        write_text_file(
            &out_dir.join("src").join(format!("{}NativeComponent.ts", view.name)),
            &out.native_component_ts.content,
        )?;
        write_text_file(
            &out_dir.join("ios").join(&out.ios_component_view_mm.relative_path),
            &out.ios_component_view_mm.content,
        )?;
        write_text_file(
            &android_java.join(&out.android_view_manager_kt.relative_path),
            &out.android_view_manager_kt.content,
        )?;
    }
    let (pkg_file, pkg_content) =
        nativeview_codegen::targets::kotlin_java::export_rn_android::emit_android_combined_react_package_kt(
            &ctx.spec,
        );
    write_text_file(&android_java.join(pkg_file), &pkg_content)?;

    write_text_file(&out_dir.join("src/index.ts"), &emit_rn_pkg_index_ts(&ctx.spec)?)?;
    write_text_file(&out_dir.join("package.json"), &emit_rn_pkg_package_json(ctx)?)?;
    write_text_file(
        &out_dir.join(format!("{}.podspec", ctx.ios_module_name)),
        &emit_rn_podspec(ctx, manifest)?,
    )?;
    write_text_file(
        &out_dir.join("android/build.gradle"),
        &emit_rn_android_build_gradle(ctx, manifest)?,
    )?;
    write_text_file(
        &out_dir.join("android/src/main/AndroidManifest.xml"),
        &emit_android_library_manifest_xml()?,
    )?;

    let notes = build_component_mobile_native_libs(
        app,
        manifest,
        ctx,
        out_dir,
        release,
        platforms,
        manifest.apple.resolved_rn_min_ios(),
    )?;

    Ok(BuiltExportPackage {
        target: BuildTarget::RnPkg,
        out_dir: out_dir.to_path_buf(),
        package_name: ctx.npm_package_name.clone(),
        version: ctx.version.clone(),
        views: ctx.spec.views.iter().map(|v| v.name.clone()).collect(),
        notes,
    })
}

/// Executes a live `--target nitro-ui-pkg` build into `out_dir`.
pub(crate) fn build_nitro_ui_pkg(
    app: &AppContext,
    sdk_root: &NvSdkRoot,
    manifest: &NvManifest,
    ctx: &ExportContext,
    out_dir: &Path,
    release: bool,
    platforms: &ExportPlatformSelection,
) -> Result<BuiltExportPackage, String> {
    validate_export_host_modules(app, BuildTarget::NitroUiPkg)?;
    prepare_clean_out_dir(out_dir, app, sdk_root)?;

    println!("==> Generating thin margelo/nitro-ui bare wrappers...");
    let bundle = nativeview_codegen::export_target(&ctx.spec, ExportTarget::NitroUi)
        .map_err(|e| format!("export_nitro_ui failed: {e}"))?;
    for file in &bundle.files {
        if file.relative_path == "nitro.json" {
            let nitro_json =
                nativeview_codegen::emit_nitro_json_with_module_name(&ctx.spec, Some(&ctx.ios_module_name));
            write_text_file(&out_dir.join("nitro.json"), &nitro_json.content)?;
        } else {
            write_text_file(&out_dir.join(&file.relative_path), &file.content)?;
        }
    }

    write_text_file(
        &out_dir.join("ios/anchor/include/NvExportAnchor.h"),
        &emit_apple_export_anchor_h(ctx)?,
    )?;
    write_text_file(
        &out_dir.join("ios/anchor/NvExportAnchor.m"),
        &emit_apple_export_anchor_m(ctx)?,
    )?;
    write_text_file(&out_dir.join("src/index.ts"), &emit_nitro_pkg_index_ts(&ctx.spec)?)?;
    write_text_file(&out_dir.join("package.json"), &emit_nitro_pkg_package_json(ctx)?)?;
    write_text_file(
        &out_dir.join("Package.swift"),
        &emit_nitro_package_swift(ctx, manifest)?,
    )?;
    write_text_file(
        &out_dir.join("android/build.gradle"),
        &emit_nitro_android_build_gradle()?,
    )?;

    let notes = build_component_mobile_native_libs(
        app,
        manifest,
        ctx,
        out_dir,
        release,
        platforms,
        manifest.apple.resolved_nitro_min_ios(),
    )?;

    Ok(BuiltExportPackage {
        target: BuildTarget::NitroUiPkg,
        out_dir: out_dir.to_path_buf(),
        package_name: ctx.npm_package_name.clone(),
        version: ctx.version.clone(),
        views: ctx.spec.views.iter().map(|v| v.name.clone()).collect(),
        notes,
    })
}