yaml 2.0.0-4 → 2.0.0-8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/README.md +5 -5
  2. package/browser/dist/compose/compose-collection.js +12 -9
  3. package/browser/dist/compose/compose-doc.js +23 -6
  4. package/browser/dist/compose/compose-node.js +27 -17
  5. package/browser/dist/compose/compose-scalar.js +21 -23
  6. package/browser/dist/compose/composer.js +108 -78
  7. package/browser/dist/compose/resolve-block-map.js +41 -29
  8. package/browser/dist/compose/resolve-block-scalar.js +14 -17
  9. package/browser/dist/compose/resolve-block-seq.js +21 -17
  10. package/browser/dist/compose/resolve-end.js +7 -8
  11. package/browser/dist/compose/resolve-flow-collection.js +158 -199
  12. package/browser/dist/compose/resolve-flow-scalar.js +62 -26
  13. package/browser/dist/compose/resolve-props.js +72 -37
  14. package/browser/dist/compose/util-contains-newline.js +15 -12
  15. package/browser/dist/compose/util-map-includes.js +17 -0
  16. package/browser/dist/doc/Document.js +74 -99
  17. package/browser/dist/doc/anchors.js +72 -0
  18. package/browser/dist/doc/createNode.js +35 -19
  19. package/browser/dist/doc/directives.js +5 -0
  20. package/browser/dist/errors.js +16 -12
  21. package/browser/dist/index.js +3 -3
  22. package/browser/dist/nodes/Alias.js +51 -28
  23. package/browser/dist/nodes/Collection.js +23 -92
  24. package/browser/dist/nodes/Node.js +9 -1
  25. package/browser/dist/nodes/Pair.js +16 -231
  26. package/browser/dist/nodes/YAMLMap.js +8 -4
  27. package/browser/dist/nodes/YAMLSeq.js +7 -4
  28. package/browser/dist/nodes/addPairToJSMap.js +103 -0
  29. package/browser/dist/nodes/toJS.js +12 -10
  30. package/browser/dist/options.js +1 -2
  31. package/browser/dist/parse/cst-scalar.js +219 -0
  32. package/browser/dist/parse/cst-stringify.js +61 -0
  33. package/browser/dist/parse/cst-visit.js +97 -0
  34. package/{dist/parse/tokens.js → browser/dist/parse/cst.js} +12 -7
  35. package/browser/dist/parse/lexer.js +149 -125
  36. package/browser/dist/parse/parser.js +272 -196
  37. package/browser/dist/public-api.js +11 -14
  38. package/browser/dist/schema/Schema.js +28 -0
  39. package/browser/dist/{tags/failsafe → schema/common}/map.js +0 -0
  40. package/browser/dist/schema/common/null.js +13 -0
  41. package/browser/dist/{tags/failsafe → schema/common}/seq.js +1 -1
  42. package/browser/dist/{tags/failsafe → schema/common}/string.js +0 -0
  43. package/browser/dist/schema/core/bool.js +19 -0
  44. package/browser/dist/schema/core/float.js +40 -0
  45. package/browser/dist/schema/core/int.js +38 -0
  46. package/browser/dist/schema/core/schema.js +23 -0
  47. package/browser/dist/{tags/json.js → schema/json/schema.js} +5 -6
  48. package/browser/dist/schema/tags.js +79 -0
  49. package/browser/dist/{tags → schema}/yaml-1.1/binary.js +0 -0
  50. package/browser/dist/schema/yaml-1.1/bool.js +26 -0
  51. package/browser/dist/schema/yaml-1.1/float.js +43 -0
  52. package/browser/dist/schema/yaml-1.1/int.js +71 -0
  53. package/browser/dist/{tags → schema}/yaml-1.1/omap.js +0 -0
  54. package/browser/dist/{tags → schema}/yaml-1.1/pairs.js +9 -6
  55. package/browser/dist/schema/yaml-1.1/schema.js +37 -0
  56. package/browser/dist/{tags → schema}/yaml-1.1/set.js +0 -0
  57. package/browser/dist/{tags → schema}/yaml-1.1/timestamp.js +0 -0
  58. package/browser/dist/stringify/stringify.js +8 -6
  59. package/browser/dist/stringify/stringifyCollection.js +122 -0
  60. package/browser/dist/stringify/stringifyComment.js +14 -0
  61. package/browser/dist/stringify/stringifyDocument.js +64 -0
  62. package/browser/dist/stringify/stringifyPair.js +111 -0
  63. package/browser/dist/stringify/stringifyString.js +53 -52
  64. package/browser/dist/visit.js +20 -1
  65. package/dist/compose/compose-collection.d.ts +4 -4
  66. package/dist/compose/compose-collection.js +12 -9
  67. package/dist/compose/compose-doc.d.ts +4 -3
  68. package/dist/compose/compose-doc.js +23 -6
  69. package/dist/compose/compose-node.d.ts +15 -7
  70. package/dist/compose/compose-node.js +27 -17
  71. package/dist/compose/compose-scalar.d.ts +4 -3
  72. package/dist/compose/compose-scalar.js +20 -22
  73. package/dist/compose/composer.d.ts +28 -23
  74. package/dist/compose/composer.js +109 -79
  75. package/dist/compose/resolve-block-map.d.ts +5 -4
  76. package/dist/compose/resolve-block-map.js +41 -29
  77. package/dist/compose/resolve-block-scalar.d.ts +5 -3
  78. package/dist/compose/resolve-block-scalar.js +14 -17
  79. package/dist/compose/resolve-block-seq.d.ts +4 -4
  80. package/dist/compose/resolve-block-seq.js +21 -17
  81. package/dist/compose/resolve-end.d.ts +3 -2
  82. package/dist/compose/resolve-end.js +7 -8
  83. package/dist/compose/resolve-flow-collection.d.ts +4 -5
  84. package/dist/compose/resolve-flow-collection.js +157 -198
  85. package/dist/compose/resolve-flow-scalar.d.ts +5 -3
  86. package/dist/compose/resolve-flow-scalar.js +62 -26
  87. package/dist/compose/resolve-props.d.ts +16 -10
  88. package/dist/compose/resolve-props.js +72 -37
  89. package/dist/compose/util-contains-newline.d.ts +1 -1
  90. package/dist/compose/util-contains-newline.js +15 -12
  91. package/dist/compose/util-empty-scalar-position.d.ts +1 -1
  92. package/dist/compose/util-map-includes.d.ts +4 -0
  93. package/dist/compose/util-map-includes.js +19 -0
  94. package/dist/doc/Document.d.ts +35 -15
  95. package/dist/doc/Document.js +72 -97
  96. package/dist/doc/anchors.d.ts +24 -0
  97. package/dist/doc/anchors.js +77 -0
  98. package/dist/doc/createNode.d.ts +10 -11
  99. package/dist/doc/createNode.js +34 -18
  100. package/dist/doc/directives.d.ts +1 -0
  101. package/dist/doc/directives.js +5 -0
  102. package/dist/errors.d.ts +11 -8
  103. package/dist/errors.js +16 -12
  104. package/dist/index.d.ts +5 -3
  105. package/dist/index.js +3 -3
  106. package/dist/nodes/Alias.d.ts +19 -9
  107. package/dist/nodes/Alias.js +51 -28
  108. package/dist/nodes/Collection.d.ts +9 -17
  109. package/dist/nodes/Collection.js +22 -91
  110. package/dist/nodes/Node.d.ts +10 -4
  111. package/dist/nodes/Node.js +9 -0
  112. package/dist/nodes/Pair.d.ts +10 -13
  113. package/dist/nodes/Pair.js +15 -230
  114. package/dist/nodes/Scalar.d.ts +6 -3
  115. package/dist/nodes/YAMLMap.d.ts +3 -3
  116. package/dist/nodes/YAMLMap.js +8 -4
  117. package/dist/nodes/YAMLSeq.d.ts +3 -3
  118. package/dist/nodes/YAMLSeq.js +7 -4
  119. package/dist/nodes/addPairToJSMap.d.ts +3 -0
  120. package/dist/nodes/addPairToJSMap.js +105 -0
  121. package/dist/nodes/toJS.d.ts +4 -5
  122. package/dist/nodes/toJS.js +12 -10
  123. package/dist/options.d.ts +41 -25
  124. package/dist/options.js +1 -2
  125. package/dist/parse/cst-scalar.d.ts +58 -0
  126. package/dist/parse/cst-scalar.js +223 -0
  127. package/dist/parse/cst-stringify.d.ts +8 -0
  128. package/dist/parse/cst-stringify.js +63 -0
  129. package/dist/parse/cst-visit.d.ts +39 -0
  130. package/dist/parse/cst-visit.js +99 -0
  131. package/dist/parse/{tokens.d.ts → cst.d.ts} +23 -7
  132. package/{browser/dist/parse/tokens.js → dist/parse/cst.js} +27 -1
  133. package/dist/parse/lexer.d.ts +7 -14
  134. package/dist/parse/lexer.js +150 -126
  135. package/dist/parse/parser.d.ts +31 -24
  136. package/dist/parse/parser.js +274 -198
  137. package/dist/public-api.d.ts +7 -7
  138. package/dist/public-api.js +11 -14
  139. package/dist/{doc → schema}/Schema.d.ts +6 -3
  140. package/dist/schema/Schema.js +30 -0
  141. package/dist/{tags/failsafe → schema/common}/map.d.ts +0 -0
  142. package/dist/{tags/failsafe → schema/common}/map.js +0 -0
  143. package/dist/schema/common/null.d.ts +4 -0
  144. package/dist/schema/common/null.js +15 -0
  145. package/dist/{tags/failsafe → schema/common}/seq.d.ts +0 -0
  146. package/dist/{tags/failsafe → schema/common}/seq.js +1 -1
  147. package/dist/{tags/failsafe → schema/common}/string.d.ts +0 -0
  148. package/dist/{tags/failsafe → schema/common}/string.js +0 -0
  149. package/dist/schema/core/bool.d.ts +4 -0
  150. package/dist/schema/core/bool.js +21 -0
  151. package/dist/schema/core/float.d.ts +4 -0
  152. package/dist/schema/core/float.js +44 -0
  153. package/dist/schema/core/int.d.ts +4 -0
  154. package/dist/schema/core/int.js +42 -0
  155. package/dist/schema/core/schema.d.ts +1 -0
  156. package/dist/schema/core/schema.js +25 -0
  157. package/dist/schema/json/schema.d.ts +2 -0
  158. package/dist/{tags/json.js → schema/json/schema.js} +5 -6
  159. package/dist/schema/tags.d.ts +41 -0
  160. package/dist/schema/tags.js +82 -0
  161. package/dist/{tags → schema}/types.d.ts +3 -7
  162. package/dist/{tags → schema}/yaml-1.1/binary.d.ts +0 -0
  163. package/dist/{tags → schema}/yaml-1.1/binary.js +0 -0
  164. package/dist/schema/yaml-1.1/bool.d.ts +7 -0
  165. package/dist/schema/yaml-1.1/bool.js +29 -0
  166. package/dist/schema/yaml-1.1/float.d.ts +4 -0
  167. package/dist/schema/yaml-1.1/float.js +47 -0
  168. package/dist/schema/yaml-1.1/int.d.ts +5 -0
  169. package/dist/schema/yaml-1.1/int.js +76 -0
  170. package/dist/{tags → schema}/yaml-1.1/omap.d.ts +0 -0
  171. package/dist/{tags → schema}/yaml-1.1/omap.js +0 -0
  172. package/dist/{tags → schema}/yaml-1.1/pairs.d.ts +3 -2
  173. package/dist/{tags → schema}/yaml-1.1/pairs.js +9 -6
  174. package/dist/schema/yaml-1.1/schema.d.ts +1 -0
  175. package/dist/schema/yaml-1.1/schema.js +39 -0
  176. package/dist/{tags → schema}/yaml-1.1/set.d.ts +1 -1
  177. package/dist/{tags → schema}/yaml-1.1/set.js +0 -0
  178. package/dist/{tags → schema}/yaml-1.1/timestamp.d.ts +0 -0
  179. package/dist/{tags → schema}/yaml-1.1/timestamp.js +0 -0
  180. package/dist/stringify/stringify.d.ts +1 -2
  181. package/dist/stringify/stringify.js +8 -6
  182. package/dist/stringify/stringifyCollection.d.ts +21 -0
  183. package/dist/stringify/stringifyCollection.js +124 -0
  184. package/dist/stringify/stringifyComment.d.ts +2 -0
  185. package/dist/stringify/stringifyComment.js +17 -0
  186. package/dist/stringify/stringifyDocument.d.ts +3 -0
  187. package/dist/stringify/stringifyDocument.js +66 -0
  188. package/dist/stringify/stringifyPair.d.ts +3 -0
  189. package/dist/stringify/stringifyPair.js +113 -0
  190. package/dist/stringify/stringifyString.js +53 -52
  191. package/dist/test-events.d.ts +1 -2
  192. package/dist/test-events.js +25 -12
  193. package/dist/util.d.ts +1 -1
  194. package/dist/visit.d.ts +10 -1
  195. package/dist/visit.js +20 -1
  196. package/package.json +9 -8
  197. package/browser/dist/doc/Anchors.js +0 -102
  198. package/browser/dist/doc/Schema.js +0 -27
  199. package/browser/dist/doc/getSchemaTags.js +0 -30
  200. package/browser/dist/stringify/addComment.js +0 -17
  201. package/browser/dist/tags/core.js +0 -109
  202. package/browser/dist/tags/failsafe/index.js +0 -7
  203. package/browser/dist/tags/index.js +0 -34
  204. package/browser/dist/tags/yaml-1.1/index.js +0 -152
  205. package/dist/doc/Anchors.d.ts +0 -36
  206. package/dist/doc/Anchors.js +0 -104
  207. package/dist/doc/Schema.js +0 -29
  208. package/dist/doc/getSchemaTags.d.ts +0 -3
  209. package/dist/doc/getSchemaTags.js +0 -32
  210. package/dist/stringify/addComment.d.ts +0 -2
  211. package/dist/stringify/addComment.js +0 -20
  212. package/dist/tags/core.d.ts +0 -14
  213. package/dist/tags/core.js +0 -119
  214. package/dist/tags/failsafe/index.d.ts +0 -1
  215. package/dist/tags/failsafe/index.js +0 -9
  216. package/dist/tags/index.d.ts +0 -31
  217. package/dist/tags/index.js +0 -37
  218. package/dist/tags/json.d.ts +0 -2
  219. package/dist/tags/yaml-1.1/index.d.ts +0 -2
  220. package/dist/tags/yaml-1.1/index.js +0 -154
