diplodocus 0.15.0

Build coherent documentation websites for polyglot software projects.
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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
//! Typed parsing and loading of workspace configuration.
//!
//! These types retain declarations before semantic validation. Parsing checks
//! YAML syntax, field types, required fields, supported enum values, and coherent
//! collection execution settings. It does not resolve filesystem paths or
//! references, validate document execution authority, or discover inputs.
//! Use [`crate::configuration_validation::validate_configuration`] for workspace
//! identity and reference validation.
//! Use [`crate::paths::resolve_workspace_paths`] for explicit filesystem validation.

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

use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;

use crate::diagnostics::{
    Diagnostic, DiagnosticCode, DiagnosticEntity, DiagnosticPath, DiagnosticSource, Severity,
};
use crate::documents::AuthoredFormat;
use crate::ir::SourceSpan;

/// The declarations in a root `diplodocus.yaml` file, in source order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct WorkspaceConfiguration {
    /// Project-wide identity.
    pub project: ProjectConfiguration,
    /// Portable defaults used when generating a site from the snapshot.
    #[serde(default, skip_serializing_if = "PresentationDefaults::is_default")]
    pub presentation: PresentationDefaults,
    /// Explicit local source repositories; omission declares none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub repositories: Vec<RepositoryConfiguration>,
    /// Explicit bundles for browser components in authored pages.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub components: Vec<crate::components::ComponentConfiguration>,
    /// Explicit packages and internal components to document; omission declares none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub packages: Vec<PackageConfiguration>,
    /// Portable API bundles to import.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub package_bundles: Vec<PackageBundleConfiguration>,
    /// Authored content collections.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub content: Vec<ContentConfiguration>,
    /// Explicit conceptual API groups.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub concepts: Vec<ConceptConfiguration>,
    /// Implementation and release relationships between packages.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub relationships: Vec<RelationshipConfiguration>,
}

/// A package bundle source and its expected package identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PackageBundleConfiguration {
    /// Package ID declared by the producer.
    pub package: String,
    /// Artifact path relative to the configuration directory.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,
    /// Public GitHub release asset and its pins.
    #[serde(
        rename = "github-release",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub github_release: Option<GitHubBundleRelease>,
    /// Site-relative package root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mount: Option<String>,
    /// Use the explicitly declared local package.
    #[serde(rename = "local-override", default, skip_serializing_if = "is_false")]
    pub local_override: bool,
}

fn is_false(value: &bool) -> bool {
    !value
}

/// Coordinates and integrity pins for a public GitHub release asset.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GitHubBundleRelease {
    /// GitHub owner and repository.
    pub repository: String,
    /// Explicit release tag.
    pub tag: String,
    /// Uploaded asset filename.
    pub asset: String,
    /// Full producer source commit.
    pub revision: String,
    /// SHA-256 of the SQLite file.
    pub sha256: String,
}

pub(crate) fn valid_package_mount(path: &str) -> bool {
    path.split('/').all(|part| {
        !part.is_empty()
            && part
                .bytes()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_'))
    }) && !matches!(
        path.split('/').next(),
        Some("assets" | "__diplodocus" | "_redirects")
    )
}

/// Project-wide documentation settings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ProjectConfiguration {
    /// Display name of the project.
    pub name: String,
}

/// Portable site metadata, independent of extraction and execution policy.
///
/// The built-in theme escapes text and uses validated branding images.
/// No local theme paths, output directories, or execution authority belong here.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct PresentationDefaults {
    /// Public files retained even when no authored document references them.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub assets: Vec<SiteAsset>,
    /// Icon and web manifest links included in every complete HTML page.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub icons: Vec<SiteIcon>,
    /// Site title and branding; `None` uses the workspace's project name.
    pub title: Option<String>,
    /// Default HTML and social description, overridden by page metadata.
    pub description: Option<String>,
    /// Metadata overrides keyed by generated site-relative HTML path.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub pages: BTreeMap<String, PageMetadata>,
    /// Optional wide, centered homepage, with the same navbar as documentation pages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub home: Option<HomeDefaults>,
    /// Additional project sections shown after Guide in the navbar.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub sections: Vec<NavigationSection>,
    /// Repository links shown in the navbar.
    #[serde(skip_serializing_if = "HeaderDefaults::is_default")]
    pub header: HeaderDefaults,
    /// Authored navigation trees; omission keeps automatic directory grouping.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sidebar: Option<SidebarConfiguration>,
    /// Optional image shown before the site title in the navbar's home link.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logo: Option<LogoDefaults>,
    /// Optional site-wide image and accessible description for link previews.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub open_graph: Option<OpenGraphDefaults>,
    /// Public site root, including any hosting prefix; `None` omits crawler metadata.
    #[serde(
        deserialize_with = "deserialize_site_url",
        skip_serializing_if = "Option::is_none"
    )]
    pub site_url: Option<String>,
    /// Public URL spelling used by page links, search, and crawler metadata.
    #[serde(skip_serializing_if = "CanonicalUrlStyle::is_default")]
    pub canonical_url_style: CanonicalUrlStyle,
    /// Permanent redirects from old site-root URL paths to generated HTML paths.
    /// Destinations follow `canonical_url_style`; sources omit the hosting prefix.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub redirects: BTreeMap<String, DiagnosticPath>,
    /// Legacy fragment IDs attached to headings or API targets on generated HTML pages.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub fragment_aliases: BTreeMap<String, BTreeMap<String, FragmentAliasTarget>>,
    /// Optional notices and links shown at the bottom of every page.
    #[serde(skip_serializing_if = "FooterDefaults::is_default")]
    pub footer: FooterDefaults,
}

