day-cli 0.1.2

Declarative app development API using native UI toolkits
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
//! Day.toml — the project manifest (DESIGN.md §17.3).
//!
//! Follows the Tauri / Dioxus model: a dedicated manifest file that doubles as the project
//! marker (`find_project` walks up to the nearest `Day.toml`). Two rules keep it honest:
//!
//! * **Derive, don't restate**: `name` and `version` come from the sibling `Cargo.toml`'s
//!   `[package]` — they are never written in Day.toml, so app identity can't drift from the
//!   crate's.
//! * **Base + overrides**: `[app]` holds the base properties; any of them can be overridden
//!   per platform (`[app.ios]`), per toolkit (`[app.qt]`), or per full target
//!   (`[app.macos-appkit]`) — most specific wins (see [`Manifest::resolve`]).

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
    /// Manifest schema version (currently 1).
    pub schema: u32,
    pub app: App,
    #[serde(default)]
    pub window: Window,
    /// Code-signing / notarization configuration (§16.5, §17.3). Values may reference environment
    /// variables as `${VAR}` — resolved at use time (see `pack::settings::interpolate`), never at
    /// parse time, so `day sign --check` can report missing variables without failing the parse.
    #[serde(default)]
    pub signing: Option<Signing>,
    /// OS permissions this app declares, and the user-facing reason for each (docs/permissions.md).
    /// `day build` turns these into `<uses-permission>` entries, `Info.plist` usage descriptions,
    /// and HarmonyOS `requestPermissions` — the declaration every mobile OS requires before the app
    /// may even ask. `#[serde(default)]`, so every Day.toml written before this existed still parses.
    #[serde(default)]
    pub permissions: Permissions,
}

/// `[permissions]`. Every key is a portable permission name from `day_build::permissions` except the
/// reserved `raw`, which carries per-platform escape hatches.
///
/// This struct carries no `deny_unknown_fields` because the `flatten` map has to absorb the
/// permission keys (the same reason [`App`] doesn't) — [`parse_manifest`] validates the names
/// instead, and rejects a typo with the list of valid ones, which is the better error anyway.
#[derive(Debug, Default, Deserialize)]
pub struct Permissions {
    #[serde(default)]
    pub raw: RawPermissions,
    #[serde(flatten)]
    pub declared: BTreeMap<String, Declaration>,
}

/// How one permission is declared. The short forms cover the common cases:
/// `camera = "Attach photos to your notes."` and `notifications = true`.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum Declaration {
    /// `<name> = "<reason>"`
    Reason(String),
    /// `<name> = true` declares a permission that needs no reason on any platform (notifications).
    /// `<name> = false` is the opposite: an explicit "not this one", useful to hold the line against
    /// a permission a dependency might otherwise pull in.
    Enabled(bool),
    /// The long form, for per-platform reason overrides or a platform subset.
    Detailed(Box<DeclarationTable>),
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct DeclarationTable {
    pub reason: Option<String>,
    pub ios_reason: Option<String>,
    pub macos_reason: Option<String>,
    pub ohos_reason: Option<String>,
    /// Restrict the declaration to a subset of `ios` / `macos` / `android` / `ohos`. Default: every
    /// platform the permission maps to.
    pub platforms: Option<Vec<String>>,
}

impl Declaration {
    /// The reason to use for `platform`, most specific first.
    pub fn reason_for(&self, platform: &str) -> Option<&str> {
        match self {
            Declaration::Reason(r) => Some(r.as_str()),
            Declaration::Enabled(_) => None,
            Declaration::Detailed(t) => {
                let specific = match platform {
                    "ios" => t.ios_reason.as_deref(),
                    "macos" => t.macos_reason.as_deref(),
                    "ohos" => t.ohos_reason.as_deref(),
                    _ => None,
                };
                specific.or(t.reason.as_deref())
            }
        }
    }

    /// Whether the app actually wants this permission. `<name> = false` declares that it does not.
    pub fn enabled(&self) -> bool {
        !matches!(self, Declaration::Enabled(false))
    }

