« get me outta code hell

html.js « util « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/util/html.js
blob: b1668558ff9c81f8751b2a2a49c695bf529e4bd9 (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
// Some really, really simple functions for formatting HTML content.

import {inspect} from 'node:util';

import {empty} from '#sugar';
import * as commonValidators from '#validators';

// COMPREHENSIVE!
// https://html.spec.whatwg.org/multipage/syntax.html#void-elements
export const selfClosingTags = [
  'area',
  'base',
  'br',
  'col',
  'embed',
  'hr',
  'img',
  'input',
  'link',
  'meta',
  'source',
  'track',
  'wbr',
];

// Pass to tag() as an attributes key to make tag() return a 8lank string if the
// provided content is empty. Useful for when you'll only 8e showing an element
// according to the presence of content that would 8elong there.
export const onlyIfContent = Symbol();

// Pass to tag() as an attributes key to make children be joined together by the
// provided string. This is handy, for example, for joining lines by <br> tags,
// or putting some other divider between each child. Note this will only have an
// effect if the tag content is passed as an array of children and not a single
// string.
export const joinChildren = Symbol();

// Pass to tag() as an attributes key to prevent additional whitespace from
// being added to the inner start and end of the tag's content - basically,
// ensuring that the start of the content begins immediately after the ">"
// ending the opening tag, and ends immediately before the "<" at the start of
// the closing tag. This has effect when a single child spans multiple lines,
// or when there are multiple children.
export const noEdgeWhitespace = Symbol();

// Note: This is only guaranteed to return true for blanks (as returned by
// html.blank()) and false for Tags and Templates (regardless of contents or
// other properties). Don't depend on this to match any other values.
export function isBlank(value) {
  if (isTag(value)) {
    return false;
  }

  if (isTemplate(value)) {
    return false;
  }

  if (!Array.isArray(value)) {
    return false;
  }

  return value.length === 0;
}

export function isTag(value) {
  return value instanceof Tag;
}

export function isTemplate(value) {
  return value instanceof Template;
}

export function isHTML(value) {
  if (typeof value === 'string') {
    return true;
  }

  if (value === null || value === undefined || value === false) {
    return true;
  }

  if (isBlank(value) || isTag(value) || isTemplate(value)) {
    return true;
  }

  if (Array.isArray(value)) {
    if (value.every(isHTML)) {
      return true;
    }
  }

  return false;
}

export function isAttributes(value) {
  if (typeof value !== 'object' || Array.isArray(value)) {
    return false;
  }

  if (value === null) {
    return false;
  }

  if (isTag(value) || isTemplate(value)) {
    return false;
  }

  // TODO: Validate attribute values (just the general shape)

  return true;
}

export const validators = {
  // TODO: Move above implementations here and detail errors

  isBlank(value) {
    if (!isBlank(value)) {
      throw new TypeError(`Expected html.blank()`);
    }

    return true;
  },

  isTag(value) {
    if (!isTag(value)) {
      throw new TypeError(`Expected HTML tag`);
    }

    return true;
  },

  isTemplate(value) {
    if (!isTemplate(value)) {
      throw new TypeError(`Expected HTML template`);
    }

    return true;
  },

  isHTML(value) {
    if (!isHTML(value)) {
      throw new TypeError(`Expected HTML content`);
    }

    return true;
  },

  isAttributes(value) {
    if (!isAttributes(value)) {
      throw new TypeError(`Expected HTML attributes`);
    }

    return true;
  },
};

export function blank() {
  return [];
}

export function tag(tagName, ...args) {
  let content;
  let attributes;

  if (
    typeof args[0] === 'object' &&
    !(Array.isArray(args[0]) ||
      args[0] instanceof Tag ||
      args[0] instanceof Template)
  ) {
    attributes = args[0];
    content = args[1];
  } else {
    content = args[0];
  }

  return new Tag(tagName, attributes, content);
}

export function tags(content, attributes = null) {
  return new Tag(null, attributes, content);
}

export class Tag {
  #tagName = '';
  #content = null;
  #attributes = null;

  constructor(tagName, attributes, content) {
    this.tagName = tagName;
    this.attributes = attributes;
    this.content = content;
  }

  clone() {
    return Reflect.construct(this.constructor, [
      this.tagName,
      this.attributes,
      this.content,
    ]);
  }

  set tagName(value) {
    if (value === undefined || value === null) {
      this.tagName = '';
      return;
    }

    if (typeof value !== 'string') {
      throw new Error(`Expected tagName to be a string`);
    }

    if (selfClosingTags.includes(value) && this.content.length) {
      throw new Error(`Tag <${value}> is self-closing but this tag has content`);
    }

    this.#tagName = value;
  }

  get tagName() {
    return this.#tagName;
  }

  set attributes(attributes) {
    if (attributes instanceof Attributes) {
      this.#attributes = attributes;
    } else {
      this.#attributes = new Attributes(attributes);
    }
  }

  get attributes() {
    if (this.#attributes === null) {
      this.attributes = {};
    }

    return this.#attributes;
  }

  set content(value) {
    if (
      this.selfClosing &&
      !(value === null ||
        value === undefined ||
        !value ||
        Array.isArray(value) && value.filter(Boolean).length === 0)
    ) {
      throw new Error(`Tag <${this.tagName}> is self-closing but got content`);
    }

    let contentArray;

    if (Array.isArray(value)) {
      contentArray = value;
    } else {
      contentArray = [value];
    }

    this.#content = contentArray
      .flat(Infinity)
      .filter(Boolean);

    this.#content.toString = () => this.#stringifyContent();
  }

  get content() {
    if (this.#content === null) {
      this.#content = [];
    }

    return this.#content;
  }

  get selfClosing() {
    if (this.tagName) {
      return selfClosingTags.includes(this.tagName);
    } else {
      return false;
    }
  }

  #setAttributeFlag(attribute, value) {
    if (value) {
      this.attributes.set(attribute, true);
    } else {
      this.attributes.remove(attribute);
    }
  }

  #getAttributeFlag(attribute) {
    return !!this.attributes.get(attribute);
  }

  #setAttributeString(attribute, value) {
    // Note: This function accepts and records the empty string ('')
    // distinctly from null/undefined.

    if (value === undefined || value === null) {
      this.attributes.remove(attribute);
      return undefined;
    } else {
      this.attributes.set(attribute, String(value));
    }
  }

  #getAttributeString(attribute) {
    const value = this.attributes.get(attribute);

    if (value === undefined || value === null) {
      return undefined;
    } else {
      return String(value);
    }
  }

  set onlyIfContent(value) {
    this.#setAttributeFlag(onlyIfContent, value);
  }

  get onlyIfContent() {
    return this.#getAttributeFlag(onlyIfContent);
  }

  set joinChildren(value) {
    this.#setAttributeString(joinChildren, value);
  }

  get joinChildren() {
    return this.#getAttributeString(joinChildren);
  }

  set noEdgeWhitespace(value) {
    this.#setAttributeFlag(noEdgeWhitespace, value);
  }

  get noEdgeWhitespace() {
    return this.#getAttributeFlag(noEdgeWhitespace);
  }

  toString() {
    const attributesString = this.attributes.toString();
    const contentString = this.content.toString();

    if (this.onlyIfContent && !contentString) {
      return '';
    }

    if (!this.tagName) {
      return contentString;
    }

    const openTag = (attributesString
      ? `<${this.tagName} ${attributesString}>`
      : `<${this.tagName}>`);

    if (this.selfClosing) {
      return openTag;
    }

    const closeTag = `</${this.tagName}>`;

    if (!this.content.length) {
      return openTag + closeTag;
    }

    if (!contentString.includes('\n')) {
      return openTag + contentString + closeTag;
    }

    const parts = [
      openTag,
      contentString
        .split('\n')
        .map((line, i) =>
          (i === 0 && this.noEdgeWhitespace
            ? line
            : '    ' + line))
        .join('\n'),
      closeTag,
    ];

    return parts.join(
      (this.noEdgeWhitespace
        ? ''
        : '\n'));
  }

  #stringifyContent() {
    if (this.selfClosing) {
      return '';
    }

    const joiner =
      (this.joinChildren === undefined
        ? '\n'
        : (this.joinChildren === ''
            ? ''
            : `\n${this.joinChildren}\n`));

    return this.content
      .map(item => item.toString())
      .filter(Boolean)
      .join(joiner);
  }

  static normalize(content) {
    // Normalizes contents that are valid from an `isHTML` perspective so
    // that it's always a pure, single Tag object.

    if (content instanceof Template) {
      return Tag.normalize(Template.resolve(content));
    }

    if (content instanceof Tag) {
      return content;
    }

    return new Tag(null, null, content);
  }

  [inspect.custom]() {
    if (this.tagName) {
      if (empty(this.content)) {
        return `Tag <${this.tagName} />`;
      } else {
        return `Tag <${this.tagName}> (${this.content.length} items)`;
      }
    } else {
      if (empty(this.content)) {
        return `Tag (no name)`;
      } else {
        return `Tag (no name, ${this.content.length} items)`;
      }
    }
  }
}

