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
//! Deterministic XML & JSON platform manifest emitters for [`super::NvManifest`].

use std::collections::BTreeSet;

use nativeview_codegen::xml_escape;
use serde_json::{json, Value};

use super::{
    sanitize_android_package_id, validate_non_empty_label, validate_rel_asset_path, AndroidShell,
    EntitlementValue, ManifestAppInfo, ManifestError, NvManifest,
};

fn push_plist_str(out: &mut String, indent: &str, key: &str, val: &str) {
    out.push_str(&format!(
        "{indent}<key>{}</key>\n{indent}<string>{}</string>\n",
        xml_escape(key),
        xml_escape(val)
    ));
}

fn push_plist_bool(out: &mut String, indent: &str, key: &str, val: bool) {
    out.push_str(&format!(
        "{indent}<key>{}</key>\n{indent}<{}/>\n",
        xml_escape(key),
        if val { "true" } else { "false" }
    ));
}

fn push_plist_int(out: &mut String, indent: &str, key: &str, val: u32) {
    out.push_str(&format!("{indent}<key>{}</key>\n{indent}<integer>{val}</integer>\n", xml_escape(key)));
}

fn push_url_types(out: &mut String, bundle_id: &str, schemes: &[String]) {
    if schemes.is_empty() {
        return;
    }
    out.push_str("  <key>CFBundleURLTypes</key>\n  <array>\n    <dict>\n");
    push_plist_str(out, "      ", "CFBundleTypeRole", "Editor");
    push_plist_str(out, "      ", "CFBundleURLName", bundle_id);
    out.push_str("      <key>CFBundleURLSchemes</key>\n      <array>\n");
    for s in schemes {
        out.push_str(&format!("        <string>{}</string>\n", xml_escape(s)));
    }
    out.push_str("      </array>\n    </dict>\n  </array>\n");
}

pub(super) fn emit_macos_info_plist(
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    bundle_id_override: Option<&str>,
) -> String {
    let display_name = manifest.resolved_name(info);
    let bundle_id = bundle_id_override
        .map(str::to_owned)
        .unwrap_or_else(|| manifest.resolved_id(info));
    let executable = manifest.resolved_executable(info);

    let mut out = String::from(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
         <plist version=\"1.0\">\n\
         <dict>\n",
    );
    push_plist_str(&mut out, "  ", "CFBundleDevelopmentRegion", "en");
    push_plist_str(&mut out, "  ", "CFBundleDisplayName", &display_name);
    push_plist_str(&mut out, "  ", "CFBundleExecutable", &executable);
    push_plist_str(&mut out, "  ", "CFBundleIdentifier", &bundle_id);
    push_plist_str(&mut out, "  ", "CFBundleInfoDictionaryVersion", "6.0");
    push_plist_str(&mut out, "  ", "CFBundleName", &display_name);
    push_plist_str(&mut out, "  ", "CFBundlePackageType", "APPL");
    push_plist_str(&mut out, "  ", "CFBundleShortVersionString", &info.package_version);
    push_plist_str(&mut out, "  ", "CFBundleVersion", &info.package_version);
    push_plist_str(&mut out, "  ", "LSMinimumSystemVersion", &manifest.apple.min_macos);
    push_plist_bool(&mut out, "  ", "NSHighResolutionCapable", true);
    if manifest.app.presence.requires_macos_ls_ui_element() {
        push_plist_bool(&mut out, "  ", "LSUIElement", true);
        push_plist_bool(&mut out, "  ", "NSSupportsAutomaticTermination", false);
    }
    push_plist_str(&mut out, "  ", "NvPresence", manifest.app.presence.as_str());
    if let Some(w) = manifest.app.width {
        push_plist_int(&mut out, "  ", "NvWindowWidth", w);
    }
    if let Some(h) = manifest.app.height {
        push_plist_int(&mut out, "  ", "NvWindowHeight", h);
    }
    push_url_types(&mut out, &bundle_id, &manifest.apple.url_schemes);
    for (k, v) in &manifest.apple.usage_descriptions {
        push_plist_str(&mut out, "  ", k, v);
    }
    out.push_str("</dict>\n</plist>\n");
    out
}

