portaki-cli 8.6.0

Portaki module CLI (portaki) — init, build, lint, test, and OCI publish
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
//! Les métadonnées de catalogue que le code sait déjà dire.
//!
//! `portaki.module.json` répétait l'id, la version, l'auteur, le nom et la description : autant
//! de choses que `portaki_module!(…)`, `Cargo.toml` et les bundles i18n portent déjà. Le build
//! les en tire et comble ce que le manifeste écrit à la main ne dit pas ; ce qu'il dit l'emporte,
//! le temps que les modules s'en délestent.

use std::path::Path;

use anyhow::{Context, Result};
use serde_json::{json, Map, Value};

use portaki_sdk::permission;

use super::generator::EmissionFile;

/// Là où `portaki build` dépose le catalogue déduit.
pub const BUILT_CATALOG: &str = "target/portaki/catalog.json";

/// Le catalogue déduit de l'émission `module` et des bundles i18n.
///
/// Le nom et la description sont les traductions de leurs clés, par langue courte (`fr-FR` →
/// `fr`) ; une langue sans la clé est omise plutôt que remplie de la clé brute.
pub fn catalog_defaults(emissions: &[EmissionFile], i18n_dir: &Path, locales: &[String]) -> Value {
    let Some(module) = emissions.iter().find(|e| e.kind == "module") else {
        return Value::Object(Map::new());
    };
    let data = &module.data;
    let extra = data["catalog"].as_object().cloned().unwrap_or_default();

    let bundles: Vec<(String, Value)> = locales
        .iter()
        .filter_map(|locale| {
            let text = std::fs::read_to_string(i18n_dir.join(format!("{locale}.json"))).ok()?;
            let lang = locale.split('-').next().unwrap_or(locale).to_string();
            Some((lang, serde_json::from_str(&text).ok()?))
        })
        .collect();
    let translated = |key: &Value| -> Value {
        let key = key.as_str().unwrap_or_default();
        Value::Object(
            bundles
                .iter()
                .filter_map(|(lang, bundle)| Some((lang.clone(), bundle.get(key)?.clone())))
                .collect(),
        )
    };

    let mut author = json!({ "name": data["author"]["name"] });
    if let Some(url) = extra.get("authorUrl") {
        author["url"] = url.clone();
    }
    if let Some(kind) = extra.get("type") {
        author["type"] = kind.clone();
    }

    let mut catalog = json!({
        "id": data["id"],
        "version": data["version"],
        "name": translated(&data["displayName"]),
        "description": translated(&data["description"]),
        "author": author,
    });
    for key in [
        "icon",
        "type",
        "maturity",
        "sortOrder",
        "audience",
        "hostScheduledSync",
    ] {
        if let Some(value) = extra.get(key) {
            catalog[key] = value.clone();
        }
    }
    // Ce que le module fournit à un autre : le texte vit dans i18n, sous `feeds.<module>`.
    if let Some(feeds) = extra.get("feeds").and_then(Value::as_array) {
        catalog["feeds"] = feeds
            .iter()
            .map(|module| {
                let key = format!("feeds.{}", module.as_str().unwrap_or_default());
                json!({ "module": module, "what": translated(&Value::String(key)) })
            })
            .collect();
    }
    // Les descriptions d'e-mails, traduites ; le reste de l'entrée vient du manifeste du build.
    let emails: Vec<Value> = emissions
        .iter()
        .filter(|e| e.kind == "email")
        .filter_map(|e| {
            let key = e.data.get("descriptionKey")?;
            Some(json!({ "id": e.data["id"], "description": translated(key) }))
        })
        .collect();
    if !emails.is_empty() {
        catalog["emails"] = Value::Array(emails);
    }

    // `#[email_vars]` : par modèle, les variables que le module fournit.
    if let Some(declared) = emissions
        .iter()
        .find(|e| e.kind == "email_vars")
        .and_then(|e| e.data["declared"].as_array())
    {
        catalog["emailVars"] = declared
            .iter()
            .filter_map(|entry| {
                Some((
                    entry["template"].as_str()?.to_string(),
                    entry["vars"].clone(),
                ))
            })
            .collect::<Map<String, Value>>()
            .into();
    }

    if let Some(fields) = config_fields(emissions, &translated) {
        catalog["config"] = json!({ "fields": fields });
    }

    let (host, guest) = surfaces(
        emissions,
        data["id"].as_str().unwrap_or_default(),
        &translated,
    );
    if !host.is_empty() {
        catalog["hostSurfaces"] = Value::Array(host);
    }
    if !guest.is_empty() {
        catalog["guestSurfaces"] = Value::Array(guest);
    }
    catalog
}

