UNPKG

2.27 kBJavaScriptView Raw
1'use strict';
2
3var log = require('../log.js');
4var merge = require('../schema/yaml-1.1/merge.js');
5var stringify = require('../stringify/stringify.js');
6var identity = require('./identity.js');
7var toJS = require('./toJS.js');
8
9function addPairToJSMap(ctx, map, { key, value }) {
10 if (identity.isNode(key) && key.addToJSMap)
11 key.addToJSMap(ctx, map, value);
12 // TODO: Should drop this special case for bare << handling
13 else if (merge.isMergeKey(ctx, key))
14 merge.addMergeToJSMap(ctx, map, value);
15 else {
16 const jsKey = toJS.toJS(key, '', ctx);
17 if (map instanceof Map) {
18 map.set(jsKey, toJS.toJS(value, jsKey, ctx));
19 }
20 else if (map instanceof Set) {
21 map.add(jsKey);
22 }
23 else {
24 const stringKey = stringifyKey(key, jsKey, ctx);
25 const jsValue = toJS.toJS(value, stringKey, ctx);
26 if (stringKey in map)
27 Object.defineProperty(map, stringKey, {
28 value: jsValue,
29 writable: true,
30 enumerable: true,
31 configurable: true
32 });
33 else
34 map[stringKey] = jsValue;
35 }
36 }
37 return map;
38}
39function stringifyKey(key, jsKey, ctx) {
40 if (jsKey === null)
41 return '';
42 if (typeof jsKey !== 'object')
43 return String(jsKey);
44 if (identity.isNode(key) && ctx?.doc) {
45 const strCtx = stringify.createStringifyContext(ctx.doc, {});
46 strCtx.anchors = new Set();
47 for (const node of ctx.anchors.keys())
48 strCtx.anchors.add(node.anchor);
49 strCtx.inFlow = true;
50 strCtx.inStringifyKey = true;
51 const strKey = key.toString(strCtx);
52 if (!ctx.mapKeyWarned) {
53 let jsonStr = JSON.stringify(strKey);
54 if (jsonStr.length > 40)
55 jsonStr = jsonStr.substring(0, 36) + '..."';
56 log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
57 ctx.mapKeyWarned = true;
58 }
59 return strKey;
60 }
61 return JSON.stringify(jsKey);
62}
63
64exports.addPairToJSMap = addPairToJSMap;