pub(super) fn validate_apple_version(
    field: &'static str,
    raw: &str,
) -> Result<String, ManifestError> {
    let trimmed = raw.trim();
    let parts: Vec<&str> = trimmed.split('.').collect();
    if parts.is_empty()
        || parts.len() > 3
        || parts.iter().any(|p| p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()))
    {
        return Err(ManifestError::InvalidField {
            field,
            reason: format!(
                "invalid Apple OS version '{raw}' (expected dotted numeric like '17.0' or '13.5.1')"
            ),
        });
    }
    Ok(trimmed.to_owned())
}

pub(super) fn emit_ios_info_plist(
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    include_pairing_defaults: bool,
) -> String {
    let display_name = manifest.resolved_name(info);
    let bundle_id = manifest.resolved_id(info);
    let executable = manifest.resolved_executable(info);

    let mut out = String::from(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
         <plist version=\"1.0\">\n\
         <dict>\n",
    );
    push_plist_str(&mut out, "  ", "CFBundleDevelopmentRegion", "en");
    push_plist_str(&mut out, "  ", "CFBundleDisplayName", &display_name);
    push_plist_str(&mut out, "  ", "CFBundleExecutable", &executable);
    push_plist_str(&mut out, "  ", "CFBundleIdentifier", &bundle_id);
    push_plist_str(&mut out, "  ", "CFBundleInfoDictionaryVersion", "6.0");
    push_plist_str(&mut out, "  ", "CFBundleName", &display_name);
    push_plist_str(&mut out, "  ", "CFBundlePackageType", "APPL");
    push_plist_str(&mut out, "  ", "CFBundleShortVersionString", &info.package_version);
    push_plist_str(&mut out, "  ", "CFBundleVersion", &info.package_version);
    push_plist_bool(&mut out, "  ", "LSRequiresIPhoneOS", true);
    push_plist_str(&mut out, "  ", "MinimumOSVersion", &manifest.apple.min_ios);
    out.push_str(
        "  <key>UILaunchScreen</key>\n\
         \x20 <dict/>\n\
         \x20 <key>UIDeviceFamily</key>\n\
         \x20 <array>\n\
         \x20   <integer>1</integer>\n\
         \x20   <integer>2</integer>\n\
         \x20 </array>\n\
         \x20 <key>UIApplicationSupportsIndirectInputEvents</key>\n\
         \x20 <true/>\n\
         \x20 <key>UISupportedInterfaceOrientations</key>\n\
         \x20 <array>\n\
         \x20   <string>UIInterfaceOrientationPortrait</string>\n\
         \x20   <string>UIInterfaceOrientationLandscapeLeft</string>\n\
         \x20   <string>UIInterfaceOrientationLandscapeRight</string>\n\
         \x20 </array>\n\
         \x20 <key>UIViewControllerBasedStatusBarAppearance</key>\n\
         \x20 <true/>\n",
    );
    out.push_str("  <key>UIApplicationSceneManifest</key>\n  <dict>\n");
    push_plist_bool(&mut out, "    ", "UIApplicationSupportsMultipleScenes", manifest.app.multi_scene);
    out.push_str(
        "    <key>UISceneConfigurations</key>\n\
         \x20   <dict>\n\
         \x20     <key>UIWindowSceneSessionRoleApplication</key>\n\
         \x20     <array>\n\
         \x20       <dict>\n\
         \x20         <key>UISceneConfigurationName</key>\n\
         \x20         <string>Default Configuration</string>\n\
         \x20         <key>UISceneDelegateClassName</key>\n\
         \x20         <string>NvIosSceneDelegate</string>\n\
         \x20       </dict>\n\
         \x20     </array>\n\
         \x20   </dict>\n\
         \x20 </dict>\n",
    );
    let mut schemes = manifest.apple.url_schemes.clone();
    if include_pairing_defaults && !schemes.iter().any(|s| s.eq_ignore_ascii_case("nv")) {
        schemes.push("nv".to_owned());
    }
    push_url_types(&mut out, &bundle_id, &schemes);
    if include_pairing_defaults
        && !manifest.apple.usage_descriptions.contains_key("NSLocalNetworkUsageDescription")
    {
        push_plist_str(
            &mut out,
            "  ",
            "NSLocalNetworkUsageDescription",
            "NV iOS Shell connects to a paired local NV host over the local network for live UI streaming.",
        );
    }
    for (k, v) in &manifest.apple.usage_descriptions {
        push_plist_str(&mut out, "  ", k, v);
    }
    out.push_str("</dict>\n</plist>\n");
    out
}

