nsh-cli 0.4.0

The nsh command line tool: build, package and run apps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
//! `nsh package`: builds an installable app from the prebuilt runtime, the
//! app bundle and its assets. Needs no Rust; iOS packaging uses Xcode's
//! command line tools (`codesign`, and `actool` for icons), macOS packaging
//! `codesign` and `sips`, Linux packaging `tar`; Windows packaging needs
//! nothing (`windows.rs`), nor does the web's (`web.rs`). Each desktop OS
//! packages with its native backend's runner; GPUI is the backend for
//! embedding in GPUI apps and has no package of its own.

use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

use anyhow::{Context as _, bail};
use serde::Deserialize;

use crate::{
    runtime::{self, Platform},
    ui,
};

/// Where the app runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub(crate) enum PackageTarget {
    /// iOS devices: a signed `.ipa` (or an unsigned `.app` without `--sign`).
    Ios,
    /// The iOS simulator: an ad hoc signed `.app`.
    IosSimulator,
    /// Android: a signed `.apk`.
    Android,
    /// Linux (GTK): a directory with the runner, the bundle and a `.desktop`
    /// file, and the same as a `.tar.gz`.
    Linux,
    /// macOS (AppKit): an ad hoc signed `.app`.
    Macos,
    /// Windows: a directory with the runner as `<name>.exe` (the app's
    /// icon embedded) and the bundle, and the same as a `.zip`.
    Windows,
    /// The web: a static site (`index.html` and files named by their
    /// content) for any web server or CDN.
    Web,
    /// Packages made with the GPUI runner, which is gone: GPUI is the
    /// backend for embedding in GPUI apps. Refused with the OS's own target
    /// to use instead ([`PackageTarget::desktop`]).
    #[value(hide = true)]
    Gpui,
}

impl PackageTarget {
    /// This machine's desktop target (`None` off macOS, Windows and
    /// Linux): where `--target gpui` points.
    fn desktop() -> Option<PackageTarget> {
        if cfg!(target_os = "macos") {
            Some(PackageTarget::Macos)
        } else if cfg!(windows) {
            Some(PackageTarget::Windows)
        } else if cfg!(target_os = "linux") {
            Some(PackageTarget::Linux)
        } else {
            None
        }
    }
}

/// App metadata: `nsh.json` next to the entry, overridden by flags.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct AppConfig {
    /// Display name.
    pub(crate) name: Option<String>,
    /// Bundle identifier (`com.example.app`).
    pub(crate) id: Option<String>,
    /// User-visible version (`1.2.0`).
    pub(crate) version: Option<String>,
    /// Build number.
    pub(crate) build: Option<u32>,
    /// App icon: a square PNG, ideally 1024×1024, relative to `nsh.json`.
    pub(crate) icon: Option<PathBuf>,
    /// The lowest runtime that runs a signed package (`nsh publish`).
    pub(crate) min_runtime: Option<String>,
    /// Read and checked by the bundler.
    #[serde(default, rename = "tailwind")]
    _tailwind: Option<serde::de::IgnoredAny>,
    /// Read and checked by the bundler; packages read only what the
    /// system must be told ahead (`speech`'s usage descriptions).
    #[serde(default)]
    pub(crate) capabilities: Option<serde_json::Value>,
    /// `"light"` / `"dark"` / `"system"`: the app's appearance (checked by
    /// the bundler, which hands it to the runtime); packages also start in
    /// it (the launch screen, the window's theme).
    pub(crate) appearance: Option<String>,
    /// `"statusBar"`: the status bar's default (checked by the bundler,
    /// which hands it to the runtime); iOS packages also show it from the
    /// launch screen on (Info.plist).
    pub(crate) status_bar: Option<serde_json::Value>,
    /// Read and checked by the bundler.
    #[serde(default, rename = "theme")]
    _theme: Option<serde::de::IgnoredAny>,
    /// Read and checked by the bundler.
    #[serde(default, rename = "resolve")]
    _resolve: Option<serde::de::IgnoredAny>,
    /// The app's Rust crate: its builds are the app's own (`rust_app.rs`).
    #[serde(default, rename = "rust")]
    _rust: Option<serde::de::IgnoredAny>,
    /// A Rust app's root component in its crate (`rust_app::RootConfig`).
    #[serde(default, rename = "root")]
    _root: Option<serde::de::IgnoredAny>,
    /// What the web's packages add to the page (`web.rs`).
    #[serde(default)]
    pub(crate) web: WebConfig,
}

impl AppConfig {
    /// Whether the app may recognize speech: it declares no capabilities
    /// (it gets them all) or grants `speech`.
    fn speech(&self) -> bool {
        match &self.capabilities {
            None => true,
            Some(capabilities) => {
                capabilities.get("speech") == Some(&serde_json::Value::Bool(true))
            }
        }
    }

    /// Adds what the system shows when the app first asks for the
    /// microphone and speech recognition, which it requires (it ends an app
    /// that asks without them), when the app may recognize speech.
    fn usage_descriptions(&self, info: &mut plist::Dictionary) {
        if !self.speech() {
            return;
        }
        for (key, text) in USAGE_DESCRIPTIONS {
            info.insert(key.into(), plist::Value::String(text.to_owned()));
        }
    }
}

/// The usage descriptions of an app that recognizes speech (`Speech`).
pub(crate) const USAGE_DESCRIPTIONS: [(&str, &str); 2] = [
    (
        "NSMicrophoneUsageDescription",
        "The app listens to the microphone while you dictate.",
    ),
    (
        "NSSpeechRecognitionUsageDescription",
        "The app turns what you say into text.",
    ),
];

/// `nsh.json` `"web"`.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct WebConfig {
    /// The page's host: a JS module, relative to `nsh.json`, whose
    /// `createHost(player)` returns what `nsh/host` calls reach
    /// (`createPlayer`'s `host`).
    pub(crate) host: Option<PathBuf>,
    /// The hosts the page's host module reaches (patterns, as
    /// `capabilities.network.hosts`): the page's `connect-src` allows them
    /// too, while the app's own requests stay checked against its
    /// `capabilities`.
    #[serde(default)]
    pub(crate) connect: Vec<String>,
}