/// Portable header navigation settings.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct HeaderDefaults {
    /// Group multiple packages under API by default, or show separate links.
    #[serde(skip_serializing_if = "ApiNavigation::is_default")]
    pub api: ApiNavigation,
    /// Repository IDs in display order; omission includes all public repositories.
    /// An empty list hides repository links.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repositories: Option<Vec<String>>,
}

impl HeaderDefaults {
    fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

/// How the built-in navbar displays package API links.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ApiNavigation {
    /// Show each visible package as a separate navbar link.
    Links,
    /// Group multiple visible packages in an API dropdown.
    #[default]
    Dropdown,
}

impl ApiNavigation {
    fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

/// A maintained destination for a legacy fragment ID.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum FragmentAliasTarget {
    /// Exact plain-text heading, with whitespace collapsed.
    Heading(String),
    /// Existing canonical heading or API anchor, without URL encoding.
    Anchor(String),
}

/// Head metadata for a generated page, independent of its visible content.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct PageMetadata {
    /// Complete browser and social card title, without an automatic site suffix.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Page description; omission inherits the site description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// A public file copied from a declared repository to an explicit site path.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SiteAsset {
    /// Repository containing the source file.
    pub repository: String,
    /// Repository-relative source file path.
    pub path: DiagnosticPath,
    /// Site-relative publication path, independent of the hosting prefix.
    pub publish: DiagnosticPath,
}

/// A link to a declared public icon or web manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SiteIcon {
    /// Publication path of a file in `presentation.assets`.
    pub path: DiagnosticPath,
    /// Link relationship; omission selects `icon`.
    #[serde(default)]
    pub rel: SiteIconRel,
    /// Optional MIME type hint, checked against the publication extension.
    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
    pub media_type: Option<String>,
    /// Optional icon dimensions, such as `any` or `180x180`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sizes: Option<String>,
}

/// Supported public icon and manifest link relationships.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SiteIconRel {
    /// Browser tab or shortcut icon.
    #[default]
    Icon,
    /// Home screen icon on Apple devices.
    AppleTouchIcon,
    /// Web application manifest.
    Manifest,
}

impl SiteIconRel {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Icon => "icon",
            Self::AppleTouchIcon => "apple-touch-icon",
            Self::Manifest => "manifest",
        }
    }
}

/// An explicit sidebar for every page, or sidebars selected by URL directory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SidebarConfiguration {
    /// The same authored navigation on every page.
    Single(Vec<SidebarItem>),
    /// The longest matching site-root directory prefix selects the sidebar.
    Multiple(BTreeMap<String, Vec<SidebarItem>>),
}

impl SidebarConfiguration {
    pub(crate) fn for_route(&self, route: &str) -> Option<(&str, &[SidebarItem])> {
        match self {
            Self::Single(items) => Some(("/", items)),
            Self::Multiple(sidebars) => sidebars
                .iter()
                .filter(|(prefix, _)| route.starts_with(prefix.trim_start_matches('/')))
                .max_by_key(|(prefix, _)| prefix.len())
                .map(|(prefix, items)| (prefix.as_str(), items.as_slice())),
        }
    }
}

/// A sidebar link or a group containing further links and groups.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SidebarItem {
    /// Visible label, rendered as plain text.
    pub text: String,
    /// Generated site-relative HTML route, independent of the public URL style.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link: Option<DiagnosticPath>,
    /// Children in display order; groups may also link to a landing page.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub items: Vec<SidebarItem>,
    /// Enable collapse controls, initially closed when true and open when false.
    /// Omission renders a permanently expanded group.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub collapsed: Option<bool>,
}

/// A project navigation section containing pages beneath its landing page's directory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct NavigationSection {
    /// Visible navbar and sidebar heading, without Markdown or HTML.
    pub label: String,
    /// Generated route of a visible project page, such as `reference/index.html`.
    pub path: DiagnosticPath,
}

impl NavigationSection {
    pub(crate) fn prefix(&self) -> &str {
        self.path.as_str().strip_suffix("index.html").unwrap_or("")
    }
}

/// Content for the built-in landing page at the site root.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct HomeDefaults {
    /// Main heading, rendered as plain text; newlines separate lines.
    pub tagline: String,
    /// Introduction below the main heading, rendered as plain text.
    pub description: String,
    /// Generated HTML route opened by the navbar's Guide link.
    pub guide: DiagnosticPath,
    /// Call-to-action links in display order; the first receives emphasis.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub actions: Vec<HomeAction>,
    /// Linked feature descriptions in display order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<HomeFeature>,
}