fn is_ios_compatible_entitlement(key: &str) -> bool {
    !key.starts_with("com.apple.security.") || key == "com.apple.security.application-groups"
}

pub(super) fn emit_apple_entitlements_plist(
    manifest: &NvManifest,
    ios_only: bool,
) -> Option<String> {
    let entries: Vec<(&String, &EntitlementValue)> = manifest
        .apple
        .entitlements
        .iter()
        .filter(|(k, _)| !ios_only || is_ios_compatible_entitlement(k))
        .collect();
    if entries.is_empty() {
        return None;
    }
    let mut out = String::from(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
         <plist version=\"1.0\">\n\
         <dict>\n",
    );
    for (k, v) in entries {
        match v {
            EntitlementValue::Bool(b) => push_plist_bool(&mut out, "  ", k, *b),
            EntitlementValue::String(s) => push_plist_str(&mut out, "  ", k, s),
            EntitlementValue::Array(items) => {
                out.push_str(&format!("  <key>{}</key>\n  <array>\n", xml_escape(k)));
                for item in items {
                    out.push_str(&format!("    <string>{}</string>\n", xml_escape(item)));
                }
                out.push_str("  </array>\n");
            }
        }
    }
    out.push_str("</dict>\n</plist>\n");
    Some(out)
}

pub(super) fn emit_android_manifest_xml(
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    shell: AndroidShell,
) -> String {
    let app_label = xml_escape(&manifest.resolved_name(info));
    let resizeable = manifest.app.multi_scene || manifest.app.pip;
    let mut perms = BTreeSet::new();
    perms.insert("android.permission.INTERNET");
    for p in &manifest.android.permissions {
        perms.insert(p.as_str());
    }

    let mut out = String::from("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    match shell {
        AndroidShell::Compose => {
            out.push_str("<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n");
        }
        AndroidShell::View => {
            let android_id = manifest
                .resolved_android_id(info)
                .unwrap_or_else(|_| sanitize_android_package_id(&manifest.resolved_id(info)));
            let pkg = xml_escape(&android_id);
            let ver = xml_escape(&info.package_version);
            out.push_str(&format!(
                "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n\
                 \x20   package=\"{pkg}\"\n\
                 \x20   android:versionCode=\"1\"\n\
                 \x20   android:versionName=\"{ver}\">\n\
                 \x20   <uses-sdk\n\
                 \x20       android:minSdkVersion=\"{}\"\n\
                 \x20       android:targetSdkVersion=\"{}\" />\n",
                manifest.android.min_sdk, manifest.android.target_sdk,
            ));
        }
    }
    for perm in perms {
        out.push_str(&format!(
            "    <uses-permission android:name=\"{}\" />\n",
            xml_escape(perm)
        ));
    }
    out.push_str(
        "    <queries>\n\
         \x20       <intent>\n\
         \x20           <action android:name=\"android.intent.action.VIEW\" />\n\
         \x20           <category android:name=\"android.intent.category.BROWSABLE\" />\n\
         \x20           <data android:scheme=\"https\" />\n\
         \x20       </intent>\n\
         \x20       <intent>\n\
         \x20           <action android:name=\"android.intent.action.VIEW\" />\n\
         \x20           <category android:name=\"android.intent.category.BROWSABLE\" />\n\
         \x20           <data android:scheme=\"http\" />\n\
         \x20       </intent>\n\
         \x20   </queries>\n",
    );
    let activity_name = match shell {
        AndroidShell::Compose => ".MainActivity",
        AndroidShell::View => "io.github.nativeview.android.NvMainActivity",
    };
    out.push_str(&format!(
        "    <application\n\
         \x20       android:allowBackup=\"false\"\n\
         \x20       android:label=\"{app_label}\"\n\
         \x20       android:extractNativeLibs=\"true\"\n\
         \x20       android:hardwareAccelerated=\"true\"\n\
         \x20       android:enableOnBackInvokedCallback=\"true\"\n\
         \x20       android:theme=\"@android:style/Theme.Material.NoActionBar\">\n\
         \x20       <activity\n\
         \x20           android:name=\"{activity_name}\"\n\
         \x20           android:exported=\"true\"\n\
         \x20           android:windowSoftInputMode=\"adjustNothing|stateHidden\"\n\
         \x20           android:resizeableActivity=\"{}\"\n\
         \x20           android:supportsPictureInPicture=\"{}\"",
        if resizeable { "true" } else { "false" },
        if manifest.app.pip { "true" } else { "false" },
    ));
    match shell {
        AndroidShell::View => {
            out.push_str(
                "\n            android:configChanges=\"orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|density\"",
            );
        }
        AndroidShell::Compose if manifest.app.pip => {
            out.push_str(
                "\n            android:configChanges=\"screenSize|smallestScreenSize|screenLayout|orientation\"",
            );
        }
        AndroidShell::Compose => {}
    }
    out.push_str(
        ">\n\
         \x20           <intent-filter>\n\
         \x20               <action android:name=\"android.intent.action.MAIN\" />\n\
         \x20               <category android:name=\"android.intent.category.LAUNCHER\" />\n\
         \x20           </intent-filter>\n\
         \x20       </activity>\n\
         \x20   </application>\n\
         </manifest>\n",
    );
    out
}

