« get me outta code hell

yaml.js « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/yaml.js
blob: 5da66c93d75a23afa855a4cbb22ca81e4192c66e (plain)
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
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
// yaml.js - specification for HSMusic YAML data file format and utilities for
// loading, processing, and validating YAML files and documents

import {readFile, stat} from 'node:fs/promises';
import * as path from 'node:path';
import {inspect as nodeInspect} from 'node:util';

import yaml from 'js-yaml';

import {colors, ENABLE_COLOR, logInfo, logWarn} from '#cli';
import find, {bindFind} from '#find';
import {traverse} from '#node-utils';

import T, {
  CacheableObject,
  CacheableObjectPropertyValueError,
  Thing,
} from '#things';

import {
  annotateErrorWithFile,
  conditionallySuppressError,
  decorateErrorWithIndex,
  decorateErrorWithAnnotation,
  empty,
  filterProperties,
  openAggregate,
  showAggregate,
  withAggregate,
} from '#sugar';

import {
  sortAlbumsTracksChronologically,
  sortAlphabetically,
  sortChronologically,
  sortFlashesChronologically,
} from '#wiki-data';

// --> General supporting stuff

function inspect(value) {
  return nodeInspect(value, {colors: ENABLE_COLOR});
}

// --> YAML data repository structure constants

export const WIKI_INFO_FILE = 'wiki-info.yaml';
export const BUILD_DIRECTIVE_DATA_FILE = 'build-directives.yaml';
export const HOMEPAGE_LAYOUT_DATA_FILE = 'homepage.yaml';
export const ARTIST_DATA_FILE = 'artists.yaml';
export const FLASH_DATA_FILE = 'flashes.yaml';
export const NEWS_DATA_FILE = 'news.yaml';
export const ART_TAG_DATA_FILE = 'tags.yaml';
export const GROUP_DATA_FILE = 'groups.yaml';

export const DATA_ALBUM_DIRECTORY = 'album';
export const DATA_STATIC_PAGE_DIRECTORY = 'static-page';

// --> Document processing functions

// General function for inputting a single document (usually loaded from YAML)
// and outputting an instance of a provided Thing subclass.
//
// makeProcessDocument is a factory function: the returned function will take a
// document and apply the configuration passed to makeProcessDocument in order
// to construct a Thing subclass.
function makeProcessDocument(
  thingConstructor,
  {
    // Optional early step for transforming field values before providing them
    // to the Thing's update() method. This is useful when the input format
    // (i.e. values in the document) differ from the format the actual Thing
    // expects.
    //
    // Each key and value are a field name (not an update() property) and a
    // function which takes the value for that field and returns the value which
    // will be passed on to update().
    //
    fieldTransformations = {},

    // Mapping of Thing.update() source properties to field names.
    //
    // Note this is property -> field, not field -> property. This is a
    // shorthand convenience because properties are generally typical
    // camel-cased JS properties, while fields may contain whitespace and be
    // more easily represented as quoted strings.
    //
    propertyFieldMapping,

    // Completely ignored fields. These won't throw an unknown field error if
    // they're present in a document, but they won't be used for Thing property
    // generation, either. Useful for stuff that's present in data files but not
    // yet implemented as part of a Thing's data model!
    //
    ignoredFields = [],

    // List of fields which are invalid when coexisting in a document.
    // Data objects are generally allowing with regards to what properties go
    // together, allowing for properties to be set separately from each other
    // instead of complaining about invalid or unused-data cases. But it's
    // useful to see these kinds of errors when actually validating YAML files!
    //
    // Each item of this array should itself be an object with a descriptive
    // message and a list of fields. Of those fields, none should ever coexist
    // with any other. For example:
    //
    //   [
    //     {message: '...', fields: ['A', 'B', 'C']},
    //     {message: '...', fields: ['C', 'D']},
    //   ]
    //
    // ...means A can't coexist with B or C, B can't coexist with A or C, and
    // C can't coexist iwth A, B, or D - but it's okay for D to coexist with
    // A or B.
    //
    invalidFieldCombinations = [],
  }
) {
  if (!thingConstructor) {
    throw new Error(`Missing Thing class`);
  }

  if (!propertyFieldMapping) {
    throw new Error(`Expected propertyFieldMapping to be provided`);
  }

  const knownFields = Object.values(propertyFieldMapping);

  // Invert the property-field mapping, since it'll come in handy for
  // assigning update() source values later.
  const fieldPropertyMapping = Object.fromEntries(
    Object.entries(propertyFieldMapping)
      .map(([property, field]) => [field, property]));

  const decorateErrorWithName = (fn) => {
    const nameField = propertyFieldMapping['name'];
    if (!nameField) return fn;

    return (document) => {
      try {
        return fn(document);
      } catch (error) {
        const name = document[nameField];
        error.message = name
          ? `(name: ${inspect(name)}) ${error.message}`
          : `(${colors.dim(`no name found`)}) ${error.message}`;
        throw error;
      }
    };
  };

  const fn = decorateErrorWithName((document) => {
    const nameField = propertyFieldMapping['name'];
    const namePart =
      (nameField
        ? (document[nameField]
          ? ` named ${colors.green(`"${document[nameField]}"`)}`
          : ` (name field, "${nameField}", not specified)`)
        : ``);

    const constructorPart =
      (thingConstructor[Thing.friendlyName]
        ? colors.green(thingConstructor[Thing.friendlyName])
     : thingConstructor.name
        ? colors.green(thingConstructor.name)
        : `document`);

    const aggregate = openAggregate({
      message: `Errors processing ${constructorPart}` + namePart,
    });

    const documentEntries = Object.entries(document)
      .filter(([field]) => !ignoredFields.includes(field));

    const skippedFields = new Set();

    const unknownFields = documentEntries
      .map(([field]) => field)
      .filter((field) => !knownFields.includes(field));

    if (!empty(unknownFields)) {
      aggregate.push(new UnknownFieldsError(unknownFields));

      for (const field of unknownFields) {
        skippedFields.add(field);
      }
    }

    const presentFields = Object.keys(document);

    const fieldCombinationErrors = [];

    for (const {message, fields} of invalidFieldCombinations) {
      const fieldsPresent = presentFields.filter(field => fields.includes(field));

      if (fieldsPresent.length >= 2) {
        const filteredDocument =
          filterProperties(
            document,
            fieldsPresent,
            {preserveOriginalOrder: true});

        fieldCombinationErrors.push(new FieldCombinationError(filteredDocument, message));

        for (const field of Object.keys(filteredDocument)) {
          skippedFields.add(field);
        }
      }
    }

    if (!empty(fieldCombinationErrors)) {
      aggregate.push(new FieldCombinationAggregateError(fieldCombinationErrors));
    }

    const fieldValues = {};

    for (const [field, documentValue] of documentEntries) {
      if (skippedFields.has(field)) continue;

      // This variable would like to certify itself as "not into capitalism".
      let propertyValue =
        (Object.hasOwn(fieldTransformations, field)
          ? fieldTransformations[field](documentValue)
          : documentValue);

      // Completely blank items in a YAML list are read as null.
      // They're handy to have around when filling out a document and shouldn't
      // be considered an error (or data at all).
      if (Array.isArray(propertyValue)) {
        const wasEmpty = empty(propertyValue);

        propertyValue =
          propertyValue.filter(item => item !== null);

        const isEmpty = empty(propertyValue);

        // Don't set arrays which are empty as a result of the above filter.
        // Arrays which were originally empty, i.e. `Field: []`, are still
        // valid data, but if it's just an array not containing any filled out
        // items, it should be treated as a placeholder and skipped over.
        if (isEmpty && !wasEmpty) {
          propertyValue = null;
        }
      }

      fieldValues[field] = propertyValue;
    }

    const sourceProperties = {};

    for (const [field, value] of Object.entries(fieldValues)) {
      const property = fieldPropertyMapping[field];
      sourceProperties[property] = value;
    }

    const thing = Reflect.construct(thingConstructor, []);

    const fieldValueErrors = [];

    for (const [property, value] of Object.entries(sourceProperties)) {
      const field = propertyFieldMapping[property];
      try {
        thing[property] = value;
      } catch (caughtError) {
        skippedFields.add(field);
        fieldValueErrors.push(new FieldValueError(field, property, value, caughtError));
      }
    }

    if (!empty(fieldValueErrors)) {
      aggregate.push(new FieldValueAggregateError(thingConstructor, fieldValueErrors));
    }

    if (skippedFields.size >= 1) {
      aggregate.push(
        new SkippedFieldsSummaryError(
          filterProperties(
            document,
            Array.from(skippedFields),
            {preserveOriginalOrder: true})));
    }

    return {thing, aggregate};
  });

  Object.assign(fn, {
    propertyFieldMapping,
    fieldPropertyMapping,
  });

  return fn;
}