/// A homepage action pointing to a generated page or an external website.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct HomeAction {
    /// Visible link text, without HTML or Markdown.
    pub label: String,
    /// Exactly one generated page path or absolute HTTP or HTTPS URL.
    #[serde(flatten)]
    pub target: HomeActionTarget,
    /// Optional decorative icon shown before the link text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<HomeActionIcon>,
}

/// The destination of a homepage action.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HomeActionTarget {
    /// Normalized site-relative HTML artifact path, including its extension.
    Path(DiagnosticPath),
    /// Absolute HTTP or HTTPS destination without credentials or whitespace.
    Url(#[serde(deserialize_with = "deserialize_external_url")] String),
}

impl<'de> Deserialize<'de> for HomeAction {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(rename_all = "kebab-case", deny_unknown_fields)]
        struct Declaration {
            label: String,
            path: Option<DiagnosticPath>,
            url: Option<String>,
            icon: Option<HomeActionIcon>,
        }

        let declaration = Declaration::deserialize(deserializer)?;
        let target = match (declaration.path, declaration.url) {
            (Some(path), None) => HomeActionTarget::Path(path),
            (None, Some(url)) => {
                validate_external_url(&url).map_err(D::Error::custom)?;
                HomeActionTarget::Url(url)
            }
            _ => {
                return Err(D::Error::custom(
                    "homepage actions require exactly one of path or url",
                ));
            }
        };
        Ok(Self {
            label: declaration.label,
            target,
            icon: declaration.icon,
        })
    }
}

/// A built-in SVG icon for a homepage action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HomeActionIcon {
    /// An arrow pointing right.
    ArrowRight,
    /// An open book.
    BookOpen,
    /// A pair of angle brackets.
    Code,
    /// A downward arrow above a tray.
    Download,
    /// A command prompt in a terminal window.
    Terminal,
}

/// A feature card pointing to its documentation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct HomeFeature {
    /// Short feature heading, without HTML or Markdown.
    pub title: String,
    /// Explanation, without HTML or Markdown.
    pub description: String,
    /// Normalized site-relative HTML artifact path, including its extension.
    pub path: DiagnosticPath,
}

/// A checked-in branding image within an explicitly declared repository.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct LogoDefaults {
    /// ID of the repository containing the image.
    pub repository: String,
    /// Normalized repository-relative path to an SVG, PNG, or JPEG file.
    pub path: DiagnosticPath,
}

/// A checked-in social preview image within an explicitly declared repository.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct OpenGraphDefaults {
    /// ID of the repository containing the image.
    pub repository: String,
    /// Normalized repository-relative path to a PNG or JPEG file.
    pub path: DiagnosticPath,
    /// Accessible description of the image, without HTML or Markdown.
    pub alt: String,
}

impl PresentationDefaults {
    fn is_default(&self) -> bool {
        self == &Self::default()
    }

    pub(crate) fn site_base_url(&self) -> Result<Option<url::Url>, &'static str> {
        self.site_url.as_deref().map(parse_site_url).transpose()
    }
}

/// Portable footer content; omitted fields do not appear in the generated site.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct FooterDefaults {
    /// Free-form documentation release or branch label, independent of package versions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub docs_version: Option<String>,
    /// Complete copyright notice, including the symbol, years, and holder.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub copyright: Option<String>,
    /// Alternative licenses for the site's content, displayed with "or" between them.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub licenses: Vec<FooterLink>,
    /// Project links, in display order.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub links: Vec<FooterLink>,
    /// Whether to show a linked "Built with Diplodocus" credit.
    #[serde(deserialize_with = "deserialize_boolean")]
    pub built_with: bool,
}

impl FooterDefaults {
    fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

fn deserialize_boolean<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
    struct BooleanVisitor;

    impl<'de> serde::de::Visitor<'de> for BooleanVisitor {
        type Value = bool;

        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter.write_str("a boolean")
        }

        fn visit_bool<E: serde::de::Error>(self, value: bool) -> Result<bool, E> {
            Ok(value)
        }
    }

    // Preserve YAML scalar types instead of coercing quoted boolean text.
    deserializer.deserialize_any(BooleanVisitor)
}

/// A labeled external footer link.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct FooterLink {
    /// Link text, rendered without Markdown or HTML parsing.
    pub label: String,
    /// Absolute HTTP or HTTPS destination.
    #[serde(deserialize_with = "deserialize_external_url")]
    pub url: String,
}

fn deserialize_external_url<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<String, D::Error> {
    let value = String::deserialize(deserializer)?;
    validate_external_url(&value).map_err(D::Error::custom)?;
    Ok(value)
}