fn sanitize_mv3_version(raw: &str) -> Result<String, ManifestError> {
    let base = raw.trim().split(['-', '+']).next().unwrap_or("");
    let parts: Vec<&str> = base.split('.').collect();
    if parts.is_empty() || parts.len() > 4 {
        return Err(ManifestError::InvalidField {
            field: "package.version",
            reason: "MV3 version must have 1 to 4 numeric segments (0..=65535)".to_owned(),
        });
    }
    for part in &parts {
        if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) || part.parse::<u16>().is_err() {
            return Err(ManifestError::InvalidField {
                field: "package.version",
                reason: format!("invalid MV3 version segment '{part}' in '{raw}'"),
            });
        }
    }
    Ok(base.to_owned())
}

pub(super) fn emit_web_mv3_manifest_json(
    manifest: &NvManifest,
    info: &ManifestAppInfo,
) -> Result<String, ManifestError> {
    let ext = manifest.web.extension.as_ref().ok_or_else(|| ManifestError::InvalidField {
        field: "web.extension",
        reason: "cannot emit MV3 manifest.json without [web.extension]".to_owned(),
    })?;
    let name = match ext.name.as_deref() {
        Some(n) => validate_non_empty_label("web.extension.name", n)?,
        None => validate_non_empty_label("app.name", &manifest.resolved_name(info))?,
    };
    let version = sanitize_mv3_version(&info.package_version)?;
    let popup = validate_rel_asset_path("web.extension.popup", &ext.popup)?;
    let service_worker = validate_rel_asset_path("web.extension.service_worker", &ext.service_worker)?;
    let doc: Value = json!({
        "manifest_version": 3,
        "name": name,
        "version": version,
        "action": {
            "default_popup": popup,
        },
        "background": {
            "service_worker": service_worker,
            "type": "module",
        },
        "content_security_policy": {
            "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'",
        },
    });
    serde_json::to_string_pretty(&doc)
        .map(|s| s + "\n")
        .map_err(|e| ManifestError::InvalidField { field: "manifest.json", reason: e.to_string() })
}