/// Options of `nsh package`.
pub(crate) struct PackageOptions<'a> {
    pub(crate) entry: &'a Path,
    pub(crate) target: PackageTarget,
    pub(crate) out: &'a Path,
    pub(crate) config: AppConfig,
    /// Code signing identity (device builds).
    pub(crate) sign: Option<&'a str>,
    /// Provisioning profile (device builds).
    pub(crate) profile: Option<&'a Path>,
    /// Android release keystore, key alias and password.
    pub(crate) keystore: Option<(&'a Path, &'a str, &'a str)>,
    /// Android: the ABIs of the APK (empty: [`android::DEFAULT_ABIS`], plus
    /// the device's with `run`).
    ///
    /// [`android::DEFAULT_ABIS`]: crate::android::DEFAULT_ABIS
    pub(crate) abis: &'a [String],
    /// Install and launch in the simulator or on the device afterwards
    /// (Linux, macOS, Windows: launch it; the web: serve it and open it in
    /// the browser).
    pub(crate) run: bool,
}

/// Reads `nsh.json` next to `entry`, if any; relative paths become absolute.
pub(crate) fn read_config(entry: &Path) -> anyhow::Result<AppConfig> {
    let dir = entry.parent().unwrap_or(Path::new("."));
    let path = dir.join("nsh.json");
    let Ok(text) = fs::read_to_string(&path) else {
        return Ok(AppConfig::default());
    };
    let mut config: AppConfig =
        serde_json::from_str(&text).with_context(|| format!("invalid {}", path.display()))?;
    config.icon = config.icon.map(|icon| dir.join(icon));
    config.web.host = config.web.host.map(|host| dir.join(host));
    Ok(config)
}

/// `nsh.json` `web.host` (`read_config` made it absolute), canonical: the
/// file must be inside the app's directory, symbolic links resolved, as the
/// page ships it as it is.
pub(crate) fn web_host_module(entry: &Path, host: &Path) -> anyhow::Result<PathBuf> {
    // `App.tsx`'s parent is the empty path, which does not canonicalize.
    let dir = entry.parent().filter(|d| !d.as_os_str().is_empty());
    let dir = dunce::canonicalize(dir.unwrap_or(Path::new(".")))
        .with_context(|| format!("the app's directory of {}", entry.display()))?;
    let module = dunce::canonicalize(host)
        .with_context(|| format!("nsh.json web.host {}", host.display()))?;
    if !module.starts_with(&dir) {
        bail!(
            "nsh.json web.host {} must be inside the app's directory {}",
            host.display(),
            dir.display()
        );
    }
    Ok(module)
}

/// The app's display name and id: from the config, else the entry's
/// directory name and `com.example.<name>`.
pub(crate) fn name_and_id(entry: &Path, config: &AppConfig) -> (String, String) {
    let name = config.name.clone().unwrap_or_else(|| {
        entry
            .parent()
            .and_then(|d| d.file_name())
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "App".to_owned())
    });
    let id = config.id.clone().unwrap_or_else(|| {
        let slug: String = name
            .chars()
            .filter(|c| c.is_ascii_alphanumeric())
            .collect::<String>()
            .to_lowercase();
        format!("com.example.{slug}")
    });
    (name, id)
}

/// The app's id (`nsh.json` `"id"`, else made up from its name as
/// [`name_and_id`] does): it travels with the bundle (`app.json`, the dev
/// server's messages) and names where the app keeps its data.
pub(crate) fn app_id(entry: &Path) -> anyhow::Result<String> {
    let entry = dunce::canonicalize(entry)?;
    let config = read_config(&entry).unwrap_or_default();
    Ok(name_and_id(&entry, &config).1)
}

/// [`name_and_id`] for a release (`nsh package`, `nsh publish`): the id
/// must be the app's own, written in `nsh.json`, since it also names where
/// the app keeps its data (`nsh/storage`) and two apps with one id share it.
pub(crate) fn release_name_and_id(
    entry: &Path,
    config: &AppConfig,
) -> anyhow::Result<(String, String)> {
    let Some(id) = &config.id else {
        bail!(
            "nsh.json needs an `id` for a release, in reverse-DNS form (`com.yourcompany.app`): it names the app and where it keeps its data, so no other app may use it"
        );
    };
    if id.starts_with("com.example.") {
        ui::warn(format!(
            "app id `{id}` is a placeholder: give the app an id under a domain you own before releasing it, as apps with one id share their data"
        ));
    }
    Ok(name_and_id(entry, config))
}

