cst-scalar.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. function resolveAsScalar(token, strict = true, onError) {
  6. if (token) {
  7. const _onError = (pos, code, message) => {
  8. const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
  9. if (onError)
  10. onError(offset, code, message);
  11. else
  12. throw new YAMLParseError([offset, offset + 1], code, message);
  13. };
  14. switch (token.type) {
  15. case 'scalar':
  16. case 'single-quoted-scalar':
  17. case 'double-quoted-scalar':
  18. return resolveFlowScalar(token, strict, _onError);
  19. case 'block-scalar':
  20. return resolveBlockScalar({ options: { strict } }, token, _onError);
  21. }
  22. }
  23. return null;
  24. }
  25. /**
  26. * Create a new scalar token with `value`
  27. *
  28. * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
  29. * as this function does not support any schema operations and won't check for such conflicts.
  30. *
  31. * @param value The string representation of the value, which will have its content properly indented.
  32. * @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.
  33. * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
  34. * @param context.indent The indent level of the token.
  35. * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.
  36. * @param context.offset The offset position of the token.
  37. * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
  38. */
  39. function createScalarToken(value, context) {
  40. const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;
  41. const source = stringifyString({ type, value }, {
  42. implicitKey,
  43. indent: indent > 0 ? ' '.repeat(indent) : '',
  44. inFlow,
  45. options: { blockQuote: true, lineWidth: -1 }
  46. });
  47. const end = context.end ?? [
  48. { type: 'newline', offset: -1, indent, source: '\n' }
  49. ];
  50. switch (source[0]) {
  51. case '|':
  52. case '>': {
  53. const he = source.indexOf('\n');
  54. const head = source.substring(0, he);
  55. const body = source.substring(he + 1) + '\n';
  56. const props = [
  57. { type: 'block-scalar-header', offset, indent, source: head }
  58. ];
  59. if (!addEndtoBlockProps(props, end))
  60. props.push({ type: 'newline', offset: -1, indent, source: '\n' });
  61. return { type: 'block-scalar', offset, indent, props, source: body };
  62. }
  63. case '"':
  64. return { type: 'double-quoted-scalar', offset, indent, source, end };
  65. case "'":
  66. return { type: 'single-quoted-scalar', offset, indent, source, end };
  67. default:
  68. return { type: 'scalar', offset, indent, source, end };
  69. }
  70. }
  71. /**
  72. * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.
  73. *
  74. * Best efforts are made to retain any comments previously associated with the `token`,
  75. * though all contents within a collection's `items` will be overwritten.
  76. *
  77. * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
  78. * as this function does not support any schema operations and won't check for such conflicts.
  79. *
  80. * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.
  81. * @param value The string representation of the value, which will have its content properly indented.
  82. * @param context.afterKey In most cases, values after a key should have an additional level of indentation.
  83. * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
  84. * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.
  85. * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
  86. */
  87. function setScalarValue(token, value, context = {}) {
  88. let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
  89. let indent = 'indent' in token ? token.indent : null;
  90. if (afterKey && typeof indent === 'number')
  91. indent += 2;
  92. if (!type)
  93. switch (token.type) {
  94. case 'single-quoted-scalar':
  95. type = 'QUOTE_SINGLE';
  96. break;
  97. case 'double-quoted-scalar':
  98. type = 'QUOTE_DOUBLE';
  99. break;
  100. case 'block-scalar': {
  101. const header = token.props[0];
  102. if (header.type !== 'block-scalar-header')
  103. throw new Error('Invalid block scalar header');
  104. type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';
  105. break;
  106. }
  107. default:
  108. type = 'PLAIN';
  109. }
  110. const source = stringifyString({ type, value }, {
  111. implicitKey: implicitKey || indent === null,
  112. indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',
  113. inFlow,
  114. options: { blockQuote: true, lineWidth: -1 }
  115. });
  116. switch (source[0]) {
  117. case '|':
  118. case '>':
  119. setBlockScalarValue(token, source);
  120. break;
  121. case '"':
  122. setFlowScalarValue(token, source, 'double-quoted-scalar');
  123. break;
  124. case "'":
  125. setFlowScalarValue(token, source, 'single-quoted-scalar');
  126. break;
  127. default:
  128. setFlowScalarValue(token, source, 'scalar');
  129. }
  130. }
  131. function setBlockScalarValue(token, source) {
  132. const he = source.indexOf('\n');
  133. const head = source.substring(0, he);
  134. const body = source.substring(he + 1) + '\n';
  135. if (token.type === 'block-scalar') {
  136. const header = token.props[0];
  137. if (header.type !== 'block-scalar-header')
  138. throw new Error('Invalid block scalar header');
  139. header.source = head;
  140. token.source = body;
  141. }
  142. else {
  143. const { offset } = token;
  144. const indent = 'indent' in token ? token.indent : -1;
  145. const props = [
  146. { type: 'block-scalar-header', offset, indent, source: head }
  147. ];
  148. if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))
  149. props.push({ type: 'newline', offset: -1, indent, source: '\n' });
  150. for (const key of Object.keys(token))
  151. if (key !== 'type' && key !== 'offset')
  152. delete token[key];
  153. Object.assign(token, { type: 'block-scalar', indent, props, source: body });
  154. }
  155. }
  156. /** @returns `true` if last token is a newline */
  157. function addEndtoBlockProps(props, end) {
  158. if (end)
  159. for (const st of end)
  160. switch (st.type) {
  161. case 'space':
  162. case 'comment':
  163. props.push(st);
  164. break;
  165. case 'newline':
  166. props.push(st);
  167. return true;
  168. }
  169. return false;
  170. }
  171. function setFlowScalarValue(token, source, type) {
  172. switch (token.type) {
  173. case 'scalar':
  174. case 'double-quoted-scalar':
  175. case 'single-quoted-scalar':
  176. token.type = type;
  177. token.source = source;
  178. break;
  179. case 'block-scalar': {
  180. const end = token.props.slice(1);
  181. let oa = source.length;
  182. if (token.props[0].type === 'block-scalar-header')
  183. oa -= token.props[0].source.length;
  184. for (const tok of end)
  185. tok.offset += oa;
  186. delete token.props;
  187. Object.assign(token, { type, source, end });
  188. break;
  189. }
  190. case 'block-map':
  191. case 'block-seq': {
  192. const offset = token.offset + source.length;
  193. const nl = { type: 'newline', offset, indent: token.indent, source: '\n' };
  194. delete token.items;
  195. Object.assign(token, { type, source, end: [nl] });
  196. break;
  197. }
  198. default: {
  199. const indent = 'indent' in token ? token.indent : -1;
  200. const end = 'end' in token && Array.isArray(token.end)
  201. ? token.end.filter(st => st.type === 'space' ||
  202. st.type === 'comment' ||
  203. st.type === 'newline')
  204. : [];
  205. for (const key of Object.keys(token))
  206. if (key !== 'type' && key !== 'offset')
  207. delete token[key];
  208. Object.assign(token, { type, indent, source, end });
  209. }
  210. }
  211. }
  212. export { createScalarToken, resolveAsScalar, setScalarValue };