    /// Whether this declaration applies to `platform`.
    pub fn covers(&self, platform: &str) -> bool {
        match self {
            Declaration::Detailed(t) => match &t.platforms {
                Some(list) => list.iter().any(|p| p == platform),
                None => true,
            },
            _ => true,
        }
    }
}

/// `[permissions.raw]` — platform-native declarations for anything outside the portable set.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RawPermissions {
    /// Android permission ids, e.g. `"android.permission.READ_CONTACTS"`.
    #[serde(default)]
    pub android: Vec<String>,
    /// `Info.plist` key → usage description.
    #[serde(default)]
    pub ios: BTreeMap<String, String>,
    #[serde(default)]
    pub macos: BTreeMap<String, String>,
    /// HarmonyOS entries, each needing its own reason and scene.
    #[serde(default)]
    pub ohos: Vec<RawOhosPermission>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RawOhosPermission {
    pub name: String,
    #[serde(default)]
    pub reason: Option<String>,
    /// `"inuse"` (default) or `"always"`.
    #[serde(default)]
    pub when: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Signing {
    #[serde(default)]
    pub macos: Option<MacosSigning>,
    #[serde(default)]
    pub ios: Option<IosSigning>,
    #[serde(default)]
    pub android: Option<AndroidSigning>,
    #[serde(default)]
    pub windows: Option<WindowsSigning>,
    #[serde(default)]
    pub ohos: Option<OhosSigning>,
}

/// macOS Developer-ID signing + notarization (§16.5: codesign + notarytool + stapler).
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct MacosSigning {
    /// Signing identity ("Developer ID Application: …"); "-" or absent = ad-hoc (dev tier).
    #[serde(default)]
    pub identity: Option<String>,
    /// Entitlements plist path, relative to the project root.
    #[serde(default)]
    pub entitlements: Option<String>,
    #[serde(default)]
    pub notarize: Option<Notarize>,
}

/// notarytool App Store Connect API-key auth (never interactive Apple-ID — §16.5).
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Notarize {
    pub key_id: String,
    pub issuer: String,
    /// Path to the AuthKey_<id>.p8 file.
    pub key_path: String,
}

/// iOS App Store export signing: xcodebuild automatic signing with an ASC API key.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct IosSigning {
    /// Apple Developer team id (DEVELOPMENT_TEAM).
    pub team: String,
    /// ExportOptions method; default "app-store-connect".
    #[serde(default)]
    pub export_method: Option<String>,
    /// ASC API key for `-allowProvisioningUpdates` in CI (optional locally, where the
    /// Xcode-account session signs). All three fields travel together.
    #[serde(default)]
    pub key_id: Option<String>,
    #[serde(default)]
    pub issuer: Option<String>,
    #[serde(default)]
    pub key_path: Option<String>,
}

/// Android release keystore (Gradle signingConfig; .aab is jar-signed by Gradle — §16.5).
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct AndroidSigning {
    pub keystore: String,
    pub key_alias: String,
    pub store_pass: String,
    pub key_pass: String,
}

/// Windows Authenticode: certs are HSM/service-held since 2023 — a provider enum, not a .pfx path.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct WindowsSigning {
    /// "self-signed-dev" | "signtool-cert-store" | "azure-artifact-signing"
    pub provider: String,
    /// Cert subject for the MSIX Identity Publisher (must byte-match the signing cert subject).
    #[serde(default)]
    pub publisher: Option<String>,
    /// signtool-cert-store: SHA-1 thumbprint of the installed certificate.
    #[serde(default)]
    pub thumbprint: Option<String>,
    /// azure-artifact-signing: endpoint / account / certificate-profile (+ dlib path).
    #[serde(default)]
    pub endpoint: Option<String>,
    #[serde(default)]
    pub account: Option<String>,
    #[serde(default)]
    pub profile: Option<String>,
    /// Path to Azure.CodeSigning.Dlib.dll (azure-artifact-signing).
    #[serde(default)]
    pub dlib: Option<String>,
    /// RFC-3161 timestamp URL; defaults per provider.
    #[serde(default)]
    pub timestamp_url: Option<String>,
}

