globetrotter 0.0.12

Polyglot, type-safe internationalization
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! Version 1 configuration schema and source-located YAML parsing.

use super::ConfigError;
use super::settings::SettingsLayer;
use codespan_reporting::diagnostic::{Diagnostic, Label};
use globetrotter_model::{
    self as model,
    diagnostics::{DiagnosticExt, DisplayRepr, Span, Spanned},
};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use yaml_spanned::{Mapping, Sequence, Value, value::Kind};

/// A single parsed configuration together with its source location.
#[derive(Debug)]
pub struct ConfigFile<F> {
    /// The diagnostic file id of the source file, if any.
    pub file_id: Option<F>,
    /// The directory the configuration file was loaded from.
    pub config_dir: Option<PathBuf>,
    /// The parsed configuration.
    pub config: Config,
}

/// A list of parsed configurations.
pub type Configs<F> = Vec<ConfigFile<F>>;

/// Parses the `languages` field for one config.
///
/// A missing field appends a warning, or an error when `strict` is `true`, and
/// returns an empty list. Existing diagnostics are retained.
///
/// # Errors
///
/// Returns an error if the languages section is present but not a sequence, or if
/// any language value cannot be deserialized into a [`model::Language`].
pub fn parse_languages<F>(
    value: &yaml_spanned::Spanned<Value>,
    file_id: F,
    strict: bool,
    diagnostics: &mut Vec<Diagnostic<F>>,
) -> Result<Vec<Spanned<model::Language>>, ConfigError> {
    match value.get("languages") {
        None => {
            let diagnostic = Diagnostic::warning_or_error(strict)
                .with_message("empty languages")
                .with_labels(vec![Label::primary(file_id, value.span).with_message(
                    "no languages specified - no JSON translation file will be generated",
                )]);
            diagnostics.push(diagnostic);
            Ok(vec![])
        }
        Some(value) => {
            let languages = value
                .as_sequence()
                .ok_or_else(|| ConfigError::UnexpectedType {
                    message: "list of languages must be a sequence".to_string(),
                    found: value.kind(),
                    expected: vec![Kind::Sequence],
                    span: value.span().into(),
                })?;

            let languages = languages.iter().map(parse).collect::<Result<Vec<_>, _>>()?;
            Ok(languages)
        }
    }
}

/// Parses the optional config-wide `allow` list of lint suppressions.
///
/// Entries use the same spelling as a translation key's own `allow` list
/// (`lint:duplicate`, `lint:all`) and apply to every key this config lints.
///
/// # Errors
///
/// Returns an error if `allow` is present but is not a string or a sequence of
/// strings, or if any entry is not a valid
/// [`AllowEntry`](model::lint::AllowEntry).
pub fn parse_allow(
    value: &yaml_spanned::Spanned<Value>,
) -> Result<BTreeSet<model::lint::AllowEntry>, ConfigError> {
    let Some(value) = value.get("allow") else {
        return Ok(BTreeSet::new());
    };
    match value.as_ref() {
        Value::String(entry) => Ok([parse_allow_entry(entry, value.span().into())?].into()),
        Value::Sequence(entries) => entries
            .iter()
            .map(|entry| {
                let text = entry.as_str().ok_or_else(|| ConfigError::UnexpectedType {
                    message: "allow entries must be strings".to_string(),
                    expected: vec![Kind::String],
                    found: entry.kind(),
                    span: entry.span().into(),
                })?;
                parse_allow_entry(text, entry.span().into())
            })
            .collect(),
        _other => Err(ConfigError::UnexpectedType {
            message: "allow must be a string or a sequence of strings".to_string(),
            expected: vec![Kind::String, Kind::Sequence],
            found: value.kind(),
            span: value.span().into(),
        }),
    }
}

/// Parses one `allow` entry into a typed [`AllowEntry`](model::lint::AllowEntry),
/// rejecting anything that is not a prefixed, known entry so typos fail loudly
/// rather than silently doing nothing.
fn parse_allow_entry(entry: &str, span: Span) -> Result<model::lint::AllowEntry, ConfigError> {
    entry
        .parse::<model::lint::AllowEntry>()
        .map_err(|source| ConfigError::InvalidAllowEntry {
            entry: entry.to_string(),
            source,
            span,
        })
}