fn validate_external_url(value: &str) -> Result<(), &'static str> {
    let invalid =
        "external links must use absolute HTTP or HTTPS URLs without credentials or whitespace";
    let url = url::Url::parse(value).map_err(|_| invalid)?;
    let authority = value
        .split_once("://")
        .map(|(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or_default())
        .ok_or(invalid)?;
    if !matches!(url.scheme(), "http" | "https")
        || url.host_str().is_none()
        || authority.is_empty()
        || authority.contains('@')
        || value
            .chars()
            .any(|ch| ch.is_whitespace() || ch.is_control())
    {
        return Err(invalid);
    }
    Ok(())
}

/// How a host exposes the generated HTML files.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CanonicalUrlStyle {
    /// Preserve generated filenames, including `index.html`.
    #[default]
    File,
    /// Use directory URLs for index pages and omit other `.html` suffixes.
    Clean,
}

impl CanonicalUrlStyle {
    fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

fn deserialize_site_url<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<String>, D::Error> {
    let value = Option::<String>::deserialize(deserializer)?;
    if let Some(value) = &value {
        parse_site_url(value).map_err(D::Error::custom)?;
    }
    Ok(value)
}

fn parse_site_url(value: &str) -> Result<url::Url, &'static str> {
    let invalid = "presentation.site-url must be an absolute HTTP or HTTPS URL without credentials, query parameters, fragments, or whitespace";
    if value
        .chars()
        .any(|ch| ch.is_whitespace() || ch.is_control())
    {
        return Err(invalid);
    }
    let mut url = url::Url::parse(value).map_err(|_| invalid)?;
    let authority = value
        .split_once("://")
        .map(|(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or_default())
        .ok_or(invalid)?;
    if !matches!(url.scheme(), "http" | "https")
        || url.host_str().is_none()
        || authority.is_empty()
        || authority.contains('@')
        || url.query().is_some()
        || url.fragment().is_some()
    {
        return Err(invalid);
    }
    // A hosting prefix denotes a directory even when its declaration omits the slash.
    if !url.path().ends_with('/') {
        url.set_path(&format!("{}/", url.path()));
    }
    Ok(url)
}

/// An explicitly supplied local source repository.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct RepositoryConfiguration {
    /// Stable repository identifier.
    pub id: String,
    /// Source root, relative to the configuration directory.
    pub path: PathBuf,
    /// Canonical source origin, when supplied.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Optional forge-specific template for revision, path, and line links.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_link_template: Option<String>,
    /// Explicit revision, including for sources without version-control metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
}

/// A package or internal component with explicit extraction targets.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct PackageConfiguration {
    /// Stable package identity used by references and relationships.
    pub id: String,
    /// Display name of the package.
    pub name: String,
    /// Site-wide URL slug, independent of the ecosystem and published name.
    pub slug: String,
    /// Package ecosystem identifier.
    pub ecosystem: String,
    /// Identifier of the repository containing the package.
    pub repository: String,
    /// Package root, relative to its repository.
    pub path: PathBuf,
    /// Metadata file, relative to the package root.
    pub metadata_path: PathBuf,
    /// GFM overview file, relative to the package root; omission discovers README.md.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub overview: Option<PathBuf>,
    /// Tracked dependencies and reuse policy for incremental extraction.
    #[serde(default, skip_serializing_if = "IncrementalConfiguration::is_default")]
    pub incremental: IncrementalConfiguration,
    /// Native R documentation generation and supplemental watched inputs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r: Option<RPackageConfiguration>,
    /// Distribution or component classification; defaults to `package`.
    #[serde(default)]
    pub kind: PackageKind,
    /// Navigation and search visibility; defaults to `public`.
    #[serde(default)]
    pub visibility: PackageVisibility,
    /// Explicit extraction targets; this field is required, but may be empty.
    /// An empty list disables API extraction for this package. Targets are never
    /// inferred from the ecosystem or files.
    pub targets: Vec<ExtractionTargetConfiguration>,
}

/// Documentation preparation for an R package, shared by its targets.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct RPackageConfiguration {
    /// Select roxygen2 automatically from package metadata unless overridden.
    pub documentation: RDocumentationMode,
    /// Additional maintained inputs, relative to the package root.
    pub extra_inputs: Vec<PathBuf>,
    /// Exclusively generated custom outputs, relative to the package root.
    pub generated_outputs: Vec<PathBuf>,
}

/// Authority for a package's Rd and namespace documentation inputs.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RDocumentationMode {
    /// Use roxygen2 when the package declares roxygen configuration.
    #[default]
    Auto,
    /// Generate documentation with the prepared roxygen2 installation.
    Roxygen2,
    /// Consume maintained Rd and namespace files without generation.
    Rd,
}

/// Declared inputs and dependencies for package or content preparation.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct IncrementalConfiguration {
    /// Reuse completed results when tracked inputs still match.
    pub cache: IncrementalCache,
    /// Workspace package IDs whose inputs affect this unit.
    pub depends_on: Vec<String>,
    /// Additional files or directories, relative to the unit's repository.
    pub extra_inputs: Vec<PathBuf>,
    /// Environment variable names whose values affect this unit.
    pub environment_variables: Vec<String>,
}

