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