/// Parses a source-located typed value from YAML.
///
/// # Errors
///
/// Returns an error if the value cannot be deserialized into the target type.
pub fn parse<T: serde::de::DeserializeOwned>(
    value: &yaml_spanned::Spanned<Value>,
) -> Result<Spanned<T>, ConfigError> {
    let inner: T = yaml_spanned::from_value(value).map_err(|source| ConfigError::Serde {
        source,
        span: value.span().into(),
    })?;
    Ok(Spanned::new(value.span, inner))
}

/// Parses an optional source-located typed value from YAML.
///
/// # Errors
///
/// Returns an error if the value is present but cannot be deserialized into
/// the target type.
pub fn parse_optional<T: serde::de::DeserializeOwned>(
    value: Option<&yaml_spanned::Spanned<Value>>,
) -> Result<Option<Spanned<T>>, ConfigError> {
    value.map(|value| parse(value)).transpose()
}

/// Parses one input entry from YAML.
///
/// A null entry appends a diagnostic and returns `None`.
///
/// # Errors
///
/// Returns an error if the input entry has an unexpected type or is missing
/// required fields.
pub fn parse_input<F>(
    value: &yaml_spanned::Spanned<Value>,
    file_id: F,
    strict: bool,
    diagnostics: &mut Vec<Diagnostic<F>>,
) -> Result<Option<Input>, ConfigError> {
    match value.as_ref() {
        Value::Null => {
            let diagnostic = Diagnostic::warning_or_error(strict)
                .with_message("empty input")
                .with_labels(vec![
                    Label::primary(file_id, value.span).with_message("empty input will be ignored"),
                ]);
            diagnostics.push(diagnostic);
            Ok(None)
        }
        Value::String(path) => Ok(Some(Input {
            path_or_glob_pattern: Spanned::new(value.span, path.clone()),
            exclude: Vec::new(),
            prefix: None,
            prepend_filename: None,
            prepend_relative_path: None,
            separator: None,
        })),
        Value::Mapping(mapping) => {
            // Parse the required input path.
            let path_value = mapping.get("path").ok_or_else(|| ConfigError::MissingKey {
                key: "path".to_string(),
                message: "missing path to input file".to_string(),
                span: value.span.into(),
            })?;
            let path_or_glob_pattern = parse::<PathOrGlobPattern>(path_value)?;

            // Parse the exclusion field in either accepted shape.
            let exclude = match mapping.get("exclude") {
                None => Ok(vec![]),
                Some(yaml_spanned::Spanned {
                    span,
                    inner: Value::String(path_or_glob_pattern),
                }) => Ok(vec![Spanned::new(*span, path_or_glob_pattern.clone())]),
                Some(yaml_spanned::Spanned {
                    inner: Value::Sequence(_sequence),
                    ..
                }) => Ok(vec![]),
                Some(other) => Err(ConfigError::UnexpectedType {
                    message: "exclude must be a path or a sequence of paths".to_string(),
                    found: other.kind(),
                    expected: vec![Kind::Sequence, Kind::String],
                    span: other.span().into(),
                }),
            }?;

            // Parse the optional key-prefixing policy.
            let prefix = parse_optional::<String>(mapping.get("prefix"))?;
            let prepend_filename = parse_optional::<bool>(mapping.get("prepend_filename"))?;
            let prepend_relative_path =
                parse_optional::<bool>(mapping.get("prepend_relative_path"))?;
            let separator = parse_optional::<String>(mapping.get("separator"))?;
            Ok(Some(Input {
                path_or_glob_pattern,
                exclude,
                prefix,
                prepend_filename,
                prepend_relative_path,
                separator,
            }))
        }
        _ => Err(ConfigError::UnexpectedType {
            message: "input must be a path or a mapping".to_string(),
            found: value.kind(),
            expected: vec![Kind::Mapping, Kind::String],
            span: value.span().into(),
        }),
    }
}

