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