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
//! Web topology resolution (`hosts/web-shell` vs standalone `[features] web` PWA), static HTTP
//! server startup, and lock-free incremental web rebuilds for `nv dev`.

use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};

use nativeview_cli::manifest::NvManifest;

use crate::build::pipeline::{resolved_out_dir, BuildTarget};
use crate::build::web_bundle;
use crate::cargo_env::{AppContext, NvSdkRoot};
use crate::static_http;
use crate::web_shell::{self, WebShellToolchain};

use super::watch::{web_dev_redirect, ws_bind_addr};

/// Resolved Web dev topology for a `nv dev` session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum DevWebTopology {
    /// Web builds disabled (`--no-web`, `--skia`/`--pair` default, or app without web support).
    Disabled,
    /// Workspace app hosted by `hosts/web-shell` (fast incremental `nativeview-web-shell` dev bundle).
    WorkspaceWebShell {
        web_shell_dir: PathBuf,
        web_out_dir: PathBuf,
        extra_features: Vec<String>,
        /// The app crate's `assets/`, served at `/assets/` so `asset://<rel>` (`assets/<rel>`) loads.
        app_assets_dir: PathBuf,
    },
    /// Standalone `[features] web` app built via `build::web_bundle` and served from `<out_dir>/pwa/`.
    StandaloneApp {
        out_dir: PathBuf,
        pwa_dir: PathBuf,
        web_index: String,
    },
}

impl DevWebTopology {
    pub(crate) fn is_enabled(&self) -> bool {
        !matches!(self, Self::Disabled)
    }

    pub(crate) fn is_standalone(&self) -> bool {
        matches!(self, Self::StandaloneApp { .. })
    }

    /// Output directory written by web builds (excluded from file-watcher events to prevent loops).
    pub(crate) fn excluded_output_dir(&self) -> Option<&Path> {
        match self {
            Self::Disabled => None,
            Self::WorkspaceWebShell { web_out_dir, .. } => Some(web_out_dir.as_path()),
            Self::StandaloneApp { out_dir, .. } => Some(out_dir.as_path()),
        }
    }
}

/// Returns `Some(extra_features)` when `package_name` is hosted by `hosts/web-shell`.
///
/// - `nativeview-studio-workspace` and `nativeview-example-kitchen-sink` are included in `nativeview-web-shell`'s
///   default feature set (`extra_features = &[]`).
/// - `nativeview-example-issues-client` requires opt-in `--features app-issues`.
pub(crate) fn web_shell_extra_features_for_package(
    package_name: &str,
) -> Option<&'static [&'static str]> {
    match package_name {
        "nativeview-studio-workspace" | "nativeview-example-kitchen-sink" => Some(&[]),
        "nativeview-example-issues-client" => Some(&["app-issues"]),
        _ => None,
    }
}

/// Returns `true` when Tier-1 `view!` edits should be promoted directly to Tier-2 so a pure standalone
/// Web PWA dev session (no `--skia` / `--pair` native preview) rebuilds `<out_dir>/pwa/`
/// atomically and reports accurate `web_bundle_hash` / build errors to `nv dev wait`.
pub(crate) fn should_force_tier2_for_web(
    topology: &DevWebTopology,
    skia: bool,
    pair: bool,
) -> bool {
    topology.is_standalone() && !skia && !pair
}