pub(crate) fn package(options: PackageOptions<'_>) -> anyhow::Result<()> {
    if options.target == PackageTarget::Gpui {
        let instead = PackageTarget::desktop()
            .and_then(|t| clap::ValueEnum::to_possible_value(&t))
            .map_or("macos, windows or linux".to_owned(), |v| {
                v.get_name().to_owned()
            });
        bail!(
            "GPUI is the backend for embedding in GPUI and GPUI Kit apps (`AppView`), not for packages: \
             package this app with --target {instead}"
        );
    }
    if !options.abis.is_empty() && options.target != PackageTarget::Android {
        bail!("--abi only applies to --target android");
    }
    let entry = dunce::canonicalize(options.entry)?;
    let config = &options.config;
    let (name, id) = release_name_and_id(&entry, config)?;
    let executable: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
    let executable = if executable.is_empty() {
        "App".to_owned()
    } else {
        executable
    };

    // Web apps load what `import()` brings in when it is used; native
    // packages are one bundle. A Rust app has none: its runner mounts its
    // root (`rust_app::RustApp::runtime`).
    let built = if crate::rust_app::is_root(&entry) {
        crate::build::rust_root()
    } else {
        let compile = match options.target {
            PackageTarget::Web => crate::build::compile_split,
            _ => crate::build::compile,
        };
        let built = compile(&entry, true).map_err(|e| e.into_error(&entry))?;
        ui::done(format!("built {} {}", ui::path(&entry), built.summary("")));
        built
    };
    let platform = match options.target {
        PackageTarget::Ios => Platform::IphoneOs,
        PackageTarget::IosSimulator => Platform::IphoneSimulator,
        PackageTarget::Android => {
            return package_android(&options, config, &name, &id, &built);
        }
        PackageTarget::Linux => {
            let app = App {
                name: &name,
                id: &id,
                executable: &executable,
            };
            return package_linux(&options, config, &app, &built);
        }
        PackageTarget::Macos => {
            let app = App {
                name: &name,
                id: &id,
                executable: &executable,
            };
            return package_macos(&options, config, &app, &built);
        }
        PackageTarget::Windows => {
            return crate::windows::package(&options, config, &name, &id, &built);
        }
        PackageTarget::Web => {
            return crate::web::package(&options, config, &name, &id, &built);
        }
        PackageTarget::Gpui => unreachable!("refused above"),
    };
    let runner = runtime::file(platform, true)?;

    fs::create_dir_all(options.out)?;
    let app = options.out.join(format!("{name}.app"));
    if app.exists() {
        fs::remove_dir_all(&app)?;
    }
    let resources = app.join("nsh");
    fs::create_dir_all(&resources)?;
    fs::copy(&runner, app.join(&executable))
        .with_context(|| format!("copy {}", runner.display()))?;
    // A Rust app has no bundle: the runner mounts its root.
    if !built.rust_root {
        fs::write(resources.join("bundle.nshc"), &built.bytecode)?;
    }
    if let Some(json) = built.capabilities_json() {
        fs::write(resources.join("capabilities.json"), json)?;
    }
    // The app's id, which names where it keeps its data (`Bundle::read`).
    fs::write(
        resources.join("app.json"),
        serde_json::json!({ "id": id }).to_string(),
    )?;
    for asset in &built.assets {
        let dest = resources.join("assets").join(&asset.path);
        if let Some(dir) = dest.parent() {
            fs::create_dir_all(dir)?;
        }
        fs::copy(&asset.source, &dest).with_context(|| format!("copy {}", asset.path))?;
    }

    let sdk = match options.target {
        PackageTarget::Ios => "iphoneos",
        PackageTarget::IosSimulator
        | PackageTarget::Android
        | PackageTarget::Linux
        | PackageTarget::Macos
        | PackageTarget::Windows
        | PackageTarget::Web
        | PackageTarget::Gpui => "iphonesimulator",
    };
    let mut info = info_plist(&name, &id, &executable, config, sdk);
    if let Some(icon) = &config.icon {
        let partial = compile_icon(icon, &app, sdk)?;
        for (key, value) in partial {
            info.insert(key, value);
        }
    }
    plist::Value::Dictionary(info).to_file_xml(app.join("Info.plist"))?;

    match options.target {
        PackageTarget::IosSimulator => {
            codesign(&app, "-", None)?;
            ui::done(format!("packaged {}", ui::path(&app)));
            if options.run {
                let udid = crate::run::simulator(None)?;
                let step = ui::Step::start(format!("installing {id} in the simulator"));
                crate::run::simctl(&["install", &udid, &app.to_string_lossy()])?;
                crate::run::simctl(&["launch", "--terminate-running-process", &udid, &id])?;
                step.done(format!("launched {id} in the simulator"));
            }
        }
        PackageTarget::Android
        | PackageTarget::Linux
        | PackageTarget::Macos
        | PackageTarget::Windows
        | PackageTarget::Web
        | PackageTarget::Gpui => {
            unreachable!("packaged above")
        }
        PackageTarget::Ios => {
            if options.run {
                bail!("--run only applies to the simulator and Android");
            }
            let (Some(identity), Some(profile)) = (options.sign, options.profile) else {
                ui::warn(format!(
                    "{} is unsigned: pass --sign <identity> and --profile <file.mobileprovision> to install it on devices",
                    ui::path(&app)
                ));
                return Ok(());
            };
            fs::copy(profile, app.join("embedded.mobileprovision"))
                .with_context(|| format!("copy {}", profile.display()))?;
            let entitlements = entitlements(profile, &id)?;
            let path = options.out.join(format!("{executable}.entitlements"));
            entitlements.to_file_xml(&path)?;
            codesign(&app, identity, Some(&path))?;
            let ipa = options.out.join(format!("{name}.ipa"));
            make_ipa(&app, &ipa)?;
            ui::done(format!("packaged {}", ui::path(&ipa)));
        }
    }
    Ok(())
}

/// A desktop app to package: its name, id and executable file name.
#[derive(Clone, Copy)]
struct App<'a> {
    name: &'a str,
    id: &'a str,
    executable: &'a str,
}

/// The ABIs of an APK: `requested`, else [`android::DEFAULT_ABIS`] and the
/// preferred ABI of the device it is installed on (`device`: its ABIs,
/// preferred first), when the runtime is built for it: an emulator's
/// `x86_64`.
///
/// [`android::DEFAULT_ABIS`]: crate::android::DEFAULT_ABIS
fn apk_abis(requested: &[String], device: Option<&[String]>) -> anyhow::Result<Vec<String>> {
    use crate::android::{ABIS, DEFAULT_ABIS};
    if !requested.is_empty() {
        let mut abis = Vec::new();
        for abi in requested {
            if !abis.contains(abi) {
                abis.push(abi.clone());
            }
        }
        if let Some(device) = device
            && !device.iter().any(|abi| abis.contains(abi))
        {
            bail!(
                "the device runs {}, which --abi leaves out",
                device.join(", ")
            );
        }
        return Ok(abis);
    }
    let mut abis: Vec<String> = DEFAULT_ABIS.iter().map(|abi| abi.to_string()).collect();
    if let Some(abi) = device
        .unwrap_or_default()
        .iter()
        .find(|abi| ABIS.contains(&abi.as_str()))
        && !abis.contains(abi)
    {
        abis.push(abi.clone());
    }
    Ok(abis)
}