export class UnknownFieldsError extends Error {
  constructor(fields) {
    super(`Unknown fields ignored: ${fields.map(field => colors.red(field)).join(', ')}`);
    this.fields = fields;
  }
}

export class FieldCombinationAggregateError extends AggregateError {
  constructor(errors) {
    super(errors, `Invalid field combinations - all involved fields ignored`);
  }
}

export class FieldCombinationError extends Error {
  constructor(fields, message) {
    const fieldNames = Object.keys(fields);

    const mainMessage = `Don't combine ${fieldNames.map(field => colors.red(field)).join(', ')}`;

    const causeMessage =
      (typeof message === 'function'
        ? message(fields)
     : typeof message === 'string'
        ? message
        : null);

    super(mainMessage, {
      cause:
        (causeMessage
          ? new Error(causeMessage)
          : null),
    });

    this.fields = fields;
  }
}

export class FieldValueAggregateError extends AggregateError {
  constructor(thingConstructor, errors) {
    super(errors, `Errors processing field values for ${colors.green(thingConstructor.name)}`);
  }
}

export class FieldValueError extends Error {
  constructor(field, property, value, caughtError) {
    const cause =
      (caughtError instanceof CacheableObjectPropertyValueError
        ? caughtError.cause
        : caughtError);

    super(
      `Failed to set ${colors.green(`"${field}"`)} field (${colors.green(property)}) to ${inspect(value)}`,
      {cause});
  }
}

export class SkippedFieldsSummaryError extends Error {
  constructor(filteredDocument) {
    const entries = Object.entries(filteredDocument);

    const lines =
      entries.map(([field, value]) =>
        ` - ${field}: ` +
        inspect(value)
          .split('\n')
          .map((line, index) => index === 0 ? line : `   ${line}`)
          .join('\n'));

    super(
      colors.bright(colors.yellow(`Altogether, skipped ${entries.length === 1 ? `1 field` : `${entries.length} fields`}:\n`)) +
      lines.join('\n') + '\n' +
      colors.bright(colors.yellow(`See above errors for details.`)));
  }
}

export const processAlbumDocument = makeProcessDocument(T.Album, {
  fieldTransformations: {
    'Artists': parseContributors,
    'Cover Artists': parseContributors,
    'Default Track Cover Artists': parseContributors,
    'Wallpaper Artists': parseContributors,
    'Banner Artists': parseContributors,

    'Date': (value) => new Date(value),
    'Date Added': (value) => new Date(value),
    'Cover Art Date': (value) => new Date(value),
    'Default Track Cover Art Date': (value) => new Date(value),

    'Banner Dimensions': parseDimensions,

    'Additional Files': parseAdditionalFiles,
  },

  propertyFieldMapping: {
    name: 'Album',
    directory: 'Directory',
    date: 'Date',
    color: 'Color',
    urls: 'URLs',

    hasTrackNumbers: 'Has Track Numbers',
    isListedOnHomepage: 'Listed on Homepage',
    isListedInGalleries: 'Listed in Galleries',

    coverArtDate: 'Cover Art Date',
    trackArtDate: 'Default Track Cover Art Date',
    dateAddedToWiki: 'Date Added',

    coverArtFileExtension: 'Cover Art File Extension',
    trackCoverArtFileExtension: 'Track Art File Extension',

    wallpaperArtistContribs: 'Wallpaper Artists',
    wallpaperStyle: 'Wallpaper Style',
    wallpaperFileExtension: 'Wallpaper File Extension',

    bannerArtistContribs: 'Banner Artists',
    bannerStyle: 'Banner Style',
    bannerFileExtension: 'Banner File Extension',
    bannerDimensions: 'Banner Dimensions',

    commentary: 'Commentary',
    additionalFiles: 'Additional Files',

    artistContribs: 'Artists',
    coverArtistContribs: 'Cover Artists',
    trackCoverArtistContribs: 'Default Track Cover Artists',
    groups: 'Groups',
    artTags: 'Art Tags',
  },
});

export const processTrackSectionDocument = makeProcessDocument(T.TrackSectionHelper, {
  fieldTransformations: {
    'Date Originally Released': (value) => new Date(value),
  },

  propertyFieldMapping: {
    name: 'Section',
    color: 'Color',
    dateOriginallyReleased: 'Date Originally Released',
  },
});

