omap.js 2.5 KB

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