/// Resolves which Web topology `nv dev` should run (if any).
pub(crate) fn resolve_dev_web_topology(
    app: &AppContext,
    sdk_root: Option<&NvSdkRoot>,
    manifest: &NvManifest,
    web: bool,
    no_web: bool,
    skia: bool,
    pair: bool,
) -> Result<DevWebTopology, String> {
    if no_web || (!web && (skia || pair)) {
        return Ok(DevWebTopology::Disabled);
    }

    if let Some(extra) = web_shell_extra_features_for_package(&app.package_name) {
        if let Some(sdk) = sdk_root {
            let web_shell_dir = sdk.path().join("hosts").join("web-shell");
            if web_shell_dir.join("Cargo.toml").is_file() {
                return Ok(DevWebTopology::WorkspaceWebShell {
                    web_out_dir: web_shell_dir.join("pkg").join("dev"),
                    web_shell_dir,
                    extra_features: extra.iter().map(|s| (*s).to_owned()).collect(),
                    app_assets_dir: app.manifest_dir.join(nativeview_resources::APP_ASSET_DIR),
                });
            }
            if web {
                return Err(format!(
                    "package '{}' requires `hosts/web-shell`, but '{}' was not found",
                    app.package_name,
                    web_shell_dir.join("Cargo.toml").display()
                ));
            }
        } else if web {
            return Err(format!(
                "package '{}' requires `hosts/web-shell`, but no monorepo SDK root was found",
                app.package_name
            ));
        }
        return Ok(DevWebTopology::Disabled);
    }

    if app.has_web_feature {
        let out_dir = resolved_out_dir(
            &app.target_directory,
            &app.lib_name,
            BuildTarget::Web,
            None,
            None,
            &app.manifest_dir,
        );
        let pwa_dir = out_dir.join("pwa");
        return Ok(DevWebTopology::StandaloneApp {
            out_dir,
            pwa_dir,
            web_index: manifest.web.index.clone(),
        });
    }

    if web {
        return Err(format!(
            "package '{}' does not declare a `[features] web` feature in {} and is not hosted by `hosts/web-shell` (omit `--web` or add a `web` feature)",
            app.package_name,
            app.manifest_path.display()
        ));
    }

    Ok(DevWebTopology::Disabled)
}

/// Returns watched non-`.rs` web asset paths for a standalone Web app:
/// - `<app>/<manifest.web.root>` directory when `web.root != "."`, or
/// - Explicit declared `web.index` + `web.extension.{popup,service_worker,assets}` files when
///   `web.root == "."` (avoiding watching the entire crate root / `target/`).
pub(crate) fn web_asset_watch_paths(
    topology: &DevWebTopology,
    app: &AppContext,
    manifest: &NvManifest,
) -> Vec<PathBuf> {
    if !topology.is_standalone() {
        return Vec::new();
    }
    // The app's `asset://` files are staged into `<pwa>/assets/`: edits there rebuild too.
    let assets_dir = app.manifest_dir.join(nativeview_resources::APP_ASSET_DIR);
    let mut files: Vec<PathBuf> = assets_dir.is_dir().then_some(assets_dir).into_iter().collect();
    if manifest.web.root != "." {
        let web_dir = app.manifest_dir.join(&manifest.web.root);
        if web_dir.is_dir() {
            files.push(web_dir);
        }
        return files;
    }
    let mut push_unique = |rel: &str| {
        let path = app.manifest_dir.join(rel);
        if path.is_file() && !files.contains(&path) {
            files.push(path);
        }
    };
    push_unique(&manifest.web.index);
    if let Some(ext) = &manifest.web.extension {
        push_unique(&ext.popup);
        push_unique(&ext.service_worker);
        for asset in &ext.assets {
            push_unique(asset);
        }
    }
    files
}

/// Formats the user-facing local HTTP URL for a standalone Web server bound to `host:port`.
pub(crate) fn format_standalone_web_url(host: &str, port: u16) -> String {
    let trimmed = host.trim();
    if trimmed.is_empty()
        || matches!(trimmed, "127.0.0.1" | "0.0.0.0" | "::" | "::1" | "localhost")
    {
        format!("http://localhost:{port}/")
    } else if trimmed.contains(':') && !trimmed.starts_with('[') {
        format!("http://[{trimmed}]:{port}/")
    } else {
        format!("http://{trimmed}:{port}/")
    }
}

/// Started static HTTP server details for `nv dev`.
pub(crate) struct StartedDevWebServer {
    pub port: u16,
    pub url: String,
    pub banner_detail: &'static str,
}