/// OpenHarmony release signing material (hap-sign-tool).
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct OhosSigning {
    /// .p12 keystore path.
    pub keystore: String,
    pub key_alias: String,
    pub store_pass: String,
    pub key_pass: String,
    /// Release certificate (.cer) path.
    pub cert: String,
    /// Provisioning profile (.p7b) path.
    pub profile: String,
}

/// `[app]`: the Day-specific app identity. `name`/`version` are FILLED FROM Cargo.toml after
/// parsing (never written in Day.toml). Every other property can be overridden per platform /
/// toolkit / target via `[app.<key>]` tables collected in `overrides`.
#[derive(Debug, Deserialize)]
pub struct App {
    /// The crate name, from Cargo.toml `[package] name`.
    #[serde(skip)]
    pub name: String,
    /// The crate version, from Cargo.toml `[package] version`.
    #[serde(skip)]
    pub version: String,
    /// Application id / bundle id (reverse-DNS).
    pub id: String,
    /// Display title (window / app store); default: the crate name.
    #[serde(default)]
    pub title: Option<String>,
    /// Monotonic build number (versionCode / CFBundleVersion).
    #[serde(default = "default_build")]
    pub build: u64,
    /// The platform-toolkit combos this app ships on (`day app add-toolkit` appends here).
    #[serde(default)]
    pub targets: Vec<String>,
    /// `[app.<platform|toolkit|target>]` override tables — validated by `day lint`.
    /// (serde note: this flatten map is why App has no deny_unknown_fields — a typo'd scalar
    /// key still errors because it can't parse as an override TABLE.)
    #[serde(flatten)]
    pub overrides: BTreeMap<String, AppOverride>,
}

/// One `[app.<key>]` override table: any subset of the overridable `[app]` properties.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AppOverride {
    #[serde(default)]
    pub id: Option<String>,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub build: Option<u64>,
}

/// The app identity a specific target builds with, after applying `[app.<key>]` overrides.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ResolvedApp {
    pub name: String,
    pub version: String,
    pub id: String,
    pub title: String,
    pub build: u64,
}

impl Manifest {
    /// Resolve the app identity for `target` (e.g. `macos-appkit`). Override precedence, most
    /// specific wins: `[app.<target>]` > `[app.<platform>]` > `[app.<toolkit>]` > `[app]`.
    pub fn resolve(&self, target: &str) -> ResolvedApp {
        let mut out = ResolvedApp {
            name: self.app.name.clone(),
            version: self.app.version.clone(),
            id: self.app.id.clone(),
            title: self
                .app
                .title
                .clone()
                .unwrap_or_else(|| self.app.name.clone()),
            build: self.app.build,
        };
        // `[app.ohos]` is the platform table for harmony-arkui — the key comes from the
        // target catalog (`Target::os`), never from splitting the target name.
        let platform = crate::targets::find(target)
            .map(|t| t.os)
            .unwrap_or_default();
        let toolkit = target.split_once('-').map(|(_, t)| t).unwrap_or_default();
        // Increasing precedence: toolkit, then platform, then the exact target.
        for key in [toolkit, platform, target] {
            if let Some(o) = self.app.overrides.get(key) {
                if let Some(id) = &o.id {
                    out.id = id.clone();
                }
                if let Some(title) = &o.title {
                    out.title = title.clone();
                }
                if let Some(build) = o.build {
                    out.build = build;
                }
            }
        }
        out
    }
}

fn default_build() -> u64 {
    1
}

#[derive(Debug, Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Window {
    #[serde(default = "default_w")]
    pub width: f64,
    #[serde(default = "default_h")]
    pub height: f64,
}

impl Default for Window {
    fn default() -> Self {
        Window {
            width: default_w(),
            height: default_h(),
        }
    }
}

fn default_w() -> f64 {
    480.0
}
fn default_h() -> f64 {
    640.0
}

pub struct Project {
    pub root: PathBuf,
    pub manifest: Manifest,
}

