« get me outta code hell

sugar.js « util « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/util/sugar.js
blob: faf685b592d5bf74338237bc302a09ba64221af4 (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
// Syntactic sugar! (Mostly.)
// Generic functions - these are useful just a8out everywhere.
//
// Friendly(!) disclaimer: these utility functions haven't 8een tested all that
// much. Do not assume it will do exactly what you want it to do in all cases.
// It will likely only do exactly what I want it to, and only in the cases I
// decided were relevant enough to 8other handling.

import {colors} from './cli.js';

// Apparently JavaScript doesn't come with a function to split an array into
// chunks! Weird. Anyway, this is an awesome place to use a generator, even
// though we don't really make use of the 8enefits of generators any time we
// actually use this. 8ut it's still awesome, 8ecause I say so.
export function* splitArray(array, fn) {
  let lastIndex = 0;
  while (lastIndex < array.length) {
    let nextIndex = array.findIndex((item, index) => index >= lastIndex && fn(item));
    if (nextIndex === -1) {
      nextIndex = array.length;
    }
    yield array.slice(lastIndex, nextIndex);
    // Plus one because we don't want to include the dividing line in the
    // next array we yield.
    lastIndex = nextIndex + 1;
  }
}

// Null-accepting function to check if an array or set is empty. Accepts null
// (which is treated as empty) as a shorthand for "hey, check if this property
// is an array with/without stuff in it" for objects where properties that are
// PRESENT but don't currently have a VALUE are null (rather than undefined).
export function empty(value) {
  if (value === null) {
    return true;
  }

  if (Array.isArray(value)) {
    return value.length === 0;
  }

  if (value instanceof Set) {
    return value.size === 0;
  }

  throw new Error(`Expected array, set, or null`);
}

// Repeats all the items of an array a number of times.
export function repeat(times, array) {
  if (typeof array === 'string') return repeat(times, [array]);
  if (empty(array)) return [];
  if (times === 0) return [];
  if (times === 1) return array.slice();

  const out = [];
  for (let n = 1; n <= times; n++) {
    out.push(...array);
  }
  return out;
}

// Sums the values in an array, optionally taking a function which maps each
// item to a number (handy for accessing a certain property on an array of like
// objects). This also coalesces null values to zero, so if the mapping function
// returns null (or values in the array are nullish), they'll just be skipped in
// the sum.
export function accumulateSum(array, fn = x => x) {
  return array.reduce(
    (accumulator, value, index, array) =>
      accumulator +
        fn(value, index, array) ?? 0,
    0);
}

// Stitches together the items of separate arrays into one array of objects
// whose keys are the corresponding items from each array at that index.
// This is mostly useful for iterating over multiple arrays at once!
export function stitchArrays(keyToArray) {
  const errors = [];

  for (const [key, value] of Object.entries(keyToArray)) {
    if (value === null) continue;
    if (Array.isArray(value)) continue;
    errors.push(new TypeError(`(${key}) Expected array or null, got ${typeAppearance(value)}`));
  }

  if (!empty(errors)) {
    throw new AggregateError(errors, `Expected arrays or null`);
  }

  const keys = Object.keys(keyToArray);
  const arrays = Object.values(keyToArray).filter(val => Array.isArray(val));
  const length = Math.max(...arrays.map(({length}) => length));
  const results = [];

  for (let i = 0; i < length; i++) {
    const object = {};
    for (const key of keys) {
      object[key] =
        (Array.isArray(keyToArray[key])
          ? keyToArray[key][i]
          : null);
    }
    results.push(object);
  }

  return results;
}

// Turns this:
//
//   [
//     [123, 'orange', null],
//     [456, 'apple', true],
//     [789, 'banana', false],
//     [1000, 'pear', undefined],
//   ]
//
// Into this:
//
//   [
//     [123, 456, 789, 1000],
//     ['orange', 'apple', 'banana', 'pear'],
//     [null, true, false, undefined],
//   ]
//
// And back again, if you call it again on its results.
export function transposeArrays(arrays) {
  if (empty(arrays)) {
    return [];
  }

  const length = arrays[0].length;
  const results = new Array(length).fill(null).map(() => []);

  for (const array of arrays) {
    for (let i = 0; i < length; i++) {
      results[i].push(array[i]);
    }
  }

  return results;
}

export const mapInPlace = (array, fn) =>
  array.splice(0, array.length, ...array.map(fn));

export const unique = (arr) => Array.from(new Set(arr));

export const compareArrays = (arr1, arr2, {checkOrder = true} = {}) =>
  arr1.length === arr2.length &&
  (checkOrder
    ? arr1.every((x, i) => arr2[i] === x)
    : arr1.every((x) => arr2.includes(x)));

// Stolen from jq! Which pro8a8ly stole the concept from other places. Nice.
export const withEntries = (obj, fn) =>
  Object.fromEntries(fn(Object.entries(obj)));

export function setIntersection(set1, set2) {
  const intersection = new Set();
  for (const item of set1) {
    if (set2.has(item)) {
      intersection.add(item);
    }
  }
  return intersection;
}

export function filterProperties(object, properties, {
  preserveOriginalOrder = false,
} = {}) {
  if (typeof object !== 'object' || object === null) {
    throw new TypeError(`Expected object to be an object, got ${typeAppearance(object)}`);
  }

  if (!Array.isArray(properties)) {
    throw new TypeError(`Expected properties to be an array, got ${typeAppearance(properties)}`);
  }

  const filteredObject = {};

  if (preserveOriginalOrder) {
    for (const property of Object.keys(object)) {
      if (properties.includes(property)) {
        filteredObject[property] = object[property];
      }
    }
  } else {
    for (const property of properties) {
      if (Object.hasOwn(object, property)) {
        filteredObject[property] = object[property];
      }
    }
  }

  return filteredObject;
}

export function queue(array, max = 50) {
  if (max === 0) {
    return array.map((fn) => fn());
  }

  const begin = [];
  let current = 0;
  const ret = array.map(
    (fn) =>
      new Promise((resolve, reject) => {
        begin.push(() => {
          current++;
          Promise.resolve(fn()).then((value) => {
            current--;
            if (current < max && begin.length) {
              begin.shift()();
            }
            resolve(value);
          }, reject);
        });
      })
  );

  for (let i = 0; i < max && begin.length; i++) {
    begin.shift()();
  }

  return ret;
}

export function delay(ms) {
  return new Promise((res) => setTimeout(res, ms));
}

// Stolen from here: https://stackoverflow.com/a/3561711
//
// There's a proposal for a native JS function like this, 8ut it's not even
// past stage 1 yet: https://github.com/tc39/proposal-regex-escaping
export function escapeRegex(string) {
  return string.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
}

// Gets the "look" of some arbitrary value. It's like typeof, but smarter.
// Don't use this for actually validating types - it's only suitable for
// inclusion in error messages.
export function typeAppearance(value) {
  if (value === null) return 'null';
  if (value === undefined) return 'undefined';
  if (Array.isArray(value)) return 'array';
  return typeof value;
}

// Limits a string to the desired length, filling in an ellipsis at the end
// if it cuts any text off.
export function cut(text, length = 40) {
  if (text.length >= length) {
    return text.slice(0, Math.max(1, length - 3)) + '...';
  } else {
    return text;
  }
}

// Binds default values for arguments in a {key: value} type function argument
// (typically the second argument, but may be overridden by providing a
// [bindOpts.bindIndex] argument). Typically useful for preparing a function for
// reuse within one or multiple other contexts, which may not be aware of
// required or relevant values provided in the initial context.
//
// This function also passes the identity of `this` through (the returned value
// is not an arrow function), though note it's not a true bound function either
// (since Function.prototype.bind only supports positional arguments, not
// "options" specified via key/value).
//
export function bindOpts(fn, bind) {
  const bindIndex = bind[bindOpts.bindIndex] ?? 1;

  const bound = function (...args) {
    const opts = args[bindIndex] ?? {};
    return Reflect.apply(fn, this, [
      ...args.slice(0, bindIndex),
      {...bind, ...opts}
    ]);
  };

  annotateFunction(bound, {
    name: fn,
    trait: 'options-bound',
  });

  for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(fn))) {
    if (key === 'length') continue;
    if (key === 'name') continue;
    if (key === 'arguments') continue;
    if (key === 'caller') continue;
    if (key === 'prototype') continue;
    Object.defineProperty(bound, key, descriptor);
  }

  return bound;
}