/// Borrows a YAML value as a sequence.
///
/// # Errors
///
/// Returns an error if the value is not a sequence.
pub fn expect_sequence(value: &yaml_spanned::Spanned<Value>) -> Result<&Sequence, ConfigError> {
    value
        .as_sequence()
        .ok_or_else(|| ConfigError::UnexpectedType {
            message: "expected sequence".to_string(),
            expected: vec![Kind::Sequence],
            found: value.kind(),
            span: value.span().into(),
        })
}

/// Borrows a YAML value as a mapping together with its source span.
///
/// # Errors
///
/// Returns an error if the value is not a mapping.
pub fn expect_mapping(
    value: &yaml_spanned::Spanned<Value>,
) -> Result<(&yaml_spanned::spanned::Span, &Mapping), ConfigError> {
    let mapping = value
        .as_mapping()
        .ok_or_else(|| ConfigError::UnexpectedType {
            message: "expected mapping".to_string(),
            expected: vec![Kind::Mapping],
            found: value.kind(),
            span: value.span().into(),
        })?;
    Ok((value.span(), mapping))
}

/// Parses the Rust output configuration.
///
/// # Errors
///
/// Returns an error if the `rust`/`rs` output configuration has an unexpected
/// type or contains invalid output paths.
#[cfg(feature = "rust")]
pub fn parse_rust_outputs(
    value: &Mapping,
) -> Result<Option<globetrotter_rust::OutputConfig>, ConfigError> {
    use globetrotter_rust::config::OutputConfig;

    let Some(outputs) = value.get("rust").or_else(|| value.get("rs")) else {
        return Ok(None);
    };
    let paths = match outputs.as_ref() {
        Value::String(path) => Ok(vec![path.into()]),
        Value::Sequence(paths) => paths
            .iter()
            .map(|path| {
                let path = path
                    .as_string()
                    .ok_or_else(|| ConfigError::UnexpectedType {
                        message: "expected file path".to_string(),
                        expected: vec![Kind::String],
                        found: path.kind(),
                        span: path.span().into(),
                    })?;
                Ok(path.into())
            })
            .collect::<Result<Vec<PathBuf>, ConfigError>>(),
        other => Err(ConfigError::UnexpectedType {
            message: "expected file path or sequence of file paths".to_string(),
            expected: vec![Kind::Sequence, Kind::String],
            found: other.kind(),
            span: outputs.span().into(),
        }),
    }?;
    Ok(Some(OutputConfig {
        output_paths: paths,
    }))
}

/// Parses the TypeScript output configuration.
///
/// # Errors
///
/// Returns an error if the `typescript`/`ts` output configuration has an
/// unexpected type or contains invalid output paths.
#[cfg(feature = "typescript")]
pub fn parse_typescript_outputs(
    value: &Mapping,
) -> Result<Option<globetrotter_typescript::OutputConfig>, ConfigError> {
    use globetrotter_typescript::config::InterfaceTypeOutputConfig;

    let Some(outputs) = value.get("typescript").or_else(|| value.get("ts")) else {
        return Ok(None);
    };
    let (_span, outputs) = expect_mapping(outputs)?;

    let interface_type: Vec<_> = outputs
        .get("type")
        .or_else(|| outputs.get("interface"))
        .or_else(|| outputs.get("dts"))
        .map(|path| match path.as_ref() {
            Value::String(path) => Ok(vec![InterfaceTypeOutputConfig { path: path.into() }]),
            Value::Sequence(sequence) => {
                let interfaces = sequence
                    .iter()
                    .map(|path| {
                        let path = path
                            .as_string()
                            .ok_or_else(|| ConfigError::UnexpectedType {
                                message: "expected file path".to_string(),
                                expected: vec![Kind::String],
                                found: path.kind(),
                                span: path.span().into(),
                            })?;
                        Ok(InterfaceTypeOutputConfig { path: path.into() })
                    })
                    .collect::<Result<Vec<_>, ConfigError>>()?;
                Ok(interfaces)
            }
            other => Err(ConfigError::UnexpectedType {
                message: "expected file path or sequence of file paths".to_string(),
                expected: vec![Kind::Sequence, Kind::String],
                found: other.kind(),
                span: path.span().into(),
            }),
        })
        .transpose()?
        .unwrap_or_default();

    Ok(Some(globetrotter_typescript::OutputConfig {
        interface_type,
    }))
}