export function attributes(attributes) {
  return new Attributes(attributes);
}

export function parseAttributes(string) {
  return Attributes.parse(string);
}

export class Attributes {
  #attributes = Object.create(null);

  constructor(attributes) {
    this.attributes = attributes;
  }

  set attributes(value) {
    if (value === undefined || value === null) {
      this.#attributes = {};
      return;
    }

    if (typeof value !== 'object') {
      throw new Error(`Expected attributes to be an object`);
    }

    this.#attributes = Object.create(null);
    Object.assign(this.#attributes, value);
  }

  get attributes() {
    return this.#attributes;
  }

  set(attribute, value) {
    if (value === null || value === undefined) {
      this.remove(attribute);
    } else {
      this.#attributes[attribute] = value;
    }
    return value;
  }

  get(attribute) {
    return this.#attributes[attribute];
  }

  remove(attribute) {
    return delete this.#attributes[attribute];
  }

  push(attribute, ...values) {
    const oldValue = this.get(attribute);
    const newValue =
      (Array.isArray(oldValue)
        ? oldValue.concat(values)
     : oldValue
        ? [oldValue, ...values]
        : values);
    this.set(attribute, newValue);
    return newValue;
  }

  toString() {
    return Object.entries(this.attributes)
      .map(([key, val]) => {
        if (typeof val === 'undefined' || val === null)
          return [key, val, false];
        else if (typeof val === 'string')
          return [key, val, true];
        else if (typeof val === 'boolean')
          return [key, val, val];
        else if (typeof val === 'number')
          return [key, val.toString(), true];
        else if (Array.isArray(val))
          return [key, val.filter(Boolean).join(' '), val.length > 0];
        else
          throw new Error(`Attribute value for ${key} should be primitive or array, got ${typeof val}`);
      })
      .filter(([_key, _val, keep]) => keep)
      .map(([key, val]) =>
        typeof val === 'boolean'
          ? `${key}`
          : `${key}="${this.#escapeAttributeValue(val)}"`
      )
      .join(' ');
  }

  #escapeAttributeValue(value) {
    return value
      .replaceAll('"', '&quot;')
      .replaceAll("'", '&apos;');
  }

