Schema.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { MAP, SCALAR, SEQ } from '../nodes/identity.js';
  2. import { map } from './common/map.js';
  3. import { seq } from './common/seq.js';
  4. import { string } from './common/string.js';
  5. import { getTags, coreKnownTags } from './tags.js';
  6. const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
  7. class Schema {
  8. constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
  9. this.compat = Array.isArray(compat)
  10. ? getTags(compat, 'compat')
  11. : compat
  12. ? getTags(null, compat)
  13. : null;
  14. this.name = (typeof schema === 'string' && schema) || 'core';
  15. this.knownTags = resolveKnownTags ? coreKnownTags : {};
  16. this.tags = getTags(customTags, this.name, merge);
  17. this.toStringOptions = toStringDefaults ?? null;
  18. Object.defineProperty(this, MAP, { value: map });
  19. Object.defineProperty(this, SCALAR, { value: string });
  20. Object.defineProperty(this, SEQ, { value: seq });
  21. // Used by createMap()
  22. this.sortMapEntries =
  23. typeof sortMapEntries === 'function'
  24. ? sortMapEntries
  25. : sortMapEntries === true
  26. ? sortMapEntriesByKey
  27. : null;
  28. }
  29. clone() {
  30. const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
  31. copy.tags = this.tags.slice();
  32. return copy;
  33. }
  34. }
  35. export { Schema };