/// On Windows `std::fs::canonicalize` returns an extended-length `\\?\` (verbatim) path. That prefix
/// flows into `CARGO_TARGET_DIR` (ops.rs), and the windows-gnu toolchain's MinGW linker
/// (`ld`/`collect2`) can't parse `\\?\` object-file arguments — it drops the prefix and reports
/// `cannot find \\symbols.o`, failing the link (hit on windows-gtk / windows-qt; MSVC's link.exe
/// tolerates it, so xaml was unaffected). De-verbatim the path so every subtool gets a plain
/// absolute path — still absolute, so the xcodebuild-SYMROOT need in `find_project` holds. No-op off
/// Windows, where canonicalize never adds a verbatim prefix.
fn strip_verbatim(p: PathBuf) -> PathBuf {
    #[cfg(windows)]
    if let Some(s) = p.to_str() {
        // `\\?\UNC\server\share` → `\\server\share`; `\\?\D:\path` → `D:\path`.
        if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
            return PathBuf::from(format!(r"\\{rest}"));
        }
        if let Some(rest) = s.strip_prefix(r"\\?\") {
            return PathBuf::from(rest);
        }
    }
    p
}

/// Check `[permissions]` against the declaration table, with messages a human can act on.
///
/// This runs over the raw TOML BEFORE the typed parse on purpose. `Declaration` is an untagged
/// enum, so serde reports any malformed entry as "data did not match any variant of untagged enum
/// Declaration" — which names neither the permission nor the key at fault. Both mistakes it catches
/// are the same class: a permission that silently fails to be declared is a crash on iOS.
fn validate_permissions(day_toml: &str) -> Result<(), String> {
    /// The long form's keys, in `DeclarationTable`'s kebab-case spelling.
    const LONG_FORM: &[&str] = &[
        "reason",
        "ios-reason",
        "macos-reason",
        "ohos-reason",
        "platforms",
    ];

    let raw: toml::Value = toml::from_str(day_toml).map_err(|e| format!("Day.toml: {e}"))?;
    let Some(perms) = raw.get("permissions").and_then(|v| v.as_table()) else {
        return Ok(());
    };
    for (key, value) in perms {
        if key == "raw" {
            continue; // the escape hatch, checked by its own deny_unknown_fields
        }
        if day_build::permissions::find(key).is_none() {
            return Err(format!(
                "Day.toml: [permissions] {key:?} is not a known permission (valid: {})",
                day_build::permissions::names().join(", ")
            ));
        }
        if let Some(table) = value.as_table() {
            for k in table.keys() {
                if !LONG_FORM.contains(&k.as_str()) {
                    return Err(format!(
                        "Day.toml: [permissions.{key}] has unknown key {k:?} (valid: {})",
                        LONG_FORM.join(", ")
                    ));
                }
            }
        }
    }
    Ok(())
}

/// Parse Day.toml text + the sibling Cargo.toml's `[package]` into a Manifest.
pub fn parse_manifest(day_toml: &str, cargo_toml: &str) -> Result<Manifest, String> {
    // Before the typed parse: serde's untagged `Declaration` turns any mistake in [permissions]
    // into an unactionable "data did not match any variant".
    validate_permissions(day_toml)?;
    let mut manifest: Manifest = toml::from_str(day_toml).map_err(|e| format!("Day.toml: {e}"))?;
    if manifest.schema != 1 {
        return Err(format!(
            "Day.toml: unsupported schema version {}",
            manifest.schema
        ));
    }
    // `name`/`version` are derived, never restated (a permissive parse: version may be
    // workspace-inherited in exotic layouts — fall back rather than fail).
    let cargo: toml::Value = toml::from_str(cargo_toml).map_err(|e| format!("Cargo.toml: {e}"))?;
    let package = cargo
        .get("package")
        .ok_or("Cargo.toml: no [package] table")?;
    manifest.app.name = package
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or("Cargo.toml: no package.name")?
        .to_string();
    manifest.app.version = package
        .get("version")
        .and_then(|v| v.as_str())
        .unwrap_or("0.1.0")
        .to_string();
    Ok(manifest)
}