bindOpts.bindIndex = Symbol();

// Utility function for providing useful interfaces to the JS AggregateError
// class.
//
// Generally, this works by returning a set of interfaces which operate on
// functions: wrap() takes a function and returns a new function which passes
// its arguments through and appends any resulting error to the internal error
// list; call() simplifies this process by wrapping the provided function and
// then calling it immediately. Once the process for which errors should be
// aggregated is complete, close() constructs and throws an AggregateError
// object containing all caught errors (or doesn't throw anything if there were
// no errors).
export function openAggregate({
  // Constructor to use, defaulting to the builtin AggregateError class.
  // Anything passed here should probably extend from that! May be used for
  // letting callers programatically distinguish between multiple aggregate
  // errors.
  //
  // This should be provided using the aggregateThrows utility function.
  [openAggregate.errorClassSymbol]: errorClass = AggregateError,

  // Optional human-readable message to describe the aggregate error, if
  // constructed.
  message = '',

  // Optional flag to indicate that this layer of the aggregate error isn't
  // generally useful outside of developer debugging purposes - it will be
  // skipped by default when using showAggregate, showing contained errors
  // inline with other children of this aggregate's parent.
  translucent = false,

  // Value to return when a provided function throws an error. If this is a
  // function, it will be called with the arguments given to the function.
  // (This is primarily useful when wrapping a function and then providing it
  // to another utility, e.g. array.map().)
  returnOnFail = null,
} = {}) {
  const errors = [];

  const aggregate = {};

  aggregate.wrap =
    (fn) =>
    (...args) => {
      try {
        return fn(...args);
      } catch (error) {
        errors.push(error);
        return typeof returnOnFail === 'function'
          ? returnOnFail(...args)
          : returnOnFail;
      }
    };

  aggregate.wrapAsync =
    (fn) =>
    (...args) => {
      return fn(...args).then(
        (value) => value,
        (error) => {
          errors.push(error);
          return typeof returnOnFail === 'function'
            ? returnOnFail(...args)
            : returnOnFail;
        }
      );
    };

  aggregate.push = (error) => {
    errors.push(error);
  };

  aggregate.call = (fn, ...args) => {
    return aggregate.wrap(fn)(...args);
  };

  aggregate.callAsync = (fn, ...args) => {
    return aggregate.wrapAsync(fn)(...args);
  };

  aggregate.nest = (...args) => {
    return aggregate.call(() => withAggregate(...args));
  };

  aggregate.nestAsync = (...args) => {
    return aggregate.callAsync(() => withAggregateAsync(...args));
  };

  aggregate.map = (...args) => {
    const parent = aggregate;
    const {result, aggregate: child} = mapAggregate(...args);
    parent.call(child.close);
    return result;
  };

  aggregate.mapAsync = async (...args) => {
    const parent = aggregate;
    const {result, aggregate: child} = await mapAggregateAsync(...args);
    parent.call(child.close);
    return result;
  };

  aggregate.filter = (...args) => {
    const parent = aggregate;
    const {result, aggregate: child} = filterAggregate(...args);
    parent.call(child.close);
    return result;
  };

  aggregate.throws = aggregateThrows;

  aggregate.close = () => {
    if (errors.length) {
      const error = Reflect.construct(errorClass, [errors, message]);

      if (translucent) {
        error[Symbol.for(`hsmusic.aggregate.translucent`)] = true;
      }

      throw error;
    }
  };

  return aggregate;
}