/// An APK with the release runtime: `AppActivity` runs `assets/nsh/bundle.nshc`.
fn package_android(
    options: &PackageOptions<'_>,
    config: &AppConfig,
    name: &str,
    id: &str,
    built: &crate::build::Built,
) -> anyhow::Result<()> {
    use crate::android::{self, Apk, Signing};
    let sdk = android::Sdk::find()?;
    let serial = if options.run {
        Some(android::device(&sdk)?)
    } else {
        None
    };
    let device = match &serial {
        Some(serial) => Some(android::device_abis(&sdk, serial)?),
        None => None,
    };
    let abis = apk_abis(options.abis, device.as_deref())?;
    let runtime = runtime::android(false, &abis)?;
    // A Rust app has no bundle: `AppActivity` runs its root (the
    // manifest's `com.longbridge.nsh.RUST`).
    let mut assets = Vec::new();
    if !built.rust_root {
        assets.push(("nsh/bundle.nshc".to_owned(), built.bytecode.clone()));
    }
    if let Some(json) = built.capabilities_json() {
        assets.push(("nsh/capabilities.json".to_owned(), json.into_bytes()));
    }
    // The app's id, which names where it keeps its data.
    assets.push((
        "nsh/app.json".to_owned(),
        serde_json::json!({ "id": id }).to_string().into_bytes(),
    ));
    for asset in &built.assets {
        let bytes = fs::read(&asset.source).with_context(|| format!("read {}", asset.path))?;
        assets.push((format!("nsh/assets/{}", asset.path), bytes));
    }
    let signing = match options.keystore {
        Some((path, alias, password)) => Signing::Keystore {
            path: path.to_path_buf(),
            alias: alias.to_owned(),
            password: password.to_owned(),
        },
        None => {
            ui::warn("signing with the debug key: pass --keystore for store releases");
            Signing::Debug
        }
    };
    fs::create_dir_all(options.out)?;
    let apk_path = options.out.join(format!("{name}.apk"));
    let version = config.version.as_deref().unwrap_or("1.0.0");
    let step = ui::Step::start(format!("packaging {}", ui::path(&apk_path)));
    android::build_apk(
        &sdk,
        &Apk {
            package: id,
            label: name,
            version_name: version,
            version_code: config.build.unwrap_or(1),
            activity: "com.longbridge.nsh.AppActivity",
            dev: false,
            rust: built.rust_root,
            dark: config.appearance.as_deref() == Some("dark"),
            runtime: &runtime,
            abis: &abis,
            icon: config.icon.as_deref(),
            assets,
            signing,
        },
        &apk_path,
    )?;
    step.done(format!(
        "packaged {} {}",
        ui::path(&apk_path),
        ui::dim(format!("({})", abis.join(", ")))
    ));
    if let Some(serial) = serial {
        let step = ui::Step::start(format!("installing {id} on {serial}"));
        android::adb(
            &sdk,
            &serial,
            &["install", "-r", &apk_path.to_string_lossy()],
        )?;
        android::adb(
            &sdk,
            &serial,
            &[
                "shell",
                "am",
                "start",
                "-n",
                &format!("{id}/com.longbridge.nsh.AppActivity"),
            ],
        )?;
        step.done(format!("launched {id} on {serial}"));
    }
    Ok(())
}

