dumper.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. 'use strict';
  2. /*eslint-disable no-use-before-define*/
  3. var common = require('./common');
  4. var YAMLException = require('./exception');
  5. var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
  6. var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
  7. var _toString = Object.prototype.toString;
  8. var _hasOwnProperty = Object.prototype.hasOwnProperty;
  9. var CHAR_TAB = 0x09; /* Tab */
  10. var CHAR_LINE_FEED = 0x0A; /* LF */
  11. var CHAR_SPACE = 0x20; /* Space */
  12. var CHAR_EXCLAMATION = 0x21; /* ! */
  13. var CHAR_DOUBLE_QUOTE = 0x22; /* " */
  14. var CHAR_SHARP = 0x23; /* # */
  15. var CHAR_PERCENT = 0x25; /* % */
  16. var CHAR_AMPERSAND = 0x26; /* & */
  17. var CHAR_SINGLE_QUOTE = 0x27; /* ' */
  18. var CHAR_ASTERISK = 0x2A; /* * */
  19. var CHAR_COMMA = 0x2C; /* , */
  20. var CHAR_MINUS = 0x2D; /* - */
  21. var CHAR_COLON = 0x3A; /* : */
  22. var CHAR_GREATER_THAN = 0x3E; /* > */
  23. var CHAR_QUESTION = 0x3F; /* ? */
  24. var CHAR_COMMERCIAL_AT = 0x40; /* @ */
  25. var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
  26. var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
  27. var CHAR_GRAVE_ACCENT = 0x60; /* ` */
  28. var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
  29. var CHAR_VERTICAL_LINE = 0x7C; /* | */
  30. var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
  31. var ESCAPE_SEQUENCES = {};
  32. ESCAPE_SEQUENCES[0x00] = '\\0';
  33. ESCAPE_SEQUENCES[0x07] = '\\a';
  34. ESCAPE_SEQUENCES[0x08] = '\\b';
  35. ESCAPE_SEQUENCES[0x09] = '\\t';
  36. ESCAPE_SEQUENCES[0x0A] = '\\n';
  37. ESCAPE_SEQUENCES[0x0B] = '\\v';
  38. ESCAPE_SEQUENCES[0x0C] = '\\f';
  39. ESCAPE_SEQUENCES[0x0D] = '\\r';
  40. ESCAPE_SEQUENCES[0x1B] = '\\e';
  41. ESCAPE_SEQUENCES[0x22] = '\\"';
  42. ESCAPE_SEQUENCES[0x5C] = '\\\\';
  43. ESCAPE_SEQUENCES[0x85] = '\\N';
  44. ESCAPE_SEQUENCES[0xA0] = '\\_';
  45. ESCAPE_SEQUENCES[0x2028] = '\\L';
  46. ESCAPE_SEQUENCES[0x2029] = '\\P';
  47. var DEPRECATED_BOOLEANS_SYNTAX = [
  48. 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
  49. 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
  50. ];
  51. function compileStyleMap(schema, map) {
  52. var result, keys, index, length, tag, style, type;
  53. if (map === null) return {};
  54. result = {};
  55. keys = Object.keys(map);
  56. for (index = 0, length = keys.length; index < length; index += 1) {
  57. tag = keys[index];
  58. style = String(map[tag]);
  59. if (tag.slice(0, 2) === '!!') {
  60. tag = 'tag:yaml.org,2002:' + tag.slice(2);
  61. }
  62. type = schema.compiledTypeMap['fallback'][tag];
  63. if (type && _hasOwnProperty.call(type.styleAliases, style)) {
  64. style = type.styleAliases[style];
  65. }
  66. result[tag] = style;
  67. }
  68. return result;
  69. }
  70. function encodeHex(character) {
  71. var string, handle, length;
  72. string = character.toString(16).toUpperCase();
  73. if (character <= 0xFF) {
  74. handle = 'x';
  75. length = 2;
  76. } else if (character <= 0xFFFF) {
  77. handle = 'u';
  78. length = 4;
  79. } else if (character <= 0xFFFFFFFF) {
  80. handle = 'U';
  81. length = 8;
  82. } else {
  83. throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
  84. }
  85. return '\\' + handle + common.repeat('0', length - string.length) + string;
  86. }
  87. function State(options) {
  88. this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
  89. this.indent = Math.max(1, (options['indent'] || 2));
  90. this.skipInvalid = options['skipInvalid'] || false;
  91. this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
  92. this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
  93. this.sortKeys = options['sortKeys'] || false;
  94. this.lineWidth = options['lineWidth'] || 80;
  95. this.noRefs = options['noRefs'] || false;
  96. this.noCompatMode = options['noCompatMode'] || false;
  97. this.condenseFlow = options['condenseFlow'] || false;
  98. this.implicitTypes = this.schema.compiledImplicit;
  99. this.explicitTypes = this.schema.compiledExplicit;
  100. this.tag = null;
  101. this.result = '';
  102. this.duplicates = [];
  103. this.usedDuplicates = null;
  104. }
  105. // Indents every line in a string. Empty lines (\n only) are not indented.
  106. function indentString(string, spaces) {
  107. var ind = common.repeat(' ', spaces),
  108. position = 0,
  109. next = -1,
  110. result = '',
  111. line,
  112. length = string.length;
  113. while (position < length) {
  114. next = string.indexOf('\n', position);
  115. if (next === -1) {
  116. line = string.slice(position);
  117. position = length;
  118. } else {
  119. line = string.slice(position, next + 1);
  120. position = next + 1;
  121. }
  122. if (line.length && line !== '\n') result += ind;
  123. result += line;
  124. }
  125. return result;
  126. }
  127. function generateNextLine(state, level) {
  128. return '\n' + common.repeat(' ', state.indent * level);
  129. }
  130. function testImplicitResolving(state, str) {
  131. var index, length, type;
  132. for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
  133. type = state.implicitTypes[index];
  134. if (type.resolve(str)) {
  135. return true;
  136. }
  137. }
  138. return false;
  139. }
  140. // [33] s-white ::= s-space | s-tab
  141. function isWhitespace(c) {
  142. return c === CHAR_SPACE || c === CHAR_TAB;
  143. }
  144. // Returns true if the character can be printed without escaping.
  145. // From YAML 1.2: "any allowed characters known to be non-printable
  146. // should also be escaped. [However,] This isn’t mandatory"
  147. // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
  148. function isPrintable(c) {
  149. return (0x00020 <= c && c <= 0x00007E)
  150. || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
  151. || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
  152. || (0x10000 <= c && c <= 0x10FFFF);
  153. }
  154. // Simplified test for values allowed after the first character in plain style.
  155. function isPlainSafe(c) {
  156. // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
  157. // where nb-char ::= c-printable - b-char - c-byte-order-mark.
  158. return isPrintable(c) && c !== 0xFEFF
  159. // - c-flow-indicator
  160. && c !== CHAR_COMMA
  161. && c !== CHAR_LEFT_SQUARE_BRACKET
  162. && c !== CHAR_RIGHT_SQUARE_BRACKET
  163. && c !== CHAR_LEFT_CURLY_BRACKET
  164. && c !== CHAR_RIGHT_CURLY_BRACKET
  165. // - ":" - "#"
  166. && c !== CHAR_COLON
  167. && c !== CHAR_SHARP;
  168. }
  169. // Simplified test for values allowed as the first character in plain style.
  170. function isPlainSafeFirst(c) {
  171. // Uses a subset of ns-char - c-indicator
  172. // where ns-char = nb-char - s-white.
  173. return isPrintable(c) && c !== 0xFEFF
  174. && !isWhitespace(c) // - s-white
  175. // - (c-indicator ::=
  176. // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
  177. && c !== CHAR_MINUS
  178. && c !== CHAR_QUESTION
  179. && c !== CHAR_COLON
  180. && c !== CHAR_COMMA
  181. && c !== CHAR_LEFT_SQUARE_BRACKET
  182. && c !== CHAR_RIGHT_SQUARE_BRACKET
  183. && c !== CHAR_LEFT_CURLY_BRACKET
  184. && c !== CHAR_RIGHT_CURLY_BRACKET
  185. // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
  186. && c !== CHAR_SHARP
  187. && c !== CHAR_AMPERSAND
  188. && c !== CHAR_ASTERISK
  189. && c !== CHAR_EXCLAMATION
  190. && c !== CHAR_VERTICAL_LINE
  191. && c !== CHAR_GREATER_THAN
  192. && c !== CHAR_SINGLE_QUOTE
  193. && c !== CHAR_DOUBLE_QUOTE
  194. // | “%” | “@” | “`”)
  195. && c !== CHAR_PERCENT
  196. && c !== CHAR_COMMERCIAL_AT
  197. && c !== CHAR_GRAVE_ACCENT;
  198. }
  199. // Determines whether block indentation indicator is required.
  200. function needIndentIndicator(string) {
  201. var leadingSpaceRe = /^\n* /;
  202. return leadingSpaceRe.test(string);
  203. }
  204. var STYLE_PLAIN = 1,
  205. STYLE_SINGLE = 2,
  206. STYLE_LITERAL = 3,
  207. STYLE_FOLDED = 4,
  208. STYLE_DOUBLE = 5;
  209. // Determines which scalar styles are possible and returns the preferred style.
  210. // lineWidth = -1 => no limit.
  211. // Pre-conditions: str.length > 0.
  212. // Post-conditions:
  213. // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
  214. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
  215. // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
  216. function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
  217. var i;
  218. var char;
  219. var hasLineBreak = false;
  220. var hasFoldableLine = false; // only checked if shouldTrackWidth
  221. var shouldTrackWidth = lineWidth !== -1;
  222. var previousLineBreak = -1; // count the first line correctly
  223. var plain = isPlainSafeFirst(string.charCodeAt(0))
  224. && !isWhitespace(string.charCodeAt(string.length - 1));
  225. if (singleLineOnly) {
  226. // Case: no block styles.
  227. // Check for disallowed characters to rule out plain and single.
  228. for (i = 0; i < string.length; i++) {
  229. char = string.charCodeAt(i);
  230. if (!isPrintable(char)) {
  231. return STYLE_DOUBLE;
  232. }
  233. plain = plain && isPlainSafe(char);
  234. }
  235. } else {
  236. // Case: block styles permitted.
  237. for (i = 0; i < string.length; i++) {
  238. char = string.charCodeAt(i);
  239. if (char === CHAR_LINE_FEED) {
  240. hasLineBreak = true;
  241. // Check if any line can be folded.
  242. if (shouldTrackWidth) {
  243. hasFoldableLine = hasFoldableLine ||
  244. // Foldable line = too long, and not more-indented.
  245. (i - previousLineBreak - 1 > lineWidth &&
  246. string[previousLineBreak + 1] !== ' ');
  247. previousLineBreak = i;
  248. }
  249. } else if (!isPrintable(char)) {
  250. return STYLE_DOUBLE;
  251. }
  252. plain = plain && isPlainSafe(char);
  253. }
  254. // in case the end is missing a \n
  255. hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
  256. (i - previousLineBreak - 1 > lineWidth &&
  257. string[previousLineBreak + 1] !== ' '));
  258. }
  259. // Although every style can represent \n without escaping, prefer block styles
  260. // for multiline, since they're more readable and they don't add empty lines.
  261. // Also prefer folding a super-long line.
  262. if (!hasLineBreak && !hasFoldableLine) {
  263. // Strings interpretable as another type have to be quoted;
  264. // e.g. the string 'true' vs. the boolean true.
  265. return plain && !testAmbiguousType(string)
  266. ? STYLE_PLAIN : STYLE_SINGLE;
  267. }
  268. // Edge case: block indentation indicator can only have one digit.
  269. if (indentPerLevel > 9 && needIndentIndicator(string)) {
  270. return STYLE_DOUBLE;
  271. }
  272. // At this point we know block styles are valid.
  273. // Prefer literal style unless we want to fold.
  274. return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
  275. }
  276. // Note: line breaking/folding is implemented for only the folded style.
  277. // NB. We drop the last trailing newline (if any) of a returned block scalar
  278. // since the dumper adds its own newline. This always works:
  279. // • No ending newline => unaffected; already using strip "-" chomping.
  280. // • Ending newline => removed then restored.
  281. // Importantly, this keeps the "+" chomp indicator from gaining an extra line.
  282. function writeScalar(state, string, level, iskey) {
  283. state.dump = (function () {
  284. if (string.length === 0) {
  285. return "''";
  286. }
  287. if (!state.noCompatMode &&
  288. DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
  289. return "'" + string + "'";
  290. }
  291. var indent = state.indent * Math.max(1, level); // no 0-indent scalars
  292. // As indentation gets deeper, let the width decrease monotonically
  293. // to the lower bound min(state.lineWidth, 40).
  294. // Note that this implies
  295. // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
  296. // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
  297. // This behaves better than a constant minimum width which disallows narrower options,
  298. // or an indent threshold which causes the width to suddenly increase.
  299. var lineWidth = state.lineWidth === -1
  300. ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
  301. // Without knowing if keys are implicit/explicit, assume implicit for safety.
  302. var singleLineOnly = iskey
  303. // No block styles in flow mode.
  304. || (state.flowLevel > -1 && level >= state.flowLevel);
  305. function testAmbiguity(string) {
  306. return testImplicitResolving(state, string);
  307. }
  308. switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
  309. case STYLE_PLAIN:
  310. return string;
  311. case STYLE_SINGLE:
  312. return "'" + string.replace(/'/g, "''") + "'";
  313. case STYLE_LITERAL:
  314. return '|' + blockHeader(string, state.indent)
  315. + dropEndingNewline(indentString(string, indent));
  316. case STYLE_FOLDED:
  317. return '>' + blockHeader(string, state.indent)
  318. + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
  319. case STYLE_DOUBLE:
  320. return '"' + escapeString(string, lineWidth) + '"';
  321. default:
  322. throw new YAMLException('impossible error: invalid scalar style');
  323. }
  324. }());
  325. }
  326. // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
  327. function blockHeader(string, indentPerLevel) {
  328. var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
  329. // note the special case: the string '\n' counts as a "trailing" empty line.
  330. var clip = string[string.length - 1] === '\n';
  331. var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
  332. var chomp = keep ? '+' : (clip ? '' : '-');
  333. return indentIndicator + chomp + '\n';
  334. }
  335. // (See the note for writeScalar.)
  336. function dropEndingNewline(string) {
  337. return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
  338. }
  339. // Note: a long line without a suitable break point will exceed the width limit.
  340. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
  341. function foldString(string, width) {
  342. // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
  343. // unless they're before or after a more-indented line, or at the very
  344. // beginning or end, in which case $k$ maps to $k$.
  345. // Therefore, parse each chunk as newline(s) followed by a content line.
  346. var lineRe = /(\n+)([^\n]*)/g;
  347. // first line (possibly an empty line)
  348. var result = (function () {
  349. var nextLF = string.indexOf('\n');
  350. nextLF = nextLF !== -1 ? nextLF : string.length;
  351. lineRe.lastIndex = nextLF;
  352. return foldLine(string.slice(0, nextLF), width);
  353. }());
  354. // If we haven't reached the first content line yet, don't add an extra \n.
  355. var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
  356. var moreIndented;
  357. // rest of the lines
  358. var match;
  359. while ((match = lineRe.exec(string))) {
  360. var prefix = match[1], line = match[2];
  361. moreIndented = (line[0] === ' ');
  362. result += prefix
  363. + (!prevMoreIndented && !moreIndented && line !== ''
  364. ? '\n' : '')
  365. + foldLine(line, width);
  366. prevMoreIndented = moreIndented;
  367. }
  368. return result;
  369. }
  370. // Greedy line breaking.
  371. // Picks the longest line under the limit each time,
  372. // otherwise settles for the shortest line over the limit.
  373. // NB. More-indented lines *cannot* be folded, as that would add an extra \n.
  374. function foldLine(line, width) {
  375. if (line === '' || line[0] === ' ') return line;
  376. // Since a more-indented line adds a \n, breaks can't be followed by a space.
  377. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
  378. var match;
  379. // start is an inclusive index. end, curr, and next are exclusive.
  380. var start = 0, end, curr = 0, next = 0;
  381. var result = '';
  382. // Invariants: 0 <= start <= length-1.
  383. // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
  384. // Inside the loop:
  385. // A match implies length >= 2, so curr and next are <= length-2.
  386. while ((match = breakRe.exec(line))) {
  387. next = match.index;
  388. // maintain invariant: curr - start <= width
  389. if (next - start > width) {
  390. end = (curr > start) ? curr : next; // derive end <= length-2
  391. result += '\n' + line.slice(start, end);
  392. // skip the space that was output as \n
  393. start = end + 1; // derive start <= length-1
  394. }
  395. curr = next;
  396. }
  397. // By the invariants, start <= length-1, so there is something left over.
  398. // It is either the whole string or a part starting from non-whitespace.
  399. result += '\n';
  400. // Insert a break if the remainder is too long and there is a break available.
  401. if (line.length - start > width && curr > start) {
  402. result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
  403. } else {
  404. result += line.slice(start);
  405. }
  406. return result.slice(1); // drop extra \n joiner
  407. }
  408. // Escapes a double-quoted string.
  409. function escapeString(string) {
  410. var result = '';
  411. var char, nextChar;
  412. var escapeSeq;
  413. for (var i = 0; i < string.length; i++) {
  414. char = string.charCodeAt(i);
  415. // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
  416. if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
  417. nextChar = string.charCodeAt(i + 1);
  418. if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
  419. // Combine the surrogate pair and store it escaped.
  420. result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
  421. // Advance index one extra since we already used that char here.
  422. i++; continue;
  423. }
  424. }
  425. escapeSeq = ESCAPE_SEQUENCES[char];
  426. result += !escapeSeq && isPrintable(char)
  427. ? string[i]
  428. : escapeSeq || encodeHex(char);
  429. }
  430. return result;
  431. }
  432. function writeFlowSequence(state, level, object) {
  433. var _result = '',
  434. _tag = state.tag,
  435. index,
  436. length;
  437. for (index = 0, length = object.length; index < length; index += 1) {
  438. // Write only valid elements.
  439. if (writeNode(state, level, object[index], false, false)) {
  440. if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
  441. _result += state.dump;
  442. }
  443. }
  444. state.tag = _tag;
  445. state.dump = '[' + _result + ']';
  446. }
  447. function writeBlockSequence(state, level, object, compact) {
  448. var _result = '',
  449. _tag = state.tag,
  450. index,
  451. length;
  452. for (index = 0, length = object.length; index < length; index += 1) {
  453. // Write only valid elements.
  454. if (writeNode(state, level + 1, object[index], true, true)) {
  455. if (!compact || index !== 0) {
  456. _result += generateNextLine(state, level);
  457. }
  458. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  459. _result += '-';
  460. } else {
  461. _result += '- ';
  462. }
  463. _result += state.dump;
  464. }
  465. }
  466. state.tag = _tag;
  467. state.dump = _result || '[]'; // Empty sequence if no valid values.
  468. }
  469. function writeFlowMapping(state, level, object) {
  470. var _result = '',
  471. _tag = state.tag,
  472. objectKeyList = Object.keys(object),
  473. index,
  474. length,
  475. objectKey,
  476. objectValue,
  477. pairBuffer;
  478. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  479. pairBuffer = state.condenseFlow ? '"' : '';
  480. if (index !== 0) pairBuffer += ', ';
  481. objectKey = objectKeyList[index];
  482. objectValue = object[objectKey];
  483. if (!writeNode(state, level, objectKey, false, false)) {
  484. continue; // Skip this pair because of invalid key;
  485. }
  486. if (state.dump.length > 1024) pairBuffer += '? ';
  487. pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
  488. if (!writeNode(state, level, objectValue, false, false)) {
  489. continue; // Skip this pair because of invalid value.
  490. }
  491. pairBuffer += state.dump;
  492. // Both key and value are valid.
  493. _result += pairBuffer;
  494. }
  495. state.tag = _tag;
  496. state.dump = '{' + _result + '}';
  497. }
  498. function writeBlockMapping(state, level, object, compact) {
  499. var _result = '',
  500. _tag = state.tag,
  501. objectKeyList = Object.keys(object),
  502. index,
  503. length,
  504. objectKey,
  505. objectValue,
  506. explicitPair,
  507. pairBuffer;
  508. // Allow sorting keys so that the output file is deterministic
  509. if (state.sortKeys === true) {
  510. // Default sorting
  511. objectKeyList.sort();
  512. } else if (typeof state.sortKeys === 'function') {
  513. // Custom sort function
  514. objectKeyList.sort(state.sortKeys);
  515. } else if (state.sortKeys) {
  516. // Something is wrong
  517. throw new YAMLException('sortKeys must be a boolean or a function');
  518. }
  519. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  520. pairBuffer = '';
  521. if (!compact || index !== 0) {
  522. pairBuffer += generateNextLine(state, level);
  523. }
  524. objectKey = objectKeyList[index];
  525. objectValue = object[objectKey];
  526. if (!writeNode(state, level + 1, objectKey, true, true, true)) {
  527. continue; // Skip this pair because of invalid key.
  528. }
  529. explicitPair = (state.tag !== null && state.tag !== '?') ||
  530. (state.dump && state.dump.length > 1024);
  531. if (explicitPair) {
  532. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  533. pairBuffer += '?';
  534. } else {
  535. pairBuffer += '? ';
  536. }
  537. }
  538. pairBuffer += state.dump;
  539. if (explicitPair) {
  540. pairBuffer += generateNextLine(state, level);
  541. }
  542. if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
  543. continue; // Skip this pair because of invalid value.
  544. }
  545. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  546. pairBuffer += ':';
  547. } else {
  548. pairBuffer += ': ';
  549. }
  550. pairBuffer += state.dump;
  551. // Both key and value are valid.
  552. _result += pairBuffer;
  553. }
  554. state.tag = _tag;
  555. state.dump = _result || '{}'; // Empty mapping if no valid pairs.
  556. }
  557. function detectType(state, object, explicit) {
  558. var _result, typeList, index, length, type, style;
  559. typeList = explicit ? state.explicitTypes : state.implicitTypes;
  560. for (index = 0, length = typeList.length; index < length; index += 1) {
  561. type = typeList[index];
  562. if ((type.instanceOf || type.predicate) &&
  563. (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
  564. (!type.predicate || type.predicate(object))) {
  565. state.tag = explicit ? type.tag : '?';
  566. if (type.represent) {
  567. style = state.styleMap[type.tag] || type.defaultStyle;
  568. if (_toString.call(type.represent) === '[object Function]') {
  569. _result = type.represent(object, style);
  570. } else if (_hasOwnProperty.call(type.represent, style)) {
  571. _result = type.represent[style](object, style);
  572. } else {
  573. throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
  574. }
  575. state.dump = _result;
  576. }
  577. return true;
  578. }
  579. }
  580. return false;
  581. }
  582. // Serializes `object` and writes it to global `result`.
  583. // Returns true on success, or false on invalid object.
  584. //
  585. function writeNode(state, level, object, block, compact, iskey) {
  586. state.tag = null;
  587. state.dump = object;
  588. if (!detectType(state, object, false)) {
  589. detectType(state, object, true);
  590. }
  591. var type = _toString.call(state.dump);
  592. if (block) {
  593. block = (state.flowLevel < 0 || state.flowLevel > level);
  594. }
  595. var objectOrArray = type === '[object Object]' || type === '[object Array]',
  596. duplicateIndex,
  597. duplicate;
  598. if (objectOrArray) {
  599. duplicateIndex = state.duplicates.indexOf(object);
  600. duplicate = duplicateIndex !== -1;
  601. }
  602. if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
  603. compact = false;
  604. }
  605. if (duplicate && state.usedDuplicates[duplicateIndex]) {
  606. state.dump = '*ref_' + duplicateIndex;
  607. } else {
  608. if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
  609. state.usedDuplicates[duplicateIndex] = true;
  610. }
  611. if (type === '[object Object]') {
  612. if (block && (Object.keys(state.dump).length !== 0)) {
  613. writeBlockMapping(state, level, state.dump, compact);
  614. if (duplicate) {
  615. state.dump = '&ref_' + duplicateIndex + state.dump;
  616. }
  617. } else {
  618. writeFlowMapping(state, level, state.dump);
  619. if (duplicate) {
  620. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  621. }
  622. }
  623. } else if (type === '[object Array]') {
  624. if (block && (state.dump.length !== 0)) {
  625. writeBlockSequence(state, level, state.dump, compact);
  626. if (duplicate) {
  627. state.dump = '&ref_' + duplicateIndex + state.dump;
  628. }
  629. } else {
  630. writeFlowSequence(state, level, state.dump);
  631. if (duplicate) {
  632. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  633. }
  634. }
  635. } else if (type === '[object String]') {
  636. if (state.tag !== '?') {
  637. writeScalar(state, state.dump, level, iskey);
  638. }
  639. } else {
  640. if (state.skipInvalid) return false;
  641. throw new YAMLException('unacceptable kind of an object to dump ' + type);
  642. }
  643. if (state.tag !== null && state.tag !== '?') {
  644. state.dump = '!<' + state.tag + '> ' + state.dump;
  645. }
  646. }
  647. return true;
  648. }
  649. function getDuplicateReferences(object, state) {
  650. var objects = [],
  651. duplicatesIndexes = [],
  652. index,
  653. length;
  654. inspectNode(object, objects, duplicatesIndexes);
  655. for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
  656. state.duplicates.push(objects[duplicatesIndexes[index]]);
  657. }
  658. state.usedDuplicates = new Array(length);
  659. }
  660. function inspectNode(object, objects, duplicatesIndexes) {
  661. var objectKeyList,
  662. index,
  663. length;
  664. if (object !== null && typeof object === 'object') {
  665. index = objects.indexOf(object);
  666. if (index !== -1) {
  667. if (duplicatesIndexes.indexOf(index) === -1) {
  668. duplicatesIndexes.push(index);
  669. }
  670. } else {
  671. objects.push(object);
  672. if (Array.isArray(object)) {
  673. for (index = 0, length = object.length; index < length; index += 1) {
  674. inspectNode(object[index], objects, duplicatesIndexes);
  675. }
  676. } else {
  677. objectKeyList = Object.keys(object);
  678. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  679. inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
  680. }
  681. }
  682. }
  683. }
  684. }
  685. function dump(input, options) {
  686. options = options || {};
  687. var state = new State(options);
  688. if (!state.noRefs) getDuplicateReferences(input, state);
  689. if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
  690. return '';
  691. }
  692. function safeDump(input, options) {
  693. return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
  694. }
  695. module.exports.dump = dump;
  696. module.exports.safeDump = safeDump;