/// Find the nearest ancestor directory containing Day.toml (from `start` or cwd).
pub fn find_project(start: Option<&Path>) -> Result<Project, String> {
    let mut dir = match start {
        Some(p) => p.to_path_buf(),
        None => std::env::current_dir().map_err(|e| e.to_string())?,
    };
    loop {
        let candidate = dir.join("Day.toml");
        if candidate.exists() {
            let day_toml = std::fs::read_to_string(&candidate).map_err(|e| e.to_string())?;
            let cargo_path = dir.join("Cargo.toml");
            let cargo_toml = std::fs::read_to_string(&cargo_path).map_err(|e| {
                format!(
                    "{}: {e} (Day.toml marks a Day project, which is also a cargo package)",
                    cargo_path.display()
                )
            })?;
            let manifest = parse_manifest(&day_toml, &cargo_toml)?;
            // Always hand back an ABSOLUTE root. A relative `--project` (e.g. `apps/showcase`) would
            // otherwise flow into build-tool arguments like xcodebuild's `SYMROOT` as a relative path;
            // xcodebuild resolves relative build paths against each target's own working directory, so
            // the app target and a SwiftPM package dependency scatter their products into different
            // trees (a missing `*_*.bundle` copy failure). Absolute paths resolve identically everywhere.
            let root = std::fs::canonicalize(&dir).unwrap_or_else(|_| {
                std::env::current_dir()
                    .map(|cwd| cwd.join(&dir))
                    .unwrap_or_else(|_| dir.clone())
            });
            return Ok(Project {
                root: strip_verbatim(root),
                manifest,
            });
        }
        if !dir.pop() {
            return Err("no Day.toml found in this directory or any ancestor".into());
        }
    }
}

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

    const CARGO: &str = "[package]\nname = \"demo-app\"\nversion = \"1.2.3\"\n";

    #[test]
    fn identity_derives_from_cargo_toml() {
        let m = parse_manifest("schema = 1\n[app]\nid = \"dev.example.demo\"\n", CARGO).unwrap();
        assert_eq!(m.app.name, "demo-app");
        assert_eq!(m.app.version, "1.2.3");
        let r = m.resolve("macos-appkit");
        assert_eq!(r.title, "demo-app"); // no title ⇒ crate name
        assert_eq!(r.build, 1);
    }

    #[test]
    fn overrides_resolve_most_specific_wins() {
        let m = parse_manifest(
            r#"
schema = 1

[app]
id = "dev.example.demo"
title = "Demo"
targets = ["ios-uikit", "macos-appkit", "macos-qt"]

# toolkit-wide override
[app.qt]
title = "Demo (Qt)"

# platform override beats toolkit
[app.macos]
id = "dev.example.demo.mac"

# exact target beats both
[app.macos-qt]
title = "Demo for macOS Qt"
build = 7
"#,
            CARGO,
        )
        .unwrap();
        assert_eq!(m.resolve("ios-uikit").title, "Demo");
        assert_eq!(m.resolve("macos-appkit").id, "dev.example.demo.mac");
        assert_eq!(m.resolve("macos-appkit").title, "Demo");
        let mq = m.resolve("macos-qt");
        assert_eq!(mq.id, "dev.example.demo.mac"); // platform
        assert_eq!(mq.title, "Demo for macOS Qt"); // exact target beats [app.qt]
        assert_eq!(mq.build, 7);
        assert_eq!(m.resolve("linux-qt").title, "Demo (Qt)"); // toolkit layer
    }

    #[test]
    fn schema_and_shape_are_validated() {
        assert!(parse_manifest("schema = 2\n[app]\nid = \"x\"\n", CARGO).is_err());
        assert!(parse_manifest("schema = 1\n", CARGO).is_err()); // no [app]
        // A typo'd scalar under [app] can't parse as an override table.
        assert!(parse_manifest("schema = 1\n[app]\nid = \"x\"\ntitel = \"y\"\n", CARGO).is_err());
    }

    #[cfg(windows)]
    #[test]
    fn strip_verbatim_deverbatims_windows_paths() {
        // Drive + UNC verbatim prefixes are removed so the MinGW linker can read the paths.
        assert_eq!(
            strip_verbatim(PathBuf::from(r"\\?\D:\a\day\day\apps\showcase")),
            PathBuf::from(r"D:\a\day\day\apps\showcase")
        );
        assert_eq!(
            strip_verbatim(PathBuf::from(r"\\?\UNC\server\share\proj")),
            PathBuf::from(r"\\server\share\proj")
        );
        // A plain absolute path is already fine — leave it untouched.
        assert_eq!(
            strip_verbatim(PathBuf::from(r"D:\a\proj")),
            PathBuf::from(r"D:\a\proj")
        );
        // canonicalize() really does hand back a verbatim path here; the result must not.
        let canon = std::fs::canonicalize(".").unwrap();
        assert!(!strip_verbatim(canon).to_string_lossy().starts_with(r"\\?\"));
    }

    /// Adding `permissions` to a `deny_unknown_fields` struct must not break the manifests already
    /// checked into every app in the tree.
    #[test]
    fn manifest_without_permissions_still_parses() {
        let m = parse_manifest("schema = 1\n[app]\nid = \"dev.x.demo\"\n", CARGO).expect("parse");
        assert!(m.permissions.declared.is_empty());
        assert!(m.permissions.raw.android.is_empty());
    }

    #[test]
    fn permission_declaration_forms() {
        let toml = r#"
schema = 1
[app]
id = "dev.x.demo"

[permissions]
camera = "Scan a document."
notifications = true

[permissions.photos]
reason = "Attach a picture."
ios-reason = "Day attaches pictures from your library."
platforms = ["ios", "android"]

[permissions.raw]
android = ["android.permission.READ_CONTACTS"]
ios = { NSContactsUsageDescription = "Find friends." }
ohos = [{ name = "ohos.permission.READ_CONTACTS", reason = "Find friends.", when = "inuse" }]
"#;
        let m = parse_manifest(toml, CARGO).expect("parse");
        assert_eq!(m.permissions.declared.len(), 3);

        let camera = &m.permissions.declared["camera"];
        assert_eq!(camera.reason_for("ios"), Some("Scan a document."));
        assert!(camera.covers("ohos"));

        // `true` declares the permission without a reason — the notifications shape.
        assert_eq!(
            m.permissions.declared["notifications"].reason_for("ios"),
            None
        );

        // The per-platform override wins over the shared reason; other platforms fall back to it.
        let photos = &m.permissions.declared["photos"];
        assert_eq!(
            photos.reason_for("ios"),
            Some("Day attaches pictures from your library.")
        );
        assert_eq!(photos.reason_for("ohos"), Some("Attach a picture."));
        assert!(photos.covers("android"));
        assert!(
            !photos.covers("ohos"),
            "platforms = [...] must exclude ohos"
        );

        assert_eq!(
            m.permissions.raw.android,
            ["android.permission.READ_CONTACTS"]
        );
        assert_eq!(
            m.permissions
                .raw
                .ios
                .get("NSContactsUsageDescription")
                .map(String::as_str),
            Some("Find friends.")
        );
        assert_eq!(
            m.permissions.raw.ohos[0].name,
            "ohos.permission.READ_CONTACTS"
        );
    }

    /// A misspelled permission must fail the parse with the valid names, not be ignored — an
    /// undeclared permission is a runtime crash on iOS.
    #[test]
    fn unknown_permission_name_is_rejected() {
        let err = parse_manifest(
            "schema = 1\n[app]\nid = \"dev.x.demo\"\n[permissions]\ncammera = \"typo\"\n",
            CARGO,
        )
        .expect_err("should reject");
        assert!(err.contains("cammera"), "{err}");
        assert!(
            err.contains("camera"),
            "the error must list the valid names: {err}"
        );
    }

    /// An unknown key inside the long form is a typo too, and `deny_unknown_fields` catches it.
    #[test]
    fn unknown_key_inside_a_declaration_is_rejected() {
        let err = parse_manifest(
            "schema = 1\n[app]\nid = \"dev.x.demo\"\n[permissions.camera]\nresaon = \"typo\"\n",
            CARGO,
        )
        .expect_err("should reject");
        assert!(
            err.contains("resaon") || err.contains("unknown field"),
            "{err}"
        );
    }
}