workshop-rs 1.20.0

Canonical multi-locale Overwatch Workshop semantic core: catalog, parser, WIR, validation, emitter.
Documentation
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
use std::collections::{BTreeMap, HashMap};
use std::sync::OnceLock;

use serde::Deserialize;

use crate::core::error::{CatalogError, Result, WorkshopError};

use super::{
    CATALOG_DATA, Catalog, CatalogEntry, EnumDomain, EnumMember, Kind, Locale,
    LocalizedStringEntry, NormalizedIndex, ParamCoercions, Provenance, TargetMeta,
    normalize_spelling,
};

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CatalogFile {
    schema_version: u32,
    locales: Vec<String>,
    target: TargetMeta,
    provenance: Provenance,
    #[serde(default)]
    version: Option<String>,
    #[serde(default)]
    digest: Option<String>,
    #[serde(default)]
    structural: Vec<EntryFile>,
    #[serde(default)]
    actions: Vec<EntryFile>,
    #[serde(default)]
    values: Vec<EntryFile>,
    #[serde(default)]
    events: Vec<EntryFile>,
    #[serde(default)]
    operators: Vec<EntryFile>,
    #[serde(default)]
    settings: Vec<EntryFile>,
    #[serde(default)]
    localized_strings: Vec<LocalizedStringFile>,
    #[serde(default)]
    enums: Vec<EnumFile>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct EntryFile {
    id: String,
    aliases: HashMap<String, AliasFile>,
    /// The declared parameter list. `None` means the entry declares no
    /// signature at all; `Some` — even empty, as on the zero-argument
    /// `else`/`end` constructs — declares a call signature.
    #[serde(default)]
    params: Option<Vec<String>>,
    /// Reviewed semantic parameter names, parallel to `params`.
    #[serde(default)]
    param_names: Vec<String>,
    #[serde(default)]
    param_aliases: Vec<HashMap<String, AliasFile>>,
    /// Canonical enum domain per parameter position (parallel to `params`);
    /// empty when no parameter domains are documented.
    #[serde(default)]
    param_domains: Vec<Option<String>>,
    /// Default value per parameter position (parallel to `params`),
    /// resolved when a call omits the argument. `None` means no default is
    /// declared. Default value syntax: `null`, a numeric literal, localized
    /// string text, `Domain.MEMBER` (builtin enum member), or a catalog value
    /// id resolved as a zero-argument call. Every default is pinned-reference
    /// probe evidence, never copied from upstream game data.
    #[serde(default)]
    param_defaults: Vec<Option<String>>,
    #[serde(default)]
    param_types: Vec<Option<String>>,
    #[serde(default)]
    param_coercions: Vec<Option<ParamCoercions>>,
    #[serde(default)]
    return_type: Option<String>,
    /// Reviewed reevaluation coverage keyed by enum member id (e.g.
    /// `COLOR`), listing the parameter positions each member keeps
    /// re-evaluating. Declared only on actions whose `*Reeval` parameter
    /// selects the reevaluation mode; validated against that domain's
    /// members and the parameter arity.
    #[serde(default)]
    reevaluation_coverage: Option<BTreeMap<String, Vec<usize>>>,
    #[serde(default)]
    variadic: bool,
}

#[derive(Deserialize)]
struct LocalizedStringFile {
    id: String,
    aliases: HashMap<String, AliasFile>,
}

#[derive(Deserialize)]
struct EnumFile {
    domain: String,
    #[serde(default)]
    aliases: HashMap<String, AliasFile>,
    members: Vec<MemberFile>,
}

#[derive(Deserialize)]
struct MemberFile {
    id: String,
    aliases: HashMap<String, AliasFile>,
}

/// A locale may have one canonical emitter spelling or several reviewed
/// spellings observed across current Workshop producers. The string form is
/// retained for the common case; the array form makes conflicts explicit in
/// the data instead of forcing parser branches or silently choosing one.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum AliasFile {
    One(String),
    Many(Vec<String>),
}