/// Binds and spawns the static HTTP server for the active [`DevWebTopology`].
pub(crate) fn start_dev_web_server(
    topology: &DevWebTopology,
    host: &str,
    web_port_req: u16,
    ws_port: u16,
    web_lock: Arc<RwLock<()>>,
) -> Result<Option<StartedDevWebServer>, String> {
    match topology {
        DevWebTopology::Disabled => Ok(None),
        DevWebTopology::WorkspaceWebShell { web_shell_dir, app_assets_dir, .. } => {
            let web_bind = ws_bind_addr(host, web_port_req);
            let listener = TcpListener::bind(&web_bind)
                .map_err(|e| format!("failed to bind web-shell HTTP {web_bind}: {e}"))?;
            let actual_port = listener.local_addr().map(|a| a.port()).unwrap_or(web_port_req);
            let redirect: static_http::Redirect =
                Arc::new(move |target, req_host| web_dev_redirect(target, req_host, ws_port));
            let serve_root = web_shell_dir.clone();
            let mounts = vec![(format!("/{}/", nativeview_resources::APP_ASSET_DIR), app_assets_dir.clone())];
            std::thread::spawn(move || {
                static_http::serve_mounted(listener, serve_root, mounts, web_lock, Some(redirect));
            });
            Ok(Some(StartedDevWebServer {
                port: actual_port,
                url: format!("http://127.0.0.1:{actual_port}/"),
                banner_detail: "dev bundle, rebuilt on save; pass --no-web to skip",
            }))
        }
        DevWebTopology::StandaloneApp { pwa_dir, web_index, .. } => {
            let web_bind = ws_bind_addr(host, web_port_req);
            let listener = TcpListener::bind(&web_bind)
                .map_err(|e| format!("failed to bind standalone web HTTP {web_bind}: {e}"))?;
            let actual_port = listener.local_addr().map(|a| a.port()).unwrap_or(web_port_req);
            let redirect = static_http::custom_index_redirect(web_index);
            let serve_root = pwa_dir.clone();
            std::thread::spawn(move || {
                static_http::serve(listener, serve_root, web_lock, redirect);
            });
            Ok(Some(StartedDevWebServer {
                port: actual_port,
                url: format_standalone_web_url(host, actual_port),
                banner_detail: "standalone PWA, rebuilt on save; pass --no-web to skip",
            }))
        }
    }
}

fn get_or_prepare_toolchain(
    slot: &Mutex<Option<WebShellToolchain>>,
    prepare: impl FnOnce() -> Result<WebShellToolchain, String>,
) -> Result<WebShellToolchain, String> {
    let mut guard = slot.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(tc) = guard.clone() {
        return Ok(tc);
    }
    let tc = prepare()?;
    *guard = Some(tc.clone());
    Ok(tc)
}

/// Runs one lock-free incremental Web rebuild for the active [`DevWebTopology`], returning the
/// bundle content hash on success. `web_lock.write()` is held ONLY during the atomic publish swap.
pub(crate) fn rebuild_dev_web(
    topology: &DevWebTopology,
    app: &AppContext,
    sdk_root: Option<&NvSdkRoot>,
    manifest: &NvManifest,
    web_toolchain_slot: &Mutex<Option<WebShellToolchain>>,
    web_lock: &RwLock<()>,
) -> Result<Option<String>, String> {
    match topology {
        DevWebTopology::Disabled => Ok(None),
        DevWebTopology::WorkspaceWebShell {
            web_out_dir,
            extra_features,
            ..
        } => {
            let sdk = sdk_root.ok_or_else(|| {
                "workspace `hosts/web-shell` rebuild requires a monorepo SDK root".to_owned()
            })?;
            let toolchain = get_or_prepare_toolchain(web_toolchain_slot, || {
                web_shell::prepare_web_shell_toolchain(sdk.path())
            })?;
            let staged = web_shell::stage_web_shell_dev_bundle(
                sdk.path(),
                &app.target_directory,
                web_out_dir,
                &toolchain,
                extra_features,
            )?;
            let hash = staged.hash().to_owned();
            let _serving_paused = web_lock.write();
            web_shell::publish_staged_bundle(staged, web_out_dir)?;
            Ok(Some(hash))
        }
        DevWebTopology::StandaloneApp { out_dir, .. } => {
            let toolchain = get_or_prepare_toolchain(web_toolchain_slot, || {
                web_bundle::prepare_web_app_toolchain(app, sdk_root)
            })?;
            let staged = web_bundle::stage_web_app_with_toolchain(
                app,
                manifest,
                out_dir,
                false,
                &toolchain,
            )?;
            let hash = staged.hash().to_owned();
            let _serving_paused = web_lock.write();
            web_bundle::publish_staged_web_app(staged, out_dir)?;
            Ok(Some(hash))
        }
    }
}