  static parse(string) {
    const attributes = Object.create(null);

    const skipWhitespace = i => {
      if (!/\s/.test(string[i])) {
        return i;
      }

      const match = string.slice(i).match(/[^\s]/);
      if (match) {
        return i + match.index;
      }

      return string.length;
    };

    for (let i = 0; i < string.length; ) {
      i = skipWhitespace(i);
      const aStart = i;
      const aEnd = i + string.slice(i).match(/[\s=]|$/).index;
      const attribute = string.slice(aStart, aEnd);
      i = skipWhitespace(aEnd);
      if (string[i] === '=') {
        i = skipWhitespace(i + 1);
        let end, endOffset;
        if (string[i] === '"' || string[i] === "'") {
          end = string[i];
          endOffset = 1;
          i++;
        } else {
          end = '\\s';
          endOffset = 0;
        }
        const vStart = i;
        const vEnd = i + string.slice(i).match(new RegExp(`${end}|$`)).index;
        const value = string.slice(vStart, vEnd);
        i = vEnd + endOffset;
        attributes[attribute] = value;
      } else {
        attributes[attribute] = attribute;
      }
    }

    return (
      Reflect.construct(this, [
        Object.fromEntries(
          Object.entries(attributes)
            .map(([key, val]) => [
              key,
              (val === 'true'
                ? true
             : val === 'false'
                ? false
             : val === key
                ? true
                : val),
            ])),
      ]));
  }

  [inspect.custom]() {
    return `Attributes <${this.toString() || 'no attributes'}>`;
  }
}

export function resolve(tagOrTemplate, {normalize = null} = {}) {
  if (normalize === 'tag') {
    return Tag.normalize(tagOrTemplate);
  } else if (normalize === 'string') {
    return Tag.normalize(tagOrTemplate).toString();
  } else if (normalize) {
    throw new TypeError(`Expected normalize to be 'tag', 'string', or null`);
  } else {
    return Template.resolve(tagOrTemplate);
  }
}

export function template(description) {
  return new Template(description);
}

export class Template {
  #description = {};
  #slotValues = {};