impl AliasFile {
    fn into_spellings(self, id: &str, locale: &str) -> Result<Vec<String>> {
        let spellings = match self {
            AliasFile::One(spelling) => vec![spelling],
            AliasFile::Many(spellings) => spellings,
        };
        if spellings.is_empty() || spellings.iter().any(String::is_empty) {
            return Err(CatalogError::validation(format!(
                "catalog entry '{}' declares an empty alias for locale '{}'",
                id, locale
            )));
        }
        Ok(spellings)
    }
}
impl Catalog {
    /// Parse and validate catalog data, verifying the declared content
    /// digest when the data carries one.
    pub fn load(json: &str) -> Result<Catalog> {
        let catalog = Self::load_unverified(json)?;
        if let Some(declared) = &catalog.catalog_digest {
            let computed = content_digest(json)?;
            if declared != &computed {
                return Err(CatalogError::validation(format!(
                    "catalog digest mismatch: declared '{declared}', content '{computed}' — \
                     run the catalog pipeline (workshop-catalog-gen build)"
                )));
            }
        }
        Ok(catalog)
    }

    /// Parse and validate catalog data without digest verification. Used by
    /// the catalog pipeline so a stale digest can be repaired by `build`.
    pub fn load_unverified(json: &str) -> Result<Catalog> {
        let file: CatalogFile = serde_json::from_str(json)
            .map_err(|error| CatalogError::malformed(format!("catalog data: {error}")))?;
        if file.schema_version != 1 {
            return Err(CatalogError::malformed(format!(
                "unsupported catalog schemaVersion {}",
                file.schema_version
            )));
        }
        let locales: Vec<Locale> = file.locales.iter().map(|s| Locale::new(s)).collect();
        if locales.is_empty() {
            return Err(CatalogError::malformed(
                "catalog declares no locales".to_string(),
            ));
        }

        let mut catalog = Catalog {
            detection_index: None,
            schema_version: file.schema_version,
            locales,
            target: file.target,
            provenance: file.provenance,
            catalog_version: file.version.unwrap_or_else(|| "dev".to_string()),
            catalog_digest: file.digest,
            entries: Vec::new(),
            localized_strings: Vec::new(),
            enums: Vec::new(),
            by_id: Default::default(),
            alias_to_entry: HashMap::new(),
            localized_string_by_id: HashMap::new(),
            localized_string_alias: HashMap::new(),
            enum_by_domain: HashMap::new(),
            enum_alias_to_domain: HashMap::new(),
            enum_alias_to_member: HashMap::new(),
            bare_member_index: HashMap::new(),
            normalized: NormalizedIndex::default(),
        };

        for (kind, items) in [
            (Kind::Structural, file.structural),
            (Kind::Action, file.actions),
            (Kind::Value, file.values),
            (Kind::Event, file.events),
            (Kind::Operator, file.operators),
            (Kind::Setting, file.settings),
        ] {
            for item in items {
                catalog.insert_entry(kind, item)?;
            }
        }
        for item in file.localized_strings {
            catalog.insert_localized_string(item)?;
        }
        for domain in file.enums {
            catalog.insert_enum(domain)?;
        }
        for domain in &catalog.enums {
            for member in &domain.members {
                for (locale, spellings) in &member.aliases {
                    for spelling in spellings {
                        catalog
                            .bare_member_index
                            .entry(locale.clone())
                            .or_default()
                            .entry(spelling.clone())
                            .or_default()
                            .push((domain.domain.clone(), member.member.clone()));
                    }
                }
            }
        }
        catalog.build_normalized_index();
        catalog.validate_param_domains()?;
        catalog.detection_index =
            Some(super::detect::AliasIndex::build(&catalog).map_err(|error| {
                CatalogError::validation(format!("locale detection index: {error}"))
            })?);
        Ok(catalog)
    }

    /// The built-in catalog data.
    pub fn builtin() -> Result<Catalog> {
        Self::builtin_ref().cloned().map_err(Clone::clone)
    }