/// Parses the JSON output configuration.
///
/// # Errors
///
/// Returns an error if the `json`/`translations` output configuration has an
/// unexpected type or is missing required fields.
pub fn parse_json_outputs(value: &Mapping) -> Result<Vec<JsonOutputConfig>, ConfigError> {
    let Some(outputs) = value.get("json").or_else(|| value.get("translations")) else {
        return Ok(vec![]);
    };

    let parse_json_output =
        |value: &yaml_spanned::Spanned<Value>| -> Result<JsonOutputConfig, ConfigError> {
            match value.as_ref() {
                Value::String(path) => Ok(JsonOutputConfig {
                    path: Spanned::new(value.span, path.into()),
                    style: None,
                }),
                Value::Mapping(mapping) => {
                    // Parse the required path before its optional layout.
                    let path = mapping.get("path").ok_or_else(|| ConfigError::MissingKey {
                        key: "path".to_string(),
                        message: "missing path to output JSON file".to_string(),
                        span: value.span().into(),
                    })?;
                    let path = parse::<PathBuf>(path)?;
                    let style = parse_optional::<JsonOutputStyle>(mapping.get("style"))?;
                    Ok(JsonOutputConfig { path, style })
                }
                other => Err(ConfigError::UnexpectedType {
                    message: "expected file path or sequence of file paths".to_string(),
                    expected: vec![Kind::Sequence, Kind::String],
                    found: other.kind(),
                    span: value.span().into(),
                }),
            }
        };

    if let Value::Sequence(sequence) = outputs.as_ref() {
        let interfaces = sequence
            .iter()
            .map(&parse_json_output)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(interfaces)
    } else {
        let output = parse_json_output(outputs)?;
        Ok(vec![output])
    }
}

/// Parses the `inputs` or `translations` field for one config.
///
/// A missing field appends a diagnostic and returns an empty list. Null input
/// entries are omitted after [`parse_input`] reports them.
///
/// # Errors
///
/// Returns an error if the inputs section is present but not a sequence, or if
/// any input entry has an unexpected structure.
pub fn parse_inputs<F: Copy + PartialEq>(
    value: &yaml_spanned::Spanned<Value>,
    config_span: Option<yaml_spanned::spanned::Span>,
    file_id: F,
    strict: bool,
    diagnostics: &mut Vec<Diagnostic<F>>,
) -> Result<Vec<Input>, ConfigError> {
    let Some(inputs) = value.get("inputs").or(value.get("translations")) else {
        let diagnostic = Diagnostic::warning_or_error(strict)
            .with_message("empty inputs")
            .with_labels(vec![
                Label::primary(file_id, config_span.unwrap_or(value.span))
                    .with_message("no inputs specified - nothing will be generated"),
            ]);
        diagnostics.push(diagnostic);
        return Ok(vec![]);
    };
    let inputs = inputs
        .as_sequence()
        .ok_or_else(|| ConfigError::UnexpectedType {
            message: "inputs must be a sequence".to_string(),
            found: inputs.kind(),
            expected: vec![Kind::Sequence],
            span: inputs.span().into(),
        })?;
    let inputs = inputs
        .iter()
        .filter_map(|input| parse_input(input, file_id, strict, diagnostics).transpose())
        .collect::<Result<Vec<_>, _>>()?;
    Ok(inputs)
}

/// Parses the `outputs` field for one config.
///
/// A missing field appends a diagnostic and returns an empty output set.
///
/// # Errors
///
/// Returns an error if the `outputs` field is present but not a mapping, or if
/// any output sub-configuration has an unexpected shape.
pub fn parse_outputs<F: Copy + PartialEq>(
    value: &yaml_spanned::Spanned<Value>,
    config_span: Option<yaml_spanned::spanned::Span>,
    file_id: F,
    strict: bool,
    diagnostics: &mut Vec<Diagnostic<F>>,
) -> Result<Outputs, ConfigError> {
    let Some(outputs) = value.get("outputs") else {
        let diagnostic = Diagnostic::warning_or_error(strict)
            .with_message("empty outputs")
            .with_labels(vec![
                Label::primary(file_id, config_span.unwrap_or(value.span))
                    .with_message("no outputs specified - nothing will be generated"),
            ]);
        diagnostics.push(diagnostic);
        return Ok(Outputs::default());
    };
    let (_span, outputs) = expect_mapping(outputs)?;

    Ok(Outputs {
        json: parse_json_outputs(outputs)?,
        #[cfg(feature = "typescript")]
        typescript: parse_typescript_outputs(outputs)?,
        #[cfg(feature = "rust")]
        rust: parse_rust_outputs(outputs)?,
        #[cfg(feature = "golang")]
        golang: None,
        #[cfg(feature = "python")]
        python: None,
    })
}

