omap.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { isScalar, isPair } from '../../nodes/identity.js';
  2. import { toJS } from '../../nodes/toJS.js';
  3. import { YAMLMap } from '../../nodes/YAMLMap.js';
  4. import { YAMLSeq } from '../../nodes/YAMLSeq.js';
  5. import { resolvePairs, createPairs } from './pairs.js';
  6. class YAMLOMap extends YAMLSeq {
  7. constructor() {
  8. super();
  9. this.add = YAMLMap.prototype.add.bind(this);
  10. this.delete = YAMLMap.prototype.delete.bind(this);
  11. this.get = YAMLMap.prototype.get.bind(this);
  12. this.has = YAMLMap.prototype.has.bind(this);
  13. this.set = YAMLMap.prototype.set.bind(this);
  14. this.tag = YAMLOMap.tag;
  15. }
  16. /**
  17. * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
  18. * but TypeScript won't allow widening the signature of a child method.
  19. */
  20. toJSON(_, ctx) {
  21. if (!ctx)
  22. return super.toJSON(_);
  23. const map = new Map();
  24. if (ctx?.onCreate)
  25. ctx.onCreate(map);
  26. for (const pair of this.items) {
  27. let key, value;
  28. if (isPair(pair)) {
  29. key = toJS(pair.key, '', ctx);
  30. value = toJS(pair.value, key, ctx);
  31. }
  32. else {
  33. key = toJS(pair, '', ctx);
  34. }
  35. if (map.has(key))
  36. throw new Error('Ordered maps must not include duplicate keys');
  37. map.set(key, value);
  38. }
  39. return map;
  40. }
  41. static from(schema, iterable, ctx) {
  42. const pairs = createPairs(schema, iterable, ctx);
  43. const omap = new this();
  44. omap.items = pairs.items;
  45. return omap;
  46. }
  47. }
  48. YAMLOMap.tag = 'tag:yaml.org,2002:omap';
  49. const omap = {
  50. collection: 'seq',
  51. identify: value => value instanceof Map,
  52. nodeClass: YAMLOMap,
  53. default: false,
  54. tag: 'tag:yaml.org,2002:omap',
  55. resolve(seq, onError) {
  56. const pairs = resolvePairs(seq, onError);
  57. const seenKeys = [];
  58. for (const { key } of pairs.items) {
  59. if (isScalar(key)) {
  60. if (seenKeys.includes(key.value)) {
  61. onError(`Ordered maps must not include duplicate keys: ${key.value}`);
  62. }
  63. else {
  64. seenKeys.push(key.value);
  65. }
  66. }
  67. }
  68. return Object.assign(new YAMLOMap(), pairs);
  69. },
  70. createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
  71. };
  72. export { YAMLOMap, omap };