    /// The built-in catalog, parsed and indexed once per process.
    pub fn builtin_ref() -> std::result::Result<&'static Catalog, &'static WorkshopError> {
        static DATA: OnceLock<Result<Catalog>> = OnceLock::new();
        match DATA.get_or_init(|| Self::load(CATALOG_DATA)) {
            Ok(catalog) => Ok(catalog),
            Err(error) => Err(error),
        }
    }
    /// Mirror the verbatim spelling indexes under whitespace-collapsed
    /// keys (#448). A normalized key claimed by distinct targets is poisoned
    /// (`None`) so it resolves nothing rather than guessing; identical
    /// targets (two declared spellings that differ only in whitespace, such
    /// as zh-CN `66号公路`/`66 号公路`) keep their single meaning.
    fn build_normalized_index(&mut self) {
        fn insert<T: PartialEq + Clone>(
            map: &mut HashMap<String, Option<T>>,
            key: String,
            value: T,
        ) {
            match map.get_mut(&key) {
                Some(slot) if *slot != Some(value.clone()) => *slot = None,
                Some(_) => {}
                None => {
                    map.insert(key, Some(value));
                }
            }
        }

        let mut normalized = NormalizedIndex::default();
        for (locale, by_kind) in &self.alias_to_entry {
            let by_kind_norm = normalized
                .alias_to_entry
                .entry(locale.clone())
                .or_insert_with(|| std::array::from_fn(|_| HashMap::new()));
            for (kind_index, map) in by_kind.iter().enumerate() {
                for (spelling, &entry_index) in map {
                    let key = normalize_spelling(spelling);
                    if key != spelling.as_str() {
                        insert(&mut by_kind_norm[kind_index], key.into_owned(), entry_index);
                    }
                }
            }
        }
        for (locale, map) in &self.localized_string_alias {
            let norm = normalized
                .localized_string_alias
                .entry(locale.clone())
                .or_default();
            for (spelling, &string_index) in map {
                let key = normalize_spelling(spelling);
                if key != spelling.as_str() {
                    insert(norm, key.into_owned(), string_index);
                }
            }
        }
        for (locale, map) in &self.enum_alias_to_domain {
            let norm = normalized
                .enum_alias_to_domain
                .entry(locale.clone())
                .or_default();
            for (spelling, domain) in map {
                let key = normalize_spelling(spelling);
                if key != spelling.as_str() {
                    insert(norm, key.into_owned(), domain.clone());
                }
            }
        }
        for (locale, domains) in &self.enum_alias_to_member {
            let norm = normalized
                .enum_alias_to_member
                .entry(locale.clone())
                .or_default();
            for (domain, map) in domains {
                let norm_map = norm.entry(domain.clone()).or_default();
                for (spelling, &indexes) in map {
                    let key = normalize_spelling(spelling);
                    if key != spelling.as_str() {
                        insert(norm_map, key.into_owned(), indexes);
                    }
                }
            }
        }
        for (locale, map) in &self.bare_member_index {
            let norm = normalized.bare_member.entry(locale.clone()).or_default();
            for (spelling, matches) in map {
                let key = normalize_spelling(spelling);
                if key != spelling.as_str() {
                    let merged = norm.entry(key.into_owned()).or_default();
                    for pair in matches {
                        if !merged.contains(pair) {
                            merged.push(pair.clone());
                        }
                    }
                }
            }
        }
        self.normalized = normalized;
    }