/// Les champs de `#[portaki_sdk::config]`, libellés traduits : la macro ne porte que des clés.
///
/// Une option de `select` se libelle par la clé `<label>.<valeur>`. Une liste de lignes reçoit son
/// `item` (sous-clés traduites, identifiant) de la forme `#[params]` du type de ligne.
fn config_fields(
    emissions: &[EmissionFile],
    translated: &dyn Fn(&Value) -> Value,
) -> Option<Vec<Value>> {
    let config = emissions.iter().find(|e| e.kind == "config")?;
    let mut fields = config.data["fields"].as_array()?.clone();
    portaki_sdk::config::resolve_items(&mut fields, |name| {
        emissions
            .iter()
            .find(|e| e.kind == "params" && e.data["name"] == name)
            .map(|e| e.data.clone())
    });
    Some(
        fields
            .iter()
            .map(|field| {
                let mut entry = field.clone();
                entry["label"] = translated(&field["label"]);
                if let Some(key) = field.get("description") {
                    entry["description"] = translated(key);
                }
                if let Some(options) = field["options"].as_array() {
                    entry["options"] = options
                        .iter()
                        .map(|value| {
                            let key = option_label_key(field, value);
                            json!({ "value": value, "label": translated(&Value::String(key)) })
                        })
                        .collect();
                }
                entry
            })
            .collect(),
    )
}

fn option_label_key(field: &Value, value: &Value) -> String {
    format!(
        "{}.{}",
        field["label"].as_str().unwrap_or_default(),
        value.as_str().unwrap_or_default()
    )
}

/// Les entrées de navigation que les `#[surface]` décrivent, triées pour un manifeste stable.
///
/// Côté hôte, une entrée par `placement` ; le `pathSegment` est l'id du module pour la surface
/// `main` — l'onglet ou la fiche du module —, l'id de la surface sinon, sauf `path` explicite.
/// Côté invité, une entrée par surface qui a une `path` : les autres se rendent sans lien.
fn surfaces(
    emissions: &[EmissionFile],
    module_id: &str,
    translated: &dyn Fn(&Value) -> Value,
) -> (Vec<Value>, Vec<Value>) {
    let mut host = Vec::new();
    let mut guest = Vec::new();
    for surface in emissions.iter().filter(|e| e.kind == "surface") {
        let data = &surface.data;
        let Some(nav) = data["catalog"].as_object() else {
            continue;
        };
        let id = data["id"].as_str().unwrap_or_default();
        if data["context"] == "host" {
            let segment = nav
                .get("path")
                .and_then(Value::as_str)
                .unwrap_or(if id == "main" { module_id } else { id });
            for placement in nav
                .get("placement")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
            {
                let mut entry = json!({ "type": placement, "pathSegment": segment });
                if let Some(key) = nav.get("label_key") {
                    entry["label"] = translated(key);
                }
                if let Some(icon) = nav.get("icon") {
                    entry["icon"] = icon.clone();
                }
                if let Some(design) = nav.get("design_id") {
                    entry["hostUi"] = json!({ "designId": design });
                }
                host.push(entry);
            }
        } else if let Some(path) = nav.get("path") {
            let mut entry = json!({ "surfaceId": id, "path": path });
            for (from, to) in [
                ("label_key", "labelKey"),
                ("role", "role"),
                ("embeds", "embedsHostFragments"),
            ] {
                if let Some(value) = nav.get(from) {
                    entry[to] = value.clone();
                }
            }
            guest.push(entry);
        }
    }
    // Les entrées que le tableau de bord dessine sans surface.
    for nav in emissions.iter().filter(|e| e.kind == "nav") {
        let data = &nav.data;
        let mut entry = json!({ "type": data["placement"], "pathSegment": data["path"] });
        if let Some(key) = data.get("label_key") {
            entry["label"] = translated(key);
        }
        if let Some(icon) = data.get("icon") {
            entry["icon"] = icon.clone();
        }
        if let Some(design) = data.get("design_id") {
            entry["hostUi"] = json!({ "designId": design });
        }
        host.push(entry);
    }
    host.sort_by_key(|e| (e["pathSegment"].to_string(), e["type"].to_string()));
    // Par route : la page du module avant ses sous-pages (`issue-report` avant `issue-report/form`).
    guest.sort_by_key(|e| (e["path"].to_string(), e["surfaceId"].to_string()));
    (host, guest)
}