  constructor(description) {
    if (!description[Stationery.validated]) {
      Template.validateDescription(description);
    }

    this.#description = description;
  }

  clone() {
    const clone = Reflect.construct(this.constructor, [
      this.#description,
    ]);

    clone.setSlots(this.#slotValues);

    return clone;
  }

  static validateDescription(description) {
    if (typeof description !== 'object') {
      throw new TypeError(`Expected object, got ${typeof description}`);
    }

    if (description === null) {
      throw new TypeError(`Expected object, got null`);
    }

    const topErrors = [];

    if (!('content' in description)) {
      topErrors.push(new TypeError(`Expected description.content`));
    } else if (typeof description.content !== 'function') {
      topErrors.push(new TypeError(`Expected description.content to be function`));
    }

    if ('annotation' in description) {
      if (typeof description.annotation !== 'string') {
        topErrors.push(new TypeError(`Expected annotation to be string`));
      }
    }

    if ('slots' in description) validateSlots: {
      if (typeof description.slots !== 'object') {
        topErrors.push(new TypeError(`Expected description.slots to be object`));
        break validateSlots;
      }

      try {
        this.validateSlotsDescription(description.slots);
      } catch (slotError) {
        topErrors.push(slotError);
      }
    }

    if (!empty(topErrors)) {
      throw new AggregateError(topErrors,
        (typeof description.annotation === 'string'
          ? `Errors validating template "${description.annotation}" description`
          : `Errors validating template description`));
    }

    return true;
  }

  static validateSlotsDescription(slots) {
    const slotErrors = [];

    for (const [slotName, slotDescription] of Object.entries(slots)) {
      if (typeof slotDescription !== 'object' || slotDescription === null) {
        slotErrors.push(new TypeError(`(${slotName}) Expected slot description to be object`));
        continue;
      }

      if ('default' in slotDescription) validateDefault: {
        if (
          slotDescription.default === undefined ||
          slotDescription.default === null
        ) {
          slotErrors.push(new TypeError(`(${slotName}) Leave slot default unspecified instead of undefined or null`));
          break validateDefault;
        }

        try {
          Template.validateSlotValueAgainstDescription(slotDescription.default, slotDescription);
        } catch (error) {
          error.message = `(${slotName}) Error validating slot default value: ${error.message}`;
          slotErrors.push(error);
        }
      }

      if ('validate' in slotDescription && 'type' in slotDescription) {
        slotErrors.push(new TypeError(`(${slotName}) Don't specify both slot validate and type`));
      } else if (!('validate' in slotDescription || 'type' in slotDescription)) {
        slotErrors.push(new TypeError(`(${slotName}) Expected either slot validate or type`));
      } else if ('validate' in slotDescription) {
        if (typeof slotDescription.validate !== 'function') {
          slotErrors.push(new TypeError(`(${slotName}) Expected slot validate to be function`));
        }
      } else if ('type' in slotDescription) {
        const acceptableSlotTypes = [
          'string',
          'number',
          'bigint',
          'boolean',
          'symbol',
          'html',
        ];

        if (slotDescription.type === 'function') {
          slotErrors.push(new TypeError(`(${slotName}) Functions shouldn't be provided to slots`));
        } else if (slotDescription.type === 'object') {
          slotErrors.push(new TypeError(`(${slotName}) Provide validate function instead of type: object`));
        } else if (!acceptableSlotTypes.includes(slotDescription.type)) {
          slotErrors.push(new TypeError(`(${slotName}) Expected slot type to be one of ${acceptableSlotTypes.join(', ')}`));
        }
      }
    }

    if (!empty(slotErrors)) {
      throw new AggregateError(slotErrors, `Errors in slot descriptions`);
    }

    return true;
  }

  slot(slotName, value) {
    this.setSlot(slotName, value);
    return this;
  }

  slots(slotNamesToValues) {
    this.setSlots(slotNamesToValues);
    return this;
  }

  setSlot(slotName, value) {
    const description = this.#getSlotDescriptionOrError(slotName);

    try {
      Template.validateSlotValueAgainstDescription(value, description);
    } catch (error) {
      error.message =
        (this.description.annotation
          ? `Error validating template "${this.description.annotation}" slot "${slotName}" value: ${error.message}`
          : `Error validating template slot "${slotName}" value: ${error.message}`);
      throw error;
    }

    this.#slotValues[slotName] = value;
  }

  setSlots(slotNamesToValues) {
    if (
      typeof slotNamesToValues !== 'object' ||
      Array.isArray(slotNamesToValues) ||
      slotNamesToValues === null
    ) {
      throw new TypeError(`Expected object mapping of slot names to values`);
    }

    const slotErrors = [];

    for (const [slotName, value] of Object.entries(slotNamesToValues)) {
      const description = this.#getSlotDescriptionNoError(slotName);
      if (!description) {
        slotErrors.push(new TypeError(`(${slotName}) Template doesn't have a "${slotName}" slot`));
        continue;
      }

      try {
        Template.validateSlotValueAgainstDescription(value, description);
      } catch (error) {
        error.message = `(${slotName}) ${error.message}`;
        slotErrors.push(error);
      }
    }

    if (!empty(slotErrors)) {
      throw new AggregateError(slotErrors,
        (this.description.annotation
          ? `Error validating template "${this.description.annotation}" slots`
          : `Error validating template slots`));
    }

    Object.assign(this.#slotValues, slotNamesToValues);
  }

  static validateSlotValueAgainstDescription(value, description) {
    if (value === undefined) {
      throw new TypeError(`Specify value as null or don't specify at all`);
    }

    // Null is always an acceptable slot value.
    if (value !== null) {
      if ('validate' in description) {
        description.validate({
          ...commonValidators,
          ...validators,
        })(value);
      }

      if ('type' in description) {
        const {type} = description;
        if (type === 'html') {
          if (!isHTML(value)) {
            throw new TypeError(`Slot expects html (tag, template or blank), got ${typeof value}`);
          }
        } else {
          if (typeof value !== type) {
            throw new TypeError(`Slot expects ${type}, got ${typeof value}`);
          }
        }
      }
    }

    return true;
  }

  getSlotValue(slotName) {
    const description = this.#getSlotDescriptionOrError(slotName);
    const providedValue = this.#slotValues[slotName] ?? null;

    if (description.type === 'html') {
      if (!providedValue) {
        return blank();
      }

      if (providedValue instanceof Tag || providedValue instanceof Template) {
        return providedValue.clone();
      }

      return providedValue;
    }

    if (providedValue !== null) {
      return providedValue;
    }

    if ('default' in description) {
      return description.default;
    }

    return null;
  }

  getSlotDescription(slotName) {
    return this.#getSlotDescriptionOrError(slotName);
  }

  #getSlotDescriptionNoError(slotName) {
    if (this.#description.slots) {
      if (Object.hasOwn(this.#description.slots, slotName)) {
        return this.#description.slots[slotName];
      }
    }

    return null;
  }

  #getSlotDescriptionOrError(slotName) {
    const description = this.#getSlotDescriptionNoError(slotName);

    if (!description) {
      throw new TypeError(
        (this.description.annotation
          ? `Template "${this.description.annotation}" doesn't have a "${slotName}" slot`
          : `Template doesn't have a "${slotName}" slot`));
    }

    return description;
  }

  set content(_value) {
    throw new Error(`Template content can't be changed after constructed`);
  }

  get content() {
    const slots = {};

    for (const slotName of Object.keys(this.description.slots ?? {})) {
      slots[slotName] = this.getSlotValue(slotName);
    }

    return this.description.content(slots);
  }

  set description(_value) {
    throw new Error(`Template description can't be changed after constructed`);
  }

  get description() {
    return this.#description;
  }

  toString() {
    return this.content.toString();
  }

  static resolve(tagOrTemplate) {
    // Flattens contents of a template, recursively "resolving" until a
    // non-template is ready (or just returns a provided non-template
    // argument as-is).

    if (!(tagOrTemplate instanceof Template)) {
      return tagOrTemplate;
    }

    let {content} = tagOrTemplate;

    while (content instanceof Template) {
      content = content.content;
    }

    return content;
  }

  [inspect.custom]() {
    const {annotation} = this.description;
    if (annotation) {
      return `Template "${annotation}"`;
    } else {
      return `Template (no annotation)`;
    }
  }
}

export function stationery(description) {
  return new Stationery(description);
}

export class Stationery {
  #templateDescription = null;

  static validated = Symbol('Stationery.validated');

  constructor(templateDescription) {
    Template.validateDescription(templateDescription);
    templateDescription[Stationery.validated] = true;
    this.#templateDescription = templateDescription;
  }

  template() {
    return new Template(this.#templateDescription);
  }

  [inspect.custom]() {
    const {annotation} = this.#templateDescription;
    if (annotation) {
      return `Stationery "${annotation}"`;
    } else {
      return `Stationery (no annotation)`;
    }
  }
}