    fn insert_entry(&mut self, kind: Kind, item: EntryFile) -> Result<()> {
        let index = self.entries.len();
        let aliases = self.collect_aliases(
            &item.id,
            &format!("entry '{}'", item.id),
            item.aliases,
            true,
            |catalog, locale, spelling| {
                let locale_map = catalog.alias_to_entry.entry(locale.clone()).or_default();
                if locale_map[kind.as_index()].contains_key(spelling) {
                    return Err(CatalogError::validation(format!(
                        "duplicate {} alias '{spelling}' for locale '{locale}'",
                        kind.as_str()
                    )));
                }
                locale_map[kind.as_index()].insert(spelling.to_string(), index);
                Ok(())
            },
        )?;
        if self.by_id[kind.as_index()].contains_key(&item.id) {
            return Err(CatalogError::validation(format!(
                "duplicate {} id '{}'",
                kind.as_str(),
                item.id
            )));
        }
        // The primary locale's surface is complete: every builtin carries a
        // primary-locale alias. Additional declared locales may be partially
        // covered; missing target-locale mappings fail explicitly at
        // conversion/emission time (ADR-0001 Decision 7).
        // A signature-bearing entry is any action or value, or a structural
        // entry that declares its parameter list — `"params": []` marks a
        // zero-argument construct such as `else`/`end`, while section
        // keywords declare no `params` field and stay without a signature.
        let callable = matches!(kind, Kind::Action | Kind::Value)
            || (kind == Kind::Structural && item.params.is_some());
        let params = item.params.unwrap_or_default();
        let param_names = match item.param_names {
            names if names.is_empty() => None,
            names if names.len() != params.len() => {
                return Err(CatalogError::validation(format!(
                    "{} '{}' declares {} param names for {} params",
                    kind.as_str(),
                    item.id,
                    names.len(),
                    params.len()
                )));
            }
            names if names == params => None,
            names => Some(names),
        };
        self.by_id[kind.as_index()].insert(item.id.clone(), index);
        let item_id = item.id.clone();
        self.entries.push(CatalogEntry {
            id: item.id,
            kind,
            callable,
            params,
            param_names,
            param_aliases: item
                .param_aliases
                .into_iter()
                .map(|aliases| {
                    aliases
                        .into_iter()
                        .map(|(locale, alias)| {
                            let locale_key = Locale::new(&locale);
                            let spellings = alias.into_spellings(&item_id, locale_key.as_str())?;
                            Ok((locale_key, spellings))
                        })
                        .collect::<Result<HashMap<_, _>>>()
                })
                .collect::<Result<Vec<_>>>()?,
            param_domains: item.param_domains,
            param_defaults: item.param_defaults,
            param_types: item.param_types,
            param_coercions: item.param_coercions,
            return_type: item.return_type,
            reevaluation_coverage: item.reevaluation_coverage,
            variadic: item.variadic,
            aliases,
        });
        Ok(())
    }

    fn insert_localized_string(&mut self, item: LocalizedStringFile) -> Result<()> {
        if self.localized_string_by_id.contains_key(&item.id) {
            return Err(CatalogError::validation(format!(
                "duplicate localized string id '{}'",
                item.id
            )));
        }
        let index = self.localized_strings.len();
        let aliases = self.collect_aliases(
            &item.id,
            &format!("localized string '{}'", item.id),
            item.aliases,
            true,
            |catalog, locale, spelling| {
                let locale_map = catalog
                    .localized_string_alias
                    .entry(locale.clone())
                    .or_default();
                if locale_map.contains_key(spelling) {
                    return Err(CatalogError::validation(format!(
                        "duplicate localized string alias '{spelling}' for locale '{locale}'"
                    )));
                }
                locale_map.insert(spelling.to_string(), index);
                Ok(())
            },
        )?;
        self.localized_string_by_id.insert(item.id.clone(), index);
        self.localized_strings.push(LocalizedStringEntry {
            id: item.id,
            aliases,
        });
        Ok(())
    }

