react / wstein / node_modules / jest-cli / node_modules / istanbul / node_modules / js-yaml / lib / js-yaml / dumper.js
80698 views'use strict';12/*eslint-disable no-use-before-define*/34var common = require('./common');5var YAMLException = require('./exception');6var DEFAULT_FULL_SCHEMA = require('./schema/default_full');7var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');89var _toString = Object.prototype.toString;10var _hasOwnProperty = Object.prototype.hasOwnProperty;1112var CHAR_TAB = 0x09; /* Tab */13var CHAR_LINE_FEED = 0x0A; /* LF */14var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */15var CHAR_SPACE = 0x20; /* Space */16var CHAR_EXCLAMATION = 0x21; /* ! */17var CHAR_DOUBLE_QUOTE = 0x22; /* " */18var CHAR_SHARP = 0x23; /* # */19var CHAR_PERCENT = 0x25; /* % */20var CHAR_AMPERSAND = 0x26; /* & */21var CHAR_SINGLE_QUOTE = 0x27; /* ' */22var CHAR_ASTERISK = 0x2A; /* * */23var CHAR_COMMA = 0x2C; /* , */24var CHAR_MINUS = 0x2D; /* - */25var CHAR_COLON = 0x3A; /* : */26var CHAR_GREATER_THAN = 0x3E; /* > */27var CHAR_QUESTION = 0x3F; /* ? */28var CHAR_COMMERCIAL_AT = 0x40; /* @ */29var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */30var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */31var CHAR_GRAVE_ACCENT = 0x60; /* ` */32var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */33var CHAR_VERTICAL_LINE = 0x7C; /* | */34var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */3536var ESCAPE_SEQUENCES = {};3738ESCAPE_SEQUENCES[0x00] = '\\0';39ESCAPE_SEQUENCES[0x07] = '\\a';40ESCAPE_SEQUENCES[0x08] = '\\b';41ESCAPE_SEQUENCES[0x09] = '\\t';42ESCAPE_SEQUENCES[0x0A] = '\\n';43ESCAPE_SEQUENCES[0x0B] = '\\v';44ESCAPE_SEQUENCES[0x0C] = '\\f';45ESCAPE_SEQUENCES[0x0D] = '\\r';46ESCAPE_SEQUENCES[0x1B] = '\\e';47ESCAPE_SEQUENCES[0x22] = '\\"';48ESCAPE_SEQUENCES[0x5C] = '\\\\';49ESCAPE_SEQUENCES[0x85] = '\\N';50ESCAPE_SEQUENCES[0xA0] = '\\_';51ESCAPE_SEQUENCES[0x2028] = '\\L';52ESCAPE_SEQUENCES[0x2029] = '\\P';5354var DEPRECATED_BOOLEANS_SYNTAX = [55'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',56'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'57];5859function compileStyleMap(schema, map) {60var result, keys, index, length, tag, style, type;6162if (null === map) {63return {};64}6566result = {};67keys = Object.keys(map);6869for (index = 0, length = keys.length; index < length; index += 1) {70tag = keys[index];71style = String(map[tag]);7273if ('!!' === tag.slice(0, 2)) {74tag = 'tag:yaml.org,2002:' + tag.slice(2);75}7677type = schema.compiledTypeMap[tag];7879if (type && _hasOwnProperty.call(type.styleAliases, style)) {80style = type.styleAliases[style];81}8283result[tag] = style;84}8586return result;87}8889function encodeHex(character) {90var string, handle, length;9192string = character.toString(16).toUpperCase();9394if (character <= 0xFF) {95handle = 'x';96length = 2;97} else if (character <= 0xFFFF) {98handle = 'u';99length = 4;100} else if (character <= 0xFFFFFFFF) {101handle = 'U';102length = 8;103} else {104throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');105}106107return '\\' + handle + common.repeat('0', length - string.length) + string;108}109110function State(options) {111this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;112this.indent = Math.max(1, (options['indent'] || 2));113this.skipInvalid = options['skipInvalid'] || false;114this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);115this.styleMap = compileStyleMap(this.schema, options['styles'] || null);116this.sortKeys = options['sortKeys'] || false;117118this.implicitTypes = this.schema.compiledImplicit;119this.explicitTypes = this.schema.compiledExplicit;120121this.tag = null;122this.result = '';123124this.duplicates = [];125this.usedDuplicates = null;126}127128function indentString(string, spaces) {129var ind = common.repeat(' ', spaces),130position = 0,131next = -1,132result = '',133line,134length = string.length;135136while (position < length) {137next = string.indexOf('\n', position);138if (next === -1) {139line = string.slice(position);140position = length;141} else {142line = string.slice(position, next + 1);143position = next + 1;144}145if (line.length && line !== '\n') {146result += ind;147}148result += line;149}150151return result;152}153154function generateNextLine(state, level) {155return '\n' + common.repeat(' ', state.indent * level);156}157158function testImplicitResolving(state, str) {159var index, length, type;160161for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {162type = state.implicitTypes[index];163164if (type.resolve(str)) {165return true;166}167}168169return false;170}171172function StringBuilder(source) {173this.source = source;174this.result = '';175this.checkpoint = 0;176}177178StringBuilder.prototype.takeUpTo = function (position) {179var er;180181if (position < this.checkpoint) {182er = new Error('position should be > checkpoint');183er.position = position;184er.checkpoint = this.checkpoint;185throw er;186}187188this.result += this.source.slice(this.checkpoint, position);189this.checkpoint = position;190return this;191};192193StringBuilder.prototype.escapeChar = function () {194var character, esc;195196character = this.source.charCodeAt(this.checkpoint);197esc = ESCAPE_SEQUENCES[character] || encodeHex(character);198this.result += esc;199this.checkpoint += 1;200201return this;202};203204StringBuilder.prototype.finish = function () {205if (this.source.length > this.checkpoint) {206this.takeUpTo(this.source.length);207}208};209210function writeScalar(state, object, level) {211var simple, first, spaceWrap, folded, literal, single, double,212sawLineFeed, linePosition, longestLine, indent, max, character,213position, escapeSeq, hexEsc, previous, lineLength, modifier,214trailingLineBreaks, result;215216if (0 === object.length) {217state.dump = "''";218return;219}220221if (-1 !== DEPRECATED_BOOLEANS_SYNTAX.indexOf(object)) {222state.dump = "'" + object + "'";223return;224}225226simple = true;227first = object.length ? object.charCodeAt(0) : 0;228spaceWrap = (CHAR_SPACE === first ||229CHAR_SPACE === object.charCodeAt(object.length - 1));230231// Simplified check for restricted first characters232// http://www.yaml.org/spec/1.2/spec.html#ns-plain-first%28c%29233if (CHAR_MINUS === first ||234CHAR_QUESTION === first ||235CHAR_COMMERCIAL_AT === first ||236CHAR_GRAVE_ACCENT === first) {237simple = false;238}239240// can only use > and | if not wrapped in spaces.241if (spaceWrap) {242simple = false;243folded = false;244literal = false;245} else {246folded = true;247literal = true;248}249250single = true;251double = new StringBuilder(object);252253sawLineFeed = false;254linePosition = 0;255longestLine = 0;256257indent = state.indent * level;258max = 80;259if (indent < 40) {260max -= indent;261} else {262max = 40;263}264265for (position = 0; position < object.length; position++) {266character = object.charCodeAt(position);267if (simple) {268// Characters that can never appear in the simple scalar269if (!simpleChar(character)) {270simple = false;271} else {272// Still simple. If we make it all the way through like273// this, then we can just dump the string as-is.274continue;275}276}277278if (single && character === CHAR_SINGLE_QUOTE) {279single = false;280}281282escapeSeq = ESCAPE_SEQUENCES[character];283hexEsc = needsHexEscape(character);284285if (!escapeSeq && !hexEsc) {286continue;287}288289if (character !== CHAR_LINE_FEED &&290character !== CHAR_DOUBLE_QUOTE &&291character !== CHAR_SINGLE_QUOTE) {292folded = false;293literal = false;294} else if (character === CHAR_LINE_FEED) {295sawLineFeed = true;296single = false;297if (position > 0) {298previous = object.charCodeAt(position - 1);299if (previous === CHAR_SPACE) {300literal = false;301folded = false;302}303}304if (folded) {305lineLength = position - linePosition;306linePosition = position;307if (lineLength > longestLine) {308longestLine = lineLength;309}310}311}312313if (character !== CHAR_DOUBLE_QUOTE) {314single = false;315}316317double.takeUpTo(position);318double.escapeChar();319}320321if (simple && testImplicitResolving(state, object)) {322simple = false;323}324325modifier = '';326if (folded || literal) {327trailingLineBreaks = 0;328if (object.charCodeAt(object.length - 1) === CHAR_LINE_FEED) {329trailingLineBreaks += 1;330if (object.charCodeAt(object.length - 2) === CHAR_LINE_FEED) {331trailingLineBreaks += 1;332}333}334335if (trailingLineBreaks === 0) {336modifier = '-';337} else if (trailingLineBreaks === 2) {338modifier = '+';339}340}341342if (literal && longestLine < max) {343folded = false;344}345346// If it's literally one line, then don't bother with the literal.347// We may still want to do a fold, though, if it's a super long line.348if (!sawLineFeed) {349literal = false;350}351352if (simple) {353state.dump = object;354} else if (single) {355state.dump = '\'' + object + '\'';356} else if (folded) {357result = fold(object, max);358state.dump = '>' + modifier + '\n' + indentString(result, indent);359} else if (literal) {360if (!modifier) {361object = object.replace(/\n$/, '');362}363state.dump = '|' + modifier + '\n' + indentString(object, indent);364} else if (double) {365double.finish();366state.dump = '"' + double.result + '"';367} else {368throw new Error('Failed to dump scalar value');369}370371return;372}373374// The `trailing` var is a regexp match of any trailing `\n` characters.375//376// There are three cases we care about:377//378// 1. One trailing `\n` on the string. Just use `|` or `>`.379// This is the assumed default. (trailing = null)380// 2. No trailing `\n` on the string. Use `|-` or `>-` to "chomp" the end.381// 3. More than one trailing `\n` on the string. Use `|+` or `>+`.382//383// In the case of `>+`, these line breaks are *not* doubled (like the line384// breaks within the string), so it's important to only end with the exact385// same number as we started.386function fold(object, max) {387var result = '',388position = 0,389length = object.length,390trailing = /\n+$/.exec(object),391newLine;392393if (trailing) {394length = trailing.index + 1;395}396397while (position < length) {398newLine = object.indexOf('\n', position);399if (newLine > length || newLine === -1) {400if (result) {401result += '\n\n';402}403result += foldLine(object.slice(position, length), max);404position = length;405} else {406if (result) {407result += '\n\n';408}409result += foldLine(object.slice(position, newLine), max);410position = newLine + 1;411}412}413if (trailing && trailing[0] !== '\n') {414result += trailing[0];415}416417return result;418}419420function foldLine(line, max) {421if (line === '') {422return line;423}424425var foldRe = /[^\s] [^\s]/g,426result = '',427prevMatch = 0,428foldStart = 0,429match = foldRe.exec(line),430index,431foldEnd,432folded;433434while (match) {435index = match.index;436437// when we cross the max len, if the previous match would've438// been ok, use that one, and carry on. If there was no previous439// match on this fold section, then just have a long line.440if (index - foldStart > max) {441if (prevMatch !== foldStart) {442foldEnd = prevMatch;443} else {444foldEnd = index;445}446447if (result) {448result += '\n';449}450folded = line.slice(foldStart, foldEnd);451result += folded;452foldStart = foldEnd + 1;453}454prevMatch = index + 1;455match = foldRe.exec(line);456}457458if (result) {459result += '\n';460}461462// if we end up with one last word at the end, then the last bit might463// be slightly bigger than we wanted, because we exited out of the loop.464if (foldStart !== prevMatch && line.length - foldStart > max) {465result += line.slice(foldStart, prevMatch) + '\n' +466line.slice(prevMatch + 1);467} else {468result += line.slice(foldStart);469}470471return result;472}473474// Returns true if character can be found in a simple scalar475function simpleChar(character) {476return CHAR_TAB !== character &&477CHAR_LINE_FEED !== character &&478CHAR_CARRIAGE_RETURN !== character &&479CHAR_COMMA !== character &&480CHAR_LEFT_SQUARE_BRACKET !== character &&481CHAR_RIGHT_SQUARE_BRACKET !== character &&482CHAR_LEFT_CURLY_BRACKET !== character &&483CHAR_RIGHT_CURLY_BRACKET !== character &&484CHAR_SHARP !== character &&485CHAR_AMPERSAND !== character &&486CHAR_ASTERISK !== character &&487CHAR_EXCLAMATION !== character &&488CHAR_VERTICAL_LINE !== character &&489CHAR_GREATER_THAN !== character &&490CHAR_SINGLE_QUOTE !== character &&491CHAR_DOUBLE_QUOTE !== character &&492CHAR_PERCENT !== character &&493CHAR_COLON !== character &&494!ESCAPE_SEQUENCES[character] &&495!needsHexEscape(character);496}497498// Returns true if the character code needs to be escaped.499function needsHexEscape(character) {500return !((0x00020 <= character && character <= 0x00007E) ||501(0x00085 === character) ||502(0x000A0 <= character && character <= 0x00D7FF) ||503(0x0E000 <= character && character <= 0x00FFFD) ||504(0x10000 <= character && character <= 0x10FFFF));505}506507function writeFlowSequence(state, level, object) {508var _result = '',509_tag = state.tag,510index,511length;512513for (index = 0, length = object.length; index < length; index += 1) {514// Write only valid elements.515if (writeNode(state, level, object[index], false, false)) {516if (0 !== index) {517_result += ', ';518}519_result += state.dump;520}521}522523state.tag = _tag;524state.dump = '[' + _result + ']';525}526527function writeBlockSequence(state, level, object, compact) {528var _result = '',529_tag = state.tag,530index,531length;532533for (index = 0, length = object.length; index < length; index += 1) {534// Write only valid elements.535if (writeNode(state, level + 1, object[index], true, true)) {536if (!compact || 0 !== index) {537_result += generateNextLine(state, level);538}539_result += '- ' + state.dump;540}541}542543state.tag = _tag;544state.dump = _result || '[]'; // Empty sequence if no valid values.545}546547function writeFlowMapping(state, level, object) {548var _result = '',549_tag = state.tag,550objectKeyList = Object.keys(object),551index,552length,553objectKey,554objectValue,555pairBuffer;556557for (index = 0, length = objectKeyList.length; index < length; index += 1) {558pairBuffer = '';559560if (0 !== index) {561pairBuffer += ', ';562}563564objectKey = objectKeyList[index];565objectValue = object[objectKey];566567if (!writeNode(state, level, objectKey, false, false)) {568continue; // Skip this pair because of invalid key;569}570571if (state.dump.length > 1024) {572pairBuffer += '? ';573}574575pairBuffer += state.dump + ': ';576577if (!writeNode(state, level, objectValue, false, false)) {578continue; // Skip this pair because of invalid value.579}580581pairBuffer += state.dump;582583// Both key and value are valid.584_result += pairBuffer;585}586587state.tag = _tag;588state.dump = '{' + _result + '}';589}590591function writeBlockMapping(state, level, object, compact) {592var _result = '',593_tag = state.tag,594objectKeyList = Object.keys(object),595index,596length,597objectKey,598objectValue,599explicitPair,600pairBuffer;601602// Allow sorting keys so that the output file is deterministic603if (state.sortKeys === true) {604// Default sorting605objectKeyList.sort();606} else if (typeof state.sortKeys === 'function') {607// Custom sort function608objectKeyList.sort(state.sortKeys);609} else if (state.sortKeys) {610// Something is wrong611throw new YAMLException('sortKeys must be a boolean or a function');612}613614for (index = 0, length = objectKeyList.length; index < length; index += 1) {615pairBuffer = '';616617if (!compact || 0 !== index) {618pairBuffer += generateNextLine(state, level);619}620621objectKey = objectKeyList[index];622objectValue = object[objectKey];623624if (!writeNode(state, level + 1, objectKey, true, true)) {625continue; // Skip this pair because of invalid key.626}627628explicitPair = (null !== state.tag && '?' !== state.tag) ||629(state.dump && state.dump.length > 1024);630631if (explicitPair) {632if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {633pairBuffer += '?';634} else {635pairBuffer += '? ';636}637}638639pairBuffer += state.dump;640641if (explicitPair) {642pairBuffer += generateNextLine(state, level);643}644645if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {646continue; // Skip this pair because of invalid value.647}648649if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {650pairBuffer += ':';651} else {652pairBuffer += ': ';653}654655pairBuffer += state.dump;656657// Both key and value are valid.658_result += pairBuffer;659}660661state.tag = _tag;662state.dump = _result || '{}'; // Empty mapping if no valid pairs.663}664665function detectType(state, object, explicit) {666var _result, typeList, index, length, type, style;667668typeList = explicit ? state.explicitTypes : state.implicitTypes;669670for (index = 0, length = typeList.length; index < length; index += 1) {671type = typeList[index];672673if ((type.instanceOf || type.predicate) &&674(!type.instanceOf || (('object' === typeof object) && (object instanceof type.instanceOf))) &&675(!type.predicate || type.predicate(object))) {676677state.tag = explicit ? type.tag : '?';678679if (type.represent) {680style = state.styleMap[type.tag] || type.defaultStyle;681682if ('[object Function]' === _toString.call(type.represent)) {683_result = type.represent(object, style);684} else if (_hasOwnProperty.call(type.represent, style)) {685_result = type.represent[style](object, style);686} else {687throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');688}689690state.dump = _result;691}692693return true;694}695}696697return false;698}699700// Serializes `object` and writes it to global `result`.701// Returns true on success, or false on invalid object.702//703function writeNode(state, level, object, block, compact) {704state.tag = null;705state.dump = object;706707if (!detectType(state, object, false)) {708detectType(state, object, true);709}710711var type = _toString.call(state.dump);712713if (block) {714block = (0 > state.flowLevel || state.flowLevel > level);715}716717if ((null !== state.tag && '?' !== state.tag) || (2 !== state.indent && level > 0)) {718compact = false;719}720721var objectOrArray = '[object Object]' === type || '[object Array]' === type,722duplicateIndex,723duplicate;724725if (objectOrArray) {726duplicateIndex = state.duplicates.indexOf(object);727duplicate = duplicateIndex !== -1;728}729730if (duplicate && state.usedDuplicates[duplicateIndex]) {731state.dump = '*ref_' + duplicateIndex;732} else {733if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {734state.usedDuplicates[duplicateIndex] = true;735}736if ('[object Object]' === type) {737if (block && (0 !== Object.keys(state.dump).length)) {738writeBlockMapping(state, level, state.dump, compact);739if (duplicate) {740state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump;741}742} else {743writeFlowMapping(state, level, state.dump);744if (duplicate) {745state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;746}747}748} else if ('[object Array]' === type) {749if (block && (0 !== state.dump.length)) {750writeBlockSequence(state, level, state.dump, compact);751if (duplicate) {752state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump;753}754} else {755writeFlowSequence(state, level, state.dump);756if (duplicate) {757state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;758}759}760} else if ('[object String]' === type) {761if ('?' !== state.tag) {762writeScalar(state, state.dump, level);763}764} else {765if (state.skipInvalid) {766return false;767}768throw new YAMLException('unacceptable kind of an object to dump ' + type);769}770771if (null !== state.tag && '?' !== state.tag) {772state.dump = '!<' + state.tag + '> ' + state.dump;773}774}775776return true;777}778779function getDuplicateReferences(object, state) {780var objects = [],781duplicatesIndexes = [],782index,783length;784785inspectNode(object, objects, duplicatesIndexes);786787for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {788state.duplicates.push(objects[duplicatesIndexes[index]]);789}790state.usedDuplicates = new Array(length);791}792793function inspectNode(object, objects, duplicatesIndexes) {794var type = _toString.call(object),795objectKeyList,796index,797length;798799if (null !== object && 'object' === typeof object) {800index = objects.indexOf(object);801if (-1 !== index) {802if (-1 === duplicatesIndexes.indexOf(index)) {803duplicatesIndexes.push(index);804}805} else {806objects.push(object);807808if (Array.isArray(object)) {809for (index = 0, length = object.length; index < length; index += 1) {810inspectNode(object[index], objects, duplicatesIndexes);811}812} else {813objectKeyList = Object.keys(object);814815for (index = 0, length = objectKeyList.length; index < length; index += 1) {816inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);817}818}819}820}821}822823function dump(input, options) {824options = options || {};825826var state = new State(options);827828getDuplicateReferences(input, state);829830if (writeNode(state, 0, input, true, true)) {831return state.dump + '\n';832}833return '';834}835836function safeDump(input, options) {837return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));838}839840module.exports.dump = dump;841module.exports.safeDump = safeDump;842843844