/// Ce que les macros nomment sans pouvoir le vérifier : des clés i18n, des queries.
///
/// Une macro ne voit ni les bundles ni les autres attributs du module. Le build, lui, a tout : une
/// clé absente d'une langue ou une query mal orthographiée s'arrête ici, pas dans le dashboard
/// d'un hôte.
pub fn check_references(
    emissions: &[EmissionFile],
    i18n_dir: &Path,
    locales: &[String],
) -> anyhow::Result<()> {
    let mut keys: Vec<String> = Vec::new();
    for emission in emissions {
        let data = &emission.data;
        let named: Vec<Option<&Value>> = match emission.kind.as_str() {
            "module" => {
                for module in data["catalog"]["feeds"].as_array().into_iter().flatten() {
                    keys.push(format!("feeds.{}", module.as_str().unwrap_or_default()));
                }
                vec![data.get("displayName"), data.get("description")]
            }
            "surface" => vec![data["catalog"].get("label_key")],
            "nav" => vec![data.get("label_key")],
            "email" => vec![data.get("descriptionKey")],
            "config" => {
                for field in data["fields"].as_array().into_iter().flatten() {
                    for option in field["options"].as_array().into_iter().flatten() {
                        keys.push(option_label_key(field, option));
                    }
                }
                data["fields"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .flat_map(|field| [field.get("label"), field.get("description")])
                    .collect()
            }
            _ => Vec::new(),
        };
        keys.extend(
            named
                .into_iter()
                .flatten()
                .filter_map(Value::as_str)
                .map(str::to_string),
        );
    }

    let mut missing = Vec::new();
    for locale in locales {
        let bundle: Value = std::fs::read_to_string(i18n_dir.join(format!("{locale}.json")))
            .ok()
            .and_then(|text| serde_json::from_str(&text).ok())
            .unwrap_or_default();
        for key in &keys {
            if bundle.get(key).is_none() {
                missing.push(format!("{key} ({locale})"));
            }
        }
    }
    if !missing.is_empty() {
        anyhow::bail!(
            "i18n keys the module declares but does not translate: {}",
            missing.join(", ")
        );
    }

    let configs: Vec<&str> = emissions
        .iter()
        .filter(|e| e.kind == "config")
        .filter_map(|e| e.data["name"].as_str())
        .collect();
    if configs.len() > 1 {
        anyhow::bail!(
            "#[portaki_sdk::config] is on {} — a module has one configuration",
            configs.join(" and ")
        );
    }

    if emissions.iter().filter(|e| e.kind == "email_vars").count() > 1 {
        anyhow::bail!("#[email_vars] is on more than one function — a module has one emailContext");
    }

    let queries: Vec<&str> = emissions
        .iter()
        .filter(|e| e.kind == "query")
        .filter_map(|e| e.data["name"].as_str())
        .collect();
    for emission in emissions.iter().filter(|e| e.kind == "module") {
        let sync = &emission.data["catalog"]["hostScheduledSync"];
        for (attribute, field) in [
            ("scheduled_sync_sources", "sourcesQuery"),
            ("scheduled_sync_apply", "applyQuery"),
        ] {
            if let Some(query) = sync[field].as_str() {
                if !queries.contains(&query) {
                    anyhow::bail!("{attribute} names `{query}`, and no #[query] has that name");
                }
            }
        }
    }
    Ok(())
}

/// Chaque feature de `portaki-sdk` et la permission qu'elle déclare.
pub(crate) const FEATURE_PERMISSIONS: [(&str, &str); 7] = [
    ("kv", permission::KV),
    ("repo", permission::REPO),
    ("email", permission::EMAIL),
    ("events", permission::EVENTS),
    ("platform", permission::PLATFORM),
    ("guest-files", permission::GUEST_FILES),
    ("stay-guest-contact", permission::STAY_GUEST_CONTACT_READ),
];

/// Les permissions que le code réclame : une par feature de `portaki-sdk` activée — l'API
/// qu'elle garde n'existe pas sans elle —, et `connectors:<id>` pour chaque connecteur déclaré.
pub fn permissions(emissions: &[EmissionFile], sdk_features: &[String]) -> Vec<String> {
    let mut found: Vec<String> = FEATURE_PERMISSIONS
        .iter()
        .filter(|(feature, _)| sdk_features.iter().any(|f| f == feature))
        .map(|(_, permission)| permission.to_string())
        .chain(
            emissions
                .iter()
                .filter(|e| e.kind == "connector_builtin" || e.kind == "connector_custom")
                .filter_map(|e| e.data["id"].as_str())
                .map(|id| format!("{}{id}", permission::CONNECTORS_PREFIX)),
        )
        .collect();
    found.sort();
    found.dedup();
    found
}

/// Comble les clés que le manifeste écrit à la main ne porte pas. Ce qu'il porte l'emporte.
pub fn fill_catalog(raw: &str, catalog: &str) -> Result<String> {
    let catalog: Value = serde_json::from_str(catalog).context("parse built catalog")?;
    let Some(defaults) = catalog.as_object().filter(|c| !c.is_empty()) else {
        return Ok(raw.to_string());
    };
    let mut manifest: Value = serde_json::from_str(raw).context("parse module manifest")?;
    let Some(object) = manifest.as_object_mut() else {
        return Ok(raw.to_string());
    };
    let before = object.clone();
    for (key, value) in defaults {
        if is_empty(value) {
            continue;
        }
        match (object.get_mut(key), IDENTITY.iter().find(|(k, _)| k == key)) {
            (None, _) => {
                object.insert(key.clone(), value.clone());
            }
            // Une permission que le code réclame s'ajoute ; celles écrites à la main restent.
            (Some(Value::Array(declared)), None) if key == "permissions" => {
                for permission in value.as_array().into_iter().flatten() {
                    if !declared.contains(permission) {
                        declared.push(permission.clone());
                    }
                }
            }
            // `config` : ce que le manifeste écrit à la main l'emporte clé par clé — ses `fields`
            // entiers s'il en a, ceux du code sinon, à côté de son `globalAlert`.
            (Some(Value::Object(declared)), None) if key == "config" => {
                for (field, built) in value.as_object().into_iter().flatten() {
                    declared
                        .entry(field.clone())
                        .or_insert_with(|| built.clone());
                }
            }
            (Some(Value::Array(declared)), Some((_, fields))) => merge_entries(
                declared,
                value.as_array().map(Vec::as_slice).unwrap_or_default(),
                fields,
            ),
            _ => {}
        }
    }
    if *object == before {
        return Ok(raw.to_string());
    }
    serde_json::to_string_pretty(&manifest).context("serialise module manifest")
}

/// Les listes fusionnées entrée par entrée, et les champs qui identifient une entrée.
const IDENTITY: [(&str, &[&str]); 3] = [
    ("hostSurfaces", &["type", "pathSegment"]),
    ("guestSurfaces", &["surfaceId"]),
    ("emails", &["id"]),
];

/// Ajoute les entrées du code que le manifeste n'a pas, et comble les champs qu'il tait sur
/// celles qu'il a. Une entrée écrite à la main que le code ignore — la tâche de frise de
/// `checklist`, qui n'a pas de surface — reste telle quelle.
fn merge_entries(declared: &mut Vec<Value>, built: &[Value], identity: &[&str]) {
    let same = |a: &Value, b: &Value| identity.iter().all(|field| a.get(*field) == b.get(*field));
    for entry in built {
        match declared.iter_mut().find(|d| same(d, entry)) {
            Some(Value::Object(existing)) => {
                for (field, value) in entry.as_object().into_iter().flatten() {
                    if !is_empty(value) {
                        existing
                            .entry(field.clone())
                            .or_insert_with(|| value.clone());
                    }
                }
            }
            Some(_) => {}
            None => declared.push(entry.clone()),
        }
    }
}

/// Un nom sans aucune traduction n'apprend rien au catalogue.
fn is_empty(value: &Value) -> bool {
    value.is_null() || value.as_object().is_some_and(Map::is_empty)
}

#[cfg(test)]
mod tests {
    use super::{catalog_defaults, fill_catalog};
    use crate::manifest::generator::EmissionFile;
    use serde_json::json;

    fn module() -> Vec<EmissionFile> {
        vec![EmissionFile {
            kind: "module".into(),
            data: json!({
                "id": "issue-report",
                "version": "0.6.0",
                "displayName": "module.displayName",
                "description": "module.description",
                "author": { "name": "Portaki" },
                "catalog": { "icon": "danger-triangle", "type": "official",
                             "authorUrl": "https://portaki.app", "sortOrder": 90 },
            }),
        }]
    }

    #[test]
    fn the_catalog_reads_the_module_and_its_translations() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("fr-FR.json"),
            r#"{"module.displayName":"Signaler","module.description":"Un souci"}"#,
        )
        .expect("fr");
        std::fs::write(
            dir.path().join("en-US.json"),
            r#"{"module.displayName":"Report"}"#,
        )
        .expect("en");

        let catalog = catalog_defaults(
            &module(),
            dir.path(),
            &["en-US".to_string(), "fr-FR".to_string()],
        );

        assert_eq!(
            catalog,
            json!({
                "id": "issue-report",
                "version": "0.6.0",
                "name": { "en": "Report", "fr": "Signaler" },
                "description": { "fr": "Un souci" },
                "author": { "name": "Portaki", "url": "https://portaki.app", "type": "official" },
                "icon": "danger-triangle",
                "type": "official",
                "sortOrder": 90,
            })
        );
    }

    #[test]
    fn the_hand_written_manifest_keeps_what_it_says() {
        let raw = r#"{"id":"issue-report","icon":"bell","permissions":["repo"]}"#;
        let catalog = r#"{"id":"x","icon":"danger-triangle","maturity":"stable","name":{}}"#;

        let filled: serde_json::Value =
            serde_json::from_str(&fill_catalog(raw, catalog).expect("fill")).expect("parse");

        assert_eq!(filled["id"], "issue-report");
        assert_eq!(filled["icon"], "bell");
        assert_eq!(filled["maturity"], "stable");
        assert!(
            filled.get("name").is_none(),
            "an untranslated name is left out"
        );
    }

    #[test]
    fn surfaces_become_navigation_entries() {
        let mut emissions = module();
        let surface = |data: serde_json::Value| EmissionFile {
            kind: "surface".into(),
            data,
        };
        emissions.push(surface(
            json!({ "context": "host", "id": "main", "renderFn": "a",
            "catalog": { "placement": ["property-workspace-tab"], "design_id": "report-v1",
                         "label_key": "nav.tab", "icon": "danger-triangle" } }),
        ));
        emissions.push(surface(
            json!({ "context": "host", "id": "issue-stats", "renderFn": "b",
            "catalog": { "placement": ["property-stats-detail", "property-stats-card"] } }),
        ));
        emissions.push(surface(
            json!({ "context": "guest", "id": "guest.form", "renderFn": "c",
            "catalog": { "path": "issue-report/form", "label_key": "nav.form" } }),
        ));
        emissions.push(surface(
            json!({ "context": "guest", "id": "home.card", "renderFn": "d" }),
        ));
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("fr-FR.json"), r#"{"nav.tab":"Onglet"}"#).expect("fr");

        let catalog = catalog_defaults(&emissions, dir.path(), &["fr-FR".to_string()]);

        assert_eq!(
            catalog["hostSurfaces"],
            json!([
                { "type": "property-workspace-tab", "pathSegment": "issue-report",
                  "label": { "fr": "Onglet" }, "icon": "danger-triangle",
                  "hostUi": { "designId": "report-v1" } },
                { "type": "property-stats-card", "pathSegment": "issue-stats" },
                { "type": "property-stats-detail", "pathSegment": "issue-stats" },
            ])
        );
        assert_eq!(
            catalog["guestSurfaces"],
            json!([{ "surfaceId": "guest.form", "path": "issue-report/form", "labelKey": "nav.form" }])
        );
    }

    #[test]
    fn surfaces_merge_entry_by_entry_and_the_hand_written_ones_stay() {
        let raw = r#"{"hostSurfaces":[
            {"type":"property-stats-card","pathSegment":"s","label":{"fr":"Main"}},
            {"type":"workspace-timeline-task","pathSegment":"tasks"}]}"#;
        let catalog = r#"{"hostSurfaces":[
            {"type":"property-stats-card","pathSegment":"s","label":{"fr":"Code"},"icon":"i"},
            {"type":"property-stats-detail","pathSegment":"s"}]}"#;

        let filled: serde_json::Value =
            serde_json::from_str(&fill_catalog(raw, catalog).expect("fill")).expect("parse");

        assert_eq!(
            filled["hostSurfaces"],
            json!([
                { "type": "property-stats-card", "pathSegment": "s", "label": { "fr": "Main" }, "icon": "i" },
                { "type": "workspace-timeline-task", "pathSegment": "tasks" },
                { "type": "property-stats-detail", "pathSegment": "s" },
            ])
        );
        assert_eq!(
            fill_catalog(&filled.to_string(), catalog).expect("again"),
            filled.to_string()
        );
    }

    #[test]
    fn permissions_come_from_sdk_features_and_connectors() {
        let mut emissions = module();
        emissions.push(EmissionFile {
            kind: "connector_custom".into(),
            data: json!({ "id": "nuki" }),
        });
        let features = ["repo", "email", "not-a-permission", "guest-files"].map(String::from);

        assert_eq!(
            super::permissions(&emissions, &features),
            ["connectors:nuki", "email", "guest:files", "repo"]
        );
    }

    #[test]
    fn permissions_add_to_the_hand_written_list() {
        let raw = r#"{"permissions":["platform","email"]}"#;
        let filled: serde_json::Value = serde_json::from_str(
            &fill_catalog(raw, r#"{"permissions":["email","repo"]}"#).expect("fill"),
        )
        .expect("parse");
        assert_eq!(filled["permissions"], json!(["platform", "email", "repo"]));
    }

    #[test]
    fn residual_fields_come_from_the_code_too() {
        let mut emissions = module();
        emissions[0].data["catalog"]["audience"] = json!("host");
        emissions[0].data["catalog"]["feeds"] = json!(["access-guide"]);
        emissions[0].data["catalog"]["hostScheduledSync"] = json!({ "platformFetch": true });
        emissions.push(EmissionFile {
            kind: "nav".into(),
            data: json!({ "placement": "workspace-timeline-task", "path": "tasks",
                          "label_key": "nav.tasks", "icon": "sparkles" }),
        });
        emissions.push(EmissionFile {
            kind: "email".into(),
            data: json!({ "id": "sync-failed", "descriptionKey": "email.syncFailed" }),
        });
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("fr-FR.json"),
            r#"{"nav.tasks":"Tâches","feeds.access-guide":"le code","email.syncFailed":"Échec"}"#,
        )
        .expect("fr");

        let catalog = catalog_defaults(&emissions, dir.path(), &["fr-FR".to_string()]);

        assert_eq!(catalog["audience"], "host");
        assert_eq!(catalog["hostScheduledSync"]["platformFetch"], true);
        assert_eq!(
            catalog["feeds"],
            json!([{ "module": "access-guide", "what": { "fr": "le code" } }])
        );
        assert_eq!(
            catalog["hostSurfaces"],
            json!([{ "type": "workspace-timeline-task", "pathSegment": "tasks",
                     "label": { "fr": "Tâches" }, "icon": "sparkles" }])
        );
        assert_eq!(
            catalog["emails"],
            json!([{ "id": "sync-failed", "description": { "fr": "Échec" } }])
        );
    }

    #[test]
    fn email_vars_become_a_map_by_template() {
        let mut emission = json!({ "kind": "email_vars", "declared": [
            { "template": "EmailTemplateKey::Arrival", "vars": ["EmailVar::WifiName", "EmailVar::HostPhone"] },
            { "template": "EmailTemplateKey::StayLink", "vars": ["EmailVar::WifiName"] },
        ]});
        super::super::generator::resolve_vocabulary(&mut emission).expect("resolve");
        let mut emissions = module();
        emissions.push(EmissionFile {
            kind: "email_vars".into(),
            data: emission,
        });
        let dir = tempfile::tempdir().expect("tempdir");

        let catalog = catalog_defaults(&emissions, dir.path(), &[]);

        assert_eq!(
            catalog["emailVars"],
            json!({ "arrival": ["wifiName", "hostPhone"], "stay-link": ["wifiName"] })
        );
        emissions.push(emissions.last().unwrap().clone());
        let twice = super::check_references(&emissions, dir.path(), &[]).unwrap_err();
        assert!(twice.to_string().contains("#[email_vars]"), "{twice}");
    }

    #[test]
    fn a_declared_key_or_query_that_does_not_exist_stops_the_build() {
        let dir = tempfile::tempdir().expect("tempdir");
        let both = |fr: &str, en: &str| {
            std::fs::write(dir.path().join("fr-FR.json"), fr).expect("fr");
            std::fs::write(dir.path().join("en-US.json"), en).expect("en");
        };
        let locales = ["fr-FR".to_string(), "en-US".to_string()];
        let mut emissions = module();
        emissions[0].data["catalog"]["hostScheduledSync"] = json!({ "applyQuery": "applyFeeds" });
        emissions.push(EmissionFile {
            kind: "query".into(),
            data: json!({ "name": "applyFeeds" }),
        });
        let keys = r#"{"module.displayName":"x","module.description":"y"}"#;

        both(keys, keys);
        super::check_references(&emissions, dir.path(), &locales).expect("all there");

        both(keys, r#"{"module.displayName":"x"}"#);
        let missing = super::check_references(&emissions, dir.path(), &locales).unwrap_err();
        assert!(
            missing.to_string().contains("module.description (en-US)"),
            "{missing}"
        );

        both(keys, keys);
        emissions[0].data["catalog"]["hostScheduledSync"] = json!({ "applyQuery": "applyFeed" });
        let typo = super::check_references(&emissions, dir.path(), &locales).unwrap_err();
        assert!(typo.to_string().contains("applyFeed"), "{typo}");
    }

    fn with_config() -> Vec<EmissionFile> {
        let mut emissions = module();
        emissions.push(EmissionFile {
            kind: "config".into(),
            data: json!({ "name": "Config", "fields": [
                { "key": "ssid", "type": "text", "required": true, "recommended": false,
                  "label": "config.ssid" },
                { "key": "password", "type": "secret", "required": false, "recommended": true,
                  "label": "config.password", "description": "config.password.help" },
                { "key": "security", "type": "select", "required": false, "recommended": false,
                  "label": "config.security", "options": ["wpa2", "wep"] },
                { "key": "contacts", "type": "structured", "required": false,
                  "recommended": false, "label": "config.contacts", "itemType": "Contact" },
            ] }),
        });
        emissions
    }

    #[test]
    fn translated_row_fields_come_from_the_row_params() {
        let mut emissions = with_config();
        emissions.push(EmissionFile {
            kind: "params".into(),
            data: json!({ "kind": "params", "name": "Contact", "fields": [
                { "name": "id", "type": "string", "required": true },
                { "name": "role", "type": "ref", "ref": "I18nText", "required": true },
                { "name": "phone", "type": "string", "required": true },
            ] }),
        });
        let dir = tempfile::tempdir().expect("tempdir");
        let catalog = catalog_defaults(&emissions, dir.path(), &[]);
        assert_eq!(
            catalog["config"]["fields"][3],
            json!({ "key": "contacts", "type": "structured", "required": false,
                    "recommended": false, "label": {},
                    "item": { "id": "id", "localized": ["role"] } })
        );
    }

    const CONFIG_FR: &str = r#"{"config.ssid":"Nom du réseau","config.password":"Mot de passe",
        "config.password.help":"Au dos de la box","config.security":"Sécurité",
        "config.security.wpa2":"WPA2","config.security.wep":"WEP","config.contacts":"Contacts"}"#;

    #[test]
    fn config_labels_are_translated_from_the_bundles() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("fr-FR.json"), CONFIG_FR).expect("fr");

        let catalog = catalog_defaults(&with_config(), dir.path(), &["fr-FR".to_string()]);

        assert_eq!(
            catalog["config"],
            json!({ "fields": [
                { "key": "ssid", "type": "text", "required": true, "recommended": false,
                  "label": { "fr": "Nom du réseau" } },
                { "key": "password", "type": "secret", "required": false, "recommended": true,
                  "label": { "fr": "Mot de passe" }, "description": { "fr": "Au dos de la box" } },
                { "key": "security", "type": "select", "required": false, "recommended": false,
                  "label": { "fr": "Sécurité" }, "options": [
                    { "value": "wpa2", "label": { "fr": "WPA2" } },
                    { "value": "wep", "label": { "fr": "WEP" } } ] },
                { "key": "contacts", "type": "structured", "required": false,
                  "recommended": false, "label": { "fr": "Contacts" } },
            ] })
        );
    }

    #[test]
    fn a_config_label_missing_from_a_bundle_stops_the_build() {
        let dir = tempfile::tempdir().expect("tempdir");
        let module_keys = r#""module.displayName":"x","module.description":"y""#;
        let fr = CONFIG_FR.replacen('{', &format!("{{{module_keys},"), 1);
        std::fs::write(dir.path().join("fr-FR.json"), &fr).expect("fr");
        std::fs::write(
            dir.path().join("en-US.json"),
            fr.replace(r#""config.security.wep":"WEP","#, ""),
        )
        .expect("en");
        let locales = ["fr-FR".to_string(), "en-US".to_string()];

        let missing = super::check_references(&with_config(), dir.path(), &locales).unwrap_err();
        assert_eq!(
            missing.to_string(),
            "i18n keys the module declares but does not translate: config.security.wep (en-US)"
        );

        let mut two = with_config();
        two.push(EmissionFile {
            kind: "config".into(),
            data: json!({ "name": "Other", "fields": [] }),
        });
        std::fs::write(dir.path().join("en-US.json"), &fr).expect("en");
        let error = super::check_references(&two, dir.path(), &locales).unwrap_err();
        assert!(error.to_string().contains("Config and Other"), "{error}");
    }

    #[test]
    fn hand_written_config_fields_win_and_the_rest_is_filled() {
        let built = r#"{"config":{"fields":[{"key":"ssid"}]}}"#;
        let alert_only = r#"{"config":{"globalAlert":{"type":"info"}}}"#;
        let filled: serde_json::Value =
            serde_json::from_str(&fill_catalog(alert_only, built).expect("fill")).expect("parse");
        assert_eq!(
            filled["config"],
            json!({ "globalAlert": { "type": "info" }, "fields": [{ "key": "ssid" }] })
        );

        let hand_written = r#"{"config":{"fields":[{"key":"legacy"}]}}"#;
        assert_eq!(
            fill_catalog(hand_written, built).expect("fill"),
            hand_written
        );
    }

    #[test]
    fn nothing_to_fill_leaves_the_manifest_untouched() {
        let raw = r#"{"id":"issue-report"}"#;
        assert_eq!(fill_catalog(raw, r#"{"id":"x"}"#).expect("fill"), raw);
        assert_eq!(fill_catalog(raw, "{}").expect("fill"), raw);
    }
}