impl IncrementalConfiguration {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

/// Whether a unit permits reuse of completed preparation results.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum IncrementalCache {
    /// Reuse results after checking their recorded inputs.
    #[default]
    Auto,
    /// Prepare the unit afresh on each command attempt.
    Off,
}

/// Whether a documentation unit represents a package or an internal component.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PackageKind {
    /// A distributable package.
    #[default]
    Package,
    /// An explicitly documented component.
    Component,
}

/// Visibility of a package in generated navigation and search.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PackageVisibility {
    /// Included in project navigation and search.
    #[default]
    Public,
    /// Addressable and searchable, but omitted from project navigation by default.
    Internal,
    /// Available as a semantic target without navigation or search entries.
    Hidden,
}

/// An explicit source target consumed by one API extractor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ExtractionTargetConfiguration {
    /// Target identifier within its package.
    pub id: String,
    /// Selected extractor identifier, such as `python` or `r`.
    pub extractor: String,
    /// Source path, relative to the package root.
    pub path: PathBuf,
    /// Target role, such as `public-api` or `internal-api`.
    pub role: String,
    /// Cargo feature selection for Rust targets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rust: Option<RustTargetConfiguration>,
    /// Explicit supplemental Julia extension sources.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub julia: Option<JuliaTargetConfiguration>,
}

/// Static source selection for one explicit Julia target.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct JuliaTargetConfiguration {
    /// Extension entry files relative to the package root, each with its own module.
    pub extensions: Vec<PathBuf>,
}

/// Compiler feature selection for one explicit Rust library target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
pub struct RustTargetConfiguration {
    /// Additional Cargo features to enable.
    pub features: Vec<String>,
    /// Whether Cargo enables the crate's default features.
    #[serde(deserialize_with = "deserialize_boolean")]
    pub default_features: bool,
}

impl Default for RustTargetConfiguration {
    fn default() -> Self {
        Self {
            features: Vec::new(),
            default_features: true,
        }
    }
}

/// Which authored collection pages appear in sidebar navigation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ContentNavigation {
    /// Include every page in the collection.
    #[default]
    All,
    /// Include only the collection's root index page.
    Index,
    /// Omit the collection from sidebar navigation.
    None,
}

impl ContentNavigation {
    pub(crate) fn is_default(&self) -> bool {
        *self == Self::All
    }
}

/// An authored collection with independent ownership and source location.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct ContentConfiguration {
    /// Stable collection identifier.
    pub id: String,
    /// Reserved owner `project`, or a package identifier.
    pub owner: String,
    /// Repository containing the authored sources.
    pub repository: String,
    /// Source directory or single authored file, relative to its repository.
    pub path: PathBuf,
    /// URL mount beneath the owner's documentation root.
    pub mount: String,
    /// Explicit authored input profile.
    pub format: AuthoredFormat,
    /// Sidebar inclusion; does not affect rendering, search, or sitemaps.
    #[serde(default, skip_serializing_if = "ContentNavigation::is_default")]
    pub navigation: ContentNavigation,
    /// Tracked dependencies and reuse policy for authored preparation.
    #[serde(default, skip_serializing_if = "IncrementalConfiguration::is_default")]
    pub incremental: IncrementalConfiguration,
    /// Execution defaults to native knitr for Rmd and `never` for other formats.
    #[serde(default)]
    pub execution: ExecutionConfiguration,
}

impl<'de> Deserialize<'de> for ContentConfiguration {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // Validation needs both the profile and the completed execution table,
        // regardless of their order in the source or the deserialization entry point.
        #[derive(Default, Deserialize)]
        #[serde(rename_all = "kebab-case", deny_unknown_fields)]
        struct ExecutionDeclaration {
            mode: Option<ExecutionMode>,
            engine: Option<ExecutionEngine>,
            kernel: Option<String>,
            julia_project: Option<PathBuf>,
            #[serde(default)]
            declared_environment_inputs: Vec<PathBuf>,
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "kebab-case", deny_unknown_fields)]
        struct Declaration {
            id: String,
            owner: String,
            repository: String,
            path: PathBuf,
            mount: String,
            format: AuthoredFormat,
            #[serde(default)]
            navigation: ContentNavigation,
            #[serde(default)]
            incremental: IncrementalConfiguration,
            #[serde(default)]
            execution: Option<ExecutionDeclaration>,
        }

        let declaration = Declaration::deserialize(deserializer)?;
        let collection = Self {
            id: declaration.id,
            owner: declaration.owner,
            repository: declaration.repository,
            path: declaration.path,
            mount: declaration.mount,
            format: declaration.format,
            navigation: declaration.navigation,
            incremental: declaration.incremental,
            execution: {
                let execution = declaration.execution.unwrap_or_default();
                let rmd = declaration.format == AuthoredFormat::Rmd;
                ExecutionConfiguration {
                    mode: execution.mode.unwrap_or(if rmd {
                        ExecutionMode::Execute
                    } else {
                        ExecutionMode::Never
                    }),
                    engine: execution.engine.or(if rmd {
                        Some(ExecutionEngine::Knitr)
                    } else {
                        None
                    }),
                    kernel: execution.kernel,
                    julia_project: execution.julia_project,
                    declared_environment_inputs: execution.declared_environment_inputs,
                }
            },
        };
        collection
            .validate_execution()
            .map_err(|error| D::Error::custom(format!("content `{}`: {error}", collection.id)))?;
        Ok(collection)
    }
}

