« get me outta code hell

validators.js « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/validators.js
blob: 22dc160ce48fb87e30ca42b3a91b094dceea3dd7 (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
import {inspect as nodeInspect} from 'node:util';

import {openAggregate, withAggregate} from '#aggregate';
import {colors, ENABLE_COLOR} from '#cli';
import {cut, empty, matchMultiline, typeAppearance} from '#sugar';
import {commentaryRegexCaseInsensitive, commentaryRegexCaseSensitiveOneShot}
  from '#wiki-data';

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

export function getValidatorCreator(validator) {
  return validator[Symbol.for(`hsmusic.validator.creator`)] ?? null;
}

export function getValidatorCreatorMeta(validator) {
  return validator[Symbol.for(`hsmusic.validator.creatorMeta`)] ?? null;
}

export function setValidatorCreatorMeta(validator, creator, meta) {
  validator[Symbol.for(`hsmusic.validator.creator`)] = creator;
  validator[Symbol.for(`hsmusic.validator.creatorMeta`)] = meta;
  return validator;
}

// Basic types (primitives)

export function a(noun) {
  return /[aeiou]/.test(noun[0]) ? `an ${noun}` : `a ${noun}`;
}

export function validateType(type) {
  const fn = value => {
    if (typeof value !== type)
      throw new TypeError(`Expected ${a(type)}, got ${typeAppearance(value)}`);

    return true;
  };

  setValidatorCreatorMeta(fn, validateType, {type});

  return fn;
}

export const isBoolean =
  validateType('boolean');

export const isFunction =
  validateType('function');

export const isNumber =
  validateType('number');

export const isString =
  validateType('string');

export const isSymbol =
  validateType('symbol');

// Use isObject instead, which disallows null.
export const isTypeofObject =
  validateType('object');

export function isPositive(number) {
  isNumber(number);

  if (number <= 0) throw new TypeError(`Expected positive number`);

  return true;
}

export function isNegative(number) {
  isNumber(number);

  if (number >= 0) throw new TypeError(`Expected negative number`);

  return true;
}

export function isPositiveOrZero(number) {
  isNumber(number);

  if (number < 0) throw new TypeError(`Expected positive number or zero`);

  return true;
}

export function isNegativeOrZero(number) {
  isNumber(number);

  if (number > 0) throw new TypeError(`Expected negative number or zero`);

  return true;
}

export function isInteger(number) {
  isNumber(number);

  if (number % 1 !== 0) throw new TypeError(`Expected integer`);

  return true;
}

export function isCountingNumber(number) {
  isInteger(number);
  isPositive(number);

  return true;
}

export function isWholeNumber(number) {
  isInteger(number);
  isPositiveOrZero(number);

  return true;
}

export function isStringNonEmpty(value) {
  isString(value);

  if (value.trim().length === 0)
    throw new TypeError(`Expected non-empty string`);

  return true;
}

export function optional(validator) {
  return value =>
    value === null ||
    value === undefined ||
    validator(value);
}

// Complex types (non-primitives)

export function isInstance(value, constructor) {
  isObject(value);

  if (!(value instanceof constructor))
    throw new TypeError(`Expected ${constructor.name}, got ${value.constructor.name}`);

  return true;
}

export function isDate(value) {
  isInstance(value, Date);

  if (isNaN(value))
    throw new TypeError(`Expected valid date`);

  return true;
}

export function isObject(value) {
  isTypeofObject(value);

  // Note: Please remember that null is always a valid value for properties
  // held by a CacheableObject. This assertion is exclusively for use in other
  // contexts.
  if (value === null)
    throw new TypeError(`Expected an object, got null`);

  return true;
}

export function isArray(value) {
  if (typeof value !== 'object' || value === null || !Array.isArray(value))
    throw new TypeError(`Expected an array, got ${typeAppearance(value)}`);

  return true;
}

// This one's shaped a bit different from other "is" functions.
// More like validate functions, it returns a function.
export function is(...values) {
  if (Array.isArray(values)) {
    values = new Set(values);
  }

  if (values.size === 1) {
    const expected = Array.from(values)[0];

    return (value) => {
      if (value !== expected) {
        throw new TypeError(`Expected ${expected}, got ${value}`);
      }

      return true;
    };
  }

  const fn = (value) => {
    if (!values.has(value)) {
      throw new TypeError(`Expected one of ${Array.from(values).join(' ')}, got ${value}`);
    }

    return true;
  };

  setValidatorCreatorMeta(fn, is, {values});

  return fn;
}

function validateArrayItemsHelper(itemValidator) {
  return (item, index, array) => {
    try {
      const value = itemValidator(item, index, array);

      if (value !== true) {
        throw new Error(`Expected validator to return true`);
      }
    } catch (caughtError) {
      const indexPart = colors.yellow(`zero-index ${index}`)
      const itemPart = inspect(item);
      const message = `Error at ${indexPart}: ${itemPart}`;
      const error = new Error(message, {cause: caughtError});
      error[Symbol.for('hsmusic.annotateError.indexInSourceArray')] = index;
      throw error;
    }
  };
}

export function validateArrayItems(itemValidator) {
  const helper = validateArrayItemsHelper(itemValidator);

  return (array) => {
    isArray(array);

    withAggregate({message: 'Errors validating array items'}, ({call}) => {
      for (let index = 0; index < array.length; index++) {
        call(helper, array[index], index, array);
      }
    });

    return true;
  };
}

export function strictArrayOf(itemValidator) {
  return validateArrayItems(itemValidator);
}

export function sparseArrayOf(itemValidator) {
  return validateArrayItems((item, index, array) => {
    if (item === false || item === null) {
      return true;
    }

    return itemValidator(item, index, array);
  });
}

export function looseArrayOf(itemValidator) {
  return validateArrayItems((item, index, array) => {
    if (item === false || item === null || item === undefined) {
      return true;
    }

    return itemValidator(item, index, array);
  });
}

export function validateInstanceOf(constructor) {
  const fn = (object) => isInstance(object, constructor);

  setValidatorCreatorMeta(fn, validateInstanceOf, {constructor});

  return fn;
}

// Wiki data (primitives & non-primitives)

export function isColor(color) {
  isStringNonEmpty(color);

  if (color.startsWith('#')) {
    if (![4, 5, 7, 9].includes(color.length))
      throw new TypeError(`Expected #rgb, #rgba, #rrggbb, or #rrggbbaa, got length ${color.length}`);

    if (/[^0-9a-fA-F]/.test(color.slice(1)))
      throw new TypeError(`Expected hexadecimal digits`);

    return true;
  }

  throw new TypeError(`Unknown color format`);
}

export function isCommentary(commentaryText) {
  isContentString(commentaryText);

  const rawMatches =
    Array.from(commentaryText.matchAll(commentaryRegexCaseInsensitive));

  if (empty(rawMatches)) {
    throw new TypeError(`Expected at least one commentary heading`);
  }

  const niceMatches =
    rawMatches.map(match => ({
      position: match.index,
      length: match[0].length,
    }));

  validateArrayItems(({position, length}, index) => {
    if (index === 0 && position > 0) {
      throw new TypeError(`Expected first commentary heading to be at top`);
    }

    const ownInput = commentaryText.slice(position, position + length);
    const restOfInput = commentaryText.slice(position + length);

    const upToNextLineBreak =
      (restOfInput.includes('\n')
        ? restOfInput.slice(0, restOfInput.indexOf('\n'))
        : restOfInput);

    if (/\S/.test(upToNextLineBreak)) {
      throw new TypeError(
        `Expected commentary heading to occupy entire line, got extra text:\n` +
        `${colors.green(`"${cut(ownInput, 40)}"`)} (<- heading)\n` +
        `(extra on same line ->) ${colors.red(`"${cut(upToNextLineBreak, 30)}"`)}\n` +
        `(Check for missing "|-" in YAML, or a misshapen annotation)`);
    }

    if (!commentaryRegexCaseSensitiveOneShot.test(ownInput)) {
      throw new TypeError(
        `Miscapitalization in commentary heading:\n` +
        `${colors.red(`"${cut(ownInput, 60)}"`)}\n` +
        `(Check for ${colors.red(`"<I>"`)} instead of ${colors.green(`"<i>"`)})`);
    }

    const nextHeading =
      (index === niceMatches.length - 1
        ? commentaryText.length
        : niceMatches[index + 1].position);

    const upToNextHeading =
      commentaryText.slice(position + length, nextHeading);

    if (!/\S/.test(upToNextHeading)) {
      throw new TypeError(
        `Expected commentary entry to have body text, only got a heading`);
    }

    return true;
  })(niceMatches);

  return true;
}

const isArtistRef = validateReference('artist');

export function validateProperties(spec) {
  const {
    [validateProperties.validateOtherKeys]: validateOtherKeys = null,
    [validateProperties.allowOtherKeys]: allowOtherKeys = false,
  } = spec;

  const specEntries = Object.entries(spec);
  const specKeys = Object.keys(spec);

  return (object) => {
    isObject(object);

    if (Array.isArray(object))
      throw new TypeError(`Expected an object, got array`);

    withAggregate({message: `Errors validating object properties`}, ({push}) => {
      const testEntries = specEntries.slice();

      const unknownKeys = Object.keys(object).filter((key) => !specKeys.includes(key));
      if (validateOtherKeys) {
        for (const key of unknownKeys) {
          testEntries.push([key, validateOtherKeys]);
        }
      }

      for (const [specKey, specValidator] of testEntries) {
        const value = object[specKey];
        try {
          specValidator(value);
        } catch (caughtError) {
          const keyPart = colors.green(specKey);
          const valuePart = inspect(value);
          const message = `Error for key ${keyPart}: ${valuePart}`;
          push(new Error(message, {cause: caughtError}));
        }
      }

      if (!validateOtherKeys && !allowOtherKeys && !empty(unknownKeys)) {
        push(new Error(
          `Unknown keys present (${unknownKeys.length}): [${unknownKeys.join(', ')}]`));
      }
    });

    return true;
  };
}

validateProperties.validateOtherKeys = Symbol();
validateProperties.allowOtherKeys = Symbol();

export const validateAllPropertyValues = (validator) =>
  validateProperties({
    [validateProperties.validateOtherKeys]: validator,
  });

const illeaglInvisibleSpace = {
  action: 'delete',
};

const illegalVisibleSpace = {
  action: 'replace',
  with: ' ',
  withAnnotation: `normal space`,
};

const illegalContentSpec = [
  {illegal: '\u200b', annotation: `zero-width space`, ...illeaglInvisibleSpace},
  {illegal: '\u2005', annotation: `four-per-em space`, ...illegalVisibleSpace},
  {illegal: '\u205f', annotation: `medium mathematical space`, ...illegalVisibleSpace},
  {illegal: '\xa0', annotation: `non-breaking space`, ...illegalVisibleSpace},

  {
    action: 'replace',
    illegal: '<a href',
    annotation: `HTML-style link`,
    with: '[...](...)',
    withAnnotation: `markdown`,
  },
];

for (const entry of illegalContentSpec) {
  entry.test = string =>
    string.startsWith(entry.illegal);

  if (entry.action === 'replace') {
    entry.enact = string =>
      string.replaceAll(entry.illegal, entry.with);
  }
}

const illegalSequencesInContent =
  illegalContentSpec
    .map(entry => entry.illegal)
    .map(illegal =>
      (illegal.length === 1
        ? `${illegal}+`
        : `(?:${illegal})+`))
    .join('|');

const illegalContentRegexp =
  new RegExp(illegalSequencesInContent, 'g');

const legalContentNearEndRegexp =
  new RegExp(`(?<=^|${illegalSequencesInContent})(?:(?!${illegalSequencesInContent}).)+$`);

const legalContentNearStartRegexp =
  new RegExp(`^(?:(?!${illegalSequencesInContent}).)+`);

const trimWhitespaceNearBothSidesRegexp =
  /^ +| +$/gm;

const trimWhitespaceNearEndRegexp =
  / +$/gm;

export function isContentString(content) {
  isString(content);

  const mainAggregate = openAggregate({
    message: `Errors validating content string`,
    translucent: 'single',
  });

  const illegalAggregate = openAggregate({
    message: `Illegal characters found in content string`,
  });

  for (const {match, where} of matchMultiline(content, illegalContentRegexp)) {
    const {annotation, action, ...options} =
      illegalContentSpec
        .find(entry => entry.test(match[0]));

    const matchStart = match.index;
    const matchEnd = match.index + match[0].length;

    const before =
      content
        .slice(Math.max(0, matchStart - 3), matchStart)
        .match(legalContentNearEndRegexp)
        ?.[0];

    const after =
      content
        .slice(matchEnd, Math.min(content.length, matchEnd + 3))
        .match(legalContentNearStartRegexp)
        ?.[0];

    const beforePart =
      before && `"${before}"`;

    const afterPart =
      after && `"${after}"`;

    const surroundings =
      (before && after
        ? `between ${beforePart} and ${afterPart}`
     : before
        ? `after ${beforePart}`
     : after
        ? `before ${afterPart}`
        : ``);

    const illegalPart =
      colors.red(
        (annotation
          ? `"${match[0]}" (${annotation})`
          : `"${match[0]}"`));

    const replacement =
      (action === 'replace'
        ? options.enact(match[0])
        : null);

    const replaceWithPart =
      (action === 'replace'
        ? colors.green(
            (options.withAnnotation
              ? `"${replacement}" (${options.withAnnotation})`
              : `"${replacement}"`))
        : null);

    const actionPart =
      (action === `delete`
        ? `Delete ${illegalPart}`
     : action === 'replace'
        ? `Replace ${illegalPart} with ${replaceWithPart}`
        : `Matched ${illegalPart}`);

    const parts = [
      actionPart,
      surroundings,
      `(${where})`,
    ].filter(Boolean);

    illegalAggregate.push(new TypeError(parts.join(` `)));
  }

  const isMultiline = content.includes('\n');

  const trimWhitespaceAggregate = openAggregate({
    message:
      (isMultiline
        ? `Whitespace found at end of line`
        : `Whitespace found at start or end`),
  });

  const trimWhitespaceRegexp =
    (isMultiline
      ? trimWhitespaceNearEndRegexp
      : trimWhitespaceNearBothSidesRegexp);

  for (
    const {match, lineNumber, columnNumber, containingLine} of
    matchMultiline(content, trimWhitespaceRegexp, {
      formatWhere: false,
      getContainingLine: true,
    })
  ) {
    const linePart =
      colors.yellow(`line ${lineNumber + 1}`);

    const where =
      (match[0].length === containingLine.length
        ? `as all of ${linePart}`
     : columnNumber === 0
        ? (isMultiline
            ? `at start of ${linePart}`
            : `at start`)
        : (isMultiline
            ? `at end of ${linePart}`
            : `at end`));

    const whitespacePart =
      colors.red(`"${match[0]}"`);

    const parts = [
      `Matched ${whitespacePart}`,
      where,
    ];

    trimWhitespaceAggregate.push(new TypeError(parts.join(` `)));
  }

  mainAggregate.call(() => illegalAggregate.close());
  mainAggregate.call(() => trimWhitespaceAggregate.close());
  mainAggregate.close();

  return true;
}

export function isThingClass(thingClass) {
  isFunction(thingClass);

  // This is *expressly* no faster than an instanceof check, because it's
  // deliberately still walking the prototype chain for the provided object.
  // (This is necessary because the symbol we're checking is defined only on
  // the Thing constructor, and not directly on each subclass.) However, it's
  // preferred over an instanceof check anyway, because instanceof would
  // require that the #validators module has access to #thing, which it
  // currently doesn't!
  if (!(Symbol.for('Thing.isThingConstructor') in thingClass)) {
    throw new TypeError(`Expected a Thing constructor, missing Thing.isThingConstructor`);
  }

  return true;
}

export function isThing(thing) {
  isObject(thing);

  // This *is* faster than an instanceof check, because it doesn't walk the
  // prototype chain. It works because this property is set as part of every
  // Thing subclass's inherited "public class fields" - it's set directly on
  // every constructed Thing.
  if (!Object.hasOwn(thing, Symbol.for('Thing.isThing'))) {
    throw new TypeError(`Expected a Thing, missing Thing.isThing`);
  }

  return true;
}

export const isContribution = validateProperties({
  artist: isArtistRef,
  annotation: optional(isStringNonEmpty),

  countInDurationTotals: optional(isBoolean),
  countInContributionTotals: optional(isBoolean),
});

export const isContributionList = validateArrayItems(isContribution);

export const contributionPresetPropertySpec = {
  album: [
    'artistContribs',
  ],

  flash: [
    'contributorContribs',
  ],

  track: [
    'artistContribs',
    'contributorContribs',
  ],
};

// TODO: This validator basically constructs itself as it goes.
// This is definitely some shenanigans!
export function isContributionPresetContext(list) {
  isArray(list);

  if (empty(list)) {
    throw new TypeError(`Expected at least one item`);
  }

  const isTarget =
    is(...Object.keys(contributionPresetPropertySpec));

  const [target, ...properties] = list;

  isTarget(target);

  const isProperty =
    is(...contributionPresetPropertySpec[target]);

  const isPropertyList =
    validateArrayItems(isProperty);

  isPropertyList(properties);

  return true;
}

export const isContributionPreset = validateProperties({
  annotation: isStringNonEmpty,
  context: isContributionPresetContext,

  countInDurationTotals: optional(isBoolean),
  countInContributionTotals: optional(isBoolean),
});

export const isContributionPresetList = validateArrayItems(isContributionPreset);

export const isAdditionalFile = validateProperties({
  title: isName,
  description: optional(isContentString),
  files: optional(validateArrayItems(isString)),
});

export const isAdditionalFileList = validateArrayItems(isAdditionalFile);

export const isTrackSection = validateProperties({
  name: optional(isName),
  color: optional(isColor),
  dateOriginallyReleased: optional(isDate),
  isDefaultTrackSection: optional(isBoolean),
  tracks: optional(validateReferenceList('track')),
});

export const isTrackSectionList = validateArrayItems(isTrackSection);

export function isDimensions(dimensions) {
  isArray(dimensions);

  if (dimensions.length !== 2) throw new TypeError(`Expected 2 item array`);

  if (dimensions[0] !== null) {
    isPositive(dimensions[0]);
    isInteger(dimensions[0]);
  }

  if (dimensions[1] !== null) {
    isPositive(dimensions[1]);
    isInteger(dimensions[1]);
  }

  return true;
}

export function isDirectory(directory) {
  isStringNonEmpty(directory);

  if (directory.match(/[^a-zA-Z0-9_-]/))
    throw new TypeError(`Expected only letters, numbers, dash, and underscore, got "${directory}"`);

  return true;
}

export function isDuration(duration) {
  isNumber(duration);
  isPositiveOrZero(duration);

  return true;
}

export function isFileExtension(string) {
  isStringNonEmpty(string);

  if (string[0] === '.')
    throw new TypeError(`Expected no dot (.) at the start of file extension`);

  if (string.match(/[^a-zA-Z0-9_]/))
    throw new TypeError(`Expected only alphanumeric and underscore`);

  return true;
}

export function isLanguageCode(string) {
  // TODO: This is a stub function because really we don't need a detailed
  // is-language-code parser right now.

  isString(string);

  return true;
}

export function isName(name) {
  return isContentString(name);
}

export function isURL(string) {
  isStringNonEmpty(string);

  new URL(string);

  return true;
}

export function validateReference(type = 'track') {
  return (ref) => {
    isStringNonEmpty(ref);

    const match = ref
      .trim()
      .match(/^(?:(?<typePart>\S+):(?=\S))?(?<directoryPart>.+)(?<!:)$/);

    if (!match) throw new TypeError(`Malformed reference`);

    const {groups: {typePart, directoryPart}} = match;

    if (typePart) {
      if (typePart !== type)
        throw new TypeError(`Expected ref to begin with "${type}:", got "${typePart}:"`);

      isDirectory(directoryPart);
    }

    isName(ref);

    return true;
  };
}

export function validateReferenceList(type = '') {
  return validateArrayItems(validateReference(type));
}

export function validateThing({
  referenceType: expectedReferenceType = '',
} = {}) {
  return (thing) => {
    isThing(thing);

    if (expectedReferenceType) {
      const {[Symbol.for('Thing.referenceType')]: referenceType} =
        thing.constructor;

      if (referenceType !== expectedReferenceType) {
        throw new TypeError(`Expected only ${expectedReferenceType}, got other type: ${referenceType}`);
      }
    }

    return true;
  };
}

const validateWikiData_cache = {};

export function validateWikiData({
  referenceType = '',
  allowMixedTypes = false,
} = {}) {
  if (referenceType && allowMixedTypes) {
    throw new TypeError(`Don't specify both referenceType and allowMixedTypes`);
  }

  validateWikiData_cache[referenceType] ??= {};
  validateWikiData_cache[referenceType][allowMixedTypes] ??= new WeakMap();

  const isArrayOfObjects = validateArrayItems(isObject);

  return (array) => {
    const subcache = validateWikiData_cache[referenceType][allowMixedTypes];
    if (subcache.has(array)) return subcache.get(array);

    let OK = false;

    try {
      isArrayOfObjects(array);

      if (empty(array)) {
        OK = true; return true;
      }

      const allRefTypes = new Set();

      let foundThing = false;
      let foundOtherObject = false;

      for (const object of array) {
        if (Object.hasOwn(object, Symbol.for('Thing.isThing'))) {
          // Early-exit if a non-Thing object has been found - nothing more can
          // be learned.
          if (foundOtherObject) {
            throw new TypeError(`Expected array of wiki data objects, got mixed items`);
          }

          foundThing = true;
          allRefTypes.add(object.constructor[Symbol.for('Thing.referenceType')]);
        } else {
          // Early-exit if a Thing has been found - nothing more can be learned.
          if (foundThing) {
            throw new TypeError(`Expected array of wiki data objects, got mixed items`);
          }

          foundOtherObject = true;
        }
      }

      if (foundOtherObject && !foundThing) {
        throw new TypeError(`Expected array of wiki data objects, got array of other objects`);
      }

      if (allRefTypes.size > 1) {
        if (allowMixedTypes) {
          OK = true; return true;
        }

        const types = () => Array.from(allRefTypes).join(', ');

        if (referenceType) {
          if (allRefTypes.has(referenceType)) {
            allRefTypes.remove(referenceType);
            throw new TypeError(`Expected array of only ${referenceType}, also got other types: ${types()}`)
          } else {
            throw new TypeError(`Expected array of only ${referenceType}, got other types: ${types()}`);
          }
        }

        throw new TypeError(`Expected array of unmixed reference types, got multiple: ${types()}`);
      }

      const onlyRefType = Array.from(allRefTypes)[0];

      if (referenceType && onlyRefType !== referenceType) {
        throw new TypeError(`Expected array of ${referenceType}, got array of ${onlyRefType}`)
      }

      OK = true; return true;
    } finally {
      subcache.set(array, OK);
    }
  };
}

export const isAdditionalName = validateProperties({
  name: isContentString,
  annotation: optional(isContentString),

  // TODO: This only applies for tracks, not additional names
  // in general.
  specificAlbumExclusive: optional(isBoolean),

  // TODO: This only allows indicating sourcing from a track.
  // That's okay for the current limited use of "from", but
  // could be expanded later.
  from:
    // Double TODO: Explicitly allowing both references and
    // live objects to co-exist is definitely weird, and
    // altogether questions the way we define validators...
    optional(anyOf(
      validateReferenceList('track'),
      validateWikiData({referenceType: 'track'}))),
});

export const isAdditionalNameList = validateArrayItems(isAdditionalName);

// Compositional utilities

export function anyOf(...validators) {
  const validConstants = new Set();
  const validConstructors = new Set();
  const validTypes = new Set();

  const constantValidators = [];
  const constructorValidators = [];
  const typeValidators = [];

  const leftoverValidators = [];

  for (const validator of validators) {
    const creator = getValidatorCreator(validator);
    const creatorMeta = getValidatorCreatorMeta(validator);

    switch (creator) {
      case is:
        for (const value of creatorMeta.values) {
          validConstants.add(value);
        }

        constantValidators.push(validator);
        break;

      case validateInstanceOf:
        validConstructors.add(creatorMeta.constructor);
        constructorValidators.push(validator);
        break;

      case validateType:
        validTypes.add(creatorMeta.type);
        typeValidators.push(validator);
        break;

      default:
        leftoverValidators.push(validator);
        break;
    }
  }

  return (value) => {
    const errorInfo = [];

    if (validConstants.has(value)) {
      return true;
    }

    if (!empty(validTypes)) {
      if (validTypes.has(typeof value)) {
        return true;
      }
    }

    for (const constructor of validConstructors) {
      if (value instanceof constructor) {
        return true;
      }
    }

    for (const [i, validator] of leftoverValidators.entries()) {
      try {
        const result = validator(value);

        if (result !== true) {
          throw new Error(`Check returned false`);
        }

        return true;
      } catch (error) {
        errorInfo.push([validator, i, error]);
      }
    }

    // Don't process error messages until every validator has failed.

    const errors = [];
    const prefaceErrorInfo = [];

    let offset = 0;

    if (!empty(validConstants)) {
      const constants =
        Array.from(validConstants);

      const gotPart = `, got ${value}`;

      prefaceErrorInfo.push([
        constantValidators,
        offset++,
        new TypeError(
          `Expected any of ${constants.join(' ')}` + gotPart),
      ]);
    }

    if (!empty(validTypes)) {
      const types =
        Array.from(validTypes);

      const gotType = typeAppearance(value);
      const gotPart = `, got ${gotType}`;

      prefaceErrorInfo.push([
        typeValidators,
        offset++,
        new TypeError(
          `Expected any of ${types.join(', ')}` + gotPart),
      ]);
    }

    if (!empty(validConstructors)) {
      const names =
        Array.from(validConstructors)
          .map(constructor => constructor.name);

      const gotName = value?.constructor?.name;
      const gotPart = (gotName ? `, got ${gotName}` : ``);

      prefaceErrorInfo.push([
        constructorValidators,
        offset++,
        new TypeError(
          `Expected any of ${names.join(', ')}` + gotPart),
      ]);
    }

    for (const info of errorInfo) {
      info[1] += offset;
    }

    for (const [validator, i, error] of prefaceErrorInfo.concat(errorInfo)) {
      error.message =
        (validator?.name
          ? `${i + 1}. "${validator.name}": ${error.message}`
          : `${i + 1}. ${error.message}`);

      error.check =
        (Array.isArray(validator) && validator.length === 1
          ? validator[0]
          : validator);

      errors.push(error);
    }

    const total = offset + leftoverValidators.length;
    throw new AggregateError(errors,
      `Expected any of ${total} possible checks, ` +
      `but none were true`);
  };
}