    fn validate_param_domains(&self) -> Result<()> {
        for entry in &self.entries {
            for (name, count) in [
                ("parameter alias sets", entry.param_aliases.len()),
                ("param domains", entry.param_domains.len()),
                ("param defaults", entry.param_defaults.len()),
                ("param types", entry.param_types.len()),
                ("param coercions", entry.param_coercions.len()),
            ] {
                if count > entry.params.len() {
                    return Err(CatalogError::validation(format!(
                        "{} '{}' declares more {name} than params",
                        entry.kind.as_str(),
                        entry.id
                    )));
                }
            }
            if entry.kind != Kind::Value && entry.return_type.is_some() {
                return Err(CatalogError::validation(format!(
                    "{} '{}' declares a return type but is not a value",
                    entry.kind.as_str(),
                    entry.id
                )));
            }
            for domain in entry.param_domains.iter().flatten() {
                if !self.enum_by_domain.contains_key(domain) {
                    return Err(CatalogError::validation(format!(
                        "{} '{}' declares undeclared enum domain '{domain}'",
                        entry.kind.as_str(),
                        entry.id
                    )));
                }
            }
            if let Some(coverage) = &entry.reevaluation_coverage {
                let reeval_params: Vec<usize> = (0..entry.params.len())
                    .filter(|index| {
                        entry
                            .param_domains
                            .get(*index)
                            .and_then(Option::as_deref)
                            .is_some_and(|domain| domain.ends_with("Reeval"))
                    })
                    .collect();
                if reeval_params.len() != 1 {
                    return Err(CatalogError::validation(format!(
                        "{} '{}' declares reevaluation coverage but has {} *Reeval parameters",
                        entry.kind.as_str(),
                        entry.id,
                        reeval_params.len()
                    )));
                }
                let domain_name = entry.param_domains[reeval_params[0]]
                    .as_deref()
                    .expect("filtered above");
                let domain = self
                    .enum_by_domain
                    .get(domain_name)
                    .map(|index| &self.enums[*index])
                    .expect("param domain validated above");
                for (member, positions) in coverage {
                    if !domain.members.iter().any(|m| m.member == *member) {
                        return Err(CatalogError::validation(format!(
                            "{} '{}' declares reevaluation coverage for '{member}', which is not a member of '{domain_name}'",
                            entry.kind.as_str(),
                            entry.id
                        )));
                    }
                    for position in positions {
                        if *position >= entry.params.len() {
                            return Err(CatalogError::validation(format!(
                                "{} '{}' reevaluation coverage for '{member}' names parameter {position}, out of {} params",
                                entry.kind.as_str(),
                                entry.id,
                                entry.params.len()
                            )));
                        }
                        if *position == reeval_params[0] {
                            return Err(CatalogError::validation(format!(
                                "{} '{}' reevaluation coverage for '{member}' covers the reevaluation parameter itself",
                                entry.kind.as_str(),
                                entry.id
                            )));
                        }
                    }
                }
                for member in &domain.members {
                    if !coverage.contains_key(&member.member) {
                        return Err(CatalogError::validation(format!(
                            "{} '{}' reevaluation coverage does not review '{domain_name}' member '{}'",
                            entry.kind.as_str(),
                            entry.id,
                            member.member
                        )));
                    }
                }
            }
            for aliases in &entry.param_aliases {
                for locale in aliases.keys() {
                    if !self.locales.contains(locale) {
                        return Err(CatalogError::validation(format!(
                            "{} '{}' declares parameter alias for undeclared locale '{}'",
                            entry.kind.as_str(),
                            entry.id,
                            locale
                        )));
                    }
                }
            }
        }
        Ok(())
    }

    fn insert_enum(&mut self, domain: EnumFile) -> Result<()> {
        let domain_index = self.enums.len();
        if self.enum_by_domain.contains_key(&domain.domain) {
            return Err(CatalogError::validation(format!(
                "duplicate enum domain '{}'",
                domain.domain
            )));
        }
        let primary = self.locales[0].clone();
        let mut domain_aliases = self.collect_aliases(
            &domain.domain,
            &format!("enum domain '{}'", domain.domain),
            domain.aliases,
            false,
            |catalog, locale, spelling| {
                let locale_map = catalog
                    .enum_alias_to_domain
                    .entry(locale.clone())
                    .or_default();
                if let Some(existing) = locale_map.get(spelling) {
                    return Err(CatalogError::validation(format!(
                        "duplicate enum domain alias '{spelling}' for '{existing}' and '{}' in locale '{locale}'",
                        domain.domain
                    )));
                }
                locale_map.insert(spelling.to_string(), domain.domain.clone());
                Ok(())
            },
        )?;
        domain_aliases
            .entry(primary.clone())
            .or_insert_with(|| vec![domain.domain.clone()]);
        self.enum_alias_to_domain
            .entry(primary.clone())
            .or_default()
            .entry(domain.domain.clone())
            .or_insert_with(|| domain.domain.clone());
        let mut members = Vec::new();
        for (member_index, member) in domain.members.into_iter().enumerate() {
            let aliases = self.collect_aliases(
                &member.id,
                &format!("enum {}::{}", domain.domain, member.id),
                member.aliases,
                true,
                |catalog, locale, spelling| {
                    let domain_map = catalog
                        .enum_alias_to_member
                        .entry(locale.clone())
                        .or_default()
                        .entry(domain.domain.clone())
                        .or_default();
                    if domain_map.contains_key(spelling) {
                        return Err(CatalogError::validation(format!(
                            "duplicate enum alias '{spelling}' in '{}' for locale '{locale}'",
                            domain.domain
                        )));
                    }
                    domain_map.insert(spelling.to_string(), (domain_index, member_index));
                    Ok(())
                },
            )?;
            members.push(EnumMember {
                member: member.id,
                aliases,
            });
        }
        self.enum_by_domain
            .insert(domain.domain.clone(), domain_index);
        self.enums.push(EnumDomain {
            domain: domain.domain,
            aliases: domain_aliases,
            members,
        });
        Ok(())
    }