/// Parses one configuration entry.
///
/// # Errors
///
/// Returns an error if required fields are missing, if fields have unexpected
/// types, or if nested `inputs`/`outputs` parsing fails.
pub fn parse_config<F: Copy + PartialEq>(
    name: Spanned<String>,
    config_span: Option<yaml_spanned::spanned::Span>,
    value: &yaml_spanned::Spanned<Value>,
    file_id: F,
    strict_override: Option<bool>,
    diagnostics: &mut Vec<Diagnostic<F>>,
) -> Result<Config, ConfigError> {
    // Parse settings that can later be overridden by the caller.
    let strict_config = parse_optional::<bool>(value.get("strict"))?.map(Spanned::into_inner);
    let strict = strict_override.unwrap_or(false);
    let languages = parse_languages(value, file_id, strict, diagnostics)?;
    let allow = parse_allow(value)?;
    let template_engine = parse_optional::<model::TemplateEngine>(
        value.get("engine").or_else(|| value.get("template_engine")),
    )?;
    let check_templates =
        parse_optional::<bool>(value.get("check_templates"))?.map(Spanned::into_inner);
    let dry_run = parse_optional::<bool>(value.get("dry_run"))?.map(Spanned::into_inner);
    let print_absolute_paths = parse_optional::<bool>(
        value
            .get("print_absolute_paths")
            .or_else(|| value.get("absolute")),
    )?
    .map(Spanned::into_inner);

    // Parse the input and output pipelines using the effective strictness.
    let inputs = parse_inputs(value, config_span, file_id, strict, diagnostics)?;
    let outputs = parse_outputs(value, config_span, file_id, strict, diagnostics)?;

    Ok(Config {
        name,
        languages,
        allow,
        settings: SettingsLayer {
            strict: strict_config,
            check_templates,
            dry_run,
            print_absolute_paths,
            template_engine,
        },
        inputs,
        outputs,
    })
}

/// Parses the top-level `config` or `configs` structure.
///
/// A single `config` receives the synthetic name `"config"`. A `configs`
/// sequence receives positional names, while a mapping preserves its names.
///
/// # Errors
///
/// Returns an error if the `config`/`configs` section has an unexpected type or
/// if any contained configuration cannot be parsed.
pub fn parse_configs<F: Copy + PartialEq>(
    value: &yaml_spanned::Spanned<Value>,
    config_dir: &Path,
    file_id: F,
    strict: Option<bool>,
    diagnostics: &mut Vec<Diagnostic<F>>,
) -> Result<Configs<F>, ConfigError> {
    if let Some(config) = value.get("config") {
        // Single unnamed configuration.
        let config = parse_config(
            Spanned::dummy("config".to_string()),
            None,
            config,
            file_id,
            strict,
            diagnostics,
        )?;
        return Ok(vec![ConfigFile {
            file_id: Some(file_id),
            config_dir: Some(config_dir.to_path_buf()),
            config,
        }]);
    }

    let Some(configs) = value.get("configs") else {
        let _diagnostic = Diagnostic::warning_or_error(strict.unwrap_or(false))
            .with_message("empty configurations")
            .with_labels(vec![Label::primary(file_id, value.span).with_message(
                "no configurations specified - no output will be generated",
            )]);
        return Ok(Configs::default());
    };

    // Named or positional configurations.
    match configs.as_ref() {
        Value::Sequence(seq) => seq
            .iter()
            .enumerate()
            .map(|(idx, value)| {
                let name = format!("configs[{idx}]");
                let config = parse_config(
                    Spanned::dummy(name),
                    Some(value.span),
                    value,
                    file_id,
                    strict,
                    diagnostics,
                )?;
                Ok(ConfigFile {
                    file_id: Some(file_id),
                    config_dir: Some(config_dir.to_path_buf()),
                    config,
                })
            })
            .collect::<Result<Configs<F>, _>>(),
        Value::Mapping(mapping) => mapping
            .iter()
            .map(|(name_value, value)| {
                let name = Spanned::new(
                    name_value.span,
                    name_value.as_str().unwrap_or_default().to_string(),
                );
                let config = parse_config(
                    name,
                    Some(name_value.span),
                    value,
                    file_id,
                    strict,
                    diagnostics,
                )?;
                Ok(ConfigFile {
                    file_id: Some(file_id),
                    config_dir: Some(config_dir.to_path_buf()),
                    config,
                })
            })
            .collect::<Result<Configs<F>, _>>(),
        other => Err(ConfigError::UnexpectedType {
            message: "configurations must either be a sequence or a named mapping".to_string(),
            expected: vec![
                yaml_spanned::value::Kind::Mapping,
                yaml_spanned::value::Kind::Sequence,
            ],
            found: other.kind(),
            span: configs.span().into(),
        }),
    }
}