openAggregate.errorClassSymbol = Symbol('error class');

// Utility function for providing {errorClass} parameter to aggregate functions.
export function aggregateThrows(errorClass) {
  return {[openAggregate.errorClassSymbol]: errorClass};
}

// Helper function for allowing both (fn, aggregateOpts) and (aggregateOpts, fn)
// in aggregate utilities.
function _reorganizeAggregateArguments(arg1, arg2) {
  if (typeof arg1 === 'function') {
    return {fn: arg1, opts: arg2 ?? {}};
  } else if (typeof arg2 === 'function') {
    return {fn: arg2, opts: arg1 ?? {}};
  } else {
    throw new Error(`Expected a function`);
  }
}

// Performs an ordinary array map with the given function, collating into a
// results array (with errored inputs filtered out) and an error aggregate.
//
// Optionally, override returnOnFail to disable filtering and map errored inputs
// to a particular output.
//
// Note the aggregate property is the result of openAggregate(), still unclosed;
// use aggregate.close() to throw the error. (This aggregate may be passed to a
// parent aggregate: `parent.call(aggregate.close)`!)
export function mapAggregate(array, arg1, arg2) {
  const {fn, opts} = _reorganizeAggregateArguments(arg1, arg2);
  return _mapAggregate('sync', null, array, fn, opts);
}

export function mapAggregateAsync(array, arg1, arg2) {
  const {fn, opts} = _reorganizeAggregateArguments(arg1, arg2);
  const {promiseAll = Promise.all.bind(Promise), ...remainingOpts} = opts;
  return _mapAggregate('async', promiseAll, array, fn, remainingOpts);
}

