« get me outta code hell

upd8.js « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/upd8.js
blob: de36725421728bc92aa8e9b017c9953ae3795339 (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
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
#!/usr/bin/env node

// HEY N8RDS!
//
// This is one of the 8ACKEND FILES. It's not used anywhere on the actual site
// you are pro8a8ly using right now.
//
// Specifically, this one does all the actual work of the music wiki. The
// process looks something like this:
//
//   1. Crawl the music directories. Well, not so much "crawl" as "look inside
//      the folders for each al8um, and read the metadata file descri8ing that
//      al8um and the tracks within."
//
//   2. Read that metadata. I'm writing this 8efore actually doing any of the
//      code, and I've gotta admit I have no idea what file format they're
//      going to 8e in. May8e JSON, 8ut more likely some weird custom format
//      which will 8e a lot easier to edit.
//
//      Like three years later oh god: SURPISE! We went with the latter, but
//      they're YAML now. Probably. Assuming that hasn't changed, yet.
//
//   3. Generate the page files! They're just static index.html files, and are
//      what gh-pages (or wherever this is hosted) will show to clients.
//      Hopefully pretty minimalistic HTML, 8ut like, shrug. They'll reference
//      CSS (and maaaaaaaay8e JS) files, hard-coded somewhere near the root.
//
//   4. Print an awesome message which says the process is done. This is the
//      most important step.
//
// Oh yeah, like. Just run this through some relatively recent version of
// node.js and you'll 8e fine. ...Within the project root. O8viously.

import {execSync} from 'node:child_process';
import {readFile} from 'node:fs/promises';
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';

import wrap from 'word-wrap';

import CacheableObject from '#cacheable-object';
import {displayCompositeCacheAnalysis} from '#composite';
import {processLanguageFile, watchLanguageFile, internalDefaultStringsFile}
  from '#language';
import {isMain, traverse} from '#node-utils';
import {empty, showAggregate, withEntries} from '#sugar';
import {generateURLs, urlSpec} from '#urls';
import {sortByName} from '#wiki-data';

import {
  colors,
  decorateTime,
  fileIssue,
  logWarn,
  logInfo,
  logError,
  parseOptions,
  progressCallAll,
} from '#cli';

import genThumbs, {
  CACHE_FILE as thumbsCacheFile,
  defaultMagickThreads,
  determineMediaCachePath,
  isThumb,
  migrateThumbsIntoDedicatedCacheDirectory,
  verifyImagePaths,
} from '#thumbs';

import {
  filterDuplicateDirectories,
  filterReferenceErrors,
  linkWikiDataArrays,
  loadAndProcessDataDocuments,
  sortWikiDataArrays,
  WIKI_INFO_FILE,
} from '#yaml';

import FileSizePreloader from './file-size-preloader.js';
import {listingSpec, listingTargetSpec} from './listing-spec.js';
import * as buildModes from './write/build-modes/index.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const CACHEBUST = 23;

let COMMIT;
try {
  COMMIT = execSync('git log --format="%h %B" -n 1 HEAD', {cwd: __dirname}).toString().trim();
} catch (error) {
  COMMIT = '(failed to detect)';
}

const BUILD_TIME = new Date();

const STATUS_NOT_STARTED       = `not started`;
const STATUS_NOT_APPLICABLE    = `not applicable`;
const STATUS_STARTED_NOT_DONE  = `started but not yet done`;
const STATUS_DONE_CLEAN        = `done without warnings`;
const STATUS_FATAL_ERROR       = `fatal error`;
const STATUS_HAS_WARNINGS      = `has warnings`;

const defaultStepStatus = {status: STATUS_NOT_STARTED, annotation: null};

// Defined globally for quick access outside the main() function's contents.
// This will be initialized and mutated over the course of main().
let stepStatusSummary;
let showStepStatusSummary = false;

async function main() {
  Error.stackTraceLimit = Infinity;

  stepStatusSummary = {
    determineMediaCachePath:
      {...defaultStepStatus, name: `determine media cache path`},

    migrateThumbnails:
      {...defaultStepStatus, name: `migrate thumbnails`},

    loadThumbnailCache:
      {...defaultStepStatus, name: `load thumbnail cache file`},

    generateThumbnails:
      {...defaultStepStatus, name: `generate thumbnails`},

    loadDataFiles:
      {...defaultStepStatus, name: `load and process data files`},

    linkWikiDataArrays:
      {...defaultStepStatus, name: `link wiki data arrays`},

    precacheCommonData:
      {...defaultStepStatus, name: `precache common data`},

    filterDuplicateDirectories:
      {...defaultStepStatus, name: `filter duplicate directories`},

    filterReferenceErrors:
      {...defaultStepStatus, name: `filter reference errors`},

    sortWikiDataArrays:
      {...defaultStepStatus, name: `sort wiki data arrays`},

    precacheAllData:
      {...defaultStepStatus, name: `precache nearly all data`},

    // TODO: This should be split into load/watch steps.
    loadInternalDefaultLanguage:
      {...defaultStepStatus, name: `load internal default language`},

    loadLanguageFiles:
      {...defaultStepStatus, name: `statically load custom language files`},

    watchLanguageFiles:
      {...defaultStepStatus, name: `watch custom language files`},

    initializeDefaultLanguage:
      {...defaultStepStatus, name: `initialize default language`},

    verifyImagePaths:
      {...defaultStepStatus, name: `verify missing/misplaced image paths`},

    preloadFileSizes:
      {...defaultStepStatus, name: `preload file sizes`},

    performBuild:
      {...defaultStepStatus, name: `perform selected build mode`},
  };

  const defaultQueueSize = 500;

  const buildModeFlagOptions = (
    withEntries(buildModes, entries =>
      entries.map(([key, mode]) => [key, {
        help: mode.description,
        type: 'flag',
      }])));

  const selectedBuildModeFlags = Object.keys(
    await parseOptions(process.argv.slice(2), {
      [parseOptions.handleUnknown]: () => {},
      ...buildModeFlagOptions,
    }));

  let selectedBuildModeFlag;
  let usingDefaultBuildMode;

  if (empty(selectedBuildModeFlags)) {
    selectedBuildModeFlag = 'static-build';
    usingDefaultBuildMode = true;
  } else if (selectedBuildModeFlags.length > 1) {
    logError`Building multiple modes (${selectedBuildModeFlags.join(', ')}) at once not supported.`;
    logError`Please specify a maximum of one build mode.`;
    return false;
  } else {
    selectedBuildModeFlag = selectedBuildModeFlags[0];
    usingDefaultBuildMode = false;
  }

  const selectedBuildMode = buildModes[selectedBuildModeFlag];

  // This is about to get a whole lot more stuff put in it.
  const wikiData = {
    listingSpec,
    listingTargetSpec,
  };

  const buildOptions = selectedBuildMode.getCLIOptions();

  const commonOptions = {
    'help': {
      help: `Display usage info and basic information for the \`hsmusic\` command`,
      type: 'flag',
    },

    // Data files for the site, including flash, artist, and al8um data,
    // and like a jillion other things too. Pretty much everything which
    // makes an individual wiki what it is goes here!
    'data-path': {
      help: `Specify path to data directory, including YAML files that cover all info about wiki content, layout, and structure\n\nAlways required for wiki building, but may be provided via the HSMUSIC_DATA environment variable instead`,
      type: 'value',
    },

    // Static media will 8e referenced in the site here! The contents are
    // categorized; check out MEDIA_ALBUM_ART_DIRECTORY and other constants
    // near the top of this file (upd8.js).
    'media-path': {
      help: `Specify path to media directory, including album artwork and additional files, as well as custom site layout media and other media files for reference or linking in wiki content\n\nAlways required for wiki building, but may be provided via the HSMUSIC_MEDIA environment variable instead`,
      type: 'value',
    },

    'media-cache-path': {
      help: `Specify path to media cache directory, including automatically generated thumbnails\n\nThis usually doesn't need to be provided, and will be inferred by adding "-cache" to the end of the media directory`,
      type: 'value',
    },

    // String files! For the most part, this is used for translating the
    // site to different languages, though you can also customize strings
    // for your own 8uild of the site if you'd like. Files here should all
    // match the format in strings-default.json in this repository. (If a
    // language file is missing any strings, the site code will fall 8ack
    // to what's specified in strings-default.json.)
    //
    // Unlike the other options here, this one's optional - the site will
    // 8uild with the default (English) strings if this path is left
    // unspecified.
    'lang-path': {
      help: `Specify path to language directory, including JSON files that mapping internal string keys to localized language content, and various language metadata\n\nOptional for wiki building, unless the wiki's default language is not English; may be provided via the HSMUSIC_LANG environment variable instead`,
      type: 'value',
    },

    'skip-reference-validation': {
      help: `Skips checking and reporting reference errors, which speeds up the build but may silently allow erroneous data to pass through`,
      type: 'flag',
    },

    // Thum8nail gener8tion is *usually* something you want, 8ut it can 8e
    // kinda a pain to run every time, since it does necessit8te reading
    // every media file at run time. Pass this to skip it.
    'skip-thumbs': {
      help: `Skip processing and generating thumbnails in media directory (speeds up subsequent builds, but remove this option [or use --thumbs-only] and re-run once when you add or modify media files to ensure thumbnails stay up-to-date!)`,
      type: 'flag',
    },

    // Or, if you *only* want to gener8te newly upd8ted thum8nails, you can
    // pass this flag! It exits 8efore 8uilding the rest of the site.
    'thumbs-only': {
      help: `Skip everything besides processing media directory and generating up-to-date thumbnails (useful when using --skip-thumbs for most runs)`,
      type: 'flag',
    },

    'migrate-thumbs': {
      help: `Transfer automatically generated thumbnail files out of an existing media directory and into the easier-to-manage media-cache directory`,
      type: 'flag',
    },

    'skip-file-sizes': {
      help: `Skips preloading file sizes for images and additional files, which will be left blank in the build`,
      type: 'flag',
    },

    'skip-media-validation': {
      help: `Skips checking and reporting missing and misplaced media files, which isn't necessary if you aren't adding or removing data or updating directories`,
      type: 'flag',
    },

    // Just working on data entries and not interested in actually
    // generating site HTML yet? This flag will cut execution off right
    // 8efore any site 8uilding actually happens.
    'no-build': {
      help: `Don't run a build of the site at all; only process data/media and report any errors detected`,
      type: 'flag',
    },

    'no-input': {
      help: `Don't wait on input from stdin - assume the device is headless`,
      type: 'flag',
    },

    'no-language-reloading': {
      help: `Don't reload language files while the build is running\n\nApplied by default for --static-build`,
      type: 'flag',
    },

    'no-language-reload': {alias: 'no-language-reloading'},

    // Want sweet, sweet trace8ack info in aggreg8te error messages? This
    // will print all the juicy details (or at least the first relevant
    // line) right to your output, 8ut also pro8a8ly give you a headache
    // 8ecause wow that is a lot of visual noise.
    'show-traces': {
      help: `Show JavaScript source code paths for reported errors in "aggregate" error displays\n\n(Debugging use only, but please enable this if you're reporting bugs for our issue tracker!)`,
      type: 'flag',
    },

    'show-step-summary': {
      help: `Show a summary of all the top-level build steps once hsmusic exits. This is mostly useful for progammer debugging!`,
      type: 'flag',
    },

    'queue-size': {
      help: `Process more or fewer disk files at once to optimize performance or avoid I/O errors, unlimited if set to 0 (between 500 and 700 is usually a safe range for building HSMusic on Windows machines)\nDefaults to ${defaultQueueSize}`,
      type: 'value',
      validate(size) {
        if (parseInt(size) !== parseFloat(size)) return 'an integer';
        if (parseInt(size) < 0) return 'a counting number or zero';
        return true;
      },
    },
    queue: {alias: 'queue-size'},

    'magick-threads': {
      help: `Process more or fewer thumbnail files at once with ImageMagick when generating thumbnails. (Each ImageMagick thread may also make use of multi-core processing at its own utility.)`,
      type: 'value',
      validate(threads) {
        if (parseInt(threads) !== parseFloat(threads)) return 'an integer';
        if (parseInt(threads) < 0) return 'a counting number or zero';
        return true;
      }
    },
    magick: {alias: 'magick-threads'},

    // This option is super slow and has the potential for bugs! It puts
    // CacheableObject in a mode where every instance is a Proxy which will
    // keep track of invalid property accesses.
    'show-invalid-property-accesses': {
      help: `Report accesses at runtime to nonexistant properties on wiki data objects, at a dramatic performance cost\n(Internal/development use only)`,
      type: 'flag',
    },

    'precache-mode': {
      help:
        `Change the way certain runtime-computed values are preemptively evaluated and cached\n\n` +
        `common: Preemptively compute certain properties which are needed for basic data loading and site generation\n\n` +
        `all: Compute every visible data property, optimizing rate of content generation, but causing a long stall before the build actually starts\n\n` +
        `none: Don't preemptively compute any values - strictly the most efficient, but may result in unpredictably "lopsided" performance for individual steps of loading data and building the site\n\n` +
        `Defaults to 'common'`,
      type: 'value',
      validate(value) {
        if (['common', 'all', 'none'].includes(value)) return true;
        return 'common, all, or none';
      },
    },
  };

  const cliOptions = await parseOptions(process.argv.slice(2), {
    // We don't want to error when we receive these options, so specify them
    // here, even though we won't be doing anything with them later.
    // (This is a bit of a hack.)
    ...buildModeFlagOptions,

    ...commonOptions,
    ...buildOptions,
  });

  if (cliOptions['help']) {
    const indentWrap = (spaces, str) => wrap(str, {width: 60 - spaces, indent: ' '.repeat(spaces)});

    const showOptions = (msg, options) => {
      console.log(colors.bright(msg));

      const entries = Object.entries(options);
      const sortedOptions = sortByName(entries
        .map(([name, descriptor]) => ({name, descriptor})));

      if (!sortedOptions.length) {
        console.log(`(No options available)`)
      }

      let justInsertedPaddingLine = false;

      for (const {name, descriptor} of sortedOptions) {
        if (descriptor.alias) {
          continue;
        }

        const aliases = entries
          .filter(([_name, {alias}]) => alias === name)
          .map(([name]) => name);

        let wrappedHelp, wrappedHelpLines = 0;
        if (descriptor.help) {
          wrappedHelp = indentWrap(4, descriptor.help);
          wrappedHelpLines = wrappedHelp.split('\n').length;
        }

        if (wrappedHelpLines > 0 && !justInsertedPaddingLine) {
          console.log('');
        }

        console.log(colors.bright(` --` + name) +
          (aliases.length
            ? ` (or: ${aliases.map(alias => colors.bright(`--` + alias)).join(', ')})`
            : '') +
          (descriptor.help
            ? ''
            : colors.dim('  (no help provided)')));

        if (wrappedHelp) {
          console.log(wrappedHelp);
        }

        if (wrappedHelpLines > 1) {
          console.log('');
          justInsertedPaddingLine = true;
        } else {
          justInsertedPaddingLine = false;
        }
      }

      if (!justInsertedPaddingLine) {
        console.log(``);
      }
    };

    console.log(
      colors.bright(`hsmusic (aka. Homestuck Music Wiki)\n`) +
      `static wiki software cataloguing collaborative creation\n`);

    console.log(indentWrap(0,
      `The \`hsmusic\` command provides basic control over all parts of generating user-visible HTML pages and website content/structure from provided data, media, and language directories.\n` +
      `\n` +
      `CLI options are divided into three groups:\n`));
    console.log(` 1) ` + indentWrap(4,
      `Common options: These are shared by all build modes and always have the same essential behavior`).trim());
    console.log(` 2) ` + indentWrap(4,
      `Build mode selection: One build mode may be selected (or else the default, --static-build, is used), and it decides which entire set of behavior to use for providing site content to the user`).trim());
    console.log(` 3) ` + indentWrap(4,
      `Build options: Each build mode has a set of unique options which customize behavior for that build mode`).trim());
    console.log(``);

    showOptions(`Common options`, commonOptions);
    showOptions(`Build mode selection`, buildModeFlagOptions);

    if (buildOptions) {
      showOptions(`Build options for --${selectedBuildModeFlag} (${
        usingDefaultBuildMode ? 'default' : 'selected'
      })`, buildOptions);
    }

    return true;
  }

  const dataPath = cliOptions['data-path'] || process.env.HSMUSIC_DATA;
  const mediaPath = cliOptions['media-path'] || process.env.HSMUSIC_MEDIA;
  const langPath = cliOptions['lang-path'] || process.env.HSMUSIC_LANG; // Can 8e left unset!

  const thumbsOnly = cliOptions['thumbs-only'] ?? false;
  const noInput = cliOptions['no-input'] ?? false;

  showStepStatusSummary = cliOptions['show-step-summary'] ?? false;

  const showAggregateTraces = cliOptions['show-traces'] ?? false;

  const precacheMode = cliOptions['precache-mode'] ?? 'common';
  const showInvalidPropertyAccesses = cliOptions['show-invalid-property-accesses'] ?? false;

  // Makes writing nicer on the CPU and file I/O parts of the OS, with a
  // marginal performance deficit while waiting for file writes to finish
  // before proceeding to more page processing.
  const queueSize = +(cliOptions['queue-size'] ?? defaultQueueSize);

  const magickThreads = +(cliOptions['magick-threads'] ?? defaultMagickThreads);

  if (!dataPath) {
    logError`${`Expected --data-path option or HSMUSIC_DATA to be set`}`;
  }

  if (!mediaPath) {
    logError`${`Expected --media-path option or HSMUSIC_MEDIA to be set`}`;
  }

  if (!dataPath || !mediaPath) {
    return false;
  }

  if (cliOptions['no-build']) {
    logInfo`Won't generate any site or page files this run (--no-build passed).`;

    Object.assign(stepStatusSummary.performBuild, {
      status: STATUS_NOT_APPLICABLE,
      annotation: `--no-build provided`,
    });
  } else {
    if (usingDefaultBuildMode) {
      logInfo`No build mode specified, will use default: ${selectedBuildModeFlag}`;
    } else {
      logInfo`Will use specified build mode: ${selectedBuildModeFlag}`;
    }
  }

  // Finish setting up defaults by combining information from all options.

  const _fallbackStep = (stepKey, {
    default: defaultValue,

    cli: {
      flag: cliFlag = null,
      negate: cliFlagNegates = false,
      warn: cliFlagWarning = null,
    } = {},

    buildConfig: buildConfigKey,
  }) => {
    const {[buildConfigKey]: buildConfig} = selectedBuildMode.config;
    const {[stepKey]: step} = stepStatusSummary;

    if (cliFlag && cliOptions[cliFlag]) {
      const cliPart = `--` + cliFlag;
      const modePart = `--` + selectedBuildModeFlag;
      if (buildConfig?.applicable === false) {
        if (cliFlagNegates) {
          logWarn`${cliPart} provided, but ${modePart} already skips this step`;
          logWarn`Redundant option ${cliPart}`;
        } else {
          logWarn`${cliPart} provided, but this step isn't applicable for ${modePart}`;
          logWarn`Ignoring option ${cliPart}`;
        }
      } else if (buildConfig?.required === true) {
        if (cliFlagNegates) {
          logWarn`${cliPart} provided, but ${modePart} requires this step`;
          logWarn`Ignoring option ${cliPart}`;
        } else {
          logWarn`${cliPart} provided, but ${modePart} already requires this step`;
          logWarn`Redundant option ${cliPart}`;
        }
      } else {
        if (cliFlagNegates) {
          step.status = STATUS_NOT_APPLICABLE;
          step.annotation = `--${cliFlag} provided`;
        }
        if (cliFlagWarning) {
          for (const line of cliFlagWarning.split('\n')) {
            logWarn(line);
          }
        }
      }
    }

    if (buildConfig?.applicable === false) {
      step.status = STATUS_NOT_APPLICABLE;
      step.annotation = `N/A for --${selectedBuildModeFlag}`;
      return;
    }

    if (buildConfig?.default === 'skip') {
      step.status = STATUS_NOT_APPLICABLE;
      step.annotation = `default for --${selectedBuildModeFlag}`;
      return;
    }

    switch (defaultValue) {
      case 'skip':
        step.status = STATUS_NOT_APPLICABLE;
        if (cliFlag && !cliFlagNegates) {
          step.annotation = `--${cliFlag} not provided`;
        }
        break;

      case 'perform':
        break;

      default:
        throw new Error(`Invalid default step status ${defaultValue}`);
    }
  };

  {
    let errored = false;

    const fallbackStep = (stepKey, options) => {
      try {
        _fallbackStep(stepKey, options);
      } catch (error) {
        logError`Error determining fallback for step ${stepKey}`;
        showAggregate(error);
        errored = true;
      }
    };

    fallbackStep('filterReferenceErrors', {
      default: 'perform',
      buildConfig: null,
      cli: {
        flag: 'skip-reference-validation',
        negate: true,
        warn:
          `Skipping reference validation. If any reference errors are present\n` +
          `in data, they will be silently passed along to the build.`,
      }
    });

    fallbackStep('generateThumbnails', {
      default: 'perform',
      buildConfig: 'thumbs',
      cli: {
        flag: 'skip-thumbs',
        negate: true,
      },
    });

    fallbackStep('migrateThumbnails', {
      default: 'skip',
      buildConfig: null,
      cli: {
        flag: 'migrate-thumbs',
      },
    });

    fallbackStep('preloadFileSizes', {
      default: 'perform',
      buildConfig: 'fileSizes',
      cli: {
        flag: 'skip-file-sizes',
        negate: true,
      },
    });

    fallbackStep('verifyImagePaths', {
      default: 'perform',
      buildConfig: 'mediaValidation',
      cli: {
        flag: 'skip-media-validation',
        negate: true,
        warning:
          `Skipping media validation. If any media files are missing or misplaced,\n` +
          `those errors will be silently passed along to the build.`,
      },
    });

    fallbackStep('watchLanguageFiles', {
      default: 'perform',
      buildConfig: 'languageReloading',
      cli: {
        flag: 'no-language-reloading',
        negate: true,
      },
    });

    if (errored) {
      return false;
    }
  }

  if (stepStatusSummary.generateThumbnails.status === STATUS_NOT_STARTED) {
    Object.assign(stepStatusSummary.loadThumbnailCache, {
      status: STATUS_NOT_APPLICABLE,
      annotation: `using cache from thumbnail generation`,
    });
  }

  if (stepStatusSummary.watchLanguageFiles.status === STATUS_NOT_STARTED) {
    Object.assign(stepStatusSummary.loadLanguageFiles, {
      status: STATUS_NOT_APPLICABLE,
      annotation: `watching for changes instead`,
    });
  }

  switch (precacheMode) {
    case 'common':
      Object.assign(stepStatusSummary.precacheAllData, {
        status: STATUS_NOT_APPLICABLE,
        annotation: `--precache-mode is common, not all`,
      });

      break;

    case 'all':
      Object.assign(stepStatusSummary.precacheCommonData, {
        status: STATUS_NOT_APPLICABLE,
        annotation: `--precache-mode is all, not common`,
      });

      break;

    case 'none':
      Object.assign(stepStatusSummary.precacheCommonData, {
        status: STATUS_NOT_APPLICABLE,
        annotation: `--precache-mode is none`,
      });

      Object.assign(stepStatusSummary.precacheAllData, {
        status: STATUS_NOT_APPLICABLE,
        annotation: `--precache-mode is none`,
      });

      break;
  }

  if (!langPath) {
    Object.assign(stepStatusSummary.loadLanguageFiles, {
      status: STATUS_NOT_APPLICABLE,
      annotation: `neither --lang-path nor HSMUSIC_LANG provided`,
    });

    Object.assign(stepStatusSummary.watchLanguageFiles, {
      status: STATUS_NOT_APPLICABLE,
      annotation: `neither --lang-path nor HSMUSIC_LANG provided`,
    });
  }

  if (stepStatusSummary.generateThumbnails.status === STATUS_NOT_APPLICABLE && thumbsOnly) {
    logInfo`Well, you've put yourself rather between a roc and a hard place, hmmmm?`;
    return false;
  }

  Object.assign(stepStatusSummary.determineMediaCachePath, {
    status: STATUS_STARTED_NOT_DONE,
    timeStart: Date.now(),
  });

  const {mediaCachePath, annotation: mediaCachePathAnnotation} =
    await determineMediaCachePath({
      mediaPath,
      providedMediaCachePath:
        cliOptions['media-cache-path'] || process.env.HSMUSIC_MEDIA_CACHE,
      disallowDoubling:
        stepStatusSummary.migrateThumbnails.status === STATUS_NOT_STARTED,
    });

  if (!mediaCachePath) {
    logError`Couldn't determine a media cache path. (${mediaCachePathAnnotation})`;

    switch (mediaCachePathAnnotation) {
      case 'inferred path does not have cache':
        logError`If you're certain this is the right path, you can provide it via`;
        logError`${'--media-cache-path'} or ${'HSMUSIC_MEDIA_CACHE'}, and it should work.`;
        break;

      case 'inferred path not readable':
        logError`The folder couldn't be read, which usually indicates`;
        logError`a permissions error. Try to resolve this, or provide`;
        logError`a new path with ${'--media-cache-path'} or ${'HSMUSIC_MEDIA_CACHE'}.`;
        break;

      case 'media path not provided': /* unreachable */
        logError`It seems a ${'--media-path'} (or ${'HSMUSIC_MEDIA'}) wasn't provided.`;
        logError`Make sure one of these is actually pointing to a path that exists.`;
        break;
    }

    Object.assign(stepStatusSummary.determineMediaCachePath, {
      status: STATUS_FATAL_ERROR,
      annotation: mediaCachePathAnnotation,
      timeEnd: Date.now(),
    });

    return false;
  }

  logInfo`Using media cache at: ${mediaCachePath} (${mediaCachePathAnnotation})`;

  Object.assign(stepStatusSummary.determineMediaCachePath, {
    status: STATUS_DONE_CLEAN,
    annotation: mediaCachePathAnnotation,
    timeEnd: Date.now(),
  });

  if (stepStatusSummary.migrateThumbnails.status === STATUS_NOT_STARTED) {
    Object.assign(stepStatusSummary.migrateThumbnails, {
      status: STATUS_STARTED_NOT_DONE,
      timeStart: Date.now(),
    });

    const result = await migrateThumbsIntoDedicatedCacheDirectory({
      mediaPath,
      mediaCachePath,
      queueSize,
    });

    if (result.succses) {
      Object.assign(stepStatusSummary.migrateThumbnails, {
        status: STATUS_FATAL_ERROR,
        annotation: `view log for details`,
        timeEnd: Date.now(),
      });

      return false;
    }

    logInfo`Good to go! Run hsmusic again without ${'--migrate-thumbs'} to start`;
    logInfo`using the migrated media cache.`;

    Object.assign(stepStatusSummary.migrateThumbnails, {
      status: STATUS_DONE_CLEAN,
      timeEnd: Date.now(),
    });

    return true;
  }

  const niceShowAggregate = (error, ...opts) => {
    showAggregate(error, {
      showTraces: showAggregateTraces,
      pathToFileURL: (f) => path.relative(__dirname, fileURLToPath(f)),
      ...opts,
    });
  };

  if (
    stepStatusSummary.loadThumbnailCache.status === STATUS_NOT_STARTED &&
    stepStatusSummary.generateThumbnails.status === STATUS_NOT_STARTED
  ) {
    throw new Error(`Unable to continue with both loadThumbnailCache and generateThumbnails`);
  }

  let thumbsCache;

  if (stepStatusSummary.loadThumbnailCache.status === STATUS_NOT_STARTED) {
    Object.assign(stepStatusSummary.loadThumbnailCache, {
      status: STATUS_STARTED_NOT_DONE,
      timeStart: Date.now(),
    });

    const thumbsCachePath = path.join(mediaCachePath, thumbsCacheFile);

    try {
      thumbsCache = JSON.parse(await readFile(thumbsCachePath));
    } catch (error) {
      if (error.code === 'ENOENT') {
        logError`The thumbnail cache doesn't exist, and it's necessary to build`
        logError`the website. Please run once without ${'--skip-thumbs'} - after`
        logError`that you'll be good to go and don't need to process thumbnails`
        logError`again!`;

        Object.assign(stepStatusSummary.loadThumbnailCache, {
          status: STATUS_FATAL_ERROR,
          annotation: `cache does not exist`,
          timeEnd: Date.now(),
        });

        return false;
      } else {
        logError`Malformed or unreadable thumbnail cache file: ${error}`;
        logError`Path: ${thumbsCachePath}`;
        logError`The thumbbnail cache is necessary to build the site, so you'll`;
        logError`have to investigate this to get the build working. Try running`;
        logError`again without ${'--skip-thumbs'}. If you can't get it working,`;
        logError`you're welcome to message in the HSMusic Discord and we'll try`;
        logError`to help you out with troubleshooting!`;
        logError`${'https://hsmusic.wiki/discord/'}`;

        Object.assign(stepStatusSummary.loadThumbnailCache, {
          status: STATUS_FATAL_ERROR,
          annotation: `cache malformed or unreadable`,
          timeEnd: Date.now(),
        });

        return false;
      }
    }

    logInfo`Thumbnail cache file successfully read.`;

    Object.assign(stepStatusSummary.loadThumbnailCache, {
      status: STATUS_DONE_CLEAN,
      timeEnd: Date.now(),
    });

    logInfo`Skipping thumbnail generation.`;
  } else if (stepStatusSummary.generateThumbnails.status === STATUS_NOT_STARTED) {
    Object.assign(stepStatusSummary.generateThumbnails, {
      status: STATUS_STARTED_NOT_DONE,
      timeStart: Date.now(),
    });

    logInfo`Begin thumbnail generation... -----+`;

    const result = await genThumbs({
      mediaPath,
      mediaCachePath,

      queueSize,
      magickThreads,
      quiet: !thumbsOnly,
    });

    logInfo`Done thumbnail generation! --------+`;

    if (!result.success) {
      Object.assign(stepStatusSummary.generateThumbnails, {
        status: STATUS_FATAL_ERROR,
        annotation: `view log for details`,
        timeEnd: Date.now(),
      });

      return false;
    }

    Object.assign(stepStatusSummary.generateThumbnails, {
      status: STATUS_DONE_CLEAN,
      timeEnd: Date.now(),
    });

    if (thumbsOnly) {
      return true;
    }

    thumbsCache = result.cache;
  } else {
    thumbsCache = {};
  }

  if (showInvalidPropertyAccesses) {
    CacheableObject.DEBUG_SLOW_TRACK_INVALID_PROPERTIES = true;
  }

  Object.assign(stepStatusSummary.loadDataFiles, {
    status: STATUS_STARTED_NOT_DONE,
    timeStart: Date.now(),
  });

  let processDataAggregate, wikiDataResult;

  try {
    ({aggregate: processDataAggregate, result: wikiDataResult} =
        await loadAndProcessDataDocuments({dataPath}));
  } catch (error) {
    console.error(error);

    logError`There was a JavaScript error loading data files.`;
    fileIssue();

    Object.assign(stepStatusSummary.loadDataFiles, {
      status: STATUS_FATAL_ERROR,
      annotation: `javascript error - view log for details`,
      timeEnd: Date.now(),
    });

    return false;
  }

  Object.assign(wikiData, wikiDataResult);

  {
    const logThings = (thingDataProp, label) =>
      logInfo` - ${wikiData[thingDataProp]?.length ?? colors.red('(Missing!)')} ${colors.normal(colors.dim(label))}`;
    try {
      logInfo`Loaded data and processed objects:`;
      logThings('albumData', 'albums');
      logThings('trackData', 'tracks');
      logThings('artistData', 'artists');
      if (wikiData.flashData) {
        logThings('flashData', 'flashes');
        logThings('flashActData', 'flash acts');
      }
      logThings('groupData', 'groups');
      logThings('groupCategoryData', 'group categories');
      logThings('artTagData', 'art tags');
      if (wikiData.newsData) {
        logThings('newsData', 'news entries');
      }
      logThings('staticPageData', 'static pages');
      if (wikiData.homepageLayout) {
        logInfo` - ${1} homepage layout (${
          wikiData.homepageLayout.rows.length
        } rows)`;
      }
      if (wikiData.wikiInfo) {
        logInfo` - ${1} wiki config file`;
      }
    } catch (error) {
      console.error(`Error showing data summary:`, error);
    }

    let errorless = true;
    try {
      processDataAggregate.close();
    } catch (error) {
      niceShowAggregate(error);
      logWarn`The above errors were detected while processing data files.`;
      errorless = false;
    }

    if (!wikiData.wikiInfo) {
      logError`Can't proceed without wiki info file (${WIKI_INFO_FILE}) successfully loading`;

      Object.assign(stepStatusSummary.loadDataFiles, {
        status: STATUS_FATAL_ERROR,
        annotation: `wiki info object not available`,
        timeEnd: Date.now(),
      });

      return false;
    }

    if (errorless) {
      logInfo`All data files processed without any errors - nice!`;

      Object.assign(stepStatusSummary.loadDataFiles, {
        status: STATUS_DONE_CLEAN,
        timeEnd: Date.now(),
      });
    } else {
      logWarn`If the remaining valid data is complete enough, the wiki will`;
      logWarn`still build - but all errored data will be skipped.`;
      logWarn`(Resolve errors for more complete output!)`;

      Object.assign(stepStatusSummary.loadDataFiles, {
        status: STATUS_HAS_WARNINGS,
        annotation: `view log for details`,
        timeEnd: Date.now(),
      });
    }
  }

  // Link data arrays so that all essential references between objects are
  // complete, so properties (like dates!) are inherited where that's
  // appropriate.

  Object.assign(stepStatusSummary.linkWikiDataArrays, {
    status: STATUS_STARTED_NOT_DONE,
    timeStart: Date.now(),
  });

  linkWikiDataArrays(wikiData);

  Object.assign(stepStatusSummary.linkWikiDataArrays, {
    status: STATUS_DONE_CLEAN,
    timeEnd: Date.now(),
  });

  if (precacheMode === 'common') {
    Object.assign(stepStatusSummary.precacheCommonData, {
      status: STATUS_STARTED_NOT_DONE,
      timeStart: Date.now(),
    });

    const commonDataMap = {
      albumData: new Set([
        // Needed for sorting
        'date', 'tracks',
        // Needed for computing page paths
        'commentary', 'coverArtistContribs',
      ]),

      artTagData: new Set([
        // Needed for computing page paths
        'isContentWarning',
      ]),

      artistAliasData: new Set([
        // Needed for computing page paths
        'aliasedArtist',
      ]),

      flashData: new Set([
        // Needed for sorting
        'act', 'date',
      ]),

      flashActData: new Set([
        // Needed for sorting
        'flashes',
      ]),

      groupData: new Set([
        // Needed for computing page paths
        'albums',
      ]),

      listingSpec: new Set([
        // Needed for computing page paths
        'contentFunction', 'featureFlag',
      ]),

      trackData: new Set([
        // Needed for sorting
        'album', 'date',
        // Needed for computing page paths
        'commentary', 'coverArtistContribs',
      ]),
    };

    for (const [wikiDataKey, properties] of Object.entries(commonDataMap)) {
      const thingData = wikiData[wikiDataKey];
      const allProperties = new Set(['name', 'directory', ...properties]);
      for (const thing of thingData) {
        for (const property of allProperties) {
          void thing[property];
        }
      }
    }

    Object.assign(stepStatusSummary.precacheCommonData, {
      status: STATUS_DONE_CLEAN,
      timeEnd: Date.now(),
    });
  }

  // Filter out any things with duplicate directories throughout the data,
  // warning about them too.

  Object.assign(stepStatusSummary.filterDuplicateDirectories, {
    status: STATUS_STARTED_NOT_DONE,
    timeStart: Date.now(),
  });

  const filterDuplicateDirectoriesAggregate =
    filterDuplicateDirectories(wikiData);

  try {
    filterDuplicateDirectoriesAggregate.close();
    logInfo`No duplicate directories found - nice!`;

    Object.assign(stepStatusSummary.filterDuplicateDirectories, {
      status: STATUS_DONE_CLEAN,
      timeEnd: Date.now(),
    });
  } catch (aggregate) {
    niceShowAggregate(aggregate);

    logWarn`The above duplicate directories were detected while reviewing data files.`;
    logWarn`Since it's impossible to automatically determine which one's directory is`;
    logWarn`correct, the build can't continue. Specify unique 'Directory' fields in`;
    logWarn`some or all of these data entries to resolve the errors.`;

    Object.assign(stepStatusSummary.filterDuplicateDirectories, {
      status: STATUS_FATAL_ERROR,
      annotation: `duplicate directories found`,
      timeEnd: Date.now(),
    });

    return false;
  }

  // Filter out any reference errors throughout the data, warning about them
  // too.

  if (stepStatusSummary.filterReferenceErrors.status === STATUS_NOT_STARTED) {
    Object.assign(stepStatusSummary.filterReferenceErrors, {
      status: STATUS_STARTED_NOT_DONE,
      timeStart: Date.now(),
    });

    const filterReferenceErrorsAggregate = filterReferenceErrors(wikiData);

    try {
      filterReferenceErrorsAggregate.close();

      logInfo`All references validated without any errors - nice!`;

      Object.assign(stepStatusSummary.filterReferenceErrors, {
        status: STATUS_DONE_CLEAN,
        timeEnd: Date.now(),
      });
    } catch (error) {
      niceShowAggregate(error);

      logWarn`The above errors were detected while validating references in data files.`;
      logWarn`The wiki will still build, but these connections between data objects`;
      logWarn`will be completely skipped. Resolve the errors for more complete output.`;

      Object.assign(stepStatusSummary.filterReferenceErrors, {
        status: STATUS_HAS_WARNINGS,
        annotation: `view log for details`,
        timeEnd: Date.now(),
      });
    }
  }

  // Sort data arrays so that they're all in order! This may use properties
  // which are only available after the initial linking.

  Object.assign(stepStatusSummary.sortWikiDataArrays, {
    status: STATUS_STARTED_NOT_DONE,
    timeStart: Date.now(),
  });

  sortWikiDataArrays(wikiData);

  Object.assign(stepStatusSummary.sortWikiDataArrays, {
    status: STATUS_DONE_CLEAN,
    timeEnd: Date.now(),
  });

  if (precacheMode === 'all') {
    Object.assign(stepStatusSummary.precacheAllData, {
      status: STATUS_STARTED_NOT_DONE,
      timeStart: Date.now(),
    });

    // TODO: Aggregate errors here, instead of just throwing.
    progressCallAll('Caching all data values', Object.entries(wikiData)
      .filter(([key]) =>
        key !== 'listingSpec' &&
        key !== 'listingTargetSpec')
      .map(([key, value]) =>
        key === 'wikiInfo' ? [key, [value]] :
        key === 'homepageLayout' ? [key, [value]] :
        [key, value])
      .flatMap(([_key, things]) => things)
      .map(thing => () => CacheableObject.cacheAllExposedProperties(thing)));

    Object.assign(stepStatusSummary.precacheAllData, {
      status: STATUS_DONE_CLEAN,
      timeEnd: Date.now(),
    });
  }

  if (stepStatusSummary.performBuild.status === STATUS_NOT_APPLICABLE) {
    displayCompositeCacheAnalysis();

    if (precacheMode === 'all') {
      return true;
    }
  }

  const languageReloading =
    stepStatusSummary.watchLanguageFiles.status === STATUS_NOT_STARTED;

  Object.assign(stepStatusSummary.loadInternalDefaultLanguage, {
    status: STATUS_STARTED_NOT_DONE,
    timeStart: Date.now(),
  });

  let internalDefaultLanguage;
  let internalDefaultLanguageWatcher;

  let errorLoadingInternalDefaultLanguage = false;

  if (languageReloading) {
    internalDefaultLanguageWatcher = watchLanguageFile(internalDefaultStringsFile);

    try {
      await new Promise((resolve, reject) => {
        const watcher = internalDefaultLanguageWatcher;

        const onReady = () => {
          watcher.removeListener('ready', onReady);
          watcher.removeListener('error', onError);
          resolve();
        };

        const onError = error => {
          watcher.removeListener('ready', onReady);
          watcher.removeListener('error', onError);
          watcher.close();
          reject(error);
        };

        watcher.on('ready', onReady);
        watcher.on('error', onError);
      });

      internalDefaultLanguage = internalDefaultLanguageWatcher.language;
    } catch (_error) {
      // No need to display the error here - it's already printed by
      // watchLanguageFile.
      errorLoadingInternalDefaultLanguage = true;
    }
  } else {
    internalDefaultLanguageWatcher = null;

    try {
      internalDefaultLanguage = await processLanguageFile(internalDefaultStringsFile);
    } catch (error) {
      niceShowAggregate(error);
      errorLoadingInternalDefaultLanguage = true;
    }
  }

  if (errorLoadingInternalDefaultLanguage) {
    logError`There was an error reading the internal language file.`;
    fileIssue();

    Object.assign(stepStatusSummary.loadInternalDefaultLanguage, {
      status: STATUS_FATAL_ERROR,
      annotation: `see log for details`,
      timeEnd: Date.now(),
    });

    return false;
  }

  if (languageReloading) {
    // Bypass node.js special-case handling for uncaught error events
    internalDefaultLanguageWatcher.on('error', () => {});
  }

  Object.assign(stepStatusSummary.loadInternalDefaultLanguage, {
    status: STATUS_DONE_CLEAN,
    timeEnd: Date.now(),
  });

  let customLanguageWatchers;
  let languages;

  if (langPath) {
    if (languageReloading) {
      Object.assign(stepStatusSummary.watchLanguageFiles, {
        status: STATUS_STARTED_NOT_DONE,
        timeStart: Date.now(),
      });
    } else {
      Object.assign(stepStatusSummary.loadLanguageFiles, {
        status: STATUS_STARTED_NOT_DONE,
        timeStart: Date.now(),
      });
    }

    const languageDataFiles = await traverse(langPath, {
      filterFile: name =>
        path.extname(name) === '.json' ||
        path.extname(name) === '.yaml',
      pathStyle: 'device',
    });

    let errorLoadingCustomLanguages = false;

    if (languageReloading) watchCustomLanguages: {
      Object.assign(stepStatusSummary.watchLanguageFiles, {
        status: STATUS_STARTED_NOT_DONE,
        timeStart: Date.now(),
      });

      customLanguageWatchers =
        languageDataFiles.map(file => {
          const watcher = watchLanguageFile(file);

          // Bypass node.js special-case handling for uncaught error events
          watcher.on('error', () => {});

          return watcher;
        });

      const waitingOnWatchers = new Set(customLanguageWatchers);

      const initialResults =
        await Promise.allSettled(
          customLanguageWatchers
            .map(watcher => new Promise((resolve, reject) => {
              const onReady = () => {
                watcher.removeListener('ready', onReady);
                watcher.removeListener('error', onError);
                waitingOnWatchers.delete(watcher);
                resolve();
              };

              const onError = error => {
                watcher.removeListener('ready', onReady);
                watcher.removeListener('error', onError);
                reject(error);
              };

              watcher.on('ready', onReady);
              watcher.on('error', onError);
            })));

      if (initialResults.some(({status}) => status === 'rejected')) {
        logWarn`There were errors loading custom languages from the language path`;
        logWarn`provided: ${langPath}`;

        if (noInput) {
          internalDefaultLanguageWatcher.close();

          for (const watcher of Object.values(customLanguageWatchers)) {
            watcher.close();
          }

          Object.assign(stepStatusSummary.watchLanguageFiles, {
            status: STATUS_FATAL_ERROR,
            annotation: `see log for details`,
            timeEnd: Date.now(),
          });

          errorLoadingCustomLanguages = true;
          break watchCustomLanguages;
        }

        logWarn`The build should start automatically if you investigate these.`;
        logWarn`Or, exit by pressing ^C here (control+C) and run again without`;
        logWarn`providing ${'--lang-path'} (or ${'HSMUSIC_LANG'}) to build without custom`;
        logWarn`languages.`;

        await new Promise(resolve => {
          for (const watcher of waitingOnWatchers) {
            watcher.once('ready', () => {
              waitingOnWatchers.remove(watcher);
              if (empty(waitingOnWatchers)) {
                resolve();
              }
            });
          }
        });
      }

      languages =
        Object.fromEntries(
          customLanguageWatchers
            .map(({language}) => [language.code, language]));

      Object.assign(stepStatusSummary.watchLanguageFiles, {
        status: STATUS_DONE_CLEAN,
        timeEnd: Date.now(),
      });
    } else {
      languages = {};

      const results =
        await Promise.allSettled(
          languageDataFiles
            .map(file => processLanguageFile(file)));

      for (const {status, value: language, reason: error} of results) {
        if (status === 'rejected') {
          errorLoadingCustomLanguages = true;
          niceShowAggregate(error);
        } else {
          languages[language.code] = language;
        }
      }

      if (errorLoadingCustomLanguages) {
        Object.assign(stepStatusSummary.loadLanguageFiles, {
          status: STATUS_FATAL_ERROR,
          annotation: `see log for details`,
          timeEnd: Date.now(),
        });
      } else {
        Object.assign(stepStatusSummary.loadLanguageFiles, {
          status: STATUS_DONE_CLEAN,
          timeEnd: Date.now(),
        });
      }
    }

    if (errorLoadingCustomLanguages) {
      logError`Failed to load language files. Please investigate these, or don't provide`;
      logError`--lang-path (or HSMUSIC_LANG) and build again.`;
      return false;
    }
  } else {
    languages = {};
  }

  Object.assign(stepStatusSummary.initializeDefaultLanguage, {
    status: STATUS_STARTED_NOT_DONE,
    timeStart: Date.now(),
  });

  let finalDefaultLanguage;
  let finalDefaultLanguageWatcher;
  let finalDefaultLanguageAnnotation;

  if (wikiData.wikiInfo.defaultLanguage) {
    const customDefaultLanguage = languages[wikiData.wikiInfo.defaultLanguage];

    if (!customDefaultLanguage) {
      logError`Wiki info file specified default language is ${wikiData.wikiInfo.defaultLanguage}, but no such language file exists!`;
      if (langPath) {
        logError`Check if an appropriate file exists in ${langPath}?`;
      } else {
        logError`Be sure to specify ${'--lang-path'} or ${'HSMUSIC_LANG'} with the path to language files.`;
      }

      Object.assign(stepStatusSummary.initializeDefaultLanguage, {
        status: STATUS_FATAL_ERROR,
        annotation: `wiki specifies default language whose file is not available`,
        timeEnd: Date.now(),
      });

      return false;
    }

    logInfo`Applying new default strings from custom ${customDefaultLanguage.code} language file.`;

    finalDefaultLanguage = customDefaultLanguage;
    finalDefaultLanguageAnnotation = `using wiki-specified custom default language`;

    if (languageReloading) {
      finalDefaultLanguageWatcher =
        customLanguageWatchers
          .find(({language}) => language === customDefaultLanguage);
    }
  } else if (languages[internalDefaultLanguage.code]) {
    const customDefaultLanguage = languages[internalDefaultLanguage.code];

    finalDefaultLanguage = customDefaultLanguage;
    finalDefaultLanguageAnnotation = `using inferred custom default language`;

    if (languageReloading) {
      finalDefaultLanguageWatcher =
        customLanguageWatchers
          .find(({language}) => language === customDefaultLanguage);
    }
  } else {
    languages[internalDefaultLanguage.code] = internalDefaultLanguage;

    finalDefaultLanguage = internalDefaultLanguage;
    finalDefaultLanguageAnnotation = `no custom default language specified`;

    if (languageReloading) {
      finalDefaultLanguageWatcher = internalDefaultLanguageWatcher;
    }
  }

  const closeLanguageWatchers = () => {
    if (languageReloading) {
      for (const watcher of [
        internalDefaultLanguageWatcher,
        ...customLanguageWatchers,
      ]) {
        watcher.close();
      }
    }
  };

  const inheritStringsFromInternalLanguage = () => {
    // The custom default language, if set, will be the new one providing fallback
    // strings for other languages. But on its own, it still might not be a complete
    // list of strings - so it falls back to the internal default language, which
    // won't otherwise be presented in the build.
    if (finalDefaultLanguage === internalDefaultLanguage) return;
    const {strings: inheritedStrings} = internalDefaultLanguage;
    Object.assign(finalDefaultLanguage, {inheritedStrings});
  };

  const inheritStringsFromDefaultLanguage = () => {
    const {strings: inheritedStrings} = finalDefaultLanguage;
    for (const language of Object.values(languages)) {
      if (language === finalDefaultLanguage) continue;
      Object.assign(language, {inheritedStrings});
    }
  };

  if (finalDefaultLanguage !== internalDefaultLanguage) {
    inheritStringsFromInternalLanguage();
  }

  inheritStringsFromDefaultLanguage();

  if (languageReloading) {
    if (finalDefaultLanguage !== internalDefaultLanguage) {
      internalDefaultLanguageWatcher.on('update', () => {
        inheritStringsFromInternalLanguage();
        inheritStringsFromDefaultLanguage();
      });
    }

    finalDefaultLanguageWatcher.on('update', () => {
      inheritStringsFromDefaultLanguage();
    });
  }

  logInfo`Loaded language strings: ${Object.keys(languages).join(', ')}`;

  Object.assign(stepStatusSummary.initializeDefaultLanguage, {
    status: STATUS_DONE_CLEAN,
    annotation: finalDefaultLanguageAnnotation,
    timeEnd: Date.now(),
  });

  const urls = generateURLs(urlSpec);

  let missingImagePaths;

  if (stepStatusSummary.verifyImagePaths.status === STATUS_NOT_APPLICABLE) {
    missingImagePaths = [];
  } else if (stepStatusSummary.verifyImagePaths.status === STATUS_NOT_STARTED) {
    Object.assign(stepStatusSummary.verifyImagePaths, {
      status: STATUS_STARTED_NOT_DONE,
      timeStart: Date.now(),
    });

    const results =
      await verifyImagePaths(mediaPath, {urls, wikiData});

    missingImagePaths = results.missing;
    const misplacedImagePaths = results.misplaced;

    if (empty(missingImagePaths) && empty(misplacedImagePaths)) {
      Object.assign(stepStatusSummary.verifyImagePaths, {
        status: STATUS_DONE_CLEAN,
        timeEnd: Date.now(),
      });
    } else if (empty(missingImagePaths)) {
      Object.assign(stepStatusSummary.verifyImagePaths, {
        status: STATUS_HAS_WARNINGS,
        annotation: `misplaced images detected`,
        timeEnd: Date.now(),
      });
    } else if (empty(misplacedImagePaths)) {
      Object.assign(stepStatusSummary.verifyImagePaths, {
        status: STATUS_HAS_WARNINGS,
        annotation: `missing images detected`,
        timeEnd: Date.now(),
      });
    } else {
      Object.assign(stepStatusSummary.verifyImagePaths, {
        status: STATUS_HAS_WARNINGS,
        annotation: `missing and misplaced images detected`,
        timeEnd: Date.now(),
      });
    }
  }

  let getSizeOfAdditionalFile;
  let getSizeOfImagePath;

  if (stepStatusSummary.preloadFileSizes.status === STATUS_NOT_APPLICABLE) {
    getSizeOfAdditionalFile = () => null;
    getSizeOfImagePath = () => null;
  } else if (stepStatusSummary.preloadFileSizes.status === STATUS_NOT_STARTED) {
    Object.assign(stepStatusSummary.preloadFileSizes, {
      status: STATUS_STARTED_NOT_DONE,
      timeStart: Date.now(),
    });

    const fileSizePreloader = new FileSizePreloader();

    // File sizes of additional files need to be precalculated before we can
    // actually reference 'em in site building, so get those loading right
    // away. We actually need to keep track of two things here - the on-device
    // file paths we're actually reading, and the corresponding on-site media
    // paths that will be exposed in site build code. We'll build a mapping
    // function between them so that when site code requests a site path,
    // it'll get the size of the file at the corresponding device path.
    const additionalFilePaths = [
      ...wikiData.albumData.flatMap((album) =>
        [
          ...(album.additionalFiles ?? []),
          ...album.tracks.flatMap((track) => [
            ...(track.additionalFiles ?? []),
            ...(track.sheetMusicFiles ?? []),
            ...(track.midiProjectFiles ?? []),
          ]),
        ]
          .flatMap((fileGroup) => fileGroup.files)
          .map((file) => ({
            device: path.join(
              mediaPath,
              urls
                .from('media.root')
                .toDevice('media.albumAdditionalFile', album.directory, file)
            ),
            media: urls
              .from('media.root')
              .to('media.albumAdditionalFile', album.directory, file),
          }))
      ),
    ];

    // Same dealio for images. Since just about any image can be embedded and
    // we can't super easily know which ones are referenced at runtime, just
    // cheat and get file sizes for all images under media. (This includes
    // additional files which are images.)
    const imageFilePaths =
      await traverse(mediaPath, {
        pathStyle: 'device',
        filterDir: dir => dir !== '.git',
        filterFile: file =>
          ['.png', '.gif', '.jpg'].includes(path.extname(file)) &&
          !isThumb(file),
      }).then(files => files
          .map(file => ({
            device: file,
            media:
              urls
                .from('media.root')
                .to('media.path', path.relative(mediaPath, file).split(path.sep).join('/')),
          })));

    const getSizeOfMediaFileHelper = paths => (mediaPath) => {
      const pair = paths.find(({media}) => media === mediaPath);
      if (!pair) return null;
      return fileSizePreloader.getSizeOfPath(pair.device);
    };

    getSizeOfAdditionalFile = getSizeOfMediaFileHelper(additionalFilePaths);
    getSizeOfImagePath = getSizeOfMediaFileHelper(imageFilePaths);

    logInfo`Preloading filesizes for ${additionalFilePaths.length} additional files...`;

    fileSizePreloader.loadPaths(...additionalFilePaths.map((path) => path.device));
    await fileSizePreloader.waitUntilDoneLoading();

    logInfo`Preloading filesizes for ${imageFilePaths.length} full-resolution images...`;

    fileSizePreloader.loadPaths(...imageFilePaths.map((path) => path.device));
    await fileSizePreloader.waitUntilDoneLoading();

    if (fileSizePreloader.hasErrored) {
      logWarn`Some media files couldn't be read for preloading filesizes.`;
      logWarn`This means the wiki won't display file sizes for these files.`;
      logWarn`Investigate missing or unreadable files to get that fixed!`;

      Object.assign(stepStatusSummary.preloadFileSizes, {
        status: STATUS_HAS_WARNINGS,
        annotation: `see log for details`,
        timeEnd: Date.now(),
      });
    } else {
      logInfo`Done preloading filesizes without any errors - nice!`;

      Object.assign(stepStatusSummary.preloadFileSizes, {
        status: STATUS_DONE_CLEAN,
        timeEnd: Date.now(),
      });
    }
  }

  if (stepStatusSummary.performBuild.status === STATUS_NOT_APPLICABLE) {
    return true;
  }

  const developersComment =
    `<!--\n` + [
      wikiData.wikiInfo.canonicalBase
        ? `hsmusic.wiki - ${wikiData.wikiInfo.name}, ${wikiData.wikiInfo.canonicalBase}`
        : `hsmusic.wiki - ${wikiData.wikiInfo.name}`,
      'Code copyright 2019-2023 Quasar Nebula et al (MIT License)',
      ...wikiData.wikiInfo.canonicalBase === 'https://hsmusic.wiki/' ? [
        'Data avidly compiled and localization brought to you',
        'by our awesome team and community of wiki contributors',
        '***',
        'Want to contribute? Join our Discord or leave feedback!',
        '- https://hsmusic.wiki/discord/',
        '- https://hsmusic.wiki/feedback/',
        '- https://github.com/hsmusic/',
      ] : [
        'https://github.com/hsmusic/',
      ],
      '***',
      BUILD_TIME &&
        `Site built: ${BUILD_TIME.toLocaleString('en-US', {
          dateStyle: 'long',
          timeStyle: 'long',
        })}`,
      COMMIT &&
        `Latest code commit: ${COMMIT}`,
    ]
      .filter(Boolean)
      .map(line => `    ` + line)
      .join('\n') + `\n-->`;

  Object.assign(stepStatusSummary.performBuild, {
    status: STATUS_STARTED_NOT_DONE,
    timeStart: Date.now(),
  });

  let buildModeResult;

  try {
    buildModeResult = await selectedBuildMode.go({
      cliOptions,
      dataPath,
      mediaPath,
      mediaCachePath,
      queueSize,
      srcRootPath: __dirname,

      defaultLanguage: finalDefaultLanguage,
      languages,
      missingImagePaths,
      thumbsCache,
      urls,
      urlSpec,
      wikiData,

      cachebust: '?' + CACHEBUST,
      closeLanguageWatchers,
      developersComment,
      getSizeOfAdditionalFile,
      getSizeOfImagePath,
      niceShowAggregate,
    });
  } catch (error) {
    console.error(error);

    logError`There was a JavaScript error performing the build.`;
    fileIssue();

    Object.assign(stepStatusSummary.performBuild, {
      status: STATUS_FATAL_ERROR,
      message: `javascript error - view log for details`,
      timeEnd: Date.now(),
    });

    return false;
  }

  if (buildModeResult !== true) {
    Object.assign(stepStatusSummary.performBuild, {
      status: STATUS_HAS_WARNINGS,
      annotation: `may not have completed - view log for details`,
      timeEnd: Date.now(),
    });

    return false;
  }

  Object.assign(stepStatusSummary.performBuild, {
    status: STATUS_DONE_CLEAN,
    timeEnd: Date.now(),
  });

  return true;
}

// TODO: isMain detection isn't consistent across platforms here
/* eslint-disable-next-line no-constant-condition */
if (true || isMain(import.meta.url) || path.basename(process.argv[1]) === 'hsmusic') {
  (async () => {
    let result;

    const totalTimeStart = Date.now();

    try {
      result = await main();
    } catch (error) {
      if (error instanceof AggregateError) {
        showAggregate(error);
      } else if (error.cause) {
        console.error(error);
        showAggregate(error);
      } else {
        console.error(error);
      }
    }

    const totalTimeEnd = Date.now();

    const formatDuration = timeDelta => {
      const seconds = timeDelta / 1000;

      if (seconds > 90) {
        const modSeconds = Math.floor(seconds % 60);
        const minutes = Math.floor(seconds - seconds % 60) / 60;
        return `${minutes}m${modSeconds}s`;
      }

      if (seconds < 0.1) {
        return 'instant';
      }

      const precision = (seconds > 1 ? 3 : 2);
      return `${seconds.toPrecision(precision)}s`;
    };

    if (showStepStatusSummary) {
      const totalDuration = formatDuration(totalTimeEnd - totalTimeStart);

      console.error(colors.bright(`Step summary:`));

      const longestNameLength =
        Math.max(...
          Object.values(stepStatusSummary)
            .map(({name}) => name.length));

      const stepsNotClean =
        Object.values(stepStatusSummary)
          .map(({status}) =>
            status === STATUS_HAS_WARNINGS ||
            status === STATUS_FATAL_ERROR ||
            status === STATUS_STARTED_NOT_DONE);

      const anyStepsNotClean =
        stepsNotClean.includes(true);

      const stepDetails = Object.values(stepStatusSummary);

      const stepDurations =
        stepDetails.map(({status, timeStart, timeEnd}) => {
          if (
            status === STATUS_NOT_APPLICABLE ||
            status === STATUS_NOT_STARTED ||
            status === STATUS_STARTED_NOT_DONE
          ) {
            return '-';
          }

          if (typeof timeStart !== 'number' || typeof timeEnd !== 'number') {
            return 'unknown';
          }

          return formatDuration(timeEnd - timeStart);
        });

      const longestDurationLength =
        Math.max(...stepDurations.map(duration => duration.length));

      for (let index = 0; index < stepDetails.length; index++) {
        const {name, status, annotation} = stepDetails[index];
        const duration = stepDurations[index];

        let message =
          (stepsNotClean[index]
            ? `!! `
            : ` - `);

        message += `(${duration})`.padStart(longestDurationLength + 2, ' ');
        message += ` `;
        message += `${name}: `.padEnd(longestNameLength + 4, '.');
        message += ` `;
        message += status;

        if (annotation) {
          message += ` (${annotation})`;
        }

        switch (status) {
          case STATUS_DONE_CLEAN:
            console.error(colors.green(message));
            break;

          case STATUS_NOT_STARTED:
          case STATUS_NOT_APPLICABLE:
            console.error(colors.dim(message));
            break;

          case STATUS_HAS_WARNINGS:
          case STATUS_STARTED_NOT_DONE:
            console.error(colors.yellow(message));
            break;

          case STATUS_FATAL_ERROR:
            console.error(colors.red(message));
            break;

          default:
            console.error(message);
            break;
        }
      }

      console.error(colors.bright(`Done in ${totalDuration}.`));

      if (result === true) {
        if (anyStepsNotClean) {
          console.error(colors.bright(`Final output is true, but some steps aren't clean.`));
          process.exit(1);
          return;
        } else {
          console.error(colors.bright(`Final output is true and all steps are clean.`));
        }
      } else if (result === false) {
        console.error(colors.bright(`Final output is false.`));
      } else {
        console.error(colors.bright(`Final output is not true (${result}).`));
      }
    }

    if (result !== true) {
      process.exit(1);
      return;
    }

    decorateTime.displayTime();
    CacheableObject.showInvalidAccesses();

    process.exit(0);
  })();
}