/// A file path or glob pattern, stored as a string.
pub type PathOrGlobPattern = String;

/// A single translation input source.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Input {
    /// The path or glob pattern selecting the input file(s).
    pub path_or_glob_pattern: Spanned<PathOrGlobPattern>,
    /// Paths or glob patterns to exclude from the matched inputs.
    pub exclude: Vec<Spanned<PathOrGlobPattern>>,
    /// An optional prefix prepended to every key from this input.
    pub prefix: Option<Spanned<String>>,
    /// Whether to prefix keys with the input file's stem.
    pub prepend_filename: Option<Spanned<bool>>,
    /// Whether to prefix keys with the input file's relative path segments.
    pub prepend_relative_path: Option<Spanned<bool>>,
    /// The separator used when joining prefix segments with keys.
    pub separator: Option<Spanned<String>>,
}

impl Input {
    /// Creates an input with no exclusions or key-prefix transformations.
    pub fn new(path_or_glob_pattern: impl Into<PathOrGlobPattern>) -> Self {
        Self {
            path_or_glob_pattern: Spanned::dummy(path_or_glob_pattern.into()),
            exclude: vec![],
            prefix: None,
            prepend_filename: None,
            prepend_relative_path: None,
            separator: None,
        }
    }

    /// Sets patterns to exclude from the matched inputs.
    #[must_use]
    pub fn with_exclude(mut self, exclude: impl IntoIterator<Item = PathOrGlobPattern>) -> Self {
        self.exclude = exclude.into_iter().map(Spanned::dummy).collect();
        self
    }

    /// Sets the prefix prepended to every key from this input.
    #[must_use]
    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = Some(Spanned::dummy(prefix.into()));
        self
    }

    /// Sets whether keys are prefixed with the input file's stem.
    #[must_use]
    pub fn with_prepend_filename(mut self, prepend_filename: bool) -> Self {
        self.prepend_filename = Some(Spanned::dummy(prepend_filename));
        self
    }

    /// Sets whether keys are prefixed with the input file's relative path.
    #[must_use]
    pub fn with_prepend_relative_path(mut self, prepend_relative_path: bool) -> Self {
        self.prepend_relative_path = Some(Spanned::dummy(prepend_relative_path));
        self
    }

    /// Sets the separator used when joining prefix segments with keys.
    #[must_use]
    pub fn with_separator(mut self, separator: impl Into<String>) -> Self {
        self.separator = Some(Spanned::dummy(separator.into()));
        self
    }
}

impl std::fmt::Display for Input {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Input")
            .field("path_or_glob_pattern", &self.path_or_glob_pattern.display())
            .field("prefix", &self.prefix.as_ref().map(Spanned::display))
            .field(
                "prepend_filename",
                &self.prepend_filename.as_ref().map(Spanned::display),
            )
            .field(
                "prepend_relative_path",
                &self.prepend_relative_path.as_ref().map(Spanned::display),
            )
            .field("separator", &self.separator.as_ref().map(Spanned::display))
            .field(
                "exclude",
                &self
                    .exclude
                    .iter()
                    .map(Spanned::display)
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

/// The layout style used when writing a JSON translation file.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, Default,
)]
pub enum JsonOutputStyle {
    /// A flat `translations` map keyed by fully qualified translation key.
    #[default]
    Flat,
}