// Helper function for mapAggregate which holds code common between sync and
// async versions.
export function _mapAggregate(mode, promiseAll, array, fn, aggregateOpts) {
  const failureSymbol = Symbol();

  const aggregate = openAggregate({
    returnOnFail: failureSymbol,
    ...aggregateOpts,
  });

  if (mode === 'sync') {
    const result = array
      .map(aggregate.wrap(fn))
      .filter((value) => value !== failureSymbol);
    return {result, aggregate};
  } else {
    return promiseAll(array.map(aggregate.wrapAsync(fn)))
      .then((values) => {
        const result = values.filter((value) => value !== failureSymbol);
        return {result, aggregate};
      });
  }
}

// Performs an ordinary array filter with the given function, collating into a
// results array (with errored inputs filtered out) and an error aggregate.
//
// Optionally, override returnOnFail to disable filtering errors and map errored
// inputs to a particular output.
//
// As with mapAggregate, the returned aggregate property is not yet closed.
export function filterAggregate(array, arg1, arg2) {
  const {fn, opts} = _reorganizeAggregateArguments(arg1, arg2);
  return _filterAggregate('sync', null, array, fn, opts);
}

export async function filterAggregateAsync(array, arg1, arg2) {
  const {fn, opts} = _reorganizeAggregateArguments(arg1, arg2);
  const {promiseAll = Promise.all.bind(Promise), ...remainingOpts} = opts;
  return _filterAggregate('async', promiseAll, array, fn, remainingOpts);
}

// Helper function for filterAggregate which holds code common between sync and
// async versions.
function _filterAggregate(mode, promiseAll, array, fn, aggregateOpts) {
  const failureSymbol = Symbol();

  const aggregate = openAggregate({
    returnOnFail: failureSymbol,
    ...aggregateOpts,
  });

  function filterFunction(value) {
    // Filter out results which match the failureSymbol, i.e. errored
    // inputs.
    if (value === failureSymbol) return false;

    // Always keep results which match the overridden returnOnFail
    // value, if provided.
    if (value === aggregateOpts.returnOnFail) return true;

    // Otherwise, filter according to the returned value of the wrapped
    // function.
    return value.output;
  }

  function mapFunction(value) {
    // Then turn the results back into their corresponding input, or, if
    // provided, the overridden returnOnFail value.
    return value === aggregateOpts.returnOnFail ? value : value.input;
  }

  if (mode === 'sync') {
    const result = array
      .map(aggregate.wrap((input, index, array) => {
        const output = fn(input, index, array);
        return {input, output};
      }))
      .filter(filterFunction)
      .map(mapFunction);

    return {result, aggregate};
  } else {
    return promiseAll(
      array.map(aggregate.wrapAsync(async (input, index, array) => {
        const output = await fn(input, index, array);
        return {input, output};
      }))
    ).then((values) => {
      const result = values.filter(filterFunction).map(mapFunction);

      return {result, aggregate};
    });
  }
}

// Totally sugar function for opening an aggregate, running the provided
// function with it, then closing the function and returning the result (if
// there's no throw).
export function withAggregate(arg1, arg2) {
  const {fn, opts} = _reorganizeAggregateArguments(arg1, arg2);
  return _withAggregate('sync', opts, fn);
}

export function withAggregateAsync(arg1, arg2) {
  const {fn, opts} = _reorganizeAggregateArguments(arg1, arg2);
  return _withAggregate('async', opts, fn);
}

export function _withAggregate(mode, aggregateOpts, fn) {
  const aggregate = openAggregate(aggregateOpts);

  if (mode === 'sync') {
    const result = fn(aggregate);
    aggregate.close();
    return result;
  } else {
    return fn(aggregate).then((result) => {
      aggregate.close();
      return result;
    });
  }
}

export const unhelpfulTraceLines = [
  /sugar/,
  /node:/,
  /<anonymous>/,
];

export function getUsefulTraceLine(trace, {helpful, unhelpful}) {
  if (!trace) return '';

  for (const traceLine of trace.split('\n')) {
    if (!traceLine.trim().startsWith('at')) {
      continue;
    }

    if (!empty(unhelpful)) {
      if (unhelpful.some(regex => regex.test(traceLine))) {
        continue;
      }
    }

    if (!empty(helpful)) {
      for (const regex of helpful) {
        const match = traceLine.match(regex);

        if (match) {
          return match[1] ?? traceLine;
        }
      }

      continue;
    }

    return traceLine;
  }

  return '';
}