    fn collect_aliases(
        &mut self,
        id: &str,
        label: &str,
        aliases: HashMap<String, AliasFile>,
        require_primary: bool,
        mut register: impl FnMut(&mut Self, &Locale, &str) -> Result<()>,
    ) -> Result<HashMap<Locale, Vec<String>>> {
        let mut collected = HashMap::new();
        for (locale_str, alias_file) in aliases {
            let locale = Locale::new(&locale_str);
            if !self.locales.contains(&locale) {
                return Err(CatalogError::validation(format!(
                    "{label} declares alias for undeclared locale '{locale}'"
                )));
            }
            let spellings = alias_file.into_spellings(id, locale.as_str())?;
            for spelling in &spellings {
                register(self, &locale, spelling)?;
            }
            collected.insert(locale, spellings);
        }
        let primary = &self.locales[0];
        if require_primary && !collected.contains_key(primary) {
            return Err(CatalogError::validation(format!(
                "{label} is missing a '{primary}' alias"
            )));
        }
        Ok(collected)
    }
}

/// Canonicalize catalog data: parse, validate, and re-serialize
/// deterministically (object keys sorted, stable formatting). Re-running on
/// the same input produces byte-identical output, so the data pipeline is
/// reproducible. Validation intentionally skips digest verification so a
/// stale digest can be repaired by [`build_canonical`].
pub fn canonicalize(json: &str) -> Result<String> {
    Catalog::load_unverified(json)?;
    let value: serde_json::Value = serde_json::from_str(json)
        .map_err(|error| CatalogError::malformed(format!("catalog data: {error}")))?;
    pretty_json(&value)
}

/// Rebuild the canonical catalog form with a fresh content digest: validate,
/// canonicalize, and (re)write the `digest` field. Byte-idempotent, so the
/// committed dataset and its digest are reproducible from the data file.
pub fn build_canonical(json: &str) -> Result<String> {
    let mut value: serde_json::Value = serde_json::from_str(json)
        .map_err(|error| CatalogError::malformed(format!("catalog data: {error}")))?;
    let digest = content_digest(json)?;
    if let Some(object) = value.as_object_mut() {
        object.insert("digest".to_string(), serde_json::Value::String(digest));
    }
    let output = pretty_json(&value)?;
    Catalog::load(&output)?;
    Ok(output)
}

/// The deterministic content digest of catalog data: sha256 of the canonical
/// (sorted-key, pretty) serialization of the parsed content with the
/// self-referential `digest` field removed. Independent of file formatting;
/// changes whenever any semantic content changes.
pub fn content_digest(json: &str) -> Result<String> {
    let mut value: serde_json::Value = serde_json::from_str(json)
        .map_err(|error| CatalogError::malformed(format!("catalog data: {error}")))?;
    if let Some(object) = value.as_object_mut() {
        object.remove("digest");
    }
    let canonical = pretty_json(&value)?;
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(canonical.trim_end().as_bytes());
    Ok(format!("{:x}", hasher.finalize()))
}

fn pretty_json(value: &serde_json::Value) -> Result<String> {
    serde_json::to_string_pretty(value)
        .map(|mut out| {
            out.push('\n');
            out
        })
        .map_err(|error| CatalogError::malformed(format!("cannot serialize catalog: {error}")))
}