impl ContentConfiguration {
    /// Validate the profile, mode, engine, kernel, and environment declarations together.
    ///
    /// Deserialization calls this automatically. Call it again after modifying
    /// a collection programmatically. This performs no filesystem reads, kernel
    /// discovery, or execution. Paths and kernel spelling remain as declared.
    ///
    /// # Errors
    ///
    /// Returns the first contradictory or malformed setting. Environment paths
    /// must name explicit repository-relative files and be lexically distinct.
    /// [`crate::paths::resolve_workspace_paths`] checks file existence, type, and
    /// symlink containment separately. Reading file contents remains a later step.
    pub fn validate_execution(&self) -> Result<(), ExecutionConfigurationError> {
        let execution = &self.execution;
        if execution.julia_project.is_some()
            && !(self.format == AuthoredFormat::Documenter
                && execution.mode == ExecutionMode::Execute
                && execution.engine == Some(ExecutionEngine::Julia))
        {
            return Err(ExecutionConfigurationError::JuliaProject);
        }
        if self.format == AuthoredFormat::Rmd
            && (execution.mode != ExecutionMode::Execute
                || execution.engine != Some(ExecutionEngine::Knitr)
                || execution.kernel.is_some())
        {
            return Err(ExecutionConfigurationError::RmdExecution);
        }
        if execution.mode == ExecutionMode::Never {
            for (field, declared) in [
                ("engine", execution.engine.is_some()),
                ("kernel", execution.kernel.is_some()),
                (
                    "declared-environment-inputs",
                    !execution.declared_environment_inputs.is_empty(),
                ),
            ] {
                if declared {
                    return Err(ExecutionConfigurationError::InactiveSetting { field });
                }
            }
            return Ok(());
        }

        if self.format == AuthoredFormat::Gfm {
            return Err(ExecutionConfigurationError::GfmExecution);
        }
        if self.format == AuthoredFormat::Documenter
            && (execution.engine != Some(ExecutionEngine::Julia)
                || execution.kernel.is_some()
                || execution.julia_project.is_none())
        {
            return Err(ExecutionConfigurationError::DocumenterExecution);
        }
        if let Some(project) = &execution.julia_project {
            environment_input_components(project)
                .map_err(|_| ExecutionConfigurationError::JuliaProject)?;
            if !matches!(
                project.file_name().and_then(|name| name.to_str()),
                Some("Project.toml" | "JuliaProject.toml")
            ) {
                return Err(ExecutionConfigurationError::JuliaProject);
            }
        }
        if self.format == AuthoredFormat::Qmd {
            if execution.engine != Some(ExecutionEngine::Jupyter) {
                return Err(ExecutionConfigurationError::MissingEngine);
            }
            let kernel = execution
                .kernel
                .as_deref()
                .ok_or(ExecutionConfigurationError::MissingKernel)?;
            if !valid_kernel_selector(kernel) {
                return Err(ExecutionConfigurationError::InvalidKernel);
            }
        }

        let mut inputs = HashMap::new();
        for (index, path) in execution.declared_environment_inputs.iter().enumerate() {
            let components = environment_input_components(path).map_err(|reason| {
                ExecutionConfigurationError::InvalidEnvironmentInput { index, reason }
            })?;
            if let Some(first_index) = inputs.insert(components, index) {
                return Err(ExecutionConfigurationError::DuplicateEnvironmentInput {
                    index,
                    first_index,
                });
            }
        }
        Ok(())
    }
}

pub(crate) fn valid_kernel_selector(kernel: &str) -> bool {
    !kernel.is_empty()
        && !matches!(kernel, "." | "..")
        && kernel
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_'))
}

fn environment_input_components(path: &Path) -> Result<Vec<&str>, &'static str> {
    let path = path.to_str().ok_or("paths must be valid UTF-8")?;
    if path.is_empty() {
        return Err("paths must not be empty");
    }
    if path.starts_with('/')
        || (path.as_bytes().get(1) == Some(&b':') && path.as_bytes()[0].is_ascii_alphabetic())
    {
        return Err("paths must be relative to the collection's repository");
    }
    if path.contains('\\') {
        return Err("paths must use forward-slash separators");
    }
    if path.contains('\0') {
        return Err("paths must not contain NUL bytes");
    }
    if path.contains(['*', '?', '[', ']', '{', '}']) {
        return Err("declare individual files, not glob patterns");
    }
    if matches!(path.rsplit('/').next(), Some("" | "." | "..")) {
        return Err("declare a file, not a directory reference");
    }

    let mut components = Vec::new();
    for component in path.split('/') {
        match component {
            "" | "." => {}
            ".." => {
                if components.pop().is_none() {
                    return Err("paths must not escape the collection's repository");
                }
            }
            component => components.push(component),
        }
    }
    Ok(components)
}