/// Configuration for a single JSON translation output.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct JsonOutputConfig {
    /// The output path template for the generated JSON file.
    pub path: Spanned<PathBuf>,
    /// The layout style of the generated JSON.
    pub style: Option<Spanned<JsonOutputStyle>>,
}

impl JsonOutputConfig {
    /// Creates a flat JSON output at the given path template.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            path: Spanned::dummy(path.into()),
            style: None,
        }
    }

    /// Sets the layout style of the generated JSON.
    #[must_use]
    pub fn with_style(mut self, style: impl Into<JsonOutputStyle>) -> Self {
        self.style = Some(Spanned::dummy(style.into()));
        self
    }
}

/// The set of outputs to generate for a single configuration.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct Outputs {
    /// JSON translation outputs.
    pub json: Vec<JsonOutputConfig>,

    /// TypeScript output configuration.
    #[cfg(feature = "typescript")]
    pub typescript: Option<globetrotter_typescript::OutputConfig>,

    /// Rust output configuration.
    #[cfg(feature = "rust")]
    pub rust: Option<globetrotter_rust::OutputConfig>,

    /// Go output configuration.
    #[cfg(feature = "golang")]
    pub golang: Option<globetrotter_golang::OutputConfig>,

    /// Python output configuration.
    #[cfg(feature = "python")]
    pub python: Option<globetrotter_python::OutputConfig>,
}

impl Outputs {
    /// Creates an empty output set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets all JSON outputs, replacing any existing entries.
    #[must_use]
    pub fn with_json(mut self, json: impl IntoIterator<Item = JsonOutputConfig>) -> Self {
        self.json = json.into_iter().collect();
        self
    }

    /// Sets the TypeScript output configuration.
    #[cfg(feature = "typescript")]
    #[must_use]
    pub fn with_typescript(
        mut self,
        typescript: impl Into<globetrotter_typescript::OutputConfig>,
    ) -> Self {
        self.typescript = Some(typescript.into());
        self
    }

    /// Sets the Rust output configuration.
    #[cfg(feature = "rust")]
    #[must_use]
    pub fn with_rust(mut self, rust: impl Into<globetrotter_rust::OutputConfig>) -> Self {
        self.rust = Some(rust.into());
        self
    }

    /// Sets the Go output configuration.
    #[cfg(feature = "golang")]
    #[must_use]
    pub fn with_golang(mut self, golang: impl Into<globetrotter_golang::OutputConfig>) -> Self {
        self.golang = Some(golang.into());
        self
    }

    /// Sets the Python output configuration.
    #[cfg(feature = "python")]
    #[must_use]
    pub fn with_python(mut self, python: impl Into<globetrotter_python::OutputConfig>) -> Self {
        self.python = Some(python.into());
        self
    }
}

impl std::fmt::Display for Outputs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("Outputs");
        s.field("json", &self.json);
        #[cfg(feature = "typescript")]
        s.field("typescript", &self.typescript);
        #[cfg(feature = "rust")]
        s.field("rust", &self.rust);
        #[cfg(feature = "golang")]
        s.field("golang", &self.golang);
        #[cfg(feature = "python")]
        s.field("python", &self.python);

        s.finish()
    }
}

impl Outputs {
    /// Returns `true` if no outputs are configured.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        if !self.json.is_empty() {
            return false;
        }

        #[cfg(feature = "typescript")]
        if self.typescript.as_ref().is_some_and(|c| !c.is_empty()) {
            return false;
        }

        #[cfg(feature = "rust")]
        if self.rust.as_ref().is_some_and(|c| !c.is_empty()) {
            return false;
        }

        #[cfg(feature = "golang")]
        if self.golang.as_ref().is_some_and(|c| !c.is_empty()) {
            return false;
        }

        #[cfg(feature = "python")]
        if self.python.as_ref().is_some_and(|c| !c.is_empty()) {
            return false;
        }

        true
    }
}

