Skip to main content

nsh_cli/
lib.rs

1//! The `nsh` command line tool, as a library: [`main_with`] runs it with
2//! the UI sets the hosts serve. `nsh` itself is `main_with` of the mobile
3//! UI; an app with Rust components of its own (`nsh.json` `"rust"`) gets a
4//! build of it with the app's set too.
5
6mod android;
7mod build;
8mod check;
9mod dev;
10mod entry;
11mod init;
12mod logger;
13mod net;
14mod package;
15mod run;
16mod runtime;
17mod rust_app;
18mod sign;
19mod trace;
20mod ui;
21mod windows;
22
23use std::{path::PathBuf, process::ExitCode, sync::OnceLock};
24
25use clap::{Args, Parser, Subcommand};
26use nsh_core::ui::Registry;
27
28/// The UI sets of this build ([`main_with`]).
29static UI_SETS: OnceLock<Vec<Registry>> = OnceLock::new();
30
31/// The UI sets the hosts serve: what bundles import natively, what bytecode
32/// links against, what `.nsh/types` declares.
33pub(crate) fn ui_sets() -> &'static [Registry] {
34    UI_SETS.get_or_init(|| vec![nsh_ui_mobile::registry()])
35}
36
37#[derive(Parser)]
38#[command(name = "nsh", version, about = "Build and run nsh apps")]
39struct Cli {
40    /// Show everything: log lines with their targets, cargo's output and
41    /// the hosts' own.
42    #[arg(
43        short,
44        long,
45        global = true,
46        env = "NSH_VERBOSE",
47        value_parser = clap::builder::BoolishValueParser::new()
48    )]
49    verbose: bool,
50    #[command(subcommand)]
51    command: Command,
52}
53
54#[derive(Subcommand)]
55enum Command {
56    /// Create an app: `App.tsx`, `nsh.json`, `tsconfig.json` and the type
57    /// declarations editors use (`.nsh/types`, kept up to date by the other
58    /// commands).
59    Init {
60        /// Directory of the app (created if missing).
61        #[arg(default_value = ".")]
62        dir: PathBuf,
63        /// Display name (default: the directory's name).
64        #[arg(long)]
65        name: Option<String>,
66    },
67    /// Bundle an app and compile it to QuickJS bytecode.
68    Build {
69        /// The entry module, or the app's directory (default: the current one),
70        /// whose `App.tsx` is the entry.
71        #[arg(default_value = ".")]
72        entry: PathBuf,
73        /// Output directory.
74        #[arg(short, long, default_value = "out")]
75        out: PathBuf,
76        /// Minify and strip debug info.
77        #[arg(long)]
78        release: bool,
79    },
80    /// Run an app headless and print the mount instructions and timings.
81    Trace {
82        /// The entry module, or the app's directory (default: the current one),
83        /// whose `App.tsx` is the entry.
84        #[arg(default_value = ".")]
85        entry: PathBuf,
86        /// Number of taps to send to the first pressable view (without
87        /// `--tap`).
88        #[arg(long, default_value_t = 2)]
89        taps: u32,
90        /// Tap a view (repeatable, in order): `id:<testID>`,
91        /// `label:<accessibilityLabel>`, `text:<text>`, `view:<id>`, or a
92        /// bare string matched as a testID, a label, then a text. A match
93        /// that is not pressable taps its nearest pressable ancestor.
94        #[arg(long, value_name = "SELECTOR")]
95        tap: Vec<String>,
96        /// Idle time before tapping, in milliseconds: the app must render
97        /// nothing for this long (at most 10 s). The default lets the
98        /// engine's idle GC run first, so retention bugs show up.
99        #[arg(long, default_value_t = 1200)]
100        idle_ms: u64,
101        /// Run timers and animations this long before the first tap and
102        /// after each one, in milliseconds, instead of waiting until the
103        /// app is idle.
104        #[arg(long, value_name = "MS")]
105        wait: Option<u64>,
106        /// Keep running this long after the last tap, in milliseconds.
107        #[arg(long, value_name = "MS", default_value_t = 0)]
108        duration: u64,
109        /// Simulated safe area insets in points: `top,right,bottom,left`
110        /// (or one value for all four), e.g. `47,0,34,0`.
111        #[arg(long, value_name = "INSETS", value_parser = trace::parse_insets)]
112        safe_area: Option<nsh_engine::Insets>,
113        /// Scroll the first scroll view / list by this many points, in
114        /// 10 pt frames, and print each frame's batch.
115        #[arg(long)]
116        scroll: Option<f32>,
117        /// Viewport width in points.
118        #[arg(long, default_value_t = 390.0)]
119        width: f32,
120        /// Viewport height in points.
121        #[arg(long, default_value_t = 844.0)]
122        height: f32,
123    },
124    /// Type check an app with TypeScript's native compiler (TypeScript 7,
125    /// downloaded once from the npm registry; no Node needed).
126    Check {
127        /// The entry module, or the app's directory (default: the current one),
128        /// whose `App.tsx` is the entry.
129        #[arg(default_value = ".")]
130        entry: PathBuf,
131        /// The `tsc` to run instead of the pinned TypeScript 7.
132        #[arg(long, env = "NSH_TSC")]
133        tsc: Option<PathBuf>,
134        /// Further arguments for `tsc` (after `--`).
135        #[arg(last = true)]
136        args: Vec<String>,
137    },
138    /// Serve an app to dev hosts (simulators, devices) and push rebuilds.
139    Dev {
140        /// The entry module, or the app's directory (default: the current one),
141        /// whose `App.tsx` is the entry.
142        #[arg(default_value = ".")]
143        entry: PathBuf,
144        /// Dev server port (the next free one is used if it is taken).
145        #[arg(long, default_value_t = nsh_dev::protocol::DEFAULT_PORT)]
146        port: u16,
147        /// Minify and strip debug info.
148        #[arg(long)]
149        release: bool,
150    },
151    /// Package an installable app from the prebuilt runtime (no Rust
152    /// needed). Metadata comes from `nsh.json` next to the entry, overridden
153    /// by the flags below.
154    Package(Box<PackageArgs>),
155    /// Like `dev`, and also run the app in a development host: the Mac
156    /// Catalyst app (default on macOS), the macOS (AppKit) app, the Linux
157    /// app (default on Linux), the Windows app (default on Windows), the
158    /// GPUI app (on any of the three), an iOS simulator, or an Android
159    /// device or emulator.
160    Run {
161        /// The entry module, or the app's directory (default: the current one),
162        /// whose `App.tsx` is the entry.
163        #[arg(default_value = ".")]
164        entry: PathBuf,
165        /// Dev server port (the next free one is used if it is taken).
166        #[arg(long, default_value_t = nsh_dev::protocol::DEFAULT_PORT)]
167        port: u16,
168        /// Minify and strip debug info.
169        #[arg(long)]
170        release: bool,
171        /// Log per-commit timings.
172        #[arg(long)]
173        trace: bool,
174        /// Show the performance monitor over the app: frame rate, frame and
175        /// commit costs, CPU, GPU, memory (`--target macos`).
176        #[arg(long)]
177        fps: bool,
178        /// Where to run.
179        #[arg(long, value_enum, default_value_t = run::Target::native())]
180        target: run::Target,
181        /// iOS simulator to use (name or UDID); default: a booted one, else
182        /// the newest iPhone.
183        #[arg(long)]
184        device: Option<String>,
185    },
186    /// Create a signing key: `<name>.secret` (keep it offline for a root)
187    /// and `<name>.pub` (what apps trust, for a root).
188    Keygen {
189        /// Path and name of the key files, e.g. `keys/root`.
190        name: PathBuf,
191    },
192    /// Certify a release key with a root key, for some app ids and a time
193    /// window; packages carry the certificate.
194    Certify {
195        /// The root's secret key (`.secret`).
196        #[arg(long)]
197        root: PathBuf,
198        /// The release key's public key (`.pub`).
199        #[arg(long)]
200        key: PathBuf,
201        /// App ids it may sign for: `*`, `com.example.*` or an id (repeatable).
202        #[arg(long = "apps", required = true)]
203        apps: Vec<String>,
204        /// How long it may sign, from now.
205        #[arg(long, default_value_t = 365)]
206        days: u64,
207        /// The certificate to write.
208        #[arg(short, long)]
209        out: PathBuf,
210    },
211    /// Build an app in release mode and sign it into a package (`.nshpkg`)
212    /// for apps that embed nsh to verify and run. Metadata comes from
213    /// `nsh.json` next to the entry, overridden by the flags below.
214    Publish {
215        /// The entry module, or the app's directory (default: the current one),
216        /// whose `App.tsx` is the entry.
217        #[arg(default_value = ".")]
218        entry: PathBuf,
219        /// The release key's secret key (`.secret`).
220        #[arg(long)]
221        key: PathBuf,
222        /// Its certificate (`nsh certify`).
223        #[arg(long)]
224        cert: PathBuf,
225        /// The package to write (default: `out/<id>-<build>.nshpkg`).
226        #[arg(short, long)]
227        out: Option<PathBuf>,
228        /// App id, e.g. `com.example.app`.
229        #[arg(long)]
230        id: Option<String>,
231        /// Version, e.g. `1.2.0`.
232        #[arg(long = "app-version")]
233        version: Option<String>,
234        /// Build number: must grow with every release.
235        #[arg(long)]
236        build: Option<u32>,
237    },
238    /// Verify a package as an app trusting the given roots would (without
239    /// roots: only its signature).
240    Verify {
241        /// The package (`.nshpkg`).
242        package: PathBuf,
243        /// A trusted root's public key (`.pub`; repeatable).
244        #[arg(long)]
245        root: Vec<PathBuf>,
246        /// A revocation list to apply.
247        #[arg(long)]
248        revocations: Option<PathBuf>,
249    },
250    /// Sign a revocation list: release keys and packages that must not load
251    /// any more.
252    Revoke {
253        /// The root's secret key (`.secret`).
254        #[arg(long)]
255        root: PathBuf,
256        /// Keep the entries of this list (the last one published).
257        #[arg(long)]
258        extend: Option<PathBuf>,
259        /// The list's number: higher than any published before (default
260        /// with `--extend`: that list's plus one).
261        #[arg(long)]
262        sequence: Option<u64>,
263        /// A release key id to revoke (repeatable).
264        #[arg(long = "key")]
265        keys: Vec<String>,
266        /// A package SHA-256 to revoke (repeatable; `nsh verify` prints it).
267        #[arg(long = "package")]
268        packages: Vec<String>,
269        /// The list to write.
270        #[arg(short, long)]
271        out: PathBuf,
272    },
273}
274
275/// Arguments of `nsh package`.
276#[derive(Args)]
277struct PackageArgs {
278    /// The entry module, or the app's directory (default: the current one),
279    /// whose `App.tsx` is the entry.
280    #[arg(default_value = ".")]
281    entry: PathBuf,
282    /// What to build for.
283    #[arg(long, value_enum)]
284    target: package::PackageTarget,
285    /// Output directory.
286    #[arg(short, long, default_value = "out")]
287    out: PathBuf,
288    /// Display name.
289    #[arg(long)]
290    name: Option<String>,
291    /// Bundle identifier, e.g. `com.example.app`.
292    #[arg(long)]
293    id: Option<String>,
294    /// Version, e.g. `1.2.0`.
295    #[arg(long = "app-version")]
296    version: Option<String>,
297    /// Build number.
298    #[arg(long)]
299    build: Option<u32>,
300    /// App icon: a square PNG, ideally 1024×1024.
301    #[arg(long)]
302    icon: Option<PathBuf>,
303    /// Code signing identity for devices, e.g. "Apple Development: …".
304    #[arg(long)]
305    sign: Option<String>,
306    /// Provisioning profile for devices (`.mobileprovision`).
307    #[arg(long)]
308    profile: Option<PathBuf>,
309    /// Android release keystore (default: the debug key).
310    #[arg(long, requires = "key_alias")]
311    keystore: Option<PathBuf>,
312    /// Key alias in the keystore.
313    #[arg(long)]
314    key_alias: Option<String>,
315    /// Keystore password (also `NSH_KEYSTORE_PASSWORD`).
316    #[arg(long, env = "NSH_KEYSTORE_PASSWORD", hide_env_values = true)]
317    keystore_password: Option<String>,
318    /// Install and launch the app in the simulator or on the Android device
319    /// afterwards (Linux, macOS, Windows: launch it).
320    #[arg(long)]
321    run: bool,
322}
323
324impl Command {
325    /// The entry argument of the commands that build an app.
326    fn entry_mut(&mut self) -> Option<&mut PathBuf> {
327        match self {
328            Command::Build { entry, .. }
329            | Command::Trace { entry, .. }
330            | Command::Check { entry, .. }
331            | Command::Dev { entry, .. }
332            | Command::Run { entry, .. }
333            | Command::Publish { entry, .. } => Some(entry),
334            Command::Package(args) => Some(&mut args.entry),
335            Command::Init { .. }
336            | Command::Keygen { .. }
337            | Command::Certify { .. }
338            | Command::Verify { .. }
339            | Command::Revoke { .. } => None,
340        }
341    }
342}
343
344/// Runs the command line with `ui_sets` (`nsh_ui_mobile::registry()` and
345/// an app's own registry); errors are printed.
346pub fn main_with(ui_sets: Vec<Registry>) -> ExitCode {
347    let _ = UI_SETS.set(ui_sets);
348    let cli = Cli::parse();
349    ui::init(cli.verbose);
350    logger::init();
351    let result = run(cli.command);
352    // A signal stopped the command (`ui::Stoppable`): it ends as the signal
353    // would have, and what failed as it stopped (a tool it interrupted) is
354    // no news.
355    ui::exit_if_stopped();
356    match result {
357        Ok(()) => ExitCode::SUCCESS,
358        Err(e) if e.downcast_ref::<rust_app::Restart>().is_some() => {
359            ExitCode::from(rust_app::RESTART)
360        }
361        Err(e) => {
362            ui::report(&e);
363            ExitCode::FAILURE
364        }
365    }
366}
367
368fn run(mut command: Command) -> anyhow::Result<()> {
369    let types = !matches!(command, Command::Trace { .. });
370    if let Some(entry) = command.entry_mut() {
371        *entry = entry::resolve(entry)?;
372    }
373    // An app with Rust components of its own runs in its own build of this.
374    if let Some(status) = rust_app::reexec(command.entry_mut().map(|e| e.as_path()))? {
375        // As it ended: with its exit code, or by the signal that ended it.
376        #[cfg(unix)]
377        if let Some(signal) = std::os::unix::process::ExitStatusExt::signal(&status) {
378            ui::exit_by_signal(signal);
379        }
380        std::process::exit(status.code().unwrap_or(1));
381    }
382    if types && let Some(entry) = command.entry_mut() {
383        init::write_types_for(entry);
384    }
385    dispatch(command)
386}
387
388fn dispatch(command: Command) -> anyhow::Result<()> {
389    match command {
390        Command::Init { dir, name } => init::init(&dir, name),
391        Command::Build {
392            entry,
393            out,
394            release,
395        } => build::build(&entry, &out, release),
396        Command::Trace {
397            entry,
398            taps,
399            tap,
400            idle_ms,
401            wait,
402            duration,
403            safe_area,
404            scroll,
405            width,
406            height,
407        } => trace::trace(
408            &entry,
409            trace::TraceOptions {
410                taps,
411                tap,
412                idle_ms,
413                wait,
414                duration,
415                scroll,
416                width,
417                height,
418                safe_area: safe_area.unwrap_or_default(),
419            },
420        ),
421        Command::Check { entry, tsc, args } => check::check(&entry, tsc.as_deref(), &args),
422        Command::Dev {
423            entry,
424            port,
425            release,
426        } => {
427            let session = dev::DevSession::start(&entry, port, release)?;
428            session.print_urls();
429            session.watch(|| Ok(false))
430        }
431        Command::Package(args) => {
432            let PackageArgs {
433                entry,
434                target,
435                out,
436                name,
437                id,
438                version,
439                build,
440                icon,
441                sign,
442                profile,
443                keystore,
444                key_alias,
445                keystore_password,
446                run,
447            } = *args;
448            let mut config = package::read_config(&entry)?;
449            config.name = name.or(config.name);
450            config.id = id.or(config.id);
451            config.version = version.or(config.version);
452            config.build = build.or(config.build);
453            config.icon = icon.or(config.icon);
454            package::package(package::PackageOptions {
455                entry: &entry,
456                target,
457                out: &out,
458                config,
459                sign: sign.as_deref(),
460                profile: profile.as_deref(),
461                keystore: keystore.as_deref().map(|k| {
462                    (
463                        k,
464                        key_alias.as_deref().unwrap_or_default(),
465                        keystore_password.as_deref().unwrap_or_default(),
466                    )
467                }),
468                run,
469            })
470        }
471        Command::Run {
472            entry,
473            port,
474            release,
475            trace,
476            fps,
477            target,
478            device,
479        } => run::run(
480            &entry,
481            port,
482            release,
483            run::HostFlags { trace, fps },
484            target,
485            device.as_deref(),
486        ),
487        Command::Keygen { name } => sign::keygen(&name),
488        Command::Certify {
489            root,
490            key,
491            apps,
492            days,
493            out,
494        } => sign::certify_key(&root, &key, &apps, days, &out),
495        Command::Publish {
496            entry,
497            key,
498            cert,
499            out,
500            id,
501            version,
502            build,
503        } => {
504            let mut config = package::read_config(&entry)?;
505            config.id = id.or(config.id);
506            config.version = version.or(config.version);
507            config.build = build.or(config.build);
508            sign::publish(sign::PublishOptions {
509                entry: &entry,
510                key: &key,
511                cert: &cert,
512                out,
513                config,
514            })
515        }
516        Command::Verify {
517            package,
518            root,
519            revocations,
520        } => sign::verify(&package, &root, revocations.as_deref()),
521        Command::Revoke {
522            root,
523            extend,
524            sequence,
525            keys,
526            packages,
527            out,
528        } => sign::revoke_list(&root, extend.as_deref(), sequence, &keys, &packages, &out),
529    }
530}