export function showAggregate(topError, {
  pathToFileURL = f => f,
  showTraces = true,
  showTranslucent = showTraces,
  print = true,
} = {}) {
  const translucentSymbol = Symbol.for('hsmusic.aggregate.translucent');

  const determineCause = error => {
    let cause = error.cause;
    if (showTranslucent) return cause ?? null;

    while (cause) {
      if (!cause[translucentSymbol]) return cause;
      cause = cause.cause;
    }

    return null;
  };

  const determineErrors = parentError => {
    if (!parentError.errors) return null;
    if (showTranslucent) return parentError.errors;

    const errors = [];
    for (const error of parentError.errors) {
      if (!error[translucentSymbol]) {
        errors.push(error);
        continue;
      }

      if (error.cause) {
        errors.push(determineCause(error));
      }

      if (error.errors) {
        errors.push(...determineErrors(error));
      }
    }

    return errors;
  };

  const flattenErrorStructure = (error, level = 0) => {
    const cause = determineCause(error);
    const errors = determineErrors(error);

    return {
      level,

      kind: error.constructor.name,
      message: error.message,

      trace:
        (error[Symbol.for(`hsmusic.aggregate.traceFrom`)]
          ? error[Symbol.for(`hsmusic.aggregate.traceFrom`)].stack
          : error.stack),

      cause:
        (cause
          ? flattenErrorStructure(cause, level + 1)
          : null),

      errors:
        (errors
          ? errors.map(error => flattenErrorStructure(error, level + 1))
          : null),

      options: {
        alwaysTrace:
          error[Symbol.for(`hsmusic.aggregate.alwaysTrace`)],

        helpfulTraceLines:
          error[Symbol.for(`hsmusic.aggregate.helpfulTraceLines`)],

        unhelpfulTraceLines:
          error[Symbol.for(`hsmusic.aggregate.unhelpfulTraceLines`)],
      }
    };
  };

  const recursive = ({
    level,
    kind,
    message,
    trace,
    cause,
    errors,
    options: {
      alwaysTrace,
      helpfulTraceLines: ownHelpfulTraceLines,
      unhelpfulTraceLines: ownUnhelpfulTraceLines,
    },
  }) => {
    const messagePart =
      message || `(no message)`;

    const kindPart =
      kind || `unnamed kind`;

    let headerPart =
      (showTraces
        ? `[${kindPart}] ${messagePart}`
     : errors
        ? `[${messagePart}]`
        : messagePart);

    if (showTraces || alwaysTrace) {
      const traceLine =
        getUsefulTraceLine(trace, {
          unhelpful:
            (ownUnhelpfulTraceLines
              ? unhelpfulTraceLines.concat(ownUnhelpfulTraceLines)
              : unhelpfulTraceLines),

          helpful:
            (ownHelpfulTraceLines
              ? ownHelpfulTraceLines
              : null),
        });

      const tracePart =
        (traceLine
          ? '- ' +
            traceLine
              .trim()
              .replace(/file:\/\/.*\.js/, (match) => pathToFileURL(match))
          : '(no stack trace)');

      headerPart += ` ${colors.dim(tracePart)}`;
    }

    const head1 = level % 2 === 0 ? '\u21aa' : colors.dim('\u21aa');
    const bar1 = ' ';

    const causePart =
      (cause
        ? recursive(cause)
            .split('\n')
            .map((line, i) => i === 0 ? ` ${head1} ${line}` : ` ${bar1} ${line}`)
            .join('\n')
        : '');

    const head2 = level % 2 === 0 ? '\u257f' : colors.dim('\u257f');
    const bar2 = level % 2 === 0 ? '\u2502' : colors.dim('\u254e');

    const errorsPart =
      (errors
        ? errors
            .map(error => recursive(error))
            .flatMap(str => str.split('\n'))
            .map((line, i) => i === 0 ? ` ${head2} ${line}` : ` ${bar2} ${line}`)
            .join('\n')
        : '');

    return [headerPart, errorsPart, causePart].filter(Boolean).join('\n');
  };

  const structure = flattenErrorStructure(topError);
  const message = recursive(structure);

  if (print) {
    console.error(message);
  } else {
    return message;
  }
}

export function annotateError(error, ...callbacks) {
  for (const callback of callbacks) {
    error = callback(error) ?? error;
  }

  return error;
}