@@ -1,3 +1,4 @@
1
+ import { stringifyCollection } from '../stringify/stringifyCollection.js';
1
2
  import { Collection } from './Collection.js';
2
3
  import { SEQ, isScalar } from './Node.js';
3
4
  import { isScalarValue } from './Scalar.js';
@@ -83,11 +84,13 @@ class YAMLSeq extends Collection {
83
84
  toString(ctx, onComment, onChompKeep) {
84
85
  if (!ctx)
85
86
  return JSON.stringify(this);
86
- return super._toString(ctx, {
87
- blockItem: n => (n.type === 'comment' ? n.str : `- ${n.str}`),
87
+ return stringifyCollection(this, ctx, {
88
+ blockItem: n => (n.comment ? n.str : `- ${n.str}`),
88
89
  flowChars: { start: '[', end: ']' },
89
- itemIndent: (ctx.indent || '') + ' '
90
- }, onComment, onChompKeep);
90
+ itemIndent: (ctx.indent || '') + ' ',
91
+ onChompKeep,
92
+ onComment
93
+ });
91
94
  }
92
95
  }
93
96
  function asItemIndex(key) {
@@ -0,0 +1,103 @@
1
+ import { warn } from '../log.js';
2
+ import { createStringifyContext } from '../stringify/stringify.js';
3
+ import { isSeq, isScalar, isAlias, isMap, isNode } from './Node.js';
4
+ import { Scalar } from './Scalar.js';
5
+ import { toJS } from './toJS.js';
6
+
7
+ const MERGE_KEY = '<<';
8
+ function addPairToJSMap(ctx, map, { key, value }) {
9
+ if (ctx && ctx.doc.schema.merge && isMergeKey(key)) {
10
+ if (isSeq(value))
11
+ for (const it of value.items)
12
+ mergeToJSMap(ctx, map, it);
13
+ else if (Array.isArray(value))
14
+ for (const it of value)
15
+ mergeToJSMap(ctx, map, it);
16
+ else
17
+ mergeToJSMap(ctx, map, value);
18
+ }
19
+ else {
20
+ const jsKey = toJS(key, '', ctx);
21
+ if (map instanceof Map) {
22
+ map.set(jsKey, toJS(value, jsKey, ctx));
23
+ }
24
+ else if (map instanceof Set) {
25
+ map.add(jsKey);
26
+ }
27
+ else {
28
+ const stringKey = stringifyKey(key, jsKey, ctx);
29
+ const jsValue = toJS(value, stringKey, ctx);
30
+ if (stringKey in map)
31
+ Object.defineProperty(map, stringKey, {
32
+ value: jsValue,
33
+ writable: true,
34
+ enumerable: true,
35
+ configurable: true
36
+ });
37
+ else
38
+ map[stringKey] = jsValue;
39
+ }
40
+ }
41
+ return map;
42
+ }
43
+ const isMergeKey = (key) => key === MERGE_KEY ||
44
+ (isScalar(key) &&
45
+ key.value === MERGE_KEY &&
46
+ (!key.type || key.type === Scalar.PLAIN));
47
+ // If the value associated with a merge key is a single mapping node, each of
48
+ // its key/value pairs is inserted into the current mapping, unless the key
49
+ // already exists in it. If the value associated with the merge key is a
50
+ // sequence, then this sequence is expected to contain mapping nodes and each
51
+ // of these nodes is merged in turn according to its order in the sequence.
52
+ // Keys in mapping nodes earlier in the sequence override keys specified in
53
+ // later mapping nodes. -- http://yaml.org/type/merge.html
54
+ function mergeToJSMap(ctx, map, value) {
55
+ const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;
56
+ if (!isMap(source))
57
+ throw new Error('Merge sources must be maps or map aliases');
58
+ const srcMap = source.toJSON(null, ctx, Map);
59
+ for (const [key, value] of srcMap) {
60
+ if (map instanceof Map) {
61
+ if (!map.has(key))
62
+ map.set(key, value);
63
+ }
64
+ else if (map instanceof Set) {
65
+ map.add(key);
66
+ }
67
+ else if (!Object.prototype.hasOwnProperty.call(map, key)) {
68
+ Object.defineProperty(map, key, {
69
+ value,
70
+ writable: true,
71
+ enumerable: true,
72
+ configurable: true
73
+ });
74
+ }
75
+ }
76
+ return map;
77
+ }
78
+ function stringifyKey(key, jsKey, ctx) {
79
+ if (jsKey === null)
80
+ return '';
81
+ if (typeof jsKey !== 'object')
82
+ return String(jsKey);
83
+ if (isNode(key) && ctx && ctx.doc) {
84
+ const strCtx = createStringifyContext(ctx.doc, {});
85
+ strCtx.anchors = new Set();
86
+ for (const node of ctx.anchors.keys())
87
+ strCtx.anchors.add(node.anchor);
88
+ strCtx.inFlow = true;
89
+ strCtx.inStringifyKey = true;
90
+ const strKey = key.toString(strCtx);
91
+ if (!ctx.mapKeyWarned) {
92
+ let jsonStr = JSON.stringify(strKey);
93
+ if (jsonStr.length > 40)
94
+ jsonStr = jsonStr.substring(0, 36) + '..."';
95
+ 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.`);
96
+ ctx.mapKeyWarned = true;
97
+ }
98
+ return strKey;
99
+ }
100
+ return JSON.stringify(jsKey);
101
+ }
102
+
103
+ export { addPairToJSMap };
@@ -1,3 +1,5 @@
1
+ import { hasAnchor } from './Node.js';
2
+
1
3
  /**
2
4
  * Recursively convert any node or its contents to native JavaScript
3
5
  *
@@ -12,20 +14,20 @@ function toJS(value, arg, ctx) {
12
14
  if (Array.isArray(value))
13
15
  return value.map((v, i) => toJS(v, String(i), ctx));
14
16
  if (value && typeof value.toJSON === 'function') {
15
- if (!ctx)
16
- return value.toJSON(arg);
17
- const anchor = ctx.anchors && ctx.anchors.get(value);
18
- if (anchor)
19
- ctx.onCreate = res => {
20
- anchor.res = res;
21
- delete ctx.onCreate;
22
- };
17
+ if (!ctx || !hasAnchor(value))
18
+ return value.toJSON(arg, ctx);
19
+ const data = { aliasCount: 0, count: 1, res: undefined };
20
+ ctx.anchors.set(value, data);
21
+ ctx.onCreate = res => {
22
+ data.res = res;
23
+ delete ctx.onCreate;
24
+ };
23
25
  const res = value.toJSON(arg, ctx);
24
- if (anchor && ctx.onCreate)
26
+ if (ctx.onCreate)
25
27
  ctx.onCreate(res);
26
28
  return res;
27
29
  }
28
- if (!(ctx && ctx.keep) && typeof value === 'bigint')
30
+ if (typeof value === 'bigint' && !(ctx && ctx.keep))
29
31
  return Number(value);
30
32
  return value;
31
33
  }
@@ -6,12 +6,11 @@
6
6
  * options override both.
7
7
  */
8
8
  const defaultOptions = {
9
- anchorPrefix: 'a',
10
9
  intAsBigInt: false,
11
- keepUndefined: false,
12
10
  logLevel: 'warn',
13
11
  prettyErrors: true,
14
12
  strict: true,
13
+ uniqueKeys: true,
15
14
  version: '1.2'
16
15
  };
17
16
 
@@ -0,0 +1,219 @@
1
+ import { resolveBlockScalar } from '../compose/resolve-block-scalar.js';
2
+ import { resolveFlowScalar } from '../compose/resolve-flow-scalar.js';
3
+ import { YAMLParseError } from '../errors.js';
4
+ import { stringifyString } from '../stringify/stringifyString.js';
5
+
6
+ /**
7
+ * If `token` is a CST flow or block scalar, determine its string value and a few other attributes.
8
+ * Otherwise, return `null`.
9
+ */
10
+ function resolveAsScalar(token, strict = true, onError) {
11
+ if (token) {
12
+ const _onError = (pos, code, message) => {
13
+ const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
14
+ if (onError)
15
+ onError(offset, code, message);
16
+ else
17
+ throw new YAMLParseError([offset, offset + 1], code, message);
18
+ };
19
+ switch (token.type) {
20
+ case 'scalar':
21
+ case 'single-quoted-scalar':
22
+ case 'double-quoted-scalar':
23
+ return resolveFlowScalar(token, strict, _onError);
24
+ case 'block-scalar':
25
+ return resolveBlockScalar(token, strict, _onError);
26
+ }
27
+ }
28
+ return null;
29
+ }
30
+ /**
31
+ * Create a new scalar token with `value`
32
+ *
33
+ * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
34
+ * as this function does not support any schema operations and won't check for such conflicts.
35
+ *
36
+ * @param value The string representation of the value, which will have its content properly indented.
37
+ * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.
38
+ * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
39
+ * @param context.indent The indent level of the token.
40
+ * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.
41
+ * @param context.offset The offset position of the token.
42
+ * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
43
+ */
44
+ function createScalarToken(value, context) {
45
+ var _a;
46
+ const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;
47
+ const source = stringifyString({ type, value }, {
48
+ implicitKey,
49
+ indent: indent > 0 ? ' '.repeat(indent) : '',
50
+ inFlow,
51
+ options: { lineWidth: -1 }
52
+ });
53
+ const end = (_a = context.end) !== null && _a !== void 0 ? _a : [
54
+ { type: 'newline', offset: -1, indent, source: '\n' }
55
+ ];
56
+ switch (source[0]) {
57
+ case '|':
58
+ case '>': {
59
+ const he = source.indexOf('\n');
60
+ const head = source.substring(0, he);
61
+ const body = source.substring(he + 1) + '\n';
62
+ const props = [
63
+ { type: 'block-scalar-header', offset, indent, source: head }
64
+ ];
65
+ if (!addEndtoBlockProps(props, end))
66
+ props.push({ type: 'newline', offset: -1, indent, source: '\n' });
67
+ return { type: 'block-scalar', offset, indent, props, source: body };
68
+ }
69
+ case '"':
70
+ return { type: 'double-quoted-scalar', offset, indent, source, end };
71
+ case "'":
72
+ return { type: 'single-quoted-scalar', offset, indent, source, end };
73
+ default:
74
+ return { type: 'scalar', offset, indent, source, end };
75
+ }
76
+ }
77
+ /**
78
+ * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.
79
+ *
80
+ * Best efforts are made to retain any comments previously associated with the `token`,
81
+ * though all contents within a collection's `items` will be overwritten.
82
+ *
83
+ * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
84
+ * as this function does not support any schema operations and won't check for such conflicts.
85
+ *
86
+ * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.
87
+ * @param value The string representation of the value, which will have its content properly indented.
88
+ * @param context.afterKey In most cases, values after a key should have an additional level of indentation.
89
+ * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
90
+ * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.
91
+ * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
92
+ */
93
+ function setScalarValue(token, value, context = {}) {
94
+ let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
95
+ let indent = 'indent' in token ? token.indent : null;
96
+ if (afterKey && typeof indent === 'number')
97
+ indent += 2;
98
+ if (!type)
99
+ switch (token.type) {
100
+ case 'single-quoted-scalar':
101
+ type = 'QUOTE_SINGLE';
102
+ break;
103
+ case 'double-quoted-scalar':
104
+ type = 'QUOTE_DOUBLE';
105
+ break;
106
+ case 'block-scalar': {
107
+ const header = token.props[0];
108
+ if (header.type !== 'block-scalar-header')
109
+ throw new Error('Invalid block scalar header');
110
+ type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';
111
+ break;
112
+ }
113
+ default:
114
+ type = 'PLAIN';
115
+ }
116
+ const source = stringifyString({ type, value }, {
117
+ implicitKey: implicitKey || indent === null,
118
+ indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',
119
+ inFlow,
120
+ options: { lineWidth: -1 }
121
+ });
122
+ switch (source[0]) {
123
+ case '|':
124
+ case '>':
125
+ setBlockScalarValue(token, source);
126
+ break;
127
+ case '"':
128
+ setFlowScalarValue(token, source, 'double-quoted-scalar');
129
+ break;
130
+ case "'":
131
+ setFlowScalarValue(token, source, 'single-quoted-scalar');
132
+ break;
133
+ default:
134
+ setFlowScalarValue(token, source, 'scalar');
135
+ }
136
+ }
137
+ function setBlockScalarValue(token, source) {
138
+ const he = source.indexOf('\n');
139
+ const head = source.substring(0, he);
140
+ const body = source.substring(he + 1) + '\n';
141
+ if (token.type === 'block-scalar') {
142
+ const header = token.props[0];
143
+ if (header.type !== 'block-scalar-header')
144
+ throw new Error('Invalid block scalar header');
145
+ header.source = head;
146
+ token.source = body;
147
+ }
148
+ else {
149
+ const { offset } = token;
150
+ const indent = 'indent' in token ? token.indent : -1;
151
+ const props = [
152
+ { type: 'block-scalar-header', offset, indent, source: head }
153
+ ];
154
+ if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))
155
+ props.push({ type: 'newline', offset: -1, indent, source: '\n' });
156
+ for (const key of Object.keys(token))
157
+ if (key !== 'type' && key !== 'offset')
158
+ delete token[key];
159
+ Object.assign(token, { type: 'block-scalar', indent, props, source: body });
160
+ }
161
+ }
162
+ /** @returns `true` if last token is a newline */
163
+ function addEndtoBlockProps(props, end) {
164
+ if (end)
165
+ for (const st of end)
166
+ switch (st.type) {
167
+ case 'space':
168
+ case 'comment':
169
+ props.push(st);
170
+ break;
171
+ case 'newline':
172
+ props.push(st);
173
+ return true;
174
+ }
175
+ return false;
176
+ }
177
+ function setFlowScalarValue(token, source, type) {
178
+ switch (token.type) {
179
+ case 'scalar':
180
+ case 'double-quoted-scalar':
181
+ case 'single-quoted-scalar':
182
+ token.type = type;
183
+ token.source = source;
184
+ break;
185
+ case 'block-scalar': {
186
+ const end = token.props.slice(1);
187
+ let oa = source.length;
188
+ if (token.props[0].type === 'block-scalar-header')
189
+ oa -= token.props[0].source.length;
190
+ for (const tok of end)
191
+ tok.offset += oa;
192
+ delete token.props;
193
+ Object.assign(token, { type, source, end });
194
+ break;
195
+ }
196
+ case 'block-map':
197
+ case 'block-seq': {
198
+ const offset = token.offset + source.length;
199
+ const nl = { type: 'newline', offset, indent: token.indent, source: '\n' };
200
+ delete token.items;
201
+ Object.assign(token, { type, source, end: [nl] });
202
+ break;
203
+ }
204
+ default: {
205
+ const indent = 'indent' in token ? token.indent : -1;
206
+ const end = 'end' in token && Array.isArray(token.end)
207
+ ? token.end.filter(st => st.type === 'space' ||
208
+ st.type === 'comment' ||
209
+ st.type === 'newline')
210
+ : [];
211
+ for (const key of Object.keys(token))
212
+ if (key !== 'type' && key !== 'offset')
213
+ delete token[key];
214
+ Object.assign(token, { type, indent, source, end });
215
+ }
216
+ }
217
+ }
218
+
219
+ export { createScalarToken, resolveAsScalar, setScalarValue };
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Stringify a CST document, token, or collection item
3
+ *
4
+ * Fair warning: This applies no validation whatsoever, and
5
+ * simply concatenates the sources in their logical order.
6
+ */
7
+ const stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);
8
+ function stringifyToken(token) {
9
+ switch (token.type) {
10
+ case 'block-scalar': {
11
+ let res = '';
12
+ for (const tok of token.props)
13
+ res += stringifyToken(tok);
14
+ return res + token.source;
15
+ }
16
+ case 'block-map':
17
+ case 'block-seq': {
18
+ let res = '';
19
+ for (const item of token.items)
20
+ res += stringifyItem(item);
21
+ return res;
22
+ }
23
+ case 'flow-collection': {
24
+ let res = token.start.source;
25
+ for (const item of token.items)
26
+ res += stringifyItem(item);
27
+ for (const st of token.end)
28
+ res += st.source;
29
+ return res;
30
+ }
31
+ case 'document': {
32
+ let res = stringifyItem(token);
33
+ if (token.end)
34
+ for (const st of token.end)
35
+ res += st.source;
36
+ return res;
37
+ }
38
+ default: {
39
+ let res = token.source;
40
+ if ('end' in token && token.end)
41
+ for (const st of token.end)
42
+ res += st.source;
43
+ return res;
44
+ }
45
+ }
46
+ }
47
+ function stringifyItem({ start, key, sep, value }) {
48
+ let res = '';
49
+ for (const st of start)
50
+ res += st.source;
51
+ if (key)
52
+ res += stringifyToken(key);
53
+ if (sep)
54
+ for (const st of sep)
55
+ res += st.source;
56
+ if (value)
57
+ res += stringifyToken(value);
58
+ return res;
59
+ }
60
+
61
+ export { stringify };
@@ -0,0 +1,97 @@
1
+ const BREAK = Symbol('break visit');
2
+ const SKIP = Symbol('skip children');
3
+ const REMOVE = Symbol('remove item');
4
+ /**
5
+ * Apply a visitor to a CST document or item.
6
+ *
7
+ * Walks through the tree (depth-first) starting from the root, calling a
8
+ * `visitor` function with two arguments when entering each item:
9
+ * - `item`: The current item, which included the following members:
10
+ * - `start: SourceToken[]` – Source tokens before the key or value,
11
+ * possibly including its anchor or tag.
12
+ * - `key?: Token | null` – Set for pair values. May then be `null`, if
13
+ * the key before the `:` separator is empty.
14
+ * - `sep?: SourceToken[]` – Source tokens between the key and the value,
15
+ * which should include the `:` map value indicator if `value` is set.
16
+ * - `value?: Token` – The value of a sequence item, or of a map pair.
17
+ * - `path`: The steps from the root to the current node, as an array of
18
+ * `['key' | 'value', number]` tuples.
19
+ *
20
+ * The return value of the visitor may be used to control the traversal:
21
+ * - `undefined` (default): Do nothing and continue
22
+ * - `visit.SKIP`: Do not visit the children of this token, continue with
23
+ * next sibling
24
+ * - `visit.BREAK`: Terminate traversal completely
25
+ * - `visit.REMOVE`: Remove the current item, then continue with the next one
26
+ * - `number`: Set the index of the next step. This is useful especially if
27
+ * the index of the current token has changed.
28
+ * - `function`: Define the next visitor for this item. After the original
29
+ * visitor is called on item entry, next visitors are called after handling
30
+ * a non-empty `key` and when exiting the item.
31
+ */
32
+ function visit(cst, visitor) {
33
+ if ('type' in cst && cst.type === 'document')
34
+ cst = { start: cst.start, value: cst.value };
35
+ _visit(Object.freeze([]), cst, visitor);
36
+ }
37
+ // Without the `as symbol` casts, TS declares these in the `visit`
38
+ // namespace using `var`, but then complains about that because
39
+ // `unique symbol` must be `const`.
40
+ /** Terminate visit traversal completely */
41
+ visit.BREAK = BREAK;
42
+ /** Do not visit the children of the current item */
43
+ visit.SKIP = SKIP;
44
+ /** Remove the current item */
45
+ visit.REMOVE = REMOVE;
46
+ /** Find the item at `path` from `cst` as the root */
47
+ visit.itemAtPath = (cst, path) => {
48
+ let item = cst;
49
+ for (const [field, index] of path) {
50
+ const tok = item && item[field];
51
+ if (tok && 'items' in tok) {
52
+ item = tok.items[index];
53
+ }
54
+ else
55
+ return undefined;
56
+ }
57
+ return item;
58
+ };
59
+ /**
60
+ * Get the immediate parent collection of the item at `path` from `cst` as the root.
61
+ *
62
+ * Throws an error if the collection is not found, which should never happen if the item itself exists.
63
+ */
64
+ visit.parentCollection = (cst, path) => {
65
+ const parent = visit.itemAtPath(cst, path.slice(0, -1));
66
+ const field = path[path.length - 1][0];
67
+ const coll = parent && parent[field];
68
+ if (coll && 'items' in coll)
69
+ return coll;
70
+ throw new Error('Parent collection not found');
71
+ };
72
+ function _visit(path, item, visitor) {
73
+ let ctrl = visitor(item, path);
74
+ if (typeof ctrl === 'symbol')
75
+ return ctrl;
76
+ for (const field of ['key', 'value']) {
77
+ const token = item[field];
78
+ if (token && 'items' in token) {
79
+ for (let i = 0; i < token.items.length; ++i) {
80
+ const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
81
+ if (typeof ci === 'number')
82
+ i = ci - 1;
83
+ else if (ci === BREAK)
84
+ return BREAK;
85
+ else if (ci === REMOVE) {
86
+ token.items.splice(i, 1);
87
+ i -= 1;
88
+ }
89
+ }
90
+ if (typeof ctrl === 'function' && field === 'key')
91
+ ctrl = ctrl(item, path);
92
+ }
93
+ }
94
+ return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;
95
+ }
96
+
97
+ export { visit };
@@ -1,4 +1,6 @@
1
- 'use strict';
1
+ export { createScalarToken, resolveAsScalar, setScalarValue } from './cst-scalar.js';
2
+ export { stringify } from './cst-stringify.js';
3
+ export { visit } from './cst-visit.js';
2
4
 
3
5
  /** The byte order mark */
4
6
  const BOM = '\u{FEFF}';
@@ -8,6 +10,14 @@ const DOCUMENT = '\x02'; // C0: Start of Text
8
10
  const FLOW_END = '\x18'; // C0: Cancel
9
11
  /** Next token is a scalar value */
10
12
  const SCALAR = '\x1f'; // C0: Unit Separator
13
+ /** @returns `true` if `token` is a flow or block collection */
14
+ const isCollection = (token) => !!token && 'items' in token;
15
+ /** @returns `true` if `token` is a flow or block scalar; not an alias */
16
+ const isScalar = (token) => !!token &&
17
+ (token.type === 'scalar' ||
18
+ token.type === 'single-quoted-scalar' ||
19
+ token.type === 'double-quoted-scalar' ||
20
+ token.type === 'block-scalar');
11
21
  /* istanbul ignore next */
12
22
  /** Get a printable representation of a lexer token */
13
23
  function prettyToken(token) {
@@ -85,9 +95,4 @@ function tokenType(source) {
85
95
  return null;
86
96
  }
87
97
 
88
- exports.BOM = BOM;
89
- exports.DOCUMENT = DOCUMENT;
90
- exports.FLOW_END = FLOW_END;
91
- exports.SCALAR = SCALAR;
92
- exports.prettyToken = prettyToken;
93
- exports.tokenType = tokenType;
98
+ export { BOM, DOCUMENT, FLOW_END, SCALAR, isCollection, isScalar, prettyToken, tokenType };