Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dumper.js 26KB

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