export function annotateErrorWithIndex(error, index) {
  return Object.assign(error, {
    [Symbol.for('hsmusic.annotateError.indexInSourceArray')]:
      index,

    message:
      `(${colors.yellow(`#${index + 1}`)}) ` +
      error.message,
  });
}

export function annotateErrorWithFile(error, file) {
  return Object.assign(error, {
    [Symbol.for('hsmusic.annotateError.file')]:
      file,

    message:
      error.message +
      (error.message.includes('\n') ? '\n' : ' ') +
      `(file: ${colors.bright(colors.blue(file))})`,
  });
}

export function asyncAdaptiveDecorateError(fn, callback) {
  if (typeof callback !== 'function') {
    throw new Error(`Expected callback to be a function, got ${typeAppearance(callback)}`);
  }

  const syncDecorated = function (...args) {
    try {
      return fn(...args);
    } catch (caughtError) {
      throw callback(caughtError, ...args);
    }
  };

  const asyncDecorated = async function(...args) {
    try {
      return await fn(...args);
    } catch (caughtError) {
      throw callback(caughtError, ...args);
    }
  };

  syncDecorated.async = asyncDecorated;

  return syncDecorated;
}

export function decorateError(fn, callback) {
  return asyncAdaptiveDecorateError(fn, callback);
}

export function asyncDecorateError(fn, callback) {
  return asyncAdaptiveDecorateError(fn, callback).async;
}

export function decorateErrorWithAnnotation(fn, ...annotationCallbacks) {
  return asyncAdaptiveDecorateError(fn,
    (caughtError, ...args) =>
      annotateError(caughtError,
        ...annotationCallbacks
          .map(callback => error => callback(error, ...args))));
}

export function decorateErrorWithIndex(fn) {
  return decorateErrorWithAnnotation(fn,
    (caughtError, _value, index) =>
      annotateErrorWithIndex(caughtError, index));
}

export function decorateErrorWithCause(fn, cause) {
  return asyncAdaptiveDecorateError(fn,
    (caughtError) =>
      Object.assign(caughtError, {cause}));
}

export function asyncDecorateErrorWithAnnotation(fn, ...annotationCallbacks) {
  return decorateErrorWithAnnotation(fn, ...annotationCallbacks).async;
}

export function asyncDecorateErrorWithIndex(fn) {
  return decorateErrorWithIndex(fn).async;
}

export function asyncDecorateErrorWithCause(fn, cause) {
  return decorateErrorWithCause(fn, cause).async;
}

export function conditionallySuppressError(conditionFn, callbackFn) {
  return (...args) => {
    try {
      return callbackFn(...args);
    } catch (error) {
      if (conditionFn(error, ...args) === true) {
        return;
      }

      throw error;
    }
  };
}

// Delicious function annotations, such as:
//
//   (*bound) soWeAreBackInTheMine
//   (data *unfulfilled) generateShrekTwo
//
export function annotateFunction(fn, {
  name: nameOrFunction = null,
  description: newDescription,
  trait: newTrait,
}) {
  let name;

  if (typeof nameOrFunction === 'function') {
    name = nameOrFunction.name;
  } else if (typeof nameOrFunction === 'string') {
    name = nameOrFunction;
  }

  name ??= fn.name ?? 'anonymous';

  const match = name.match(/^ *(?<prefix>.*?) *\((?<description>.*)( #(?<trait>.*))?\) *(?<suffix>.*) *$/);

  let prefix, suffix, description, trait;
  if (match) {
    ({prefix, suffix, description, trait} = match.groups);
  }

  prefix ??= '';
  suffix ??= name;
  description ??= '';
  trait ??= '';

  if (newDescription) {
    if (description) {
      description += '; ' + newDescription;
    } else {
      description = newDescription;
    }
  }

  if (newTrait) {
    if (trait) {
      trait += ' #' + newTrait;
    } else {
      trait = '#' + newTrait;
    }
  }

  let parenthesesPart;

  if (description && trait) {
    parenthesesPart = `${description} ${trait}`;
  } else if (description || trait) {
    parenthesesPart = description || trait;
  } else {
    parenthesesPart = '';
  }

  let finalName;

  if (prefix && parenthesesPart) {
    finalName = `${prefix} (${parenthesesPart}) ${suffix}`;
  } else if (parenthesesPart) {
    finalName = `(${parenthesesPart}) ${suffix}`;
  } else {
    finalName = suffix;
  }

  Object.defineProperty(fn, 'name', {value: finalName});
}