/// A directory `<out>/<name>`: the release runner as `<executable>`, the
/// bundle and assets in `nsh/` (where the runner looks, next to itself),
/// `nsh/app.json` (the window's title, the application id and the app's
/// appearance, which the window opens in), a
/// `<id>.desktop` entry and the icon; then the same as `<name>.tar.gz`.
fn package_linux(
    options: &PackageOptions<'_>,
    config: &AppConfig,
    app: &App<'_>,
    built: &crate::build::Built,
) -> anyhow::Result<()> {
    let App {
        name,
        id,
        executable,
    } = *app;
    let runner = runtime::file(Platform::Linux, true)?;
    let dir = options.out.join(name);
    let step = ui::Step::start(format!("packaging {}", ui::path(&dir)));
    if dir.exists() {
        fs::remove_dir_all(&dir)?;
    }
    let resources = dir.join("nsh");
    fs::create_dir_all(&resources)?;
    fs::copy(&runner, dir.join(executable))
        .with_context(|| format!("copy {}", runner.display()))?;
    // A Rust app has no bundle: the runner mounts its root.
    if !built.rust_root {
        fs::write(resources.join("bundle.nshc"), &built.bytecode)?;
    }
    if let Some(json) = built.capabilities_json() {
        fs::write(resources.join("capabilities.json"), json)?;
    }
    for asset in &built.assets {
        let dest = resources.join("assets").join(&asset.path);
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::copy(&asset.source, &dest).with_context(|| format!("copy {}", asset.path))?;
    }
    let version = config.version.as_deref().unwrap_or("1.0.0");
    let mut info = serde_json::json!({ "name": name, "id": id, "version": version });
    if let Some(appearance) = &config.appearance {
        info["appearance"] = appearance.as_str().into();
    }
    fs::write(resources.join("app.json"), info.to_string())?;
    if let Some(icon) = &config.icon {
        fs::copy(icon, dir.join(format!("{id}.png")))
            .with_context(|| format!("copy {}", icon.display()))?;
    }
    fs::write(
        dir.join(format!("{id}.desktop")),
        desktop_entry(name, id, executable, config.icon.is_some()),
    )?;
    let archive = options.out.join(format!("{name}.tar.gz"));
    let _ = fs::remove_file(&archive);
    let output = Command::new("tar")
        .arg("-czf")
        .arg(&archive)
        .arg("-C")
        .arg(options.out)
        .arg(name)
        .output()
        .context("run tar")?;
    if !output.status.success() {
        bail!(
            "creating {} failed: {}",
            archive.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    step.done(format!(
        "packaged {} and {}",
        ui::path(&dir),
        ui::path(&archive)
    ));
    if options.run {
        let exe = dir.join(executable);
        Command::new(&exe)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .with_context(|| format!("launch {}", exe.display()))?;
        ui::done(format!("launched {name}"));
    }
    Ok(())
}

/// `<out>/<name>.app`, a macOS app bundle: the release runner as
/// `Contents/MacOS/<executable>`, the bundle and assets in
/// `Contents/Resources/nsh/` (where the runner looks), `nsh/app.json` (the
/// window's title and the app's appearance, which the window opens in),
/// the icon as `AppIcon.icns`; signed ad hoc (Apple silicon runs no
/// unsigned code; distribute it signed with a Developer ID instead).
fn package_macos(
    options: &PackageOptions<'_>,
    config: &AppConfig,
    app: &App<'_>,
    built: &crate::build::Built,
) -> anyhow::Result<()> {
    let App {
        name,
        id,
        executable,
    } = *app;
    let runner = runtime::file(Platform::MacOs, true)?;
    let app = options.out.join(format!("{name}.app"));
    let step = ui::Step::start(format!("packaging {}", ui::path(&app)));
    if app.exists() {
        fs::remove_dir_all(&app)?;
    }
    let contents = app.join("Contents");
    let macos = contents.join("MacOS");
    let resources = contents.join("Resources");
    let nsh = resources.join("nsh");
    fs::create_dir_all(&macos)?;
    fs::create_dir_all(&nsh)?;
    fs::copy(&runner, macos.join(executable))
        .with_context(|| format!("copy {}", runner.display()))?;
    // A Rust app has no bundle: the runner mounts its root.
    if !built.rust_root {
        fs::write(nsh.join("bundle.nshc"), &built.bytecode)?;
    }
    if let Some(json) = built.capabilities_json() {
        fs::write(nsh.join("capabilities.json"), json)?;
    }
    for asset in &built.assets {
        let dest = nsh.join("assets").join(&asset.path);
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::copy(&asset.source, &dest).with_context(|| format!("copy {}", asset.path))?;
    }
    let version = config.version.as_deref().unwrap_or("1.0.0");
    let mut info = serde_json::json!({ "name": name, "id": id, "version": version });
    if let Some(appearance) = &config.appearance {
        info["appearance"] = appearance.as_str().into();
    }
    fs::write(nsh.join("app.json"), info.to_string())?;
    let icon = match &config.icon {
        Some(icon) => {
            macos_icns(icon, &resources.join("AppIcon.icns"))?;
            true
        }
        None => false,
    };
    plist::Value::Dictionary(macos_info_plist(name, id, executable, config, icon))
        .to_file_xml(contents.join("Info.plist"))
        .context("write Info.plist")?;
    let output = Command::new("codesign")
        .args(["--force", "--sign", "-", "--timestamp=none"])
        .arg(&app)
        .output()
        .context("run codesign")?;
    if !output.status.success() {
        bail!(
            "codesign failed for {}: {}",
            app.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    step.done(format!("packaged {}", ui::path(&app)));
    if options.run {
        let status = Command::new("open")
            .arg(&app)
            .status()
            .context("run open")?;
        if !status.success() {
            bail!("cannot open {}", app.display());
        }
        ui::done(format!("launched {name}"));
    }
    Ok(())
}

/// Converts `icon` (a PNG) to `icns`: an iconset of every size macOS
/// uses, scaled by `sips`, packed by `iconutil`. `sips -s format icns`
/// alone fails on 1024-pixel images, the size app icons are drawn at.
fn macos_icns(icon: &Path, icns: &Path) -> anyhow::Result<()> {
    let set = icns.with_extension("iconset");
    fs::create_dir_all(&set)?;
    let run = |cmd: &mut Command, what: &str| -> anyhow::Result<()> {
        let output = cmd.output().with_context(|| format!("run {what}"))?;
        if !output.status.success() {
            bail!(
                "converting {} to an icon failed ({what}): {}",
                icon.display(),
                String::from_utf8_lossy(&output.stderr).trim()
            );
        }
        Ok(())
    };
    let result = (|| {
        for size in [16u32, 32, 128, 256, 512] {
            for (scale, suffix) in [(1, ""), (2, "@2x")] {
                let px = (size * scale).to_string();
                run(
                    Command::new("sips")
                        .args(["-s", "format", "png", "-z", &px, &px])
                        .arg(icon)
                        .arg("--out")
                        .arg(set.join(format!("icon_{size}x{size}{suffix}.png"))),
                    "sips",
                )?;
            }
        }
        run(
            Command::new("iconutil")
                .args(["-c", "icns"])
                .arg(&set)
                .arg("-o")
                .arg(icns),
            "iconutil",
        )
    })();
    let _ = fs::remove_dir_all(&set);
    result
}

/// The `Info.plist` of a macOS app.
fn macos_info_plist(
    name: &str,
    id: &str,
    executable: &str,
    config: &AppConfig,
    icon: bool,
) -> plist::Dictionary {
    use plist::Value;
    let mut d = plist::Dictionary::new();
    let s = |v: &str| Value::String(v.to_owned());
    d.insert("CFBundleDevelopmentRegion".into(), s("en"));
    d.insert("CFBundleExecutable".into(), s(executable));
    d.insert("CFBundleIdentifier".into(), s(id));
    d.insert("CFBundleName".into(), s(name));
    d.insert("CFBundleDisplayName".into(), s(name));
    d.insert("CFBundlePackageType".into(), s("APPL"));
    d.insert(
        "CFBundleShortVersionString".into(),
        s(config.version.as_deref().unwrap_or("1.0.0")),
    );
    d.insert(
        "CFBundleVersion".into(),
        s(&config.build.unwrap_or(1).to_string()),
    );
    d.insert(
        "CFBundleSupportedPlatforms".into(),
        Value::Array(vec![s("MacOSX")]),
    );
    d.insert("LSMinimumSystemVersion".into(), s(MACOS_MINIMUM));
    d.insert("NSHighResolutionCapable".into(), true.into());
    d.insert("NSPrincipalClass".into(), s("NSApplication"));
    if icon {
        d.insert("CFBundleIconFile".into(), s("AppIcon"));
    }
    config.usage_descriptions(&mut d);
    d
}

/// The oldest macOS the AppKit runtime runs on (its display links are
/// `NSView`'s, new in macOS 14).
const MACOS_MINIMUM: &str = "14.0";

/// The app's desktop entry. Desktops match windows to it by the file's
/// name and `StartupWMClass`, which GTK sets from the application id.
/// `Exec` names the executable on the `PATH` (install the package
/// directory, or a link to the executable, there).
fn desktop_entry(name: &str, id: &str, executable: &str, icon: bool) -> String {
    let icon = if icon {
        format!("Icon={id}\n")
    } else {
        String::new()
    };
    format!(
        "[Desktop Entry]\nType=Application\nName={name}\nExec={executable}\n{icon}StartupWMClass={id}\nTerminal=false\nCategories=Utility;\n"
    )
}

fn info_plist(
    name: &str,
    id: &str,
    executable: &str,
    config: &AppConfig,
    sdk: &str,
) -> plist::Dictionary {
    use plist::Value;
    let mut d = plist::Dictionary::new();
    let s = |v: &str| Value::String(v.to_owned());
    d.insert("CFBundleDevelopmentRegion".into(), s("en"));
    d.insert("CFBundleExecutable".into(), s(executable));
    d.insert("CFBundleIdentifier".into(), s(id));
    d.insert("CFBundleName".into(), s(name));
    d.insert("CFBundleDisplayName".into(), s(name));
    d.insert("CFBundlePackageType".into(), s("APPL"));
    d.insert(
        "CFBundleShortVersionString".into(),
        s(config.version.as_deref().unwrap_or("1.0.0")),
    );
    d.insert(
        "CFBundleVersion".into(),
        s(&config.build.unwrap_or(1).to_string()),
    );
    d.insert(
        "CFBundleSupportedPlatforms".into(),
        Value::Array(vec![s(if sdk == "iphoneos" {
            "iPhoneOS"
        } else {
            "iPhoneSimulator"
        })]),
    );
    d.insert("MinimumOSVersion".into(), s(MINIMUM_OS));
    d.insert(
        "UIDeviceFamily".into(),
        Value::Array(vec![1.into(), 2.into()]),
    );
    d.insert("LSRequiresIPhoneOS".into(), true.into());
    config.usage_descriptions(&mut d);
    // A launch screen entry opts into the full screen (no letterboxing).
    d.insert(
        "UILaunchScreen".into(),
        Value::Dictionary(Default::default()),
    );
    d.insert("UIApplicationSupportsMultipleScenes".into(), false.into());
    // ProMotion iPhones run display links above 60 Hz only with this:
    // animations move at the rate scrolling does.
    d.insert("CADisableMinimumFrameDurationOnPhone".into(), true.into());
    // The app's own appearance, from the launch screen on.
    match config.appearance.as_deref() {
        Some("light") => d.insert("UIUserInterfaceStyle".into(), s("Light")),
        Some("dark") => d.insert("UIUserInterfaceStyle".into(), s("Dark")),
        _ => None,
    };
    // The status bar's default, for the launch screen (pages and dialogs
    // decide it afterwards, as view controllers).
    if let Some(setting) = config
        .status_bar
        .as_ref()
        .and_then(|v| nsh_core::StatusBarSetting::from_json(v).ok())
    {
        if let Some(style) = setting.style {
            let style = match style {
                nsh_core::StatusBarStyle::Default => "UIStatusBarStyleDefault",
                nsh_core::StatusBarStyle::Light => "UIStatusBarStyleLightContent",
                nsh_core::StatusBarStyle::Dark => "UIStatusBarStyleDarkContent",
            };
            d.insert("UIStatusBarStyle".into(), s(style));
        }
        if let Some(hidden) = setting.hidden {
            d.insert("UIStatusBarHidden".into(), hidden.into());
        }
    }
    d.insert(
        "UISupportedInterfaceOrientations".into(),
        Value::Array(vec![
            s("UIInterfaceOrientationPortrait"),
            s("UIInterfaceOrientationLandscapeLeft"),
            s("UIInterfaceOrientationLandscapeRight"),
        ]),
    );
    d.insert(
        "UISupportedInterfaceOrientations~ipad".into(),
        Value::Array(vec![
            s("UIInterfaceOrientationPortrait"),
            s("UIInterfaceOrientationPortraitUpsideDown"),
            s("UIInterfaceOrientationLandscapeLeft"),
            s("UIInterfaceOrientationLandscapeRight"),
        ]),
    );
    d
}

/// The deployment target the runtime is built for (`cargo xtask dist`).
const MINIMUM_OS: &str = "15.0";

/// Compiles `icon` into the app's asset catalog (`Assets.car`) with
/// `actool`, returning the Info.plist keys it produces.
fn compile_icon(icon: &Path, app: &Path, sdk: &str) -> anyhow::Result<plist::Dictionary> {
    let work = app.with_extension("xcassets-work");
    let set = work.join("Assets.xcassets/AppIcon.appiconset");
    fs::create_dir_all(&set)?;
    fs::copy(icon, set.join("icon.png")).with_context(|| format!("copy {}", icon.display()))?;
    fs::write(
        work.join("Assets.xcassets/Contents.json"),
        r#"{"info":{"author":"nsh","version":1}}"#,
    )?;
    // One 1024 pt image; actool derives every size (Xcode 14+ catalogs).
    fs::write(
        set.join("Contents.json"),
        r#"{"images":[{"filename":"icon.png","idiom":"universal","platform":"ios","size":"1024x1024"}],"info":{"author":"nsh","version":1}}"#,
    )?;
    let partial = work.join("partial.plist");
    let output = Command::new("xcrun")
        .args(["actool", "--compile"])
        .arg(app)
        .args(["--platform", sdk, "--minimum-deployment-target", MINIMUM_OS])
        .args(["--app-icon", "AppIcon", "--output-partial-info-plist"])
        .arg(&partial)
        .args([
            "--target-device",
            "iphone",
            "--target-device",
            "ipad",
            "--output-format",
            "human-readable-text",
        ])
        .arg(work.join("Assets.xcassets"))
        .output()
        .context("run xcrun actool (is Xcode installed?)")?;
    if !output.status.success() || !partial.exists() {
        bail!(
            "actool failed: {}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }
    let keys = plist::Value::from_file(&partial)?
        .into_dictionary()
        .unwrap_or_default();
    fs::remove_dir_all(&work)?;
    Ok(keys)
}

fn codesign(app: &Path, identity: &str, entitlements: Option<&Path>) -> anyhow::Result<()> {
    let mut cmd = Command::new("codesign");
    cmd.args(["--force", "--sign", identity]);
    if identity == "-" {
        cmd.arg("--timestamp=none");
    }
    if let Some(e) = entitlements {
        cmd.arg("--entitlements").arg(e);
    }
    let output = cmd
        .arg(app)
        .stdout(Stdio::null())
        .output()
        .context("run codesign")?;
    if !output.status.success() {
        bail!(
            "codesign failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(())
}

/// The entitlements a provisioning profile grants, checked against `id`.
fn entitlements(profile: &Path, id: &str) -> anyhow::Result<plist::Value> {
    let output = Command::new("security")
        .args(["cms", "-D", "-i"])
        .arg(profile)
        .output()
        .context("run security cms")?;
    if !output.status.success() {
        bail!("cannot read provisioning profile {}", profile.display());
    }
    let profile = plist::Value::from_reader_xml(output.stdout.as_slice())?;
    let mut entitlements = profile
        .as_dictionary()
        .and_then(|d| d.get("Entitlements"))
        .cloned()
        .context("the provisioning profile has no entitlements")?;
    let app_id = entitlements
        .as_dictionary()
        .and_then(|d| d.get("application-identifier"))
        .and_then(|v| v.as_string())
        .unwrap_or_default()
        .to_owned();
    if !profile_allows(&app_id, id) {
        bail!("the provisioning profile is for {app_id}, not {id}");
    }
    // A wildcard profile (`TEAMID.*`) signs the app as `TEAMID.<id>`, as
    // Xcode does: devices refuse an app signed with the wildcard itself.
    if let Some(dictionary) = entitlements.as_dictionary_mut() {
        dictionary.insert(
            "application-identifier".to_owned(),
            plist::Value::String(signed_app_id(&app_id, id)),
        );
    }
    Ok(entitlements)
}

/// The `application-identifier` an app with bundle id `id` is signed with
/// under a profile's (`TEAMID.com.example.app` or a wildcard such as
/// `TEAMID.*`), which covers it.
fn signed_app_id(app_id: &str, id: &str) -> String {
    match app_id.split_once('.') {
        Some((team, pattern)) if pattern.ends_with('*') => format!("{team}.{id}"),
        _ => app_id.to_owned(),
    }
}

/// Whether a profile's `application-identifier` (`TEAMID.com.example.app`,
/// or a wildcard such as `TEAMID.*`) covers bundle id `id`.
fn profile_allows(app_id: &str, id: &str) -> bool {
    app_id
        .split_once('.')
        .map(|(_, pattern)| match pattern.strip_suffix('*') {
            Some(prefix) => id.starts_with(prefix),
            None => pattern == id,
        })
        .unwrap_or(false)
}

/// `Payload/<App>.app` zipped, keeping permissions and symlinks.
fn make_ipa(app: &Path, ipa: &Path) -> anyhow::Result<()> {
    let staging = ipa.with_extension("payload");
    let payload = staging.join("Payload");
    if staging.exists() {
        fs::remove_dir_all(&staging)?;
    }
    fs::create_dir_all(&payload)?;
    let status = Command::new("ditto")
        .arg(app)
        .arg(payload.join(app.file_name().context("app name")?))
        .status()?;
    if !status.success() {
        bail!("copying the app failed");
    }
    let _ = fs::remove_file(ipa);
    // `--keepParent`: entries start with `Payload/`; `--norsrc`: no
    // `__MACOSX/` resource forks.
    let status = Command::new("ditto")
        .args(["-c", "-k", "--norsrc", "--keepParent"])
        .arg(&payload)
        .arg(ipa)
        .status()?;
    fs::remove_dir_all(&staging)?;
    if !status.success() {
        bail!("creating {} failed", ipa.display());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_apk_takes_the_phones_abis_and_the_devices() {
        let abis = |list: &[&str]| list.iter().map(|a| a.to_string()).collect::<Vec<_>>();
        let phones = abis(&["arm64-v8a", "armeabi-v7a"]);
        assert_eq!(apk_abis(&[], None).unwrap(), phones);
        // A phone: nothing more.
        assert_eq!(
            apk_abis(&[], Some(&abis(&["arm64-v8a", "armeabi-v7a", "armeabi"]))).unwrap(),
            phones
        );
        // An emulator: its own, first of those the runtime has.
        assert_eq!(
            apk_abis(&[], Some(&abis(&["x86_64", "arm64-v8a"]))).unwrap(),
            abis(&["arm64-v8a", "armeabi-v7a", "x86_64"])
        );
        // --abi, once each.
        let only = abis(&["arm64-v8a", "arm64-v8a"]);
        assert_eq!(apk_abis(&only, None).unwrap(), abis(&["arm64-v8a"]));
        let error = apk_abis(&only, Some(&abis(&["x86_64"])))
            .unwrap_err()
            .to_string();
        assert!(error.contains("x86_64"), "{error}");
    }

    #[test]
    fn apps_that_may_recognize_speech_explain_it() {
        let usage = |capabilities: Option<serde_json::Value>| {
            let config = AppConfig {
                capabilities,
                ..AppConfig::default()
            };
            let info = macos_info_plist("A", "com.a", "a", &config, false);
            let ios = info_plist("A", "com.a", "a", &config, "iphoneos");
            assert_eq!(
                info.contains_key("NSMicrophoneUsageDescription"),
                ios.contains_key("NSSpeechRecognitionUsageDescription")
            );
            info.contains_key("NSSpeechRecognitionUsageDescription")
        };
        assert!(usage(None));
        assert!(usage(Some(serde_json::json!({ "speech": true }))));
        assert!(!usage(Some(serde_json::json!({ "picker": true }))));
    }

    #[test]
    fn a_release_needs_the_apps_own_id() {
        let entry = Path::new("apps/Orders/App.tsx");
        let config = |id: Option<&str>| AppConfig {
            id: id.map(str::to_owned),
            ..AppConfig::default()
        };
        // Development makes one up from the name.
        assert_eq!(
            name_and_id(entry, &config(None)),
            ("Orders".to_owned(), "com.example.orders".to_owned())
        );
        // A release asks for it.
        let error = release_name_and_id(entry, &config(None))
            .unwrap_err()
            .to_string();
        assert!(error.contains("nsh.json needs an `id`"), "{error}");
        // The placeholder is only warned about.
        assert_eq!(
            release_name_and_id(entry, &config(Some("com.example.orders")))
                .unwrap()
                .1,
            "com.example.orders"
        );
        assert_eq!(
            release_name_and_id(entry, &config(Some("com.acme.orders"))).unwrap(),
            ("Orders".to_owned(), "com.acme.orders".to_owned())
        );
    }

    #[test]
    fn the_web_host_module_stays_in_the_app_directory() {
        let root = std::env::temp_dir().join(format!("nsh-web-host-{}", std::process::id()));
        let app = root.join("app");
        fs::create_dir_all(app.join("web")).unwrap();
        fs::write(app.join("web/host.js"), "").unwrap();
        fs::write(root.join("outside.js"), "").unwrap();
        let entry = app.join("App.tsx");
        let config = |host: &str| {
            fs::write(
                app.join("nsh.json"),
                serde_json::json!({ "web": { "host": host } }).to_string(),
            )
            .unwrap();
            read_config(&entry).unwrap().web.host.unwrap()
        };
        let inside = web_host_module(&entry, &config("web/host.js")).unwrap();
        assert_eq!(
            inside,
            dunce::canonicalize(app.join("web/host.js")).unwrap()
        );
        assert!(web_host_module(&entry, &config("./web/../web/host.js")).is_ok());
        let outside = root.join("outside.js");
        let refused = [config("../outside.js"), config(outside.to_str().unwrap())];
        #[cfg(unix)]
        let refused = {
            std::os::unix::fs::symlink(&outside, app.join("link.js")).unwrap();
            let mut refused = refused.to_vec();
            refused.push(config("link.js"));
            refused
        };
        for host in refused {
            let error = web_host_module(&entry, &host).unwrap_err().to_string();
            assert!(error.contains("inside the app's directory"), "{error}");
        }
        fs::remove_dir_all(&root).unwrap();
        // An entry named without its directory is in the working directory
        // (the crate's, under `cargo test`).
        assert!(web_host_module(Path::new("App.tsx"), Path::new("Cargo.toml")).is_ok());
    }

    /// App icons are drawn at 1024 pixels, which `sips` alone cannot
    /// convert.
    #[cfg(target_os = "macos")]
    #[test]
    fn converts_large_icons() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
        let dir = std::env::temp_dir().join(format!("nsh-icns-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let icns = dir.join("AppIcon.icns");
        macos_icns(&root.join("examples/gallery/icon.png"), &icns).unwrap();
        assert!(fs::metadata(&icns).unwrap().len() > 0);
        assert!(!dir.join("AppIcon.iconset").exists());
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn profiles_match_bundle_ids() {
        assert!(profile_allows(
            "ABCDE12345.com.example.app",
            "com.example.app"
        ));
        assert!(!profile_allows(
            "ABCDE12345.com.example.app",
            "com.example.other"
        ));
        assert!(profile_allows("ABCDE12345.*", "com.example.app"));
        assert!(profile_allows(
            "ABCDE12345.com.example.*",
            "com.example.app"
        ));
        assert!(!profile_allows("ABCDE12345.com.other.*", "com.example.app"));
        assert!(!profile_allows("", "com.example.app"));
    }

    #[test]
    fn wildcard_profiles_sign_the_bundle_id() {
        assert_eq!(
            signed_app_id("ABCDE12345.*", "com.example.app"),
            "ABCDE12345.com.example.app"
        );
        assert_eq!(
            signed_app_id("ABCDE12345.com.example.*", "com.example.app"),
            "ABCDE12345.com.example.app"
        );
        assert_eq!(
            signed_app_id("ABCDE12345.com.example.app", "com.example.app"),
            "ABCDE12345.com.example.app"
        );
    }

    #[test]
    fn gpui_points_to_this_oss_target() {
        use clap::ValueEnum as _;

        use super::PackageTarget;
        // Still parsed, so the refusal can say what to use instead.
        assert_eq!(
            PackageTarget::from_str("gpui", false).unwrap(),
            PackageTarget::Gpui
        );
        assert!(
            PackageTarget::Gpui
                .to_possible_value()
                .unwrap()
                .is_hide_set()
        );
        let expected = if cfg!(target_os = "macos") {
            Some(PackageTarget::Macos)
        } else if cfg!(windows) {
            Some(PackageTarget::Windows)
        } else if cfg!(target_os = "linux") {
            Some(PackageTarget::Linux)
        } else {
            None
        };
        assert_eq!(PackageTarget::desktop(), expected);
    }

    #[test]
    fn desktop_entries_match_windows_by_the_app_id() {
        assert_eq!(
            desktop_entry("Counter", "com.example.counter", "Counter", true),
            "[Desktop Entry]\nType=Application\nName=Counter\nExec=Counter\n\
             Icon=com.example.counter\nStartupWMClass=com.example.counter\nTerminal=false\n\
             Categories=Utility;\n"
        );
        assert!(!desktop_entry("A", "com.example.a", "A", false).contains("Icon="));
    }

    // `ditto` is macOS's.
    #[cfg(target_os = "macos")]
    #[test]
    fn ipa_holds_the_app_under_payload() {
        let dir = std::env::temp_dir().join(format!("nsh-ipa-{}", std::process::id()));
        let app = dir.join("Demo.app");
        fs::create_dir_all(app.join("nsh")).unwrap();
        fs::write(app.join("Demo"), b"binary").unwrap();
        fs::write(app.join("nsh/bundle.nshc"), b"code").unwrap();
        let ipa = dir.join("Demo.ipa");
        make_ipa(&app, &ipa).unwrap();
        let listing = Command::new("unzip").arg("-Z1").arg(&ipa).output().unwrap();
        let listing = String::from_utf8(listing.stdout).unwrap();
        let mut entries: Vec<&str> = listing.lines().collect();
        entries.sort_unstable();
        assert_eq!(
            entries,
            [
                "Payload/",
                "Payload/Demo.app/",
                "Payload/Demo.app/Demo",
                "Payload/Demo.app/nsh/",
                "Payload/Demo.app/nsh/bundle.nshc"
            ]
        );
        fs::remove_dir_all(&dir).unwrap();
    }
}