/// A single named translation configuration.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Config {
    /// The name of the configuration.
    pub name: Spanned<String>,
    /// The languages that must be present in the translations.
    pub languages: Vec<Spanned<model::Language>>,
    /// Lints suppressed for every key this configuration lints.
    pub allow: BTreeSet<model::lint::AllowEntry>,
    /// This config's settings layer.
    ///
    /// These are raw, unresolved values: caller overrides and built-in
    /// defaults are merged in by
    /// [`Settings::resolve`](super::settings::Settings::resolve). Read settled
    /// values from the resolved [`Settings`](super::settings::Settings), never
    /// from here.
    pub settings: SettingsLayer,

    /// The translation input sources.
    pub inputs: Vec<Input>,
    /// The outputs to generate.
    pub outputs: Outputs,
}

impl Config {
    /// Creates an otherwise empty configuration with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: Spanned::dummy(name.into()),
            languages: vec![],
            allow: BTreeSet::new(),
            settings: SettingsLayer::default(),
            inputs: vec![],
            outputs: Outputs::default(),
        }
    }

    /// Adds a required language.
    #[must_use]
    pub fn with_language(mut self, language: impl Into<model::Language>) -> Self {
        self.languages.push(Spanned::dummy(language.into()));
        self
    }

    /// Adds multiple required languages.
    #[must_use]
    pub fn with_languages(mut self, languages: impl IntoIterator<Item = model::Language>) -> Self {
        self.languages
            .extend(languages.into_iter().map(Spanned::dummy));
        self
    }

    /// Sets whether templates are validated.
    #[must_use]
    pub fn with_check_templates(mut self, check_templates: bool) -> Self {
        self.settings.check_templates = Some(check_templates);
        self
    }

    /// Sets whether warnings are promoted to errors.
    #[must_use]
    pub fn with_strict(mut self, strict: bool) -> Self {
        self.settings.strict = Some(strict);
        self
    }

    /// Sets whether outputs are computed but not written to disk.
    #[must_use]
    pub fn with_dry_run(mut self, dry_run: bool) -> Self {
        self.settings.dry_run = Some(dry_run);
        self
    }

    /// Sets whether output paths are logged as absolute paths.
    #[must_use]
    pub fn with_print_absolute_paths(mut self, print_absolute_paths: bool) -> Self {
        self.settings.print_absolute_paths = Some(print_absolute_paths);
        self
    }

    /// Sets the template engine.
    #[must_use]
    pub fn with_template_engine(
        mut self,
        template_engine: impl Into<model::TemplateEngine>,
    ) -> Self {
        self.settings.template_engine = Some(Spanned::dummy(template_engine.into()));
        self
    }

    /// Adds one input source.
    #[must_use]
    pub fn with_input(mut self, input: impl Into<Input>) -> Self {
        self.inputs.push(input.into());
        self
    }

    /// Adds multiple input sources.
    #[must_use]
    pub fn with_inputs(mut self, inputs: impl IntoIterator<Item = Input>) -> Self {
        self.inputs.extend(inputs);
        self
    }

    /// Sets the outputs to generate.
    #[must_use]
    pub fn with_outputs(mut self, outputs: impl Into<Outputs>) -> Self {
        self.outputs = outputs.into();
        self
    }
}

impl std::fmt::Display for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Config")
            .field("name", &self.name.display())
            .field(
                "languages",
                &self
                    .languages
                    .iter()
                    .map(Spanned::display)
                    .collect::<Vec<_>>(),
            )
            .field(
                "template_engine",
                &self.settings.template_engine.as_ref().map(Spanned::display),
            )
            .field("check_templates", &self.settings.check_templates)
            .field("strict", &self.settings.strict)
            .field("dry_run", &self.settings.dry_run)
            .field("print_absolute_paths", &self.settings.print_absolute_paths)
            .field(
                "inputs",
                &self.inputs.iter().map(DisplayRepr).collect::<Vec<_>>(),
            )
            .field("outputs", &DisplayRepr(&self.outputs))
            .finish()
    }
}

impl Config {
    /// Returns `true` if the configuration has no inputs or no outputs.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inputs.is_empty() || self.outputs.is_empty()
    }
}