/// A contradictory or malformed collection execution declaration.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ExecutionConfigurationError {
    /// R Markdown always uses native knitr execution.
    #[error("R Markdown requires `mode: execute`, `engine: knitr`, and no kernel")]
    RmdExecution,
    /// A display-only collection has execution-specific settings.
    #[error("`{field}` requires `mode: execute`")]
    InactiveSetting {
        /// The contradictory execution field.
        field: &'static str,
    },
    /// A GFM collection requested execution.
    #[error("`mode: execute` requires `format: qmd`")]
    GfmExecution,
    /// Documenter execution requires a prepared native Julia environment.
    #[error(
        "Documenter execution requires `engine: julia`, `julia-project: path/to/Project.toml`, and no kernel"
    )]
    DocumenterExecution,
    /// A Julia environment selector is absent, misplaced, or malformed.
    #[error(
        "`julia-project` must name a repository-relative Project.toml or JuliaProject.toml for Documenter execution with `engine: julia`"
    )]
    JuliaProject,
    /// Execution has no explicitly selected Jupyter engine.
    #[error("`mode: execute` requires `engine: jupyter`")]
    MissingEngine,
    /// Execution has no explicitly selected kernel.
    #[error("`mode: execute` requires an explicit kernel")]
    MissingKernel,
    /// The kernel selector is empty, a path, or outside the supported ASCII syntax.
    #[error(
        "invalid kernel selector: use ASCII letters, digits, `-`, `.`, or `_`, excluding empty names, `.` and `..`"
    )]
    InvalidKernel,
    /// An environment input does not declare an explicit repository-relative file.
    #[error("invalid `declared-environment-inputs[{index}]`: {reason}")]
    InvalidEnvironmentInput {
        /// Zero-based index of the invalid declaration.
        index: usize,
        /// Explanation of the violated path rule.
        reason: &'static str,
    },
    /// Two environment declarations normalize to the same relative path.
    #[error("`declared-environment-inputs[{index}]` duplicates input {first_index}")]
    DuplicateEnvironmentInput {
        /// Zero-based index of the duplicate declaration.
        index: usize,
        /// Zero-based index of the first declaration of that path.
        first_index: usize,
    },
}

impl ExecutionConfigurationError {
    /// Identify the collection whose programmatically constructed execution
    /// settings failed validation. No source path or span is invented.
    /// Callers with source context can attach it to the returned diagnostic.
    pub fn to_diagnostic(&self, collection: impl Into<String>) -> Diagnostic {
        Diagnostic::new(
            DiagnosticCode::InvalidExecutionConfiguration,
            Severity::Error,
            self.to_string(),
        )
        .with_entity(DiagnosticEntity::Content {
            id: collection.into(),
        })
    }
}

/// Declared execution settings, validated in their owning collection's context.
///
/// Standalone deserialization checks field types. Collection deserialization also
/// checks their consistency through [`ContentConfiguration::validate_execution`].
/// Document authority and filesystem validation remain necessary before execution.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ExecutionConfiguration {
    /// Requested mode; defaults to `never`.
    #[serde(default)]
    pub mode: ExecutionMode,
    /// Selected execution engine, when declared.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub engine: Option<ExecutionEngine>,
    /// Explicit kernel selector, such as `python3` or `ir`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kernel: Option<String>,
    /// Prepared native Julia environment's repository-relative project file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub julia_project: Option<PathBuf>,
    /// Environment manifests or lockfiles, relative to the collection's repository.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub declared_environment_inputs: Vec<PathBuf>,
}

/// Workspace-level authored execution mode.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExecutionMode {
    /// Keep cells display-only.
    #[default]
    Never,
    /// Request execution subject to the collection and document policies.
    Execute,
}

/// Supported authored execution engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExecutionEngine {
    /// A page-scoped Jupyter kernel session.
    Jupyter,
    /// A native R session using knitr.
    Knitr,
    /// A native Julia process executing Documenter examples.
    Julia,
}

/// An explicitly declared group of corresponding APIs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ConceptConfiguration {
    /// Stable concept identifier.
    pub id: String,
    /// How the member APIs correspond.
    pub kind: ConceptKind,
    /// Member declarations in source order, resolved during semantic validation.
    pub members: Vec<ConceptMember>,
}

/// How closely the APIs in a concept correspond.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ConceptKind {
    /// Members represent the same API.
    Equivalent,
    /// Members provide comparable capabilities.
    Analogous,
    /// Members have an explicitly declared association.
    Related,
}

/// An unresolved item reference in a conceptual API group.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ConceptMember {
    /// Package containing the member.
    pub package: String,
    /// Semantic item ID or a qualified name that must resolve unambiguously.
    pub item: String,
}

/// An implementation or release relationship, distinct from an API concept.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct RelationshipConfiguration {
    /// Source workspace package ID or external ecosystem-qualified coordinate.
    pub from: String,
    /// Destination workspace package ID or external ecosystem-qualified coordinate.
    pub to: String,
    /// Typed implementation or release relationship.
    pub kind: RelationshipKind,
    /// Declared version constraint, retained in its ecosystem's syntax.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version_constraint: Option<String>,
    /// Origin of the declaration, such as `explicit` or package metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<String>,
}

/// Supported implementation and release relationships between packages.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RelationshipKind {
    /// The source depends on the destination package.
    DependsOn,
    /// The source provides bindings to the destination package.
    Binds,
    /// The source wraps the destination package.
    Wraps,
    /// The source is generated from the destination package.
    GeneratedFrom,
}

/// A configuration load failure with its source path and underlying cause.
#[derive(Debug, Error)]
pub enum ConfigurationError {
    /// The configuration file could not be read as UTF-8 text.
    #[error("could not read configuration `{}`: {source}", path.display())]
    Read {
        /// Configuration path supplied by the caller.
        path: PathBuf,
        /// Underlying filesystem or UTF-8 error.
        source: std::io::Error,
    },
    /// The configuration is malformed or does not match the input schema.
    #[error("could not parse configuration `{}`: {source}", path.display())]
    Parse {
        /// Configuration path supplied by the caller.
        path: PathBuf,
        /// Underlying YAML error, including its source range when available.
        source: Box<serde_saphyr::Error>,
    },
}

impl ConfigurationError {
    /// Convert a load failure to a portable diagnostic using a caller-supplied
    /// configuration-relative path, retaining the YAML byte range when available.
    ///
    /// Runtime paths remain in this error for local troubleshooting. Filesystem
    /// causes contribute only their error kind because custom I/O messages can
    /// embed machine paths. Parser messages describe the input declarations.
    pub fn to_diagnostic(&self, path: DiagnosticPath) -> Diagnostic {
        let mut diagnostic = match self {
            Self::Read { source, .. } => Diagnostic::new(
                DiagnosticCode::ConfigurationReadFailed,
                Severity::Error,
                format!("could not read configuration: {}", source.kind()),
            ),
            Self::Parse { source, .. } => {
                let mut diagnostic = Diagnostic::new(
                    DiagnosticCode::InvalidConfiguration,
                    Severity::Error,
                    source.without_snippet().to_string(),
                );
                diagnostic.span = source.location().and_then(|location| {
                    let span = location.span();
                    let start = usize::try_from(span.byte_offset()?).ok()?;
                    let length = usize::try_from(span.byte_len()?).ok()?;
                    Some(SourceSpan {
                        start,
                        end: start.checked_add(length)?,
                    })
                });
                diagnostic
            }
        };
        diagnostic.source = Some(DiagnosticSource::Configuration { path });
        diagnostic.related_entity = Some(DiagnosticEntity::Configuration);
        diagnostic
    }
}

/// Parse declarations from a single YAML document without reading paths or executing code.
///
/// Omitted repository, package, and content collections are empty. Each declared
/// package requires a `targets` list; `targets: []` declares no API extraction.
/// Package kind, package visibility, and execution mode use their documented
/// defaults. Field names use kebab-case. Unknown fields are rejected in every
/// mapping. Paths and unresolved references retain their declared spelling.
///
/// ```
/// use diplodocus::configuration::parse_configuration;
///
/// let config = parse_configuration("project:\n  name: \"Foo\"\n")?;
/// assert_eq!(config.project.name, "Foo");
/// assert!(config.packages.is_empty());
/// # Ok::<(), Box<serde_saphyr::Error>>(())
/// ```
///
/// # Errors
///
/// Returns a YAML error for malformed syntax, duplicate keys, multiple documents,
/// missing required fields, unknown fields, incorrect field types, unsupported enum
/// values, or incoherent collection execution settings. Filesystem, identity,
/// relationship, and document-authority validation remain separate steps.
pub fn parse_configuration(
    source: &str,
) -> Result<WorkspaceConfiguration, Box<serde_saphyr::Error>> {
    // Keep field types explicit rather than coercing numbers and booleans to strings.
    serde_saphyr::from_str_with_options(
        source,
        serde_saphyr::options! {
            no_schema: true,
            strict_booleans: true,
        },
    )
    .map_err(Box::new)
}

/// Read and parse one explicitly supplied workspace configuration file.
///
/// Only the configuration file is read. Declared paths remain unresolved, and
/// parsing does not discover repositories, packages, targets, or kernels.
/// Use [`crate::paths::resolve_workspace_paths`] to resolve and validate declared
/// filesystem inputs after loading.
///
/// # Errors
///
/// Returns the source path and underlying error if reading or parsing fails.
pub fn load_configuration(
    path: impl AsRef<Path>,
) -> Result<WorkspaceConfiguration, ConfigurationError> {
    let path = path.as_ref();
    let source = fs::read_to_string(path).map_err(|source| ConfigurationError::Read {
        path: path.to_owned(),
        source,
    })?;
    parse_configuration(&source).map_err(|source| ConfigurationError::Parse {
        path: path.to_owned(),
        source,
    })
}