export const processTrackDocument = makeProcessDocument(T.Track, {
  fieldTransformations: {
    'Additional Names': parseAdditionalNames,
    'Duration': parseDuration,

    'Date First Released': (value) => new Date(value),
    'Cover Art Date': (value) => new Date(value),
    'Has Cover Art': (value) =>
      (value === true ? false :
       value === false ? true :
       value),

    'Artists': parseContributors,
    'Contributors': parseContributors,
    'Cover Artists': parseContributors,

    'Additional Files': parseAdditionalFiles,
    'Sheet Music Files': parseAdditionalFiles,
    'MIDI Project Files': parseAdditionalFiles,
  },

  propertyFieldMapping: {
    name: 'Track',
    directory: 'Directory',
    additionalNames: 'Additional Names',
    duration: 'Duration',
    color: 'Color',
    urls: 'URLs',

    dateFirstReleased: 'Date First Released',
    coverArtDate: 'Cover Art Date',
    coverArtFileExtension: 'Cover Art File Extension',
    disableUniqueCoverArt: 'Has Cover Art', // This gets transformed to flip true/false.

    alwaysReferenceByDirectory: 'Always Reference By Directory',

    lyrics: 'Lyrics',
    commentary: 'Commentary',
    additionalFiles: 'Additional Files',
    sheetMusicFiles: 'Sheet Music Files',
    midiProjectFiles: 'MIDI Project Files',

    originalReleaseTrack: 'Originally Released As',
    referencedTracks: 'Referenced Tracks',
    sampledTracks: 'Sampled Tracks',
    artistContribs: 'Artists',
    contributorContribs: 'Contributors',
    coverArtistContribs: 'Cover Artists',
    artTags: 'Art Tags',
  },

  invalidFieldCombinations: [
    {message: `Re-releases inherit references from the original`, fields: [
      'Originally Released As',
      'Referenced Tracks',
    ]},

    {message: `Re-releases inherit samples from the original`, fields: [
      'Originally Released As',
      'Sampled Tracks',
    ]},

    {message: `Re-releases inherit artists from the original`, fields: [
      'Originally Released As',
      'Artists',
    ]},

    {message: `Re-releases inherit contributors from the original`, fields: [
      'Originally Released As',
      'Contributors',
    ]},

    {
      message: ({'Has Cover Art': hasCoverArt}) =>
        (hasCoverArt
          ? `"Has Cover Art: true" is inferred from cover artist credits`
          : `Tracks without cover art must not have cover artist credits`),

      fields: [
        'Has Cover Art',
        'Cover Artists',
      ],
    },
  ],
});

export const processArtistDocument = makeProcessDocument(T.Artist, {
  propertyFieldMapping: {
    name: 'Artist',
    directory: 'Directory',
    urls: 'URLs',
    contextNotes: 'Context Notes',

    hasAvatar: 'Has Avatar',
    avatarFileExtension: 'Avatar File Extension',

    aliasNames: 'Aliases',
  },

  ignoredFields: ['Dead URLs'],
});

export const processFlashDocument = makeProcessDocument(T.Flash, {
  fieldTransformations: {
    'Date': (value) => new Date(value),

    'Contributors': parseContributors,
  },

  propertyFieldMapping: {
    name: 'Flash',
    directory: 'Directory',
    page: 'Page',
    color: 'Color',
    urls: 'URLs',

    date: 'Date',
    coverArtFileExtension: 'Cover Art File Extension',

    featuredTracks: 'Featured Tracks',
    contributorContribs: 'Contributors',
  },
});

export const processFlashActDocument = makeProcessDocument(T.FlashAct, {
  propertyFieldMapping: {
    name: 'Act',
    directory: 'Directory',

    color: 'Color',
    listTerminology: 'List Terminology',

    jump: 'Jump',
    jumpColor: 'Jump Color',
  },
});

export const processNewsEntryDocument = makeProcessDocument(T.NewsEntry, {
  fieldTransformations: {
    'Date': (value) => new Date(value),
  },

  propertyFieldMapping: {
    name: 'Name',
    directory: 'Directory',
    date: 'Date',
    content: 'Content',
  },
});

export const processArtTagDocument = makeProcessDocument(T.ArtTag, {
  propertyFieldMapping: {
    name: 'Tag',
    nameShort: 'Short Name',
    directory: 'Directory',

    color: 'Color',
    isContentWarning: 'Is CW',
  },
});

export const processGroupDocument = makeProcessDocument(T.Group, {
  propertyFieldMapping: {
    name: 'Group',
    directory: 'Directory',
    description: 'Description',
    urls: 'URLs',

    featuredAlbums: 'Featured Albums',
  },
});

export const processGroupCategoryDocument = makeProcessDocument(T.GroupCategory, {
  propertyFieldMapping: {
    name: 'Category',
    color: 'Color',
  },
});

export const processStaticPageDocument = makeProcessDocument(T.StaticPage, {
  propertyFieldMapping: {
    name: 'Name',
    nameShort: 'Short Name',
    directory: 'Directory',

    stylesheet: 'Style',
    content: 'Content',
  },
});

export const processWikiInfoDocument = makeProcessDocument(T.WikiInfo, {
  propertyFieldMapping: {
    name: 'Name',
    nameShort: 'Short Name',
    color: 'Color',
    description: 'Description',
    footerContent: 'Footer Content',
    defaultLanguage: 'Default Language',
    canonicalBase: 'Canonical Base',
    divideTrackListsByGroups: 'Divide Track Lists By Groups',
    enableFlashesAndGames: 'Enable Flashes & Games',
    enableListings: 'Enable Listings',
    enableNews: 'Enable News',
    enableArtTagUI: 'Enable Art Tag UI',
    enableGroupUI: 'Enable Group UI',
  },
});

export const processHomepageLayoutDocument = makeProcessDocument(T.HomepageLayout, {
  propertyFieldMapping: {
    sidebarContent: 'Sidebar Content',
    navbarLinks: 'Navbar Links',
  },

  ignoredFields: ['Homepage'],
});

export function makeProcessHomepageLayoutRowDocument(rowClass, spec) {
  return makeProcessDocument(rowClass, {
    ...spec,

    propertyFieldMapping: {
      name: 'Row',
      color: 'Color',
      type: 'Type',
      ...spec.propertyFieldMapping,
    },
  });
}

export const homepageLayoutRowTypeProcessMapping = {
  albums: makeProcessHomepageLayoutRowDocument(T.HomepageLayoutAlbumsRow, {
    propertyFieldMapping: {
      displayStyle: 'Display Style',
      sourceGroup: 'Group',
      countAlbumsFromGroup: 'Count',
      sourceAlbums: 'Albums',
      actionLinks: 'Actions',
    },
  }),
};

export function processHomepageLayoutRowDocument(document) {
  const type = document['Type'];

  const match = Object.entries(homepageLayoutRowTypeProcessMapping)
    .find(([key]) => key === type);

  if (!match) {
    throw new TypeError(`No processDocument function for row type ${type}!`);
  }

  return match[1](document);
}

// --> Utilities shared across document parsing functions

export function parseDuration(string) {
  if (typeof string !== 'string') {
    return string;
  }

  const parts = string.split(':').map((n) => parseInt(n));
  if (parts.length === 3) {
    return parts[0] * 3600 + parts[1] * 60 + parts[2];
  } else if (parts.length === 2) {
    return parts[0] * 60 + parts[1];
  } else {
    return 0;
  }
}

