« get me outta code hell

thing.js « things « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/things/thing.js
blob: 578a5a4e2446078358f5f082ab8786ead3b617b0 (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
// Thing: base class for wiki data types, providing wiki-specific utility
// functions on top of essential CacheableObject behavior.

import {inspect} from 'node:util';

import {color} from '#cli';
import find from '#find';
import {empty, filterProperties, openAggregate} from '#sugar';
import {getKebabCase} from '#wiki-data';

import {
  isAdditionalFileList,
  isBoolean,
  isCommentary,
  isColor,
  isContributionList,
  isDate,
  isDirectory,
  isFileExtension,
  isName,
  isString,
  isURL,
  validateArrayItems,
  validateInstanceOf,
  validateReference,
  validateReferenceList,
} from '#validators';

import CacheableObject from './cacheable-object.js';

export default class Thing extends CacheableObject {
  static referenceType = Symbol('Thing.referenceType');

  static getPropertyDescriptors = Symbol('Thing.getPropertyDescriptors');
  static getSerializeDescriptors = Symbol('Thing.getSerializeDescriptors');

  // Regularly reused property descriptors, for ease of access and generally
  // duplicating less code across wiki data types. These are specialized utility
  // functions, so check each for how its own arguments behave!
  static common = {
    name: (defaultName) => ({
      flags: {update: true, expose: true},
      update: {validate: isName, default: defaultName},
    }),

    color: () => ({
      flags: {update: true, expose: true},
      update: {validate: isColor},
    }),

    directory: () => ({
      flags: {update: true, expose: true},
      update: {validate: isDirectory},
      expose: {
        dependencies: ['name'],
        transform(directory, {name}) {
          if (directory === null && name === null) return null;
          else if (directory === null) return getKebabCase(name);
          else return directory;
        },
      },
    }),

    urls: () => ({
      flags: {update: true, expose: true},
      update: {validate: validateArrayItems(isURL)},
      expose: {transform: (value) => value ?? []},
    }),

    // A file extension! Or the default, if provided when calling this.
    fileExtension: (defaultFileExtension = null) => ({
      flags: {update: true, expose: true},
      update: {validate: isFileExtension},
      expose: {transform: (value) => value ?? defaultFileExtension},
    }),

    // Straightforward flag descriptor for a variety of property purposes.
    // Provide a default value, true or false!
    flag: (defaultValue = false) => {
      if (typeof defaultValue !== 'boolean') {
        throw new TypeError(`Always set explicit defaults for flags!`);
      }

      return {
        flags: {update: true, expose: true},
        update: {validate: isBoolean, default: defaultValue},
      };
    },

    // General date type, used as the descriptor for a bunch of properties.
    // This isn't dynamic though - it won't inherit from a date stored on
    // another object, for example.
    simpleDate: () => ({
      flags: {update: true, expose: true},
      update: {validate: isDate},
    }),

    // General string type. This should probably generally be avoided in favor
    // of more specific validation, but using it makes it easy to find where we
    // might want to improve later, and it's a useful shorthand meanwhile.
    simpleString: () => ({
      flags: {update: true, expose: true},
      update: {validate: isString},
    }),

    // External function. These should only be used as dependencies for other
    // properties, so they're left unexposed.
    externalFunction: () => ({
      flags: {update: true},
      update: {validate: (t) => typeof t === 'function'},
    }),

    // Super simple "contributions by reference" list, used for a variety of
    // properties (Artists, Cover Artists, etc). This is the property which is
    // externally provided, in the form:
    //
    //     [
    //         {who: 'Artist Name', what: 'Viola'},
    //         {who: 'artist:john-cena', what: null},
    //         ...
    //     ]
    //
    // ...processed from YAML, spreadsheet, or any other kind of input.
    contribsByRef: () => ({
      flags: {update: true, expose: true},
      update: {validate: isContributionList},
    }),

    // Artist commentary! Generally present on tracks and albums.
    commentary: () => ({
      flags: {update: true, expose: true},
      update: {validate: isCommentary},
    }),

    // This is a somewhat more involved data structure - it's for additional
    // or "bonus" files associated with albums or tracks (or anything else).
    // It's got this form:
    //
    //     [
    //         {title: 'Booklet', files: ['Booklet.pdf']},
    //         {
    //             title: 'Wallpaper',
    //             description: 'Cool Wallpaper!',
    //             files: ['1440x900.png', '1920x1080.png']
    //         },
    //         {title: 'Alternate Covers', description: null, files: [...]},
    //         ...
    //     ]
    //
    additionalFiles: () => ({
      flags: {update: true, expose: true},
      update: {validate: isAdditionalFileList},
      expose: {
        transform: (additionalFiles) =>
          additionalFiles ?? [],
      },
    }),

    // A reference list! Keep in mind this is for general references to wiki
    // objects of (usually) other Thing subclasses, not specifically leitmotif
    // references in tracks (although that property uses referenceList too!).
    //
    // The underlying function validateReferenceList expects a string like
    // 'artist' or 'track', but this utility keeps from having to hard-code the
    // string in multiple places by referencing the value saved on the class
    // instead.
    referenceList: (thingClass) => {
      const {[Thing.referenceType]: referenceType} = thingClass;
      if (!referenceType) {
        throw new Error(`The passed constructor ${thingClass.name} doesn't define Thing.referenceType!`);
      }

      return {
        flags: {update: true, expose: true},
        update: {validate: validateReferenceList(referenceType)},
      };
    },

    // Corresponding function for a single reference.
    singleReference: (thingClass) => {
      const {[Thing.referenceType]: referenceType} = thingClass;
      if (!referenceType) {
        throw new Error(`The passed constructor ${thingClass.name} doesn't define Thing.referenceType!`);
      }

      return {
        flags: {update: true, expose: true},
        update: {validate: validateReference(referenceType)},
      };
    },

    // Corresponding dynamic property to referenceList, which takes the values
    // in the provided property and searches the specified wiki data for
    // matching actual Thing-subclass objects.
    dynamicThingsFromReferenceList: (
      referenceListProperty,
      thingDataProperty,
      findFn
    ) => ({
      flags: {expose: true},

      expose: {
        dependencies: [referenceListProperty, thingDataProperty],
        compute: ({
          [referenceListProperty]: refs,
          [thingDataProperty]: thingData,
        }) =>
          refs && thingData
            ? refs
                .map((ref) => findFn(ref, thingData, {mode: 'quiet'}))
                .filter(Boolean)
            : [],
      },
    }),

    // Corresponding function for a single reference.
    dynamicThingFromSingleReference: (
      singleReferenceProperty,
      thingDataProperty,
      findFn
    ) => ({
      flags: {expose: true},

      expose: {
        dependencies: [singleReferenceProperty, thingDataProperty],
        compute: ({
          [singleReferenceProperty]: ref,
          [thingDataProperty]: thingData,
        }) => (ref && thingData ? findFn(ref, thingData, {mode: 'quiet'}) : null),
      },
    }),

    // Corresponding dynamic property to contribsByRef, which takes the values
    // in the provided property and searches the object's artistData for
    // matching actual Artist objects. The computed structure has the same form
    // as contribsByRef, but with Artist objects instead of string references:
    //
    //     [
    //         {who: (an Artist), what: 'Viola'},
    //         {who: (an Artist), what: null},
    //         ...
    //     ]
    //
    // Contributions whose "who" values don't match anything in artistData are
    // filtered out. (So if the list is all empty, chances are that either the
    // reference list is somehow messed up, or artistData isn't being provided
    // properly.)
    dynamicContribs: (contribsByRefProperty) => ({
      flags: {expose: true},
      expose: {
        dependencies: ['artistData', contribsByRefProperty],
        compute: ({artistData, [contribsByRefProperty]: contribsByRef}) =>
          Thing.findArtistsFromContribs(contribsByRef, artistData),
      },
    }),

    // Dynamically inherit a contribution list from some other object, if it
    // hasn't been overridden on this object. This is handy for solo albums
    // where all tracks have the same artist, for example.
    dynamicInheritContribs: (
      // If this property is explicitly false, the contribution list returned
      // will always be empty.
      nullerProperty,

      // Property holding contributions on the current object.
      contribsByRefProperty,

      // Property holding corresponding "default" contributions on the parent
      // object, which will fallen back to if the object doesn't have its own
      // contribs.
      parentContribsByRefProperty,

      // Data array to search in and "find" function to locate parent object
      // (which will be passed the child object and the wiki data array).
      thingDataProperty,
      findFn
    ) => ({
      flags: {expose: true},
      expose: {
        dependencies: [
          'this',
          contribsByRefProperty,
          thingDataProperty,
          nullerProperty,
          'artistData',
        ].filter(Boolean),

        compute({
          this: thing,
          [nullerProperty]: nuller,
          [contribsByRefProperty]: contribsByRef,
          [thingDataProperty]: thingData,
          artistData,
        }) {
          if (!artistData) return [];
          if (nuller === false) return [];
          const refs =
            contribsByRef ??
            findFn(thing, thingData, {mode: 'quiet'})?.[parentContribsByRefProperty];
          if (!refs) return [];
          return refs
            .map(({who: ref, what}) => ({
              who: find.artist(ref, artistData),
              what,
            }))
            .filter(({who}) => who);
        },
      },
    }),

    // Nice 'n simple shorthand for an exposed-only flag which is true when any
    // contributions are present in the specified property.
    contribsPresent: (contribsByRefProperty) => ({
      flags: {expose: true},
      expose: {
        dependencies: [contribsByRefProperty],
        compute({
          [contribsByRefProperty]: contribsByRef,
        }) {
          return !empty(contribsByRef);
        },
      }
    }),

    // Neat little shortcut for "reversing" the reference lists stored on other
    // things - for example, tracks specify a "referenced tracks" property, and
    // you would use this to compute a corresponding "referenced *by* tracks"
    // property. Naturally, the passed ref list property is of the things in the
    // wiki data provided, not the requesting Thing itself.
    reverseReferenceList: (thingDataProperty, referencerRefListProperty) => ({
      flags: {expose: true},

      expose: {
        dependencies: ['this', thingDataProperty],

        compute: ({this: thing, [thingDataProperty]: thingData}) =>
          thingData?.filter(t => t[referencerRefListProperty].includes(thing)) ?? [],
      },
    }),

    // Corresponding function for single references. Note that the return value
    // is still a list - this is for matching all the objects whose single
    // reference (in the given property) matches this Thing.
    reverseSingleReference: (thingDataProperty, referencerRefListProperty) => ({
      flags: {expose: true},

      expose: {
        dependencies: ['this', thingDataProperty],

        compute: ({this: thing, [thingDataProperty]: thingData}) =>
          thingData?.filter((t) => t[referencerRefListProperty] === thing) ?? [],
      },
    }),

    // General purpose wiki data constructor, for properties like artistData,
    // trackData, etc.
    wikiData: (thingClass) => ({
      flags: {update: true},
      update: {
        validate: validateArrayItems(validateInstanceOf(thingClass)),
      },
    }),

    // This one's kinda tricky: it parses artist "references" from the
    // commentary content, and finds the matching artist for each reference.
    // This is mostly useful for credits and listings on artist pages.
    commentatorArtists: () => ({
      flags: {expose: true},

      expose: {
        dependencies: ['artistData', 'commentary'],

        compute: ({artistData, commentary}) =>
          artistData && commentary
            ? Array.from(
                new Set(
                  Array.from(
                    commentary
                      .replace(/<\/?b>/g, '')
                      .matchAll(/<i>(?<who>.*?):<\/i>/g)
                  ).map(({groups: {who}}) =>
                    find.artist(who, artistData, {mode: 'quiet'})
                  )
                )
              )
            : [],
      },
    }),
  };

  // Default custom inspect function, which may be overridden by Thing
  // subclasses. This will be used when displaying aggregate errors and other
  // command-line logging - it's the place to provide information useful in
  // identifying the Thing being presented.
  [inspect.custom]() {
    const cname = this.constructor.name;

    return (
      (this.name ? `${cname} ${color.green(`"${this.name}"`)}` : `${cname}`) +
      (this.directory ? ` (${color.blue(Thing.getReference(this))})` : '')
    );
  }

  static getReference(thing) {
    if (!thing.constructor[Thing.referenceType]) {
      throw TypeError(`Passed Thing is ${thing.constructor.name}, which provides no [Thing.referenceType]`);
    }

    if (!thing.directory) {
      throw TypeError(`Passed ${thing.constructor.name} is missing its directory`);
    }

    return `${thing.constructor[Thing.referenceType]}:${thing.directory}`;
  }

  static findArtistsFromContribs(contribsByRef, artistData) {
    if (empty(contribsByRef)) return null;

    return (
      contribsByRef
        .map(({who, what}) => ({
          who: find.artist(who, artistData, {mode: 'quiet'}),
          what,
        }))
        .filter(({who}) => who));
  }

  static composite = {
    // Composes multiple compositional "steps" and a "base" to form a property
    // descriptor out of modular building blocks. This is an extension to the
    // more general-purpose CacheableObject property descriptor syntax, and
    // aims to make modular data processing - which lends to declarativity -
    // much easier, without fundamentally altering much of the typical syntax
    // or terminology, nor building on it to an excessive degree.
    //
    // Think of a composition as being a chain of steps which lead into a final
    // base property, which is usually responsible for returning the value that
    // will actually get exposed when the property being described is accessed.
    //
    // == The compositional base: ==
    //
    // The final item in a compositional list is its base, and it identifies
    // the essential qualities of the property descriptor. The compositional
    // steps preceding it may exit early, in which case the expose function
    // defined on the base won't be called; or they will provide dependencies
    // that the base may use to compute the final value that gets exposed for
    // this property.
    //
    // The base indicates the capabilities of the composition as a whole.
    // It should be {expose: true}, since that's the only area that preceding
    // compositional steps (currently) can actually influence. If it's also
    // {update: true}, then the composition as a whole accepts an update value
    // just like normal update-flag property descriptors - meaning it can be
    // set with `thing.someProperty = value` and that value will be paseed
    // into each (implementing) step's transform() function, as well as the
    // base. Bases usually aren't {compose: true}, but can be - check out the
    // section on "nesting compositions" for details about that.
    //
    // Every composition always has exactly one compositional base, and it's
    // always the last item in the composition list. All items preceding it
    // are compositional steps, described below.
    //
    // == Compositional steps: ==
    //
    // Compositional steps are, in essence, typical property descriptors with
    // the extra flag {compose: true}. They operate on existing dependencies,
    // and are typically dynamically constructed by "utility" functions (but
    // can also be manually declared within the step list of a composition).
    // Compositional steps serve two purposes:
    //
    //  1. exit early, if some condition is matched, returning and exposing
    //     some value directly from that step instead of continuing further
    //     down the step list;
    //
    //  2. and/or provide new, dynamically created "private" dependencies which
    //     can be accessed by further steps down the list, or at the base at
    //     the bottom, modularly supplying information that will contribute to
    //     the final value exposed for this property.
    //
    // Usually it's just one of those two, but it's fine for a step to perform
    // both jobs if the situation benefits.
    //
    // Compositional steps are the real "modular" or "compositional" part of
    // this data processing style - they're designed to be combined together
    // in dynamic, versatile ways, as each property demands it. You usually
    // define a compositional step to be returned by some ordinary static
    // property-descriptor-returning function (customarily namespaced under
    // the relevant Thing class's static `composite` field) - that lets you
    // reuse it in multiple compositions later on.
    //
    // Compositional steps are implemented with "continuation passing style",
    // meaning the connection to the next link on the chain is passed right to
    // each step's compute (or transform) function, and the implementation gets
    // to decide whether to continue on that chain or exit early by returning
    // some other value.
    //
    // Every step along the chain, apart from the base at the bottom, has to
    // have the {compose: true} step. That means its compute() or transform()
    // function will be passed an extra argument at the end, `continuation`.
    // To provide new dependencies to items further down the chain, just pass
    // them directly to this continuation() function, customarily with a hash
    // ('#') prefixing each name - for example:
    //
    //   compute({..some dependencies..}, continuation) {
    //     return continuation({
    //       '#excitingProperty': (..a value made from dependencies..),
    //     });
    //   }
    //
    // Performing an early exit is as simple as returning some other value,
    // instead of the continuation. You may also use `continuation.exit(value)`
    // to perform the exact same kind of early exit - it's just a different
    // syntax that might fit in better in certain longer compositions.
    //
    // It may be fine to simply provide new dependencies under a hard-coded
    // name, such as '#excitingProperty' above, but if you're writing a utility
    // that dynamically returns the compositional step and you suspect you
    // might want to use this step multiple times in a single composition,
    // it's customary to accept a name for the result.
    //
    // Here's a detailed example showing off early exit, dynamically operating
    // on a provided dependency name, and then providing a result in another
    // also-provided dependency name:
    //
    //   static Thing.composite.withResolvedContribs = ({
    //     from: contribsByRefDependency,
    //     to: outputDependency,
    //   }) => ({
    //     flags: {expose: true, compose: true},
    //     expose: {
    //       dependencies: [contribsByRefDependency, 'artistData'],
    //       compute({
    //         [contribsByRefDependency]: contribsByRef,
    //         artistData,
    //       }, continuation) {
    //         if (!artistData) return null;  /* early exit! */
    //         return continuation({
    //           [outputDependency]:  /* this is the important part */
    //             (..resolve contributions one way or another..),
    //         });
    //       },
    //     },
    //   });
    //
    // And how you might work that into a composition:
    //
    //   static Track[Thing.getPropertyDescriptors].coverArtists =
    //     Thing.composite.from([
    //       Track.composite.doSomethingWhichMightEarlyExit(),
    //       Thing.composite.withResolvedContribs({
    //         from: 'coverArtistContribsByRef',
    //         to: '#coverArtistContribs',
    //       }),
    //
    //       {
    //         flags: {expose: true},
    //         expose: {
    //           dependencies: ['#coverArtistContribs'],
    //           compute({'#coverArtistContribs': coverArtistContribs}) {
    //             return coverArtistContribs.map(({who}) => who);
    //           },
    //         },
    //       },
    //     ]);
    //
    // == Cache-safe dependency names: ==
    //
    // [Disclosure: The caching engine hasn't actually been implemented yet.
    //  As such, this section is subject to change, and simply provides sound
    //  forward-facing advice and interfaces.]
    //
    // It's a good idea to write individual compositional steps in such a way
    // that they're "cache-safe" - meaning the same input (dependency) values
    // will always result in the same output (continuation or early exit).
    //
    // In order to facilitate this, compositional step descriptors may specify
    // unique `mapDependencies`, `mapContinuation`, and `options` values.
    //
    // Consider the `withResolvedContribs` example adjusted to make use of
    // two of these options below:
    //
    //   static Thing.composite.withResolvedContribs = ({
    //     from: contribsByRefDependency,
    //     to: outputDependency,
    //   }) => ({
    //     flags: {expose: true, compose: true},
    //     expose: {
    //       dependencies: ['artistData'],
    //       mapDependencies: {contribsByRef: contribsByRefDependency},
    //       mapContinuation: {outputDependency},
    //       compute({
    //         contribsByRef, /* no longer in square brackets */
    //         artistData,
    //       }, continuation) {
    //         if (!artistData) return null;
    //         return continuation({
    //           outputDependency: /* no longer in square brackets */
    //             (..resolve contributions one way or another..),
    //         });
    //       },
    //     },
    //   });
    //
    // With a little destructuring and restructuring JavaScript sugar, the
    // above can be simplified some more:
    //
    //   static Thing.composite.withResolvedContribs = ({from, to}) => ({
    //     flags: {expose: true, compose: true},
    //     expose: {
    //       dependencies: ['artistData'],
    //       mapDependencies: {from},
    //       mapContinuation: {to},
    //       compute({artistData, from: contribsByRef}, continuation) {
    //         if (!artistData) return null;
    //         return continuation({
    //           to: (..resolve contributions one way or another..),
    //         });
    //       },
    //     },
    //   });
    //
    // These two properties let you separate the name-mapping behavior (for
    // dependencies and the continuation) from the main body of the compute
    // function. That means the compute function will *always* get inputs in
    // the same form (dependencies 'artistData' and 'from' above), and will
    // *always* provide its output in the same form (early return or 'to').
    //
    // Thanks to that, this `compute` function is cache-safe! Its outputs can
    // be cached corresponding to each set of mapped inputs. So it won't matter
    // whether the `from` dependency is named `coverArtistContribsByRef` or
    // `contributorContribsByRef` or something else - the compute function
    // doesn't care, and only expects that value to be provided via its `from`
    // argument. Likewise, it doesn't matter if the output should be sent to
    // '#coverArtistContribs` or `#contributorContribs` or some other name;
    // the mapping is handled automatically outside, and compute will always
    // output its value to the continuation's `to`.
    //
    // Note that `mapDependencies` and `mapContinuation` should be objects of
    // the same "shape" each run - that is, the values will change depending on
    // outside context, but the keys are always the same. You shouldn't use
    // `mapDependencies` to dynamically select more or fewer dependencies.
    // If you need to dynamically select a range of dependencies, just specify
    // them in the `dependencies` array like usual. The caching engine will
    // understand that differently named `dependencies` indicate separate
    // input-output caches should be used.
    //
    // The 'options' property makes it possible to specify external arguments
    // that fundamentally change the behavior of the `compute` function, while
    // still remaining cache-safe. It indicates that the caching engine should
    // use a completely different input-to-output cache for each permutation
    // of the 'options' values. This way, those functions are still cacheable
    // at all; they'll just be cached separately for each set of option values.
    // Values on the 'options' property will always be provided in compute's
    // dependencies under '#options' (to avoid name conflicts with other
    // dependencies).
    //
    // == To compute or to transform: ==
    //
    // A compositional step can work directly on a property's stored update
    // value, transforming it in place and either early exiting with it or
    // passing it on (via continuation) to the next item(s) in the
    // compositional step list. (If needed, these can provide dependencies
    // the same way as compute functions too - just pass that object after
    // the updated (or same) transform value in your call to continuation().)
    //
    // But in order to make them more versatile, compositional steps have an
    // extra trick up their sleeve. If a compositional step implements compute
    // and *not* transform, it can still be used in a composition targeting a
    // property which updates! These retain their full dependency-providing and
    // early exit functionality - they just won't be provided the update value.
    // If a compute-implementing step returns its continuation, then whichever
    // later step (or the base) next implements transform() will receive the
    // update value that had so far been running - as well as any dependencies
    // the compute() step returned, of course!
    //
    // Please note that a compositional step which transforms *should not*
    // specify, in its flags, {update: true}. Just provide the transform()
    // function in its expose descriptor; it will be automatically detected
    // and used when appropriate.
    //
    // It's actually possible for a step to specify both transform and compute,
    // in which case the transform() implementation will only be selected if
    // the composition's base is {update: true}. It's not exactly known why you
    // would want to specify unique-but-related transform and compute behavior,
    // but the basic possibility was too cool to skip out on.
    //
    // == Nesting compositions: ==
    //
    // Compositional steps are so convenient that you just might want to bundle
    // them together, and form a whole new step-shaped unit of its own!
    //
    // In order to allow for this while helping to ensure internal dependencies
    // remain neatly isolated from the composition which nests your bundle,
    // the Thing.composite.from() function will accept and adapt to a base that
    // specifies the {compose: true} flag, just like the steps preceding it.
    //
    // The continuation function that gets provided to the base will be mildly
    // special - after all, nothing follows the base within the composition's
    // own list! Instead of appending dependencies alongside any previously
    // provided ones to be available to the next step, the base's continuation
    // function should be used to define "exports" of the composition as a
    // whole. It's similar to the usual behavior of the continuation, just
    // expanded to the scope of the composition instead of following steps.
    //
    // For example, suppose your composition (which you expect to include in
    // other compositions) brings about several internal, hash-prefixed
    // dependencies to contribute to its own results. Those dependencies won't
    // end up "bleeding" into the dependency list of whichever composition is
    // nesting this one - they will totally disappear once all the steps in
    // the nested composition have finished up.
    //
    // To "export" the results of processing all those dependencies (provided
    // that's something you want to do and this composition isn't used purely
    // for a conditional early-exit), you'll want to define them in the
    // continuation passed to the base. (Customarily, those should start with
    // a hash just like the exports from any other compositional step; they're
    // still dynamically provided dependencies!)
    //
    from(firstArg, secondArg) {
      const debug = fn => {
        if (Thing.composite.from.debug === true) {
          const result = fn();
          if (Array.isArray(result)) {
            console.log(`[composite]`, ...result);
          } else {
            console.log(`[composite]`, result);
          }
        }
      };

      let annotation, composition;
      if (typeof firstArg === 'string') {
        [annotation, composition] = [firstArg, secondArg];
      } else {
        [annotation, composition] = [null, firstArg];
      }

      const base = composition.at(-1);
      const steps = composition.slice(0, -1);

      const aggregate = openAggregate({
        message:
          `Errors preparing Thing.composite.from() composition` +
          (annotation ? ` (${annotation})` : ''),
      });

      if (base.flags.compose && base.flags.compute) {
        push(new TypeError(`Base which composes can't also update yet`));
      }

      const exposeSteps = [];
      const exposeDependencies = new Set(base.expose?.dependencies);

      if (base.expose?.mapDependencies) {
        for (const dependency of Object.values(base.expose.mapDependencies)) {
          if (typeof dependency === 'string' && dependency.startsWith('#')) continue;
          exposeDependencies.add(dependency);
        }
      }

      for (let i = 0; i < steps.length; i++) {
        const step = steps[i];
        const message =
          (step.annotation
            ? `Errors in step #${i + 1} (${step.annotation})`
            : `Errors in step #${i + 1}`);

        aggregate.nest({message}, ({push}) => {
          if (!step.flags.compose) {
            push(new TypeError(`Steps (all but bottom item) must be {compose: true}`));
          }

          if (step.flags.update) {
            push(new Error(`Steps which update aren't supported yet`));
          }

          if (step.flags.expose) expose: {
            if (!step.expose.transform && !step.expose.compute) {
              push(new TypeError(`Steps which expose must provide at least one of transform or compute`));
              break expose;
            }

            if (step.expose.dependencies) {
              for (const dependency of step.expose.dependencies) {
                if (typeof dependency === 'string' && dependency.startsWith('#')) continue;
                exposeDependencies.add(dependency);
              }
            }

            if (step.expose.mapDependencies) {
              for (const dependency of Object.values(step.expose.mapDependencies)) {
                if (typeof dependency === 'string' && dependency.startsWith('#')) continue;
                exposeDependencies.add(dependency);
              }
            }

            let fn, type;
            if (base.flags.update) {
              if (step.expose.transform) {
                type = 'transform';
                fn = step.expose.transform;
              } else {
                type = 'compute';
                fn = step.expose.compute;
              }
            } else {
              if (step.expose.transform && !step.expose.compute) {
                push(new TypeError(`Steps which only transform can't be composed with a non-updating base`));
                break expose;
              }

              type = 'compute';
              fn = step.expose.compute;
            }

            exposeSteps.push(step.expose);
          }
        });
      }

      aggregate.close();

      const constructedDescriptor = {};

      if (annotation) {
        constructedDescriptor.annotation = annotation;
      }

      constructedDescriptor.flags = {
        update: !!base.flags.update,
        expose: !!base.flags.expose,
        compose: !!base.flags.compose,
      };

      if (base.flags.update) {
        constructedDescriptor.update = base.update;
      }

      if (base.flags.expose) {
        const expose = constructedDescriptor.expose = {};
        expose.dependencies = Array.from(exposeDependencies);

        const continuationSymbol = Symbol('continuation symbol');
        const noTransformSymbol = Symbol('no-transform symbol');

        function _filterDependencies(dependencies, step) {
          const filteredDependencies =
            (step.dependencies
              ? filterProperties(dependencies, step.dependencies)
              : {});

          if (step.mapDependencies) {
            for (const [to, from] of Object.entries(step.mapDependencies)) {
              filteredDependencies[to] = dependencies[from] ?? null;
            }
          }

          if (step.options) {
            filteredDependencies['#options'] = step.options;
          }

          return filteredDependencies;
        }

        function _assignDependencies(continuationAssignment, step) {
          if (!step.mapContinuation) {
            return continuationAssignment;
          }

          const assignDependencies = {};

          for (const [from, to] of Object.entries(step.mapContinuation)) {
            assignDependencies[to] = continuationAssignment[from] ?? null;
          }

          return assignDependencies;
        }

        function _prepareContinuation(transform, step) {
          const continuationStorage = {
            returnedWith: null,
            providedDependencies: null,
            providedValue: null,
          };

          const continuation =
            (transform
              ? (providedValue, providedDependencies = null) => {
                  continuationStorage.returnedWith = 'continuation';
                  continuationStorage.providedDependencies = providedDependencies;
                  continuationStorage.providedValue = providedValue;
                  return continuationSymbol;
                }
              : (providedDependencies = null) => {
                  continuationStorage.returnedWith = 'continuation';
                  continuationStorage.providedDependencies = providedDependencies;
                  return continuationSymbol;
                });

          continuation.exit = (providedValue) => {
            continuationStorage.returnedWith = 'exit';
            continuationStorage.providedValue = providedValue;
            return continuationSymbol;
          };

          if (base.flags.compose) {
            continuation.raise =
              (transform
                ? (providedValue, providedDependencies = null) => {
                    continuationStorage.returnedWith = 'raise';
                    continuationStorage.providedDependencies = providedDependencies;
                    continuationStorage.providedValue = providedValue;
                    return continuationSymbol;
                  }
                : (providedDependencies = null) => {
                    continuationStorage.returnedWith = 'raise';
                    continuationStorage.providedDependencies = providedDependencies;
                    return continuationSymbol;
                  });
          }

          return {continuation, continuationStorage};
        }

        function _computeOrTransform(value, initialDependencies, continuationIfApplicable) {
          const dependencies = {...initialDependencies};

          let valueSoFar = value;         // Set only for {update: true} compositions
          let exportDependencies = null;  // Set only for {compose: true} compositions

          debug(() => color.bright(`begin composition (annotation: ${annotation})`));

          for (let i = 0; i < exposeSteps.length; i++) {
            const step = exposeSteps[i];
            debug(() => [`step #${i+1}:`, step]);

            const transform =
              valueSoFar !== noTransformSymbol &&
              step.transform;

            const filteredDependencies = _filterDependencies(dependencies, step);
            const {continuation, continuationStorage} = _prepareContinuation(transform, step);

            if (transform) {
              debug(() => `step #${i+1} - transform with dependencies: ${inspect(filteredDependencies, {depth: 0})}`);
            } else {
              debug(() => `step #${i+1} - compute with dependencies: ${inspect(filteredDependencies, {depth: 0})}`);
            }

            const result =
              (transform
                ? step.transform(valueSoFar, filteredDependencies, continuation)
                : step.compute(filteredDependencies, continuation));

            if (result !== continuationSymbol) {
              if (base.flags.compose) {
                throw new TypeError(`Use continuation.exit() or continuation.raise() in {compose: true} compositions`);
              }

              debug(() => `step #${i+1} - early-exit (inferred)`);
              debug(() => `early-exit: ${inspect(result, {compact: true})}`);
              debug(() => color.bright(`end composition (annotation: ${annotation})`));

              return result;
            }

            if (continuationStorage.returnedWith === 'exit') {
              debug(() => `step #${i+1} - result: early-exit (explicit)`);
              debug(() => `early-exit: ${inspect(continuationStorage.providedValue, {compact: true})}`);
              debug(() => color.bright(`end composition (annotation: ${annotation})`));

              return continuationSymbol.providedValue;
            }

            if (continuationStorage.returnedWith === 'raise') {
              if (transform) {
                valueSoFar = continuationStorage.providedValue;
              }

              exportDependencies = _assignDependencies(continuationStorage.providedDependencies, step);

              debug(() => `step #${i+1} - result: raise`);

              break;
            }

            if (continuationStorage.returnedWith === 'continuation') {
              if (transform) {
                valueSoFar = continuationStorage.providedValue;
              }

              debug(() => `step #${i+1} - result: continuation`);

              if (continuationStorage.providedDependencies) {
                const assignDependencies = _assignDependencies(continuationStorage.providedDependencies, step);
                Object.assign(dependencies, assignDependencies);

                debug(() => [`assign dependencies:`, assignDependencies]);
              }
            }
          }

          if (exportDependencies) {
            debug(() => [`raise dependencies:`, exportDependencies]);
            debug(() => color.bright(`end composition (annotation: ${annotation})`));
            return continuationIfApplicable(exportDependencies);
          }

          debug(() => `completed all steps, reached base`);

          const filteredDependencies = _filterDependencies(dependencies, base.expose);

          // Note: base.flags.compose is not compatible with base.flags.update.
          if (base.expose.transform) {
            debug(() => `base - transform with dependencies: ${inspect(filteredDependencies, {depth: 0})}`);

            const result = base.expose.transform(valueSoFar, filteredDependencies);

            debug(() => `base - non-compose (final) result: ${inspect(result, {compact: true})}`);

            return result;
          } else if (base.flags.compose) {
            const {continuation, continuationStorage} = _prepareContinuation(false, base.expose);

            debug(() => `base - compute with dependencies: ${inspect(filteredDependencies, {depth: 0})}`);

            const result = base.expose.compute(filteredDependencies, continuation);

            if (result !== continuationSymbol) {
              throw new TypeError(`Use continuation.exit() or continuation.raise() in {compose: true} composition`);
            }

            if (continuationStorage.returnedWith === 'continuation') {
              throw new TypeError(`Use continuation.raise() in base of {compose: true} composition`);
            }

            if (continuationStorage.returnedWith === 'exit') {
              debug(() => `base - result: early-exit (explicit)`);
              debug(() => `early-exit: ${inspect(continuationStorage.providedValue, {compact: true})}`);
              debug(() => color.bright(`end composition (annotation: ${annotation})`));

              return continuationStorage.providedValue;
            }

            if (continuationStorage.returnedWith === 'raise') {
              exportDependencies = _assignDependencies(continuationStorage.providedDependencies, base.expose);

              debug(() => `base - result: raise`);
              debug(() => `raise dependencies: ${inspect(exportDependencies, {compact: true})}`);
              debug(() => color.bright(`end composition (annotation: ${annotation})`));

              return continuationIfApplicable(exportDependencies);
            }
          } else {
            debug(() => `base - compute with dependencies: ${inspect(filteredDependencies, {depth: 0})}`);

            const result = base.expose.compute(filteredDependencies);

            debug(() => `base - non-compose (final) result: ${inspect(result, {compact: true})}`);
            debug(() => color.bright(`end composition (annotation: ${annotation})`));

            return result;
          }
        }

        if (base.flags.update) {
          expose.transform =
            (value, initialDependencies, continuationIfApplicable) =>
              _computeOrTransform(value, initialDependencies, continuationIfApplicable);
        } else {
          expose.compute =
            (initialDependencies, continuationIfApplicable) =>
              _computeOrTransform(noTransformSymbol, initialDependencies, continuationIfApplicable);
        }
      }

      return constructedDescriptor;
    },

    // Provides dependencies exactly as they are (or null if not defined) to the
    // continuation. Although this can *technically* be used to alias existing
    // dependencies to some other name within the middle of a composition, it's
    // intended to be used only as a composition's base - doing so makes the
    // composition as a whole suitable as a step in some other composition,
    // providing the listed (internal) dependencies to later steps just like
    // other compositional steps.
    export(mapping) {
      const mappingEntries = Object.entries(mapping);

      return {
        annotation: `Thing.composite.export`,
        flags: {expose: true, compose: true},

        expose: {
          options: {mappingEntries},
          dependencies: Object.values(mapping),

          compute({'#options': {mappingEntries}, ...dependencies}, continuation) {
            const exports = {};

            // Note: This is slightly different behavior from filterProperties,
            // as defined in sugar.js, which doesn't fall back to null for
            // properties which don't exist on the original object.
            for (const [exportKey, dependencyKey] of mappingEntries) {
              exports[exportKey] =
                (Object.hasOwn(dependencies, dependencyKey)
                  ? dependencies[dependencyKey]
                  : null);
            }

            return continuation.raise(exports);
          }
        },
      };
    },

    // Resolves the contribsByRef contained in the provided dependency,
    // providing (named by the second argument) the result. "Resolving"
    // means mapping the "who" reference of each contribution to an artist
    // object, and filtering out those whose "who" doesn't match any artist.
    withResolvedContribs: ({from, to}) => ({
      annotation: `Thing.composite.withResolvedContribs`,
      flags: {expose: true, compose: true},

      expose: {
        dependencies: ['artistData'],
        mapDependencies: {from},
        mapContinuation: {to},
        compute: ({artistData, from}, continuation) =>
          continuation({
            to: Thing.findArtistsFromContribs(from, artistData),
          }),
      },
    }),

    // Resolves a reference by using the provided find function to match it
    // within the provided thingData dependency. This will early exit if the
    // data dependency is null, or, if earlyExitIfNotFound is set to true,
    // if the find function doesn't match anything for the reference.
    // Otherwise, the data object is provided on the output dependency;
    // or null, if the reference doesn't match anything or itself was null
    // to begin with.
    withResolvedReference: ({
      ref,
      data,
      to,
      find: findFunction,
      earlyExitIfNotFound = false,
    }) =>
      Thing.composite.from(`Thing.composite.withResolvedReference`, [
        {
          flags: {expose: true, compose: true},
          expose: {
            mapDependencies: {ref},
            mapContinuation: {to},

            compute: ({ref}, continuation) =>
              (ref
                ? continuation()
                : continuation.raise({to: null})),
          },
        },

        {
          flags: {expose: true, compose: true},
          expose: {
            mapDependencies: {data},

            compute: ({data}, continuation) =>
              (data === null
                ? continuation.exit(null)
                : continuation()),
          },
        },

        {
          flags: {expose: true, compose: true},
          expose: {
            options: {findFunction, earlyExitIfNotFound},
            mapDependencies: {ref, data},
            mapContinuation: {match: to},

            compute({ref, data, '#options': {findFunction, earlyExitIfNotFound}}, continuation) {
              const match = findFunction(ref, data, {mode: 'quiet'});

              if (match === null && earlyExitIfNotFound) {
                return continuation.exit(null);
              }

              return continuation.raise({match});
            },
          },
        },
      ]),
  };
}