export function parseAdditionalFiles(array) {
  if (!Array.isArray(array)) {
    // Error will be caught when validating against whatever this value is
    return array;
  }

  return array.map((item) => ({
    title: item['Title'],
    description: item['Description'] ?? null,
    files: item['Files'],
  }));
}

const extractAccentRegex =
  /^(?<main>.*?)(?: \((?<accent>.*)\))?$/;

export function parseContributors(contributionStrings) {
  // If this isn't something we can parse, just return it as-is.
  // The Thing object's validators will handle the data error better
  // than we're able to here.
  if (!Array.isArray(contributionStrings)) {
    return contributionStrings;
  }

  return contributionStrings.map(item => {
    if (typeof item === 'object' && item['Who'])
      return {who: item['Who'], what: item['What'] ?? null};

    if (typeof item !== 'string') return item;

    const match = item.match(extractAccentRegex);
    if (!match) return item;

    return {
      who: match.groups.main,
      what: match.groups.accent ?? null,
    };
  });
}

export function parseAdditionalNames(additionalNameStrings) {
  if (!Array.isArray(additionalNameStrings)) {
    return additionalNameStrings;
  }

  return additionalNameStrings.map(item => {
    if (typeof item === 'object' && item['Name'])
      return {name: item['Name'], annotation: item['Annotation'] ?? null};

    if (typeof item !== 'string') return item;

    const match = item.match(extractAccentRegex);
    if (!match) return item;

    return {
      name: match.groups.main,
      annotation: match.groups.accent ?? null,
    };
  });
}

function parseDimensions(string) {
  // It's technically possible to pass an array like [30, 40] through here.
  // That's not really an issue because if it isn't of the appropriate shape,
  // the Thing object's validators will handle the error.
  if (typeof string !== 'string') {
    return string;
  }

  const parts = string.split(/[x,* ]+/g);

  if (parts.length !== 2) {
    throw new Error(`Invalid dimensions: ${string} (expected "width & height")`);
  }

  const nums = parts.map((part) => Number(part.trim()));

  if (nums.includes(NaN)) {
    throw new Error(`Invalid dimensions: ${string} (couldn't parse as numbers)`);
  }

  return nums;
}

// --> Data repository loading functions and descriptors

// documentModes: Symbols indicating sets of behavior for loading and processing
// data files.
export const documentModes = {
  // onePerFile: One document per file. Expects files array (or function) and
  // processDocument function. Obviously, each specified data file should only
  // contain one YAML document (an error will be thrown otherwise). Calls save
  // with an array of processed documents (wiki objects).
  onePerFile: Symbol('Document mode: onePerFile'),

  // headerAndEntries: One or more documents per file; the first document is
  // treated as a "header" and represents data which pertains to all following
  // "entry" documents. Expects files array (or function) and
  // processHeaderDocument and processEntryDocument functions. Calls save with
  // an array of {header, entries} objects.
  //
  // Please note that the final results loaded from each file may be "missing"
  // data objects corresponding to entry documents if the processEntryDocument
  // function throws on any entries, resulting in partial data provided to
  // save() - errors will be caught and thrown in the final buildSteps
  // aggregate. However, if the processHeaderDocument function fails, all
  // following documents in the same file will be ignored as well (i.e. an
  // entire file will be excempt from the save() function's input).
  headerAndEntries: Symbol('Document mode: headerAndEntries'),

  // allInOne: One or more documents, all contained in one file. Expects file
  // string (or function) and processDocument function. Calls save with an
  // array of processed documents (wiki objects).
  allInOne: Symbol('Document mode: allInOne'),

  // oneDocumentTotal: Just a single document, represented in one file.
  // Expects file string (or function) and processDocument function. Calls
  // save with the single processed wiki document (data object).
  //
  // Please note that if the single document fails to process, the save()
  // function won't be called at all, generally resulting in an altogether
  // missing property from the global wikiData object. This should be caught
  // and handled externally.
  oneDocumentTotal: Symbol('Document mode: oneDocumentTotal'),
};

// dataSteps: Top-level array of "steps" for loading YAML document files.
//
// title:
//   Name of the step (displayed in build output)
//
// documentMode:
//   Symbol which indicates by which "mode" documents from data files are
//   loaded and processed. See documentModes export.
//
// file, files:
//   String or array of strings which are paths to YAML data files, or a
//   function which returns the above (may be async). All paths are appended to
//   the global dataPath provided externally (e.g. HSMUSIC_DATA env variable).
//   Which to provide (file or files) depends on documentMode. If this is a
//   function, it will be provided with dataPath (e.g. so that a sub-path may be
//   readdir'd), but don't path.join(dataPath) the returned value(s) yourself -
//   this will be done automatically.
//
// processDocument, processHeaderDocument, processEntryDocument:
//   Functions which take a YAML document and return an actual wiki data object;
//   all actual conversion between YAML and wiki data happens here. Which to
//   provide (one or a combination) depend on documentMode.
//
// save:
//   Function which takes all documents processed (now as wiki data objects) and
//   actually applies them to a global wiki data object, for use in page
//   generation and other behavior. Returns an object to be assigned over the
//   global wiki data object (so specify any new properties here). This is also
//   the place to perform any final post-processing on data objects (linking
//   them to each other, setting additional properties, etc). Input argument
//   format depends on documentMode.
//
export const dataSteps = [
  {
    title: `Process wiki info file`,
    file: WIKI_INFO_FILE,

    documentMode: documentModes.oneDocumentTotal,
    processDocument: processWikiInfoDocument,

    save(wikiInfo) {
      if (!wikiInfo) {
        return;
      }

      return {wikiInfo};
    },
  },

  {
    title: `Process album files`,

    files: dataPath =>
      traverse(path.join(dataPath, DATA_ALBUM_DIRECTORY), {
        filterFile: name => path.extname(name) === '.yaml',
        prefixPath: DATA_ALBUM_DIRECTORY,
      }),

    documentMode: documentModes.headerAndEntries,
    processHeaderDocument: processAlbumDocument,
    processEntryDocument(document) {
      return 'Section' in document
        ? processTrackSectionDocument(document)
        : processTrackDocument(document);
    },

    save(results) {
      const albumData = [];
      const trackData = [];

      for (const {header: album, entries} of results) {
        // We can't mutate an array once it's set as a property value,
        // so prepare the track sections that will show up in a track list
        // all the way before actually applying them. (It's okay to mutate
        // an individual section before applying it, since those are just
        // generic objects; they aren't Things in and of themselves.)
        const trackSections = [];

        let currentTrackSection = {
          name: `Default Track Section`,
          isDefaultTrackSection: true,
          tracks: [],
        };

        const albumRef = Thing.getReference(album);

        const closeCurrentTrackSection = () => {
          if (!empty(currentTrackSection.tracks)) {
            trackSections.push(currentTrackSection);
          }
        };

        for (const entry of entries) {
          if (entry instanceof T.TrackSectionHelper) {
            closeCurrentTrackSection();

            currentTrackSection = {
              name: entry.name,
              color: entry.color,
              dateOriginallyReleased: entry.dateOriginallyReleased,
              isDefaultTrackSection: false,
              tracks: [],
            };

            continue;
          }

          trackData.push(entry);

          entry.dataSourceAlbum = albumRef;

          currentTrackSection.tracks.push(Thing.getReference(entry));
        }

        closeCurrentTrackSection();

        album.trackSections = trackSections;
        albumData.push(album);
      }

      return {albumData, trackData};
    },
  },

  {
    title: `Process artists file`,
    file: ARTIST_DATA_FILE,

    documentMode: documentModes.allInOne,
    processDocument: processArtistDocument,

    save(results) {
      const artistData = results;

      const artistAliasData = results.flatMap((artist) => {
        const origRef = Thing.getReference(artist);
        return artist.aliasNames?.map((name) => {
          const alias = new T.Artist();
          alias.name = name;
          alias.isAlias = true;
          alias.aliasedArtist = origRef;
          alias.artistData = artistData;
          return alias;
        }) ?? [];
      });

      return {artistData, artistAliasData};
    },
  },

  // TODO: WD.wikiInfo.enableFlashesAndGames &&
  {
    title: `Process flashes file`,
    file: FLASH_DATA_FILE,

    documentMode: documentModes.allInOne,
    processDocument(document) {
      return 'Act' in document
        ? processFlashActDocument(document)
        : processFlashDocument(document);
    },

    save(results) {
      let flashAct;
      let flashRefs = [];

      if (results[0] && !(results[0] instanceof T.FlashAct)) {
        throw new Error(`Expected an act at top of flash data file`);
      }

      for (const thing of results) {
        if (thing instanceof T.FlashAct) {
          if (flashAct) {
            Object.assign(flashAct, {flashes: flashRefs});
          }

          flashAct = thing;
          flashRefs = [];
        } else {
          flashRefs.push(Thing.getReference(thing));
        }
      }

      if (flashAct) {
        Object.assign(flashAct, {flashes: flashRefs});
      }

      const flashData = results.filter((x) => x instanceof T.Flash);
      const flashActData = results.filter((x) => x instanceof T.FlashAct);

      return {flashData, flashActData};
    },
  },

  {
    title: `Process groups file`,
    file: GROUP_DATA_FILE,

    documentMode: documentModes.allInOne,
    processDocument(document) {
      return 'Category' in document
        ? processGroupCategoryDocument(document)
        : processGroupDocument(document);
    },

    save(results) {
      let groupCategory;
      let groupRefs = [];

      if (results[0] && !(results[0] instanceof T.GroupCategory)) {
        throw new Error(`Expected a category at top of group data file`);
      }

      for (const thing of results) {
        if (thing instanceof T.GroupCategory) {
          if (groupCategory) {
            Object.assign(groupCategory, {groups: groupRefs});
          }

          groupCategory = thing;
          groupRefs = [];
        } else {
          groupRefs.push(Thing.getReference(thing));
        }
      }

      if (groupCategory) {
        Object.assign(groupCategory, {groups: groupRefs});
      }

      const groupData = results.filter((x) => x instanceof T.Group);
      const groupCategoryData = results.filter((x) => x instanceof T.GroupCategory);

      return {groupData, groupCategoryData};
    },
  },

  {
    title: `Process homepage layout file`,

    // Kludge: This benefits from the same headerAndEntries style messaging as
    // albums and tracks (for example), but that document mode is designed to
    // support multiple files, and only one is actually getting processed here.
    files: [HOMEPAGE_LAYOUT_DATA_FILE],

    documentMode: documentModes.headerAndEntries,
    processHeaderDocument: processHomepageLayoutDocument,
    processEntryDocument: processHomepageLayoutRowDocument,

    save(results) {
      if (!results[0]) {
        return;
      }

      const {header: homepageLayout, entries: rows} = results[0];
      Object.assign(homepageLayout, {rows});
      return {homepageLayout};
    },
  },

  // TODO: WD.wikiInfo.enableNews &&
  {
    title: `Process news data file`,
    file: NEWS_DATA_FILE,

    documentMode: documentModes.allInOne,
    processDocument: processNewsEntryDocument,

    save(newsData) {
      sortChronologically(newsData);
      newsData.reverse();

      return {newsData};
    },
  },

  {
    title: `Process art tags file`,
    file: ART_TAG_DATA_FILE,

    documentMode: documentModes.allInOne,
    processDocument: processArtTagDocument,

    save(artTagData) {
      sortAlphabetically(artTagData);

      return {artTagData};
    },
  },

  {
    title: `Process static page files`,

    files: dataPath =>
      traverse(path.join(dataPath, DATA_STATIC_PAGE_DIRECTORY), {
        filterFile: name => path.extname(name) === '.yaml',
        prefixPath: DATA_STATIC_PAGE_DIRECTORY,
      }),

    documentMode: documentModes.onePerFile,
    processDocument: processStaticPageDocument,

    save(staticPageData) {
      sortAlphabetically(staticPageData);

      return {staticPageData};
    },
  },
];

export async function loadAndProcessDataDocuments({dataPath}) {
  const processDataAggregate = openAggregate({
    message: `Errors processing data files`,
  });
  const wikiDataResult = {};

  function decorateErrorWithFile(fn) {
    return decorateErrorWithAnnotation(fn,
      (caughtError, firstArg) =>
        annotateErrorWithFile(
          caughtError,
          path.relative(
            dataPath,
            (typeof firstArg === 'object'
              ? firstArg.file
              : firstArg))));
  }

  function asyncDecorateErrorWithFile(fn) {
    return decorateErrorWithFile(fn).async;
  }

  for (const dataStep of dataSteps) {
    await processDataAggregate.nestAsync(
      {message: `Errors during data step: ${colors.bright(dataStep.title)}`},
      async ({call, callAsync, map, mapAsync, push}) => {
        const {documentMode} = dataStep;

        if (!Object.values(documentModes).includes(documentMode)) {
          throw new Error(`Invalid documentMode: ${documentMode.toString()}`);
        }

        // Hear me out, it's been like 1200 years since I wrote the rest of
        // this beautifully error-containing code and I don't know how to
        // integrate this nicely. So I'm just returning the result and the
        // error that should be thrown. Yes, we're back in callback hell,
        // just without the callbacks. Thank you.
        const filterBlankDocuments = documents => {
          const aggregate = openAggregate({
            message: `Found blank documents - check for extra '${colors.cyan(`---`)}'`,
          });

          const filteredDocuments =
            documents
              .filter(doc => doc !== null);

          if (filteredDocuments.length !== documents.length) {
            const blankIndexRangeInfo =
              documents
                .map((doc, index) => [doc, index])
                .filter(([doc]) => doc === null)
                .map(([doc, index]) => index)
                .reduce((accumulator, index) => {
                  if (accumulator.length === 0) {
                    return [[index, index]];
                  }
                  const current = accumulator.at(-1);
                  const rest = accumulator.slice(0, -1);
                  if (current[1] === index - 1) {
                    return rest.concat([[current[0], index]]);
                  } else {
                    return accumulator.concat([[index, index]]);
                  }
                }, [])
                .map(([start, end]) => ({
                  start,
                  end,
                  count: end - start + 1,
                  previous:
                    (start > 0
                      ? documents[start - 1]
                      : null),
                  next:
                    (end < documents.length - 1
                      ? documents[end + 1]
                      : null),
                }));

            for (const {start, end, count, previous, next} of blankIndexRangeInfo) {
              const parts = [];

              if (count === 1) {
                const range = `#${start + 1}`;
                parts.push(`${count} document (${colors.yellow(range)}), `);
              } else {
                const range = `#${start + 1}-${end + 1}`;
                parts.push(`${count} documents (${colors.yellow(range)}), `);
              }

              if (previous === null) {
                parts.push(`at start of file`);
              } else if (next === null) {
                parts.push(`at end of file`);
              } else {
                const previousDescription = Object.entries(previous).at(0).join(': ');
                const nextDescription = Object.entries(next).at(0).join(': ');
                parts.push(`between "${colors.cyan(previousDescription)}" and "${colors.cyan(nextDescription)}"`);
              }

              aggregate.push(new Error(parts.join('')));
            }
          }

          return {documents: filteredDocuments, aggregate};
        };

        if (
          documentMode === documentModes.allInOne ||
          documentMode === documentModes.oneDocumentTotal
        ) {
          if (!dataStep.file) {
            throw new Error(`Expected 'file' property for ${documentMode.toString()}`);
          }

          const file = path.join(
            dataPath,
            typeof dataStep.file === 'function'
              ? await callAsync(dataStep.file, dataPath)
              : dataStep.file);

          const statResult = await callAsync(() =>
            stat(file).then(
              () => true,
              error => {
                if (error.code === 'ENOENT') {
                  return false;
                } else {
                  throw error;
                }
              }));

          if (statResult === false) {
            const saveResult = call(dataStep.save, {
              [documentModes.allInOne]: [],
              [documentModes.oneDocumentTotal]: {},
            }[documentMode]);

            if (!saveResult) return;

            Object.assign(wikiDataResult, saveResult);

            return;
          }

          const readResult = await callAsync(readFile, file, 'utf-8');

          if (!readResult) {
            return;
          }

          let processResults;

          switch (documentMode) {
            case documentModes.oneDocumentTotal: {
              const yamlResult = call(yaml.load, readResult);

              if (!yamlResult) {
                processResults = null;
                break;
              }

              const {thing, aggregate} =
                dataStep.processDocument(yamlResult);

              processResults = thing;

              call(() => aggregate.close());

              break;
            }

            case documentModes.allInOne: {
              const yamlResults = call(yaml.loadAll, readResult);

              if (!yamlResults) {
                processResults = [];
                return;
              }

              const {documents, aggregate: filterAggregate} =
                filterBlankDocuments(yamlResults);

              call(filterAggregate.close);

              processResults = [];

              map(documents, decorateErrorWithIndex(document => {
                const {thing, aggregate} =
                  dataStep.processDocument(document);

                processResults.push(thing);
                aggregate.close();
              }), {message: `Errors processing documents`});

              break;
            }
          }

          if (!processResults) return;

          const saveResult = call(dataStep.save, processResults);

          if (!saveResult) return;

          Object.assign(wikiDataResult, saveResult);

          return;
        }

        if (!dataStep.files) {
          throw new Error(`Expected 'files' property for ${documentMode.toString()}`);
        }

        const filesFromDataStep =
          (typeof dataStep.files === 'function'
            ? await callAsync(() =>
                dataStep.files(dataPath).then(
                  files => files,
                  error => {
                    if (error.code === 'ENOENT') {
                      return [];
                    } else {
                      throw error;
                    }
                  }))
            : dataStep.files);

        const filesUnderDataPath =
          filesFromDataStep
            .map(file => path.join(dataPath, file));

        const yamlResults = [];

        await mapAsync(filesUnderDataPath, {message: `Errors loading data files`},
          asyncDecorateErrorWithFile(async file => {
            let contents;
            try {
              contents = await readFile(file, 'utf-8');
            } catch (caughtError) {
              throw new Error(`Failed to read data file`, {cause: caughtError});
            }

            let documents;
            try {
              documents = yaml.loadAll(contents);
            } catch (caughtError) {
              throw new Error(`Failed to parse valid YAML`, {cause: caughtError});
            }

            const {documents: filteredDocuments, aggregate: filterAggregate} =
              filterBlankDocuments(documents);

            try {
              filterAggregate.close();
            } catch (caughtError) {
              // Blank documents aren't a critical error, they're just something
              // that should be noted - the (filtered) documents still get pushed.
              const pathToFile = path.relative(dataPath, file);
              annotateErrorWithFile(caughtError, pathToFile);
              push(caughtError);
            }

            yamlResults.push({file, documents: filteredDocuments});
          }));

        const processResults = [];

        switch (documentMode) {
          case documentModes.headerAndEntries:
            map(yamlResults, {message: `Errors processing documents in data files`},
              decorateErrorWithFile(({documents}) => {
                const headerDocument = documents[0];
                const entryDocuments = documents.slice(1).filter(Boolean);

                if (!headerDocument)
                  throw new Error(`Missing header document (empty file or erroneously starting with "---"?)`);

                withAggregate({message: `Errors processing documents`}, ({push}) => {
                  const {thing: headerObject, aggregate: headerAggregate} =
                    dataStep.processHeaderDocument(headerDocument);

                  try {
                    headerAggregate.close();
                  } catch (caughtError) {
                    caughtError.message = `(${colors.yellow(`header`)}) ${caughtError.message}`;
                    push(caughtError);
                  }

                  const entryObjects = [];

                  for (let index = 0; index < entryDocuments.length; index++) {
                    const entryDocument = entryDocuments[index];

                    const {thing: entryObject, aggregate: entryAggregate} =
                      dataStep.processEntryDocument(entryDocument);

                    entryObjects.push(entryObject);

                    try {
                      entryAggregate.close();
                    } catch (caughtError) {
                      caughtError.message = `(${colors.yellow(`entry #${index + 1}`)}) ${caughtError.message}`;
                      push(caughtError);
                    }
                  }

                  processResults.push({
                    header: headerObject,
                    entries: entryObjects,
                  });
                });
              }));
            break;

          case documentModes.onePerFile:
            map(yamlResults, {message: `Errors processing data files as valid documents`},
              decorateErrorWithFile(({documents}) => {
                if (documents.length > 1)
                  throw new Error(`Only expected one document to be present per file, got ${documents.length} here`);

                if (empty(documents) || !documents[0])
                  throw new Error(`Expected a document, this file is empty`);

                const {thing, aggregate} =
                  dataStep.processDocument(documents[0]);

                processResults.push(thing);
                aggregate.close();
              }));
            break;
        }

        const saveResult = call(dataStep.save, processResults);

        if (!saveResult) return;

        Object.assign(wikiDataResult, saveResult);
      }
    );
  }

  return {
    aggregate: processDataAggregate,
    result: wikiDataResult,
  };
}

// Data linking! Basically, provide (portions of) wikiData to the Things which
// require it - they'll expose dynamically computed properties as a result (many
// of which are required for page HTML generation and other expected behavior).
//
// The XXX_decacheWikiData option should be used specifically to mark
// points where you *aren't* replacing any of the arrays under wikiData with
// new values, and are using linkWikiDataArrays to instead "decache" data
// properties which depend on any of them. It's currently not possible for
// a CacheableObject to depend directly on the value of a property exposed
// on some other CacheableObject, so when those values change, you have to
// manually decache before the object will realize its cache isn't valid
// anymore.
export function linkWikiDataArrays(wikiData, {
  XXX_decacheWikiData = false,
} = {}) {
  function assignWikiData(things, ...keys) {
    if (things === undefined) return;
    for (let i = 0; i < things.length; i++) {
      const thing = things[i];
      for (let j = 0; j < keys.length; j++) {
        const key = keys[j];
        if (!(key in wikiData)) continue;
        if (XXX_decacheWikiData) thing[key] = [];
        thing[key] = wikiData[key];
      }
    }
  }

  const WD = wikiData;

  assignWikiData([WD.wikiInfo], 'groupData');

  assignWikiData(WD.albumData, 'artistData', 'artTagData', 'groupData', 'trackData');
  assignWikiData(WD.trackData, 'albumData', 'artistData', 'artTagData', 'flashData', 'trackData');
  assignWikiData(WD.artistData, 'albumData', 'artistData', 'flashData', 'trackData');
  assignWikiData(WD.groupData, 'albumData', 'groupCategoryData');
  assignWikiData(WD.groupCategoryData, 'groupData');
  assignWikiData(WD.flashData, 'artistData', 'flashActData', 'trackData');
  assignWikiData(WD.flashActData, 'flashData');
  assignWikiData(WD.artTagData, 'albumData', 'trackData');
  assignWikiData(WD.homepageLayout?.rows, 'albumData', 'groupData');
}

export function sortWikiDataArrays(wikiData) {
  Object.assign(wikiData, {
    albumData: sortChronologically(wikiData.albumData.slice()),
    trackData: sortAlbumsTracksChronologically(wikiData.trackData.slice()),
    flashData: sortFlashesChronologically(wikiData.flashData.slice()),
  });

  // Re-link data arrays, so that every object has the new, sorted versions.
  // Note that the sorting step deliberately creates new arrays (mutating
  // slices instead of the original arrays) - this is so that the object
  // caching system understands that it's working with a new ordering.
  // We still need to actually provide those updated arrays over again!
  linkWikiDataArrays(wikiData);
}

// Warn about directories which are reused across more than one of the same type
// of Thing. Directories are the unique identifier for most data objects across
// the wiki, so we have to make sure they aren't duplicated!  This also
// altogether filters out instances of things with duplicate directories (so if
// two tracks share the directory "megalovania", they'll both be skipped for the
// build, for example).
export function filterDuplicateDirectories(wikiData) {
  const deduplicateSpec = [
    'albumData',
    'artTagData',
    'artistData',
    'flashData',
    'flashActData',
    'groupData',
    'newsData',
    'trackData',
  ];

  const aggregate = openAggregate({message: `Duplicate directories found`});
  for (const thingDataProp of deduplicateSpec) {
    const thingData = wikiData[thingDataProp];
    aggregate.nest({message: `Duplicate directories found in ${colors.green('wikiData.' + thingDataProp)}`}, ({call}) => {
      const directoryPlaces = Object.create(null);
      const duplicateDirectories = [];

      for (const thing of thingData) {
        const {directory} = thing;
        if (directory in directoryPlaces) {
          directoryPlaces[directory].push(thing);
          duplicateDirectories.push(directory);
        } else {
          directoryPlaces[directory] = [thing];
        }
      }

      if (empty(duplicateDirectories)) return;

      duplicateDirectories.sort((a, b) => {
        const aL = a.toLowerCase();
        const bL = b.toLowerCase();
        return aL < bL ? -1 : aL > bL ? 1 : 0;
      });

      for (const directory of duplicateDirectories) {
        const places = directoryPlaces[directory];
        call(() => {
          throw new Error(
            `Duplicate directory ${colors.green(directory)}:\n` +
              places.map((thing) => ` - ` + inspect(thing)).join('\n')
          );
        });
      }

      const allDuplicatedThings = Object.values(directoryPlaces)
        .filter((arr) => arr.length > 1)
        .flat();

      const filteredThings = thingData
        .filter((thing) => !allDuplicatedThings.includes(thing));

      wikiData[thingDataProp] = filteredThings;
    });
  }

  // TODO: This code closes the aggregate but it generally gets closed again
  // by the caller. This works but it might be weird to assume closing an
  // aggregate twice is okay, maybe there's a better solution? Expose a new
  // function on aggregates for checking if it *would* error?
  // (i.e: errors.length > 0)
  try {
    aggregate.close();
  } catch (error) {
    // Duplicate entries were found and filtered out, resulting in altered
    // wikiData arrays. These must be re-linked so objects receive the new
    // data.
    linkWikiDataArrays(wikiData);
  }
  return aggregate;
}

// Warn about references across data which don't match anything.  This involves
// using the find() functions on all references, setting it to 'error' mode, and
// collecting everything in a structured logged (which gets logged if there are
// any errors). At the same time, we remove errored references from the thing's
// data array.
export function filterReferenceErrors(wikiData) {
  const referenceSpec = [
    ['wikiInfo', processWikiInfoDocument, {
      divideTrackListsByGroups: 'group',
    }],

    ['albumData', processAlbumDocument, {
      artistContribs: '_contrib',
      coverArtistContribs: '_contrib',
      trackCoverArtistContribs: '_contrib',
      wallpaperArtistContribs: '_contrib',
      bannerArtistContribs: '_contrib',
      groups: 'group',
      artTags: 'artTag',
    }],

    ['trackData', processTrackDocument, {
      artistContribs: '_contrib',
      contributorContribs: '_contrib',
      coverArtistContribs: '_contrib',
      referencedTracks: '_trackNotRerelease',
      sampledTracks: '_trackNotRerelease',
      artTags: 'artTag',
      originalReleaseTrack: '_trackNotRerelease',
    }],

    ['groupCategoryData', processGroupCategoryDocument, {
      groups: 'group',
    }],

    ['homepageLayout.rows', undefined, {
      sourceGroup: '_homepageSourceGroup',
      sourceAlbums: 'album',
    }],

    ['flashData', processFlashDocument, {
      contributorContribs: '_contrib',
      featuredTracks: 'track',
    }],

    ['flashActData', processFlashActDocument, {
      flashes: 'flash',
    }],
  ];

  function getNestedProp(obj, key) {
    const recursive = (o, k) =>
      k.length === 1 ? o[k[0]] : recursive(o[k[0]], k.slice(1));
    const keys = key.split(/(?<=(?<!\\)(?:\\\\)*)\./);
    return recursive(obj, keys);
  }

  const aggregate = openAggregate({message: `Errors validating between-thing references in data`});
  const boundFind = bindFind(wikiData, {mode: 'error'});
  for (const [thingDataProp, providedProcessDocumentFn, propSpec] of referenceSpec) {
    const thingData = getNestedProp(wikiData, thingDataProp);

    aggregate.nest({message: `Reference errors in ${colors.green('wikiData.' + thingDataProp)}`}, ({nest}) => {
      const things = Array.isArray(thingData) ? thingData : [thingData];

      for (const thing of things) {
        let processDocumentFn = providedProcessDocumentFn;

        if (processDocumentFn === undefined) {
          switch (thingDataProp) {
            case 'homepageLayout.rows':
              processDocumentFn = homepageLayoutRowTypeProcessMapping[thing.type]
              break;
          }
        }

        nest({message: `Reference errors in ${inspect(thing)}`}, ({nest, push, filter}) => {
          for (const [property, findFnKey] of Object.entries(propSpec)) {
            const value = CacheableObject.getUpdateValue(thing, property);

            if (value === undefined) {
              push(new TypeError(`Property ${colors.red(property)} isn't valid for ${colors.green(thing.constructor.name)}`));
              continue;
            }

            if (value === null) {
              continue;
            }

            let findFn;

            switch (findFnKey) {
              case '_contrib':
                findFn = contribRef => {
                  const alias = find.artist(contribRef.who, wikiData.artistAliasData, {mode: 'quiet'});
                  if (alias) {
                    // No need to check if the original exists here. Aliases are automatically
                    // created from a field on the original, so the original certainly exists.
                    const original = alias.aliasedArtist;
                    throw new Error(`Reference ${colors.red(contribRef.who)} is to an alias, should be ${colors.green(original.name)}`);
                  }

                  return boundFind.artist(contribRef.who);
                };
                break;

              case '_homepageSourceGroup':
                findFn = groupRef => {
                  if (groupRef === 'new-additions' || groupRef === 'new-releases') {
                    return true;
                  }

                  return boundFind.group(groupRef);
                };
                break;

              case '_trackNotRerelease':
                findFn = trackRef => {
                  const track = find.track(trackRef, wikiData.trackData, {mode: 'error'});
                  const originalRef = track && CacheableObject.getUpdateValue(track, 'originalReleaseTrack');

                  if (originalRef) {
                    // It's possible for the original to not actually exist, in this case.
                    // It should still be reported since the 'Originally Released As' field
                    // was present.
                    const original = find.track(originalRef, wikiData.trackData, {mode: 'quiet'});

                    // Prefer references by name, but only if it's unambiguous.
                    const originalByName =
                      (original
                        ? find.track(original.name, wikiData.trackData, {mode: 'quiet'})
                        : null);

                    const shouldBeMessage =
                      (originalByName
                        ? colors.green(original.name)
                     : original
                        ? colors.green('track:' + original.directory)
                        : colors.green(originalRef));

                    throw new Error(`Reference ${colors.red(trackRef)} is to a rerelease, should be ${shouldBeMessage}`);
                  }

                  return track;
                };
                break;

              default:
                findFn = boundFind[findFnKey];
                break;
            }

            const suppress = fn => conditionallySuppressError(error => {
              if (property === 'sampledTracks') {
                // Suppress "didn't match anything" errors in particular, just for samples.
                // In hsmusic-data we have a lot of "stub" sample data which don't have
                // corresponding tracks yet, so it won't be useful to report such reference
                // errors until we take the time to address that. But other errors, like
                // malformed reference strings or miscapitalized existing tracks, should
                // still be reported, as samples of existing tracks *do* display on the
                // website!
                if (error.message.includes(`Didn't match anything`)) {
                  return true;
                }
              }

              return false;
            }, fn);

            const fieldPropertyMessage =
              (processDocumentFn?.propertyFieldMapping?.[property]
                ? ` in field ${colors.green(processDocumentFn.propertyFieldMapping[property])}`
                : ` in property ${colors.green(property)}`);

            const findFnMessage =
              (findFnKey.startsWith('_')
                ? ``
                : ` (${colors.green('find.' + findFnKey)})`);

            const errorMessage =
              (Array.isArray(value)
                ? `Reference errors` + fieldPropertyMessage + findFnMessage
                : `Reference error` + fieldPropertyMessage + findFnMessage);

            if (Array.isArray(value)) {
              thing[property] = filter(
                value,
                decorateErrorWithIndex(suppress(findFn)),
                {message: errorMessage});
            } else {
              nest({message: errorMessage},
                suppress(({call}) => {
                  try {
                    call(findFn, value);
                  } catch (error) {
                    thing[property] = null;
                    throw error;
                  }
                }));
            }
          }
        });
      }
    });
  }

  return aggregate;
}

// Utility function for loading all wiki data from the provided YAML data
// directory (e.g. the root of the hsmusic-data repository). This doesn't
// provide much in the way of customization; it's meant to be used more as
// a boilerplate for more specialized output, or as a quick start in utilities
// where reporting info about data loading isn't as relevant as during the
// main wiki build process.
export async function quickLoadAllFromYAML(dataPath, {
  showAggregate: customShowAggregate = showAggregate,
} = {}) {
  const showAggregate = customShowAggregate;

  let wikiData;

  {
    const {aggregate, result} = await loadAndProcessDataDocuments({dataPath});

    wikiData = result;

    try {
      aggregate.close();
      logInfo`Loaded data without errors. (complete data)`;
    } catch (error) {
      showAggregate(error);
      logWarn`Loaded data with errors. (partial data)`;
    }
  }

  linkWikiDataArrays(wikiData);

  try {
    filterDuplicateDirectories(wikiData).close();
    logInfo`No duplicate directories found. (complete data)`;
  } catch (error) {
    showAggregate(error);
    logWarn`Duplicate directories found. (partial data)`;
  }

  try {
    filterReferenceErrors(wikiData).close();
    logInfo`No reference errors found. (complete data)`;
  } catch (error) {
    showAggregate(error);
    logWarn`Reference errors found. (partial data)`;
  }

  sortWikiDataArrays(wikiData);

  return wikiData;
}