3 Object.defineProperty(exports, '__esModule', { value: true });
5 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
7 var os = _interopDefault(require('os'));
8 var path = _interopDefault(require('path'));
9 var util = _interopDefault(require('util'));
10 var module$1 = _interopDefault(require('module'));
11 var fs = _interopDefault(require('fs'));
12 var stream = _interopDefault(require('stream'));
14 function _classCallCheck(instance, Constructor) {
15 if (!(instance instanceof Constructor)) {
16 throw new TypeError("Cannot call a class as a function");
20 function _defineProperties(target, props) {
21 for (var i = 0; i < props.length; i++) {
22 var descriptor = props[i];
23 descriptor.enumerable = descriptor.enumerable || false;
24 descriptor.configurable = true;
25 if ("value" in descriptor) descriptor.writable = true;
26 Object.defineProperty(target, descriptor.key, descriptor);
30 function _createClass(Constructor, protoProps, staticProps) {
31 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
32 if (staticProps) _defineProperties(Constructor, staticProps);
36 function _inherits(subClass, superClass) {
37 if (typeof superClass !== "function" && superClass !== null) {
38 throw new TypeError("Super expression must either be null or a function");
41 subClass.prototype = Object.create(superClass && superClass.prototype, {
48 if (superClass) _setPrototypeOf(subClass, superClass);
51 function _getPrototypeOf(o) {
52 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
53 return o.__proto__ || Object.getPrototypeOf(o);
55 return _getPrototypeOf(o);
58 function _setPrototypeOf(o, p) {
59 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
64 return _setPrototypeOf(o, p);
67 function isNativeReflectConstruct() {
68 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
69 if (Reflect.construct.sham) return false;
70 if (typeof Proxy === "function") return true;
73 Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
80 function _construct(Parent, args, Class) {
81 if (isNativeReflectConstruct()) {
82 _construct = Reflect.construct;
84 _construct = function _construct(Parent, args, Class) {
86 a.push.apply(a, args);
87 var Constructor = Function.bind.apply(Parent, a);
88 var instance = new Constructor();
89 if (Class) _setPrototypeOf(instance, Class.prototype);
94 return _construct.apply(null, arguments);
97 function _isNativeFunction(fn) {
98 return Function.toString.call(fn).indexOf("[native code]") !== -1;
101 function _wrapNativeSuper(Class) {
102 var _cache = typeof Map === "function" ? new Map() : undefined;
104 _wrapNativeSuper = function _wrapNativeSuper(Class) {
105 if (Class === null || !_isNativeFunction(Class)) return Class;
107 if (typeof Class !== "function") {
108 throw new TypeError("Super expression must either be null or a function");
111 if (typeof _cache !== "undefined") {
112 if (_cache.has(Class)) return _cache.get(Class);
114 _cache.set(Class, Wrapper);
118 return _construct(Class, arguments, _getPrototypeOf(this).constructor);
121 Wrapper.prototype = Object.create(Class.prototype, {
129 return _setPrototypeOf(Wrapper, Class);
132 return _wrapNativeSuper(Class);
135 function _assertThisInitialized(self) {
136 if (self === void 0) {
137 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
143 function _possibleConstructorReturn(self, call) {
144 if (call && (typeof call === "object" || typeof call === "function")) {
148 return _assertThisInitialized(self);
151 var isArrayish = function isArrayish(obj) {
156 return obj instanceof Array || Array.isArray(obj) || obj.length >= 0 && obj.splice instanceof Function;
159 var errorEx = function errorEx(name, properties) {
160 if (!name || name.constructor !== String) {
161 properties = name || {};
165 var errorExError = function ErrorEXError(message) {
167 return new ErrorEXError(message);
170 message = message instanceof Error ? message.message : message || this.message;
171 Error.call(this, message);
172 Error.captureStackTrace(this, errorExError);
174 Object.defineProperty(this, 'message', {
177 get: function get() {
178 var newMessage = message.split(/\r?\n/g);
180 for (var key in properties) {
181 if (!properties.hasOwnProperty(key)) {
185 var modifier = properties[key];
187 if ('message' in modifier) {
188 newMessage = modifier.message(this[key], newMessage) || newMessage;
190 if (!isArrayish(newMessage)) {
191 newMessage = [newMessage];
196 return newMessage.join('\n');
198 set: function set(v) {
202 var overwrittenStack = null;
203 var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
204 var stackGetter = stackDescriptor.get;
205 var stackValue = stackDescriptor.value;
206 delete stackDescriptor.value;
207 delete stackDescriptor.writable;
209 stackDescriptor.set = function (newstack) {
210 overwrittenStack = newstack;
213 stackDescriptor.get = function () {
214 var stack = (overwrittenStack || (stackGetter ? stackGetter.call(this) : stackValue)).split(/\r?\n+/g); // starting in Node 7, the stack builder caches the message.
217 if (!overwrittenStack) {
218 stack[0] = this.name + ': ' + this.message;
223 for (var key in properties) {
224 if (!properties.hasOwnProperty(key)) {
228 var modifier = properties[key];
230 if ('line' in modifier) {
231 var line = modifier.line(this[key]);
234 stack.splice(lineCount++, 0, ' ' + line);
238 if ('stack' in modifier) {
239 modifier.stack(this[key], stack);
243 return stack.join('\n');
246 Object.defineProperty(this, 'stack', stackDescriptor);
249 if (Object.setPrototypeOf) {
250 Object.setPrototypeOf(errorExError.prototype, Error.prototype);
251 Object.setPrototypeOf(errorExError, Error);
253 util.inherits(errorExError, Error);
259 errorEx.append = function (str, def) {
261 message: function message(v, _message) {
265 _message[0] += ' ' + str.replace('%s', v.toString());
273 errorEx.line = function (str, def) {
275 line: function line(v) {
279 return str.replace('%s', v.toString());
287 var errorEx_1 = errorEx;
289 var jsonParseBetterErrors = parseJson;
291 function parseJson(txt, reviver, context) {
292 context = context || 20;
295 return JSON.parse(txt, reviver);
297 if (typeof txt !== 'string') {
298 var isEmptyArray = Array.isArray(txt) && txt.length === 0;
299 var errorMessage = 'Cannot parse ' + (isEmptyArray ? 'an empty array' : String(txt));
300 throw new TypeError(errorMessage);
303 var syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i);
304 var errIdx = syntaxErr ? +syntaxErr[1] : e.message.match(/^Unexpected end of JSON.*/i) ? txt.length - 1 : null;
306 if (errIdx != null) {
307 var start = errIdx <= context ? 0 : errIdx - context;
308 var end = errIdx + context >= txt.length ? txt.length : errIdx + context;
309 e.message += ` while parsing near '${start === 0 ? '' : '...'}${txt.slice(start, end)}${end === txt.length ? '' : '...'}'`;
311 e.message += ` while parsing '${txt.slice(0, context * 2)}'`;
318 var JSONError = errorEx_1('JSONError', {
319 fileName: errorEx_1.append('in %s')
322 var parseJson$1 = function parseJson(input, reviver, filename) {
323 if (typeof reviver === 'string') {
330 return JSON.parse(input, reviver);
332 jsonParseBetterErrors(input, reviver);
336 err.message = err.message.replace(/\n/g, '');
337 var jsonErr = new JSONError(err);
340 jsonErr.fileName = filename;
347 function isNothing(subject) {
348 return typeof subject === 'undefined' || subject === null;
351 function isObject(subject) {
352 return typeof subject === 'object' && subject !== null;
355 function toArray(sequence) {
356 if (Array.isArray(sequence)) return sequence;else if (isNothing(sequence)) return [];
360 function extend(target, source) {
361 var index, length, key, sourceKeys;
364 sourceKeys = Object.keys(source);
366 for (index = 0, length = sourceKeys.length; index < length; index += 1) {
367 key = sourceKeys[index];
368 target[key] = source[key];
375 function repeat(string, count) {
379 for (cycle = 0; cycle < count; cycle += 1) {
386 function isNegativeZero(number) {
387 return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
390 var isNothing_1 = isNothing;
391 var isObject_1 = isObject;
392 var toArray_1 = toArray;
393 var repeat_1 = repeat;
394 var isNegativeZero_1 = isNegativeZero;
395 var extend_1 = extend;
397 isNothing: isNothing_1,
398 isObject: isObject_1,
401 isNegativeZero: isNegativeZero_1,
405 // YAML error class. http://stackoverflow.com/questions/8458984
407 function YAMLException(reason, mark) {
410 this.name = 'YAMLException';
411 this.reason = reason;
413 this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); // Include stack trace in error object
415 if (Error.captureStackTrace) {
417 Error.captureStackTrace(this, this.constructor);
419 // FF, IE 10+ and Safari 6+. Fallback for others
420 this.stack = new Error().stack || '';
422 } // Inherit from Error
425 YAMLException.prototype = Object.create(Error.prototype);
426 YAMLException.prototype.constructor = YAMLException;
428 YAMLException.prototype.toString = function toString(compact) {
429 var result = this.name + ': ';
430 result += this.reason || '(unknown reason)';
432 if (!compact && this.mark) {
433 result += ' ' + this.mark.toString();
439 var exception = YAMLException;
441 function Mark(name, buffer, position, line, column) {
443 this.buffer = buffer;
444 this.position = position;
446 this.column = column;
449 Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
450 var head, start, tail, end, snippet;
451 if (!this.buffer) return null;
452 indent = indent || 4;
453 maxLength = maxLength || 75;
455 start = this.position;
457 while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
460 if (this.position - start > maxLength / 2 - 1) {
470 while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
473 if (end - this.position > maxLength / 2 - 1) {
480 snippet = this.buffer.slice(start, end);
481 return common.repeat(' ', indent) + head + snippet + tail + '\n' + common.repeat(' ', indent + this.position - start + head.length) + '^';
484 Mark.prototype.toString = function toString(compact) {
489 where += 'in "' + this.name + '" ';
492 where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
495 snippet = this.getSnippet();
498 where += ':\n' + snippet;
507 var TYPE_CONSTRUCTOR_OPTIONS = ['kind', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'defaultStyle', 'styleAliases'];
508 var YAML_NODE_KINDS = ['scalar', 'sequence', 'mapping'];
510 function compileStyleAliases(map) {
514 Object.keys(map).forEach(function (style) {
515 map[style].forEach(function (alias) {
516 result[String(alias)] = style;
524 function Type(tag, options) {
525 options = options || {};
526 Object.keys(options).forEach(function (name) {
527 if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
528 throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
530 }); // TODO: Add tag format check.
533 this.kind = options['kind'] || null;
535 this.resolve = options['resolve'] || function () {
539 this.construct = options['construct'] || function (data) {
543 this.instanceOf = options['instanceOf'] || null;
544 this.predicate = options['predicate'] || null;
545 this.represent = options['represent'] || null;
546 this.defaultStyle = options['defaultStyle'] || null;
547 this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
549 if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
550 throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
556 /*eslint-disable max-len*/
559 function compileList(schema, name, result) {
561 schema.include.forEach(function (includedSchema) {
562 result = compileList(includedSchema, name, result);
564 schema[name].forEach(function (currentType) {
565 result.forEach(function (previousType, previousIndex) {
566 if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
567 exclude.push(previousIndex);
570 result.push(currentType);
572 return result.filter(function (type, index) {
573 return exclude.indexOf(index) === -1;
577 function compileMap()
589 function collectType(type) {
590 result[type.kind][type.tag] = result['fallback'][type.tag] = type;
593 for (index = 0, length = arguments.length; index < length; index += 1) {
594 arguments[index].forEach(collectType);
600 function Schema(definition) {
601 this.include = definition.include || [];
602 this.implicit = definition.implicit || [];
603 this.explicit = definition.explicit || [];
604 this.implicit.forEach(function (type) {
605 if (type.loadKind && type.loadKind !== 'scalar') {
606 throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
609 this.compiledImplicit = compileList(this, 'implicit', []);
610 this.compiledExplicit = compileList(this, 'explicit', []);
611 this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
614 Schema.DEFAULT = null;
616 Schema.create = function createSchema() {
619 switch (arguments.length) {
621 schemas = Schema.DEFAULT;
622 types = arguments[0];
626 schemas = arguments[0];
627 types = arguments[1];
631 throw new exception('Wrong number of arguments for Schema.create function');
634 schemas = common.toArray(schemas);
635 types = common.toArray(types);
637 if (!schemas.every(function (schema) {
638 return schema instanceof Schema;
640 throw new exception('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
643 if (!types.every(function (type$1) {
644 return type$1 instanceof type;
646 throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
657 var str = new type('tag:yaml.org,2002:str', {
659 construct: function construct(data) {
660 return data !== null ? data : '';
664 var seq = new type('tag:yaml.org,2002:seq', {
666 construct: function construct(data) {
667 return data !== null ? data : [];
671 var map = new type('tag:yaml.org,2002:map', {
673 construct: function construct(data) {
674 return data !== null ? data : {};
678 var failsafe = new schema({
679 explicit: [str, seq, map]
682 function resolveYamlNull(data) {
683 if (data === null) return true;
684 var max = data.length;
685 return max === 1 && data === '~' || max === 4 && (data === 'null' || data === 'Null' || data === 'NULL');
688 function constructYamlNull() {
692 function isNull(object) {
693 return object === null;
696 var _null = new type('tag:yaml.org,2002:null', {
698 resolve: resolveYamlNull,
699 construct: constructYamlNull,
702 canonical: function canonical() {
705 lowercase: function lowercase() {
708 uppercase: function uppercase() {
711 camelcase: function camelcase() {
715 defaultStyle: 'lowercase'
718 function resolveYamlBoolean(data) {
719 if (data === null) return false;
720 var max = data.length;
721 return max === 4 && (data === 'true' || data === 'True' || data === 'TRUE') || max === 5 && (data === 'false' || data === 'False' || data === 'FALSE');
724 function constructYamlBoolean(data) {
725 return data === 'true' || data === 'True' || data === 'TRUE';
728 function isBoolean(object) {
729 return Object.prototype.toString.call(object) === '[object Boolean]';
732 var bool = new type('tag:yaml.org,2002:bool', {
734 resolve: resolveYamlBoolean,
735 construct: constructYamlBoolean,
736 predicate: isBoolean,
738 lowercase: function lowercase(object) {
739 return object ? 'true' : 'false';
741 uppercase: function uppercase(object) {
742 return object ? 'TRUE' : 'FALSE';
744 camelcase: function camelcase(object) {
745 return object ? 'True' : 'False';
748 defaultStyle: 'lowercase'
751 function isHexCode(c) {
767 function isOctCode(c) {
775 function isDecCode(c) {
783 function resolveYamlInteger(data) {
784 if (data === null) return false;
785 var max = data.length,
789 if (!max) return false;
790 ch = data[index]; // sign
792 if (ch === '-' || ch === '+') {
798 if (index + 1 === max) return true;
799 ch = data[++index]; // base 2, base 8, base 16
805 for (; index < max; index++) {
807 if (ch === '_') continue;
808 if (ch !== '0' && ch !== '1') return false;
812 return hasDigits && ch !== '_';
819 for (; index < max; index++) {
821 if (ch === '_') continue;
822 if (!isHexCode(data.charCodeAt(index))) return false;
826 return hasDigits && ch !== '_';
830 for (; index < max; index++) {
832 if (ch === '_') continue;
833 if (!isOctCode(data.charCodeAt(index))) return false;
837 return hasDigits && ch !== '_';
838 } // base 10 (except 0) or base 60
839 // value should not start with `_`;
842 if (ch === '_') return false;
844 for (; index < max; index++) {
846 if (ch === '_') continue;
847 if (ch === ':') break;
849 if (!isDecCode(data.charCodeAt(index))) {
854 } // Should have digits and should not end with `_`
857 if (!hasDigits || ch === '_') return false; // if !base60 - done;
859 if (ch !== ':') return true; // base60 almost not used, no needs to optimize
861 return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
864 function constructYamlInteger(data) {
871 if (value.indexOf('_') !== -1) {
872 value = value.replace(/_/g, '');
877 if (ch === '-' || ch === '+') {
878 if (ch === '-') sign = -1;
879 value = value.slice(1);
883 if (value === '0') return 0;
886 if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
887 if (value[1] === 'x') return sign * parseInt(value, 16);
888 return sign * parseInt(value, 8);
891 if (value.indexOf(':') !== -1) {
892 value.split(':').forEach(function (v) {
893 digits.unshift(parseInt(v, 10));
897 digits.forEach(function (d) {
904 return sign * parseInt(value, 10);
907 function isInteger(object) {
908 return Object.prototype.toString.call(object) === '[object Number]' && object % 1 === 0 && !common.isNegativeZero(object);
911 var int_1 = new type('tag:yaml.org,2002:int', {
913 resolve: resolveYamlInteger,
914 construct: constructYamlInteger,
915 predicate: isInteger,
917 binary: function binary(obj) {
918 return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1);
920 octal: function octal(obj) {
921 return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1);
923 decimal: function decimal(obj) {
924 return obj.toString(10);
927 /* eslint-disable max-len */
928 hexadecimal: function hexadecimal(obj) {
929 return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1);
932 defaultStyle: 'decimal',
936 decimal: [10, 'dec'],
937 hexadecimal: [16, 'hex']
941 var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers
942 '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2
943 // special case, seems not from spec
944 '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + // 20:59
945 '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + // .inf
946 '|[-+]?\\.(?:inf|Inf|INF)' + // .nan
947 '|\\.(?:nan|NaN|NAN))$');
949 function resolveYamlFloat(data) {
950 if (data === null) return false;
952 if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`
953 // Probably should update regexp & check speed
954 data[data.length - 1] === '_') {
961 function constructYamlFloat(data) {
962 var value, sign, base, digits;
963 value = data.replace(/_/g, '').toLowerCase();
964 sign = value[0] === '-' ? -1 : 1;
967 if ('+-'.indexOf(value[0]) >= 0) {
968 value = value.slice(1);
971 if (value === '.inf') {
972 return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
973 } else if (value === '.nan') {
975 } else if (value.indexOf(':') >= 0) {
976 value.split(':').forEach(function (v) {
977 digits.unshift(parseFloat(v, 10));
981 digits.forEach(function (d) {
988 return sign * parseFloat(value, 10);
991 var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
993 function representYamlFloat(object, style) {
1007 } else if (Number.POSITIVE_INFINITY === object) {
1018 } else if (Number.NEGATIVE_INFINITY === object) {
1029 } else if (common.isNegativeZero(object)) {
1033 res = object.toString(10); // JS stringifier can build scientific format without dots: 5e-100,
1034 // while YAML requres dot: 5.e-100. Fix it with simple hack
1036 return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
1039 function isFloat(object) {
1040 return Object.prototype.toString.call(object) === '[object Number]' && (object % 1 !== 0 || common.isNegativeZero(object));
1043 var float_1 = new type('tag:yaml.org,2002:float', {
1045 resolve: resolveYamlFloat,
1046 construct: constructYamlFloat,
1048 represent: representYamlFloat,
1049 defaultStyle: 'lowercase'
1052 var json = new schema({
1053 include: [failsafe],
1054 implicit: [_null, bool, int_1, float_1]
1057 var core = new schema({
1061 var YAML_DATE_REGEXP = new RegExp('^([0-9][0-9][0-9][0-9])' + // [1] year
1062 '-([0-9][0-9])' + // [2] month
1063 '-([0-9][0-9])$'); // [3] day
1065 var YAML_TIMESTAMP_REGEXP = new RegExp('^([0-9][0-9][0-9][0-9])' + // [1] year
1066 '-([0-9][0-9]?)' + // [2] month
1067 '-([0-9][0-9]?)' + // [3] day
1068 '(?:[Tt]|[ \\t]+)' + // ...
1069 '([0-9][0-9]?)' + // [4] hour
1070 ':([0-9][0-9])' + // [5] minute
1071 ':([0-9][0-9])' + // [6] second
1072 '(?:\\.([0-9]*))?' + // [7] fraction
1073 '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
1074 '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
1076 function resolveYamlTimestamp(data) {
1077 if (data === null) return false;
1078 if (YAML_DATE_REGEXP.exec(data) !== null) return true;
1079 if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
1083 function constructYamlTimestamp(data) {
1096 match = YAML_DATE_REGEXP.exec(data);
1097 if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
1098 if (match === null) throw new Error('Date resolve error'); // match: [1] year [2] month [3] day
1101 month = +match[2] - 1; // JS month starts with 0
1107 return new Date(Date.UTC(year, month, day));
1108 } // match: [4] hour [5] minute [6] second [7] fraction
1116 fraction = match[7].slice(0, 3);
1118 while (fraction.length < 3) {
1123 fraction = +fraction;
1124 } // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
1128 tz_hour = +match[10];
1129 tz_minute = +(match[11] || 0);
1130 delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
1132 if (match[9] === '-') delta = -delta;
1135 date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
1136 if (delta) date.setTime(date.getTime() - delta);
1140 function representYamlTimestamp(object
1143 return object.toISOString();
1146 var timestamp = new type('tag:yaml.org,2002:timestamp', {
1148 resolve: resolveYamlTimestamp,
1149 construct: constructYamlTimestamp,
1151 represent: representYamlTimestamp
1154 function resolveYamlMerge(data) {
1155 return data === '<<' || data === null;
1158 var merge = new type('tag:yaml.org,2002:merge', {
1160 resolve: resolveYamlMerge
1163 function commonjsRequire () {
1164 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
1167 function createCommonjsModule(fn, module) {
1168 return module = { exports: {} }, fn(module, module.exports), module.exports;
1171 function getCjsExportFromNamespace (n) {
1172 return n && n['default'] || n;
1175 /*eslint-disable no-bitwise*/
1181 // A trick for browserified version, to not include `Buffer` shim
1182 var _require = commonjsRequire;
1183 NodeBuffer = _require('buffer').Buffer;
1184 } catch (__) {} // [ 64, 65, 66 ] -> [ padding, CR, LF ]
1187 var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
1189 function resolveYamlBinary(data) {
1190 if (data === null) return false;
1195 map = BASE64_MAP; // Convert one by one.
1197 for (idx = 0; idx < max; idx++) {
1198 code = map.indexOf(data.charAt(idx)); // Skip CR/LF
1200 if (code > 64) continue; // Fail on illegal characters
1202 if (code < 0) return false;
1204 } // If there are any bits left, source was corrupted
1207 return bitlen % 8 === 0;
1210 function constructYamlBinary(data) {
1213 input = data.replace(/[\r\n=]/g, ''),
1214 // remove CR/LF & padding to simplify scan
1218 result = []; // Collect by 6*4 bits (3 bytes)
1220 for (idx = 0; idx < max; idx++) {
1221 if (idx % 4 === 0 && idx) {
1222 result.push(bits >> 16 & 0xFF);
1223 result.push(bits >> 8 & 0xFF);
1224 result.push(bits & 0xFF);
1227 bits = bits << 6 | map.indexOf(input.charAt(idx));
1231 tailbits = max % 4 * 6;
1233 if (tailbits === 0) {
1234 result.push(bits >> 16 & 0xFF);
1235 result.push(bits >> 8 & 0xFF);
1236 result.push(bits & 0xFF);
1237 } else if (tailbits === 18) {
1238 result.push(bits >> 10 & 0xFF);
1239 result.push(bits >> 2 & 0xFF);
1240 } else if (tailbits === 12) {
1241 result.push(bits >> 4 & 0xFF);
1242 } // Wrap into Buffer for NodeJS and leave Array for browser
1246 // Support node 6.+ Buffer API when available
1247 return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
1253 function representYamlBinary(object
1260 max = object.length,
1261 map = BASE64_MAP; // Convert every three bytes to 4 ASCII characters.
1263 for (idx = 0; idx < max; idx++) {
1264 if (idx % 3 === 0 && idx) {
1265 result += map[bits >> 18 & 0x3F];
1266 result += map[bits >> 12 & 0x3F];
1267 result += map[bits >> 6 & 0x3F];
1268 result += map[bits & 0x3F];
1271 bits = (bits << 8) + object[idx];
1278 result += map[bits >> 18 & 0x3F];
1279 result += map[bits >> 12 & 0x3F];
1280 result += map[bits >> 6 & 0x3F];
1281 result += map[bits & 0x3F];
1282 } else if (tail === 2) {
1283 result += map[bits >> 10 & 0x3F];
1284 result += map[bits >> 4 & 0x3F];
1285 result += map[bits << 2 & 0x3F];
1287 } else if (tail === 1) {
1288 result += map[bits >> 2 & 0x3F];
1289 result += map[bits << 4 & 0x3F];
1297 function isBinary(object) {
1298 return NodeBuffer && NodeBuffer.isBuffer(object);
1301 var binary = new type('tag:yaml.org,2002:binary', {
1303 resolve: resolveYamlBinary,
1304 construct: constructYamlBinary,
1305 predicate: isBinary,
1306 represent: representYamlBinary
1309 var _hasOwnProperty = Object.prototype.hasOwnProperty;
1310 var _toString = Object.prototype.toString;
1312 function resolveYamlOmap(data) {
1313 if (data === null) return true;
1314 var objectKeys = [],
1322 for (index = 0, length = object.length; index < length; index += 1) {
1323 pair = object[index];
1325 if (_toString.call(pair) !== '[object Object]') return false;
1327 for (pairKey in pair) {
1328 if (_hasOwnProperty.call(pair, pairKey)) {
1329 if (!pairHasKey) pairHasKey = true;else return false;
1333 if (!pairHasKey) return false;
1334 if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);else return false;
1340 function constructYamlOmap(data) {
1341 return data !== null ? data : [];
1344 var omap = new type('tag:yaml.org,2002:omap', {
1346 resolve: resolveYamlOmap,
1347 construct: constructYamlOmap
1350 var _toString$1 = Object.prototype.toString;
1352 function resolveYamlPairs(data) {
1353 if (data === null) return true;
1360 result = new Array(object.length);
1362 for (index = 0, length = object.length; index < length; index += 1) {
1363 pair = object[index];
1364 if (_toString$1.call(pair) !== '[object Object]') return false;
1365 keys = Object.keys(pair);
1366 if (keys.length !== 1) return false;
1367 result[index] = [keys[0], pair[keys[0]]];
1373 function constructYamlPairs(data) {
1374 if (data === null) return [];
1381 result = new Array(object.length);
1383 for (index = 0, length = object.length; index < length; index += 1) {
1384 pair = object[index];
1385 keys = Object.keys(pair);
1386 result[index] = [keys[0], pair[keys[0]]];
1392 var pairs = new type('tag:yaml.org,2002:pairs', {
1394 resolve: resolveYamlPairs,
1395 construct: constructYamlPairs
1398 var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
1400 function resolveYamlSet(data) {
1401 if (data === null) return true;
1405 for (key in object) {
1406 if (_hasOwnProperty$1.call(object, key)) {
1407 if (object[key] !== null) return false;
1414 function constructYamlSet(data) {
1415 return data !== null ? data : {};
1418 var set = new type('tag:yaml.org,2002:set', {
1420 resolve: resolveYamlSet,
1421 construct: constructYamlSet
1424 var default_safe = new schema({
1426 implicit: [timestamp, merge],
1427 explicit: [binary, omap, pairs, set]
1430 function resolveJavascriptUndefined() {
1434 function constructJavascriptUndefined() {
1435 /*eslint-disable no-undefined*/
1439 function representJavascriptUndefined() {
1443 function isUndefined(object) {
1444 return typeof object === 'undefined';
1447 var _undefined = new type('tag:yaml.org,2002:js/undefined', {
1449 resolve: resolveJavascriptUndefined,
1450 construct: constructJavascriptUndefined,
1451 predicate: isUndefined,
1452 represent: representJavascriptUndefined
1455 function resolveJavascriptRegExp(data) {
1456 if (data === null) return false;
1457 if (data.length === 0) return false;
1459 tail = /\/([gim]*)$/.exec(data),
1460 modifiers = ''; // if regexp starts with '/' it can have modifiers and must be properly closed
1461 // `/foo/gim` - modifiers tail can be maximum 3 chars
1463 if (regexp[0] === '/') {
1464 if (tail) modifiers = tail[1];
1465 if (modifiers.length > 3) return false; // if expression starts with /, is should be properly terminated
1467 if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
1473 function constructJavascriptRegExp(data) {
1475 tail = /\/([gim]*)$/.exec(data),
1476 modifiers = ''; // `/foo/gim` - tail can be maximum 4 chars
1478 if (regexp[0] === '/') {
1479 if (tail) modifiers = tail[1];
1480 regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
1483 return new RegExp(regexp, modifiers);
1486 function representJavascriptRegExp(object
1489 var result = '/' + object.source + '/';
1490 if (object.global) result += 'g';
1491 if (object.multiline) result += 'm';
1492 if (object.ignoreCase) result += 'i';
1496 function isRegExp(object) {
1497 return Object.prototype.toString.call(object) === '[object RegExp]';
1500 var regexp = new type('tag:yaml.org,2002:js/regexp', {
1502 resolve: resolveJavascriptRegExp,
1503 construct: constructJavascriptRegExp,
1504 predicate: isRegExp,
1505 represent: representJavascriptRegExp
1508 var esprima; // Browserified version does not have esprima
1510 // 1. For node.js just require module as deps
1511 // 2. For browser try to require mudule via external AMD system.
1512 // If not found - try to fallback to window.esprima. If not
1513 // found too - then fail to parse.
1517 // workaround to exclude package from browserify list.
1518 var _require$1 = commonjsRequire;
1519 esprima = _require$1('esprima');
1522 if (typeof window !== 'undefined') esprima = window.esprima;
1525 function resolveJavascriptFunction(data) {
1526 if (data === null) return false;
1529 var source = '(' + data + ')',
1530 ast = esprima.parse(source, {
1534 if (ast.type !== 'Program' || ast.body.length !== 1 || ast.body[0].type !== 'ExpressionStatement' || ast.body[0].expression.type !== 'ArrowFunctionExpression' && ast.body[0].expression.type !== 'FunctionExpression') {
1544 function constructJavascriptFunction(data) {
1545 /*jslint evil:true*/
1546 var source = '(' + data + ')',
1547 ast = esprima.parse(source, {
1553 if (ast.type !== 'Program' || ast.body.length !== 1 || ast.body[0].type !== 'ExpressionStatement' || ast.body[0].expression.type !== 'ArrowFunctionExpression' && ast.body[0].expression.type !== 'FunctionExpression') {
1554 throw new Error('Failed to resolve function');
1557 ast.body[0].expression.params.forEach(function (param) {
1558 params.push(param.name);
1560 body = ast.body[0].expression.body.range; // Esprima's ranges include the first '{' and the last '}' characters on
1561 // function expressions. So cut them out.
1563 if (ast.body[0].expression.body.type === 'BlockStatement') {
1564 /*eslint-disable no-new-func*/
1565 return new Function(params, source.slice(body[0] + 1, body[1] - 1));
1566 } // ES6 arrow functions can omit the BlockStatement. In that case, just return
1569 /*eslint-disable no-new-func*/
1572 return new Function(params, 'return ' + source.slice(body[0], body[1]));
1575 function representJavascriptFunction(object
1578 return object.toString();
1581 function isFunction(object) {
1582 return Object.prototype.toString.call(object) === '[object Function]';
1585 var _function = new type('tag:yaml.org,2002:js/function', {
1587 resolve: resolveJavascriptFunction,
1588 construct: constructJavascriptFunction,
1589 predicate: isFunction,
1590 represent: representJavascriptFunction
1593 var default_full = schema.DEFAULT = new schema({
1594 include: [default_safe],
1595 explicit: [_undefined, regexp, _function]
1598 /*eslint-disable max-len,no-use-before-define*/
1601 var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
1602 var CONTEXT_FLOW_IN = 1;
1603 var CONTEXT_FLOW_OUT = 2;
1604 var CONTEXT_BLOCK_IN = 3;
1605 var CONTEXT_BLOCK_OUT = 4;
1606 var CHOMPING_CLIP = 1;
1607 var CHOMPING_STRIP = 2;
1608 var CHOMPING_KEEP = 3;
1609 var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
1610 var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
1611 var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
1612 var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
1613 var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
1615 function _class(obj) {
1616 return Object.prototype.toString.call(obj);
1619 function is_EOL(c) {
1627 function is_WHITE_SPACE(c) {
1635 function is_WS_OR_EOL(c) {
1647 function is_FLOW_INDICATOR(c) {
1661 function fromHexCode(c) {
1671 /*eslint-disable no-bitwise*/
1681 return lc - 0x61 + 10;
1687 function escapedHexLen(c) {
1709 function fromDecimalCode(c) {
1721 function simpleEscapeSequence(c) {
1722 /* eslint-disable indent */
1725 ? '\x00' : c === 0x61
1727 ? '\x07' : c === 0x62
1729 ? '\x08' : c === 0x74
1731 ? '\x09' : c === 0x09
1733 ? '\x09' : c === 0x6E
1735 ? '\x0A' : c === 0x76
1737 ? '\x0B' : c === 0x66
1739 ? '\x0C' : c === 0x72
1741 ? '\x0D' : c === 0x65
1743 ? '\x1B' : c === 0x20
1747 ? '\x22' : c === 0x2F
1751 ? '\x5C' : c === 0x4E
1753 ? '\x85' : c === 0x5F
1755 ? '\xA0' : c === 0x4C
1757 ? '\u2028' : c === 0x50
1762 function charFromCodepoint(c) {
1764 return String.fromCharCode(c);
1765 } // Encode UTF-16 surrogate pair
1766 // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
1769 return String.fromCharCode((c - 0x010000 >> 10) + 0xD800, (c - 0x010000 & 0x03FF) + 0xDC00);
1772 var simpleEscapeCheck = new Array(256); // integer, for fast access
1774 var simpleEscapeMap = new Array(256);
1776 for (var i = 0; i < 256; i++) {
1777 simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
1778 simpleEscapeMap[i] = simpleEscapeSequence(i);
1781 function State(input, options) {
1783 this.filename = options['filename'] || null;
1784 this.schema = options['schema'] || default_full;
1785 this.onWarning = options['onWarning'] || null;
1786 this.legacy = options['legacy'] || false;
1787 this.json = options['json'] || false;
1788 this.listener = options['listener'] || null;
1789 this.implicitTypes = this.schema.compiledImplicit;
1790 this.typeMap = this.schema.compiledTypeMap;
1791 this.length = input.length;
1795 this.lineIndent = 0;
1796 this.documents = [];
1799 this.checkLineBreaks;
1808 function generateError(state, message) {
1809 return new exception(message, new mark(state.filename, state.input, state.position, state.line, state.position - state.lineStart));
1812 function throwError(state, message) {
1813 throw generateError(state, message);
1816 function throwWarning(state, message) {
1817 if (state.onWarning) {
1818 state.onWarning.call(null, generateError(state, message));
1822 var directiveHandlers = {
1823 YAML: function handleYamlDirective(state, name, args) {
1824 var match, major, minor;
1826 if (state.version !== null) {
1827 throwError(state, 'duplication of %YAML directive');
1830 if (args.length !== 1) {
1831 throwError(state, 'YAML directive accepts exactly one argument');
1834 match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
1836 if (match === null) {
1837 throwError(state, 'ill-formed argument of the YAML directive');
1840 major = parseInt(match[1], 10);
1841 minor = parseInt(match[2], 10);
1844 throwError(state, 'unacceptable YAML version of the document');
1847 state.version = args[0];
1848 state.checkLineBreaks = minor < 2;
1850 if (minor !== 1 && minor !== 2) {
1851 throwWarning(state, 'unsupported YAML version of the document');
1854 TAG: function handleTagDirective(state, name, args) {
1857 if (args.length !== 2) {
1858 throwError(state, 'TAG directive accepts exactly two arguments');
1864 if (!PATTERN_TAG_HANDLE.test(handle)) {
1865 throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
1868 if (_hasOwnProperty$2.call(state.tagMap, handle)) {
1869 throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
1872 if (!PATTERN_TAG_URI.test(prefix)) {
1873 throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
1876 state.tagMap[handle] = prefix;
1880 function captureSegment(state, start, end, checkJson) {
1881 var _position, _length, _character, _result;
1884 _result = state.input.slice(start, end);
1887 for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
1888 _character = _result.charCodeAt(_position);
1890 if (!(_character === 0x09 || 0x20 <= _character && _character <= 0x10FFFF)) {
1891 throwError(state, 'expected valid JSON character');
1894 } else if (PATTERN_NON_PRINTABLE.test(_result)) {
1895 throwError(state, 'the stream contains non-printable characters');
1898 state.result += _result;
1902 function mergeMappings(state, destination, source, overridableKeys) {
1903 var sourceKeys, key, index, quantity;
1905 if (!common.isObject(source)) {
1906 throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
1909 sourceKeys = Object.keys(source);
1911 for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
1912 key = sourceKeys[index];
1914 if (!_hasOwnProperty$2.call(destination, key)) {
1915 destination[key] = source[key];
1916 overridableKeys[key] = true;
1921 function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
1922 var index, quantity; // The output is a plain object here, so keys can only be strings.
1923 // We need to convert keyNode to a string, but doing so can hang the process
1924 // (deeply nested arrays that explode exponentially using aliases).
1926 if (Array.isArray(keyNode)) {
1927 keyNode = Array.prototype.slice.call(keyNode);
1929 for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
1930 if (Array.isArray(keyNode[index])) {
1931 throwError(state, 'nested arrays are not supported inside keys');
1934 if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
1935 keyNode[index] = '[object Object]';
1938 } // Avoid code execution in load() via toString property
1939 // (still use its own toString for arrays, timestamps,
1940 // and whatever user schema extensions happen to have @@toStringTag)
1943 if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
1944 keyNode = '[object Object]';
1947 keyNode = String(keyNode);
1949 if (_result === null) {
1953 if (keyTag === 'tag:yaml.org,2002:merge') {
1954 if (Array.isArray(valueNode)) {
1955 for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
1956 mergeMappings(state, _result, valueNode[index], overridableKeys);
1959 mergeMappings(state, _result, valueNode, overridableKeys);
1962 if (!state.json && !_hasOwnProperty$2.call(overridableKeys, keyNode) && _hasOwnProperty$2.call(_result, keyNode)) {
1963 state.line = startLine || state.line;
1964 state.position = startPos || state.position;
1965 throwError(state, 'duplicated mapping key');
1968 _result[keyNode] = valueNode;
1969 delete overridableKeys[keyNode];
1975 function readLineBreak(state) {
1977 ch = state.input.charCodeAt(state.position);
1983 } else if (ch === 0x0D
1988 if (state.input.charCodeAt(state.position) === 0x0A
1994 throwError(state, 'a line break is expected');
1998 state.lineStart = state.position;
2001 function skipSeparationSpace(state, allowComments, checkIndent) {
2003 ch = state.input.charCodeAt(state.position);
2006 while (is_WHITE_SPACE(ch)) {
2007 ch = state.input.charCodeAt(++state.position);
2010 if (allowComments && ch === 0x23
2014 ch = state.input.charCodeAt(++state.position);
2015 } while (ch !== 0x0A
2023 readLineBreak(state);
2024 ch = state.input.charCodeAt(state.position);
2026 state.lineIndent = 0;
2032 ch = state.input.charCodeAt(++state.position);
2039 if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
2040 throwWarning(state, 'deficient indentation');
2046 function testDocumentSeparator(state) {
2047 var _position = state.position,
2049 ch = state.input.charCodeAt(_position); // Condition state.position === state.lineStart is tested
2050 // in parent on each call, for efficiency. No needs to test here again.
2056 ) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
2058 ch = state.input.charCodeAt(_position);
2060 if (ch === 0 || is_WS_OR_EOL(ch)) {
2068 function writeFoldedLines(state, count) {
2070 state.result += ' ';
2071 } else if (count > 1) {
2072 state.result += common.repeat('\n', count - 1);
2076 function readPlainScalar(state, nodeIndent, withinFlowCollection) {
2086 _result = state.result,
2089 ch = state.input.charCodeAt(state.position);
2091 if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 0x23
2122 following = state.input.charCodeAt(state.position + 1);
2124 if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
2129 state.kind = 'scalar';
2131 captureStart = captureEnd = state.position;
2132 hasPendingContent = false;
2138 following = state.input.charCodeAt(state.position + 1);
2140 if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
2143 } else if (ch === 0x23
2146 preceding = state.input.charCodeAt(state.position - 1);
2148 if (is_WS_OR_EOL(preceding)) {
2151 } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
2153 } else if (is_EOL(ch)) {
2155 _lineStart = state.lineStart;
2156 _lineIndent = state.lineIndent;
2157 skipSeparationSpace(state, false, -1);
2159 if (state.lineIndent >= nodeIndent) {
2160 hasPendingContent = true;
2161 ch = state.input.charCodeAt(state.position);
2164 state.position = captureEnd;
2166 state.lineStart = _lineStart;
2167 state.lineIndent = _lineIndent;
2172 if (hasPendingContent) {
2173 captureSegment(state, captureStart, captureEnd, false);
2174 writeFoldedLines(state, state.line - _line);
2175 captureStart = captureEnd = state.position;
2176 hasPendingContent = false;
2179 if (!is_WHITE_SPACE(ch)) {
2180 captureEnd = state.position + 1;
2183 ch = state.input.charCodeAt(++state.position);
2186 captureSegment(state, captureStart, captureEnd, false);
2193 state.result = _result;
2197 function readSingleQuotedScalar(state, nodeIndent) {
2198 var ch, captureStart, captureEnd;
2199 ch = state.input.charCodeAt(state.position);
2207 state.kind = 'scalar';
2210 captureStart = captureEnd = state.position;
2212 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
2216 captureSegment(state, captureStart, state.position, true);
2217 ch = state.input.charCodeAt(++state.position);
2222 captureStart = state.position;
2224 captureEnd = state.position;
2228 } else if (is_EOL(ch)) {
2229 captureSegment(state, captureStart, captureEnd, true);
2230 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
2231 captureStart = captureEnd = state.position;
2232 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
2233 throwError(state, 'unexpected end of the document within a single quoted scalar');
2236 captureEnd = state.position;
2240 throwError(state, 'unexpected end of the stream within a single quoted scalar');
2243 function readDoubleQuotedScalar(state, nodeIndent) {
2244 var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
2245 ch = state.input.charCodeAt(state.position);
2253 state.kind = 'scalar';
2256 captureStart = captureEnd = state.position;
2258 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
2262 captureSegment(state, captureStart, state.position, true);
2265 } else if (ch === 0x5C
2268 captureSegment(state, captureStart, state.position, true);
2269 ch = state.input.charCodeAt(++state.position);
2272 skipSeparationSpace(state, false, nodeIndent); // TODO: rework to inline fn with no type cast?
2273 } else if (ch < 256 && simpleEscapeCheck[ch]) {
2274 state.result += simpleEscapeMap[ch];
2276 } else if ((tmp = escapedHexLen(ch)) > 0) {
2280 for (; hexLength > 0; hexLength--) {
2281 ch = state.input.charCodeAt(++state.position);
2283 if ((tmp = fromHexCode(ch)) >= 0) {
2284 hexResult = (hexResult << 4) + tmp;
2286 throwError(state, 'expected hexadecimal character');
2290 state.result += charFromCodepoint(hexResult);
2293 throwError(state, 'unknown escape sequence');
2296 captureStart = captureEnd = state.position;
2297 } else if (is_EOL(ch)) {
2298 captureSegment(state, captureStart, captureEnd, true);
2299 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
2300 captureStart = captureEnd = state.position;
2301 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
2302 throwError(state, 'unexpected end of the document within a double quoted scalar');
2305 captureEnd = state.position;
2309 throwError(state, 'unexpected end of the stream within a double quoted scalar');
2312 function readFlowCollection(state, nodeIndent) {
2313 var readNext = true,
2317 _anchor = state.anchor,
2323 overridableKeys = {},
2329 ch = state.input.charCodeAt(state.position);
2339 } else if (ch === 0x7B
2351 if (state.anchor !== null) {
2352 state.anchorMap[state.anchor] = _result;
2355 ch = state.input.charCodeAt(++state.position);
2358 skipSeparationSpace(state, true, nodeIndent);
2359 ch = state.input.charCodeAt(state.position);
2361 if (ch === terminator) {
2364 state.anchor = _anchor;
2365 state.kind = isMapping ? 'mapping' : 'sequence';
2366 state.result = _result;
2368 } else if (!readNext) {
2369 throwError(state, 'missed comma between flow collection entries');
2372 keyTag = keyNode = valueNode = null;
2373 isPair = isExplicitPair = false;
2378 following = state.input.charCodeAt(state.position + 1);
2380 if (is_WS_OR_EOL(following)) {
2381 isPair = isExplicitPair = true;
2383 skipSeparationSpace(state, true, nodeIndent);
2388 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
2390 keyNode = state.result;
2391 skipSeparationSpace(state, true, nodeIndent);
2392 ch = state.input.charCodeAt(state.position);
2394 if ((isExplicitPair || state.line === _line) && ch === 0x3A
2398 ch = state.input.charCodeAt(++state.position);
2399 skipSeparationSpace(state, true, nodeIndent);
2400 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
2401 valueNode = state.result;
2405 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
2406 } else if (isPair) {
2407 _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
2409 _result.push(keyNode);
2412 skipSeparationSpace(state, true, nodeIndent);
2413 ch = state.input.charCodeAt(state.position);
2419 ch = state.input.charCodeAt(++state.position);
2425 throwError(state, 'unexpected end of the stream within a flow collection');
2428 function readBlockScalar(state, nodeIndent) {
2431 chomping = CHOMPING_CLIP,
2432 didReadContent = false,
2433 detectedIndent = false,
2434 textIndent = nodeIndent,
2436 atMoreIndented = false,
2439 ch = state.input.charCodeAt(state.position);
2445 } else if (ch === 0x3E
2453 state.kind = 'scalar';
2457 ch = state.input.charCodeAt(++state.position);
2464 if (CHOMPING_CLIP === chomping) {
2465 chomping = ch === 0x2B
2467 ? CHOMPING_KEEP : CHOMPING_STRIP;
2469 throwError(state, 'repeat of a chomping mode identifier');
2471 } else if ((tmp = fromDecimalCode(ch)) >= 0) {
2473 throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
2474 } else if (!detectedIndent) {
2475 textIndent = nodeIndent + tmp - 1;
2476 detectedIndent = true;
2478 throwError(state, 'repeat of an indentation width identifier');
2485 if (is_WHITE_SPACE(ch)) {
2487 ch = state.input.charCodeAt(++state.position);
2488 } while (is_WHITE_SPACE(ch));
2494 ch = state.input.charCodeAt(++state.position);
2495 } while (!is_EOL(ch) && ch !== 0);
2500 readLineBreak(state);
2501 state.lineIndent = 0;
2502 ch = state.input.charCodeAt(state.position);
2504 while ((!detectedIndent || state.lineIndent < textIndent) && ch === 0x20
2508 ch = state.input.charCodeAt(++state.position);
2511 if (!detectedIndent && state.lineIndent > textIndent) {
2512 textIndent = state.lineIndent;
2518 } // End of the scalar.
2521 if (state.lineIndent < textIndent) {
2522 // Perform the chomping.
2523 if (chomping === CHOMPING_KEEP) {
2524 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
2525 } else if (chomping === CHOMPING_CLIP) {
2526 if (didReadContent) {
2527 // i.e. only if the scalar is not empty.
2528 state.result += '\n';
2530 } // Break this `while` cycle and go to the funciton's epilogue.
2534 } // Folded style: use fancy rules to handle line breaks.
2538 // Lines starting with white space characters (more-indented lines) are not folded.
2539 if (is_WHITE_SPACE(ch)) {
2540 atMoreIndented = true; // except for the first content line (cf. Example 8.1)
2542 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); // End of more-indented block.
2543 } else if (atMoreIndented) {
2544 atMoreIndented = false;
2545 state.result += common.repeat('\n', emptyLines + 1); // Just one line break - perceive as the same line.
2546 } else if (emptyLines === 0) {
2547 if (didReadContent) {
2548 // i.e. only if we have already read some scalar content.
2549 state.result += ' ';
2550 } // Several line breaks - perceive as different lines.
2553 state.result += common.repeat('\n', emptyLines);
2554 } // Literal style: just add exact number of line breaks between content lines.
2557 // Keep all line breaks except the header line break.
2558 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
2561 didReadContent = true;
2562 detectedIndent = true;
2564 captureStart = state.position;
2566 while (!is_EOL(ch) && ch !== 0) {
2567 ch = state.input.charCodeAt(++state.position);
2570 captureSegment(state, captureStart, state.position, false);
2576 function readBlockSequence(state, nodeIndent) {
2579 _anchor = state.anchor,
2585 if (state.anchor !== null) {
2586 state.anchorMap[state.anchor] = _result;
2589 ch = state.input.charCodeAt(state.position);
2598 following = state.input.charCodeAt(state.position + 1);
2600 if (!is_WS_OR_EOL(following)) {
2607 if (skipSeparationSpace(state, true, -1)) {
2608 if (state.lineIndent <= nodeIndent) {
2611 ch = state.input.charCodeAt(state.position);
2617 composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
2619 _result.push(state.result);
2621 skipSeparationSpace(state, true, -1);
2622 ch = state.input.charCodeAt(state.position);
2624 if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
2625 throwError(state, 'bad indentation of a sequence entry');
2626 } else if (state.lineIndent < nodeIndent) {
2633 state.anchor = _anchor;
2634 state.kind = 'sequence';
2635 state.result = _result;
2642 function readBlockMapping(state, nodeIndent, flowIndent) {
2648 _anchor = state.anchor,
2650 overridableKeys = {},
2654 atExplicitKey = false,
2658 if (state.anchor !== null) {
2659 state.anchorMap[state.anchor] = _result;
2662 ch = state.input.charCodeAt(state.position);
2665 following = state.input.charCodeAt(state.position + 1);
2666 _line = state.line; // Save the current line.
2668 _pos = state.position; //
2669 // Explicit notation case. There are two separate blocks:
2670 // first for the key (denoted by "?") and second for the value (denoted by ":")
2677 ) && is_WS_OR_EOL(following)) {
2681 if (atExplicitKey) {
2682 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
2683 keyTag = keyNode = valueNode = null;
2687 atExplicitKey = true;
2688 allowCompact = true;
2689 } else if (atExplicitKey) {
2690 // i.e. 0x3A/* : */ === character after the explicit key.
2691 atExplicitKey = false;
2692 allowCompact = true;
2694 throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
2697 state.position += 1;
2699 // Implicit notation case. Flow-style node as the key first, then ":", and the value.
2701 } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
2702 if (state.line === _line) {
2703 ch = state.input.charCodeAt(state.position);
2705 while (is_WHITE_SPACE(ch)) {
2706 ch = state.input.charCodeAt(++state.position);
2712 ch = state.input.charCodeAt(++state.position);
2714 if (!is_WS_OR_EOL(ch)) {
2715 throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
2718 if (atExplicitKey) {
2719 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
2720 keyTag = keyNode = valueNode = null;
2724 atExplicitKey = false;
2725 allowCompact = false;
2727 keyNode = state.result;
2728 } else if (detected) {
2729 throwError(state, 'can not read an implicit mapping pair; a colon is missed');
2732 state.anchor = _anchor;
2733 return true; // Keep the result of `composeNode`.
2735 } else if (detected) {
2736 throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
2739 state.anchor = _anchor;
2740 return true; // Keep the result of `composeNode`.
2743 break; // Reading is done. Go to the epilogue.
2745 // Common reading code for both explicit and implicit notations.
2749 if (state.line === _line || state.lineIndent > nodeIndent) {
2750 if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
2751 if (atExplicitKey) {
2752 keyNode = state.result;
2754 valueNode = state.result;
2758 if (!atExplicitKey) {
2759 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
2760 keyTag = keyNode = valueNode = null;
2763 skipSeparationSpace(state, true, -1);
2764 ch = state.input.charCodeAt(state.position);
2767 if (state.lineIndent > nodeIndent && ch !== 0) {
2768 throwError(state, 'bad indentation of a mapping entry');
2769 } else if (state.lineIndent < nodeIndent) {
2775 // Special case: last mapping's node contains only the key in explicit notation.
2778 if (atExplicitKey) {
2779 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
2780 } // Expose the resulting mapping.
2785 state.anchor = _anchor;
2786 state.kind = 'mapping';
2787 state.result = _result;
2793 function readTagProperty(state) {
2801 ch = state.input.charCodeAt(state.position);
2806 if (state.tag !== null) {
2807 throwError(state, 'duplication of a tag property');
2810 ch = state.input.charCodeAt(++state.position);
2816 ch = state.input.charCodeAt(++state.position);
2817 } else if (ch === 0x21
2822 ch = state.input.charCodeAt(++state.position);
2827 _position = state.position;
2831 ch = state.input.charCodeAt(++state.position);
2832 } while (ch !== 0 && ch !== 0x3E
2836 if (state.position < state.length) {
2837 tagName = state.input.slice(_position, state.position);
2838 ch = state.input.charCodeAt(++state.position);
2840 throwError(state, 'unexpected end of the stream within a verbatim tag');
2843 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
2848 tagHandle = state.input.slice(_position - 1, state.position + 1);
2850 if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
2851 throwError(state, 'named tag handle cannot contain such characters');
2855 _position = state.position + 1;
2857 throwError(state, 'tag suffix cannot contain exclamation marks');
2861 ch = state.input.charCodeAt(++state.position);
2864 tagName = state.input.slice(_position, state.position);
2866 if (PATTERN_FLOW_INDICATORS.test(tagName)) {
2867 throwError(state, 'tag suffix cannot contain flow indicator characters');
2871 if (tagName && !PATTERN_TAG_URI.test(tagName)) {
2872 throwError(state, 'tag name cannot contain such characters: ' + tagName);
2876 state.tag = tagName;
2877 } else if (_hasOwnProperty$2.call(state.tagMap, tagHandle)) {
2878 state.tag = state.tagMap[tagHandle] + tagName;
2879 } else if (tagHandle === '!') {
2880 state.tag = '!' + tagName;
2881 } else if (tagHandle === '!!') {
2882 state.tag = 'tag:yaml.org,2002:' + tagName;
2884 throwError(state, 'undeclared tag handle "' + tagHandle + '"');
2890 function readAnchorProperty(state) {
2893 ch = state.input.charCodeAt(state.position);
2898 if (state.anchor !== null) {
2899 throwError(state, 'duplication of an anchor property');
2902 ch = state.input.charCodeAt(++state.position);
2903 _position = state.position;
2905 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
2906 ch = state.input.charCodeAt(++state.position);
2909 if (state.position === _position) {
2910 throwError(state, 'name of an anchor node must contain at least one character');
2913 state.anchor = state.input.slice(_position, state.position);
2917 function readAlias(state) {
2918 var _position, alias, ch;
2920 ch = state.input.charCodeAt(state.position);
2924 ch = state.input.charCodeAt(++state.position);
2925 _position = state.position;
2927 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
2928 ch = state.input.charCodeAt(++state.position);
2931 if (state.position === _position) {
2932 throwError(state, 'name of an alias node must contain at least one character');
2935 alias = state.input.slice(_position, state.position);
2937 if (!state.anchorMap.hasOwnProperty(alias)) {
2938 throwError(state, 'unidentified alias "' + alias + '"');
2941 state.result = state.anchorMap[alias];
2942 skipSeparationSpace(state, true, -1);
2946 function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
2947 var allowBlockStyles,
2949 allowBlockCollections,
2951 // 1: this>parent, 0: this=parent, -1: this<parent
2960 if (state.listener !== null) {
2961 state.listener('open', state);
2965 state.anchor = null;
2967 state.result = null;
2968 allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
2971 if (skipSeparationSpace(state, true, -1)) {
2974 if (state.lineIndent > parentIndent) {
2976 } else if (state.lineIndent === parentIndent) {
2978 } else if (state.lineIndent < parentIndent) {
2984 if (indentStatus === 1) {
2985 while (readTagProperty(state) || readAnchorProperty(state)) {
2986 if (skipSeparationSpace(state, true, -1)) {
2988 allowBlockCollections = allowBlockStyles;
2990 if (state.lineIndent > parentIndent) {
2992 } else if (state.lineIndent === parentIndent) {
2994 } else if (state.lineIndent < parentIndent) {
2998 allowBlockCollections = false;
3003 if (allowBlockCollections) {
3004 allowBlockCollections = atNewLine || allowCompact;
3007 if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
3008 if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
3009 flowIndent = parentIndent;
3011 flowIndent = parentIndent + 1;
3014 blockIndent = state.position - state.lineStart;
3016 if (indentStatus === 1) {
3017 if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
3020 if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
3022 } else if (readAlias(state)) {
3025 if (state.tag !== null || state.anchor !== null) {
3026 throwError(state, 'alias node should not have any properties');
3028 } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
3031 if (state.tag === null) {
3036 if (state.anchor !== null) {
3037 state.anchorMap[state.anchor] = state.result;
3040 } else if (indentStatus === 0) {
3041 // Special case: block sequences are allowed to have same indentation level as the parent.
3042 // http://www.yaml.org/spec/1.2/spec.html#id2799784
3043 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
3047 if (state.tag !== null && state.tag !== '!') {
3048 if (state.tag === '?') {
3049 for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
3050 type = state.implicitTypes[typeIndex]; // Implicit resolving is not allowed for non-scalar types, and '?'
3051 // non-specific tag is only assigned to plain scalars. So, it isn't
3052 // needed to check for 'kind' conformity.
3054 if (type.resolve(state.result)) {
3055 // `state.result` updated in resolver if matched
3056 state.result = type.construct(state.result);
3057 state.tag = type.tag;
3059 if (state.anchor !== null) {
3060 state.anchorMap[state.anchor] = state.result;
3066 } else if (_hasOwnProperty$2.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
3067 type = state.typeMap[state.kind || 'fallback'][state.tag];
3069 if (state.result !== null && type.kind !== state.kind) {
3070 throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
3073 if (!type.resolve(state.result)) {
3074 // `state.result` updated in resolver if matched
3075 throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
3077 state.result = type.construct(state.result);
3079 if (state.anchor !== null) {
3080 state.anchorMap[state.anchor] = state.result;
3084 throwError(state, 'unknown tag !<' + state.tag + '>');
3088 if (state.listener !== null) {
3089 state.listener('close', state);
3092 return state.tag !== null || state.anchor !== null || hasContent;
3095 function readDocument(state) {
3096 var documentStart = state.position,
3100 hasDirectives = false,
3103 state.version = null;
3104 state.checkLineBreaks = state.legacy;
3106 state.anchorMap = {};
3108 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
3109 skipSeparationSpace(state, true, -1);
3110 ch = state.input.charCodeAt(state.position);
3112 if (state.lineIndent > 0 || ch !== 0x25
3118 hasDirectives = true;
3119 ch = state.input.charCodeAt(++state.position);
3120 _position = state.position;
3122 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
3123 ch = state.input.charCodeAt(++state.position);
3126 directiveName = state.input.slice(_position, state.position);
3129 if (directiveName.length < 1) {
3130 throwError(state, 'directive name must not be less than one character in length');
3134 while (is_WHITE_SPACE(ch)) {
3135 ch = state.input.charCodeAt(++state.position);
3142 ch = state.input.charCodeAt(++state.position);
3143 } while (ch !== 0 && !is_EOL(ch));
3148 if (is_EOL(ch)) break;
3149 _position = state.position;
3151 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
3152 ch = state.input.charCodeAt(++state.position);
3155 directiveArgs.push(state.input.slice(_position, state.position));
3158 if (ch !== 0) readLineBreak(state);
3160 if (_hasOwnProperty$2.call(directiveHandlers, directiveName)) {
3161 directiveHandlers[directiveName](state, directiveName, directiveArgs);
3163 throwWarning(state, 'unknown document directive "' + directiveName + '"');
3167 skipSeparationSpace(state, true, -1);
3169 if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D
3171 && state.input.charCodeAt(state.position + 1) === 0x2D
3173 && state.input.charCodeAt(state.position + 2) === 0x2D
3176 state.position += 3;
3177 skipSeparationSpace(state, true, -1);
3178 } else if (hasDirectives) {
3179 throwError(state, 'directives end mark is expected');
3182 composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
3183 skipSeparationSpace(state, true, -1);
3185 if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
3186 throwWarning(state, 'non-ASCII line breaks are interpreted as content');
3189 state.documents.push(state.result);
3191 if (state.position === state.lineStart && testDocumentSeparator(state)) {
3192 if (state.input.charCodeAt(state.position) === 0x2E
3195 state.position += 3;
3196 skipSeparationSpace(state, true, -1);
3202 if (state.position < state.length - 1) {
3203 throwError(state, 'end of the stream or a document separator is expected');
3209 function loadDocuments(input, options) {
3210 input = String(input);
3211 options = options || {};
3213 if (input.length !== 0) {
3214 // Add tailing `\n` if not exists
3215 if (input.charCodeAt(input.length - 1) !== 0x0A
3217 && input.charCodeAt(input.length - 1) !== 0x0D
3224 if (input.charCodeAt(0) === 0xFEFF) {
3225 input = input.slice(1);
3229 var state = new State(input, options); // Use 0 as string terminator. That significantly simplifies bounds check.
3231 state.input += '\0';
3233 while (state.input.charCodeAt(state.position) === 0x20
3236 state.lineIndent += 1;
3237 state.position += 1;
3240 while (state.position < state.length - 1) {
3241 readDocument(state);
3244 return state.documents;
3247 function loadAll(input, iterator, options) {
3248 var documents = loadDocuments(input, options),
3252 if (typeof iterator !== 'function') {
3256 for (index = 0, length = documents.length; index < length; index += 1) {
3257 iterator(documents[index]);
3261 function load(input, options) {
3262 var documents = loadDocuments(input, options);
3264 if (documents.length === 0) {
3265 /*eslint-disable no-undefined*/
3267 } else if (documents.length === 1) {
3268 return documents[0];
3271 throw new exception('expected a single document in the stream, but found more');
3274 function safeLoadAll(input, output, options) {
3275 if (typeof output === 'function') {
3276 loadAll(input, output, common.extend({
3277 schema: default_safe
3280 return loadAll(input, common.extend({
3281 schema: default_safe
3286 function safeLoad(input, options) {
3287 return load(input, common.extend({
3288 schema: default_safe
3292 var loadAll_1 = loadAll;
3294 var safeLoadAll_1 = safeLoadAll;
3295 var safeLoad_1 = safeLoad;
3299 safeLoadAll: safeLoadAll_1,
3300 safeLoad: safeLoad_1
3303 /*eslint-disable no-use-before-define*/
3306 var _toString$2 = Object.prototype.toString;
3307 var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
3308 var CHAR_TAB = 0x09;
3311 var CHAR_LINE_FEED = 0x0A;
3314 var CHAR_SPACE = 0x20;
3317 var CHAR_EXCLAMATION = 0x21;
3320 var CHAR_DOUBLE_QUOTE = 0x22;
3323 var CHAR_SHARP = 0x23;
3326 var CHAR_PERCENT = 0x25;
3329 var CHAR_AMPERSAND = 0x26;
3332 var CHAR_SINGLE_QUOTE = 0x27;
3335 var CHAR_ASTERISK = 0x2A;
3338 var CHAR_COMMA = 0x2C;
3341 var CHAR_MINUS = 0x2D;
3344 var CHAR_COLON = 0x3A;
3347 var CHAR_GREATER_THAN = 0x3E;
3350 var CHAR_QUESTION = 0x3F;
3353 var CHAR_COMMERCIAL_AT = 0x40;
3356 var CHAR_LEFT_SQUARE_BRACKET = 0x5B;
3359 var CHAR_RIGHT_SQUARE_BRACKET = 0x5D;
3362 var CHAR_GRAVE_ACCENT = 0x60;
3365 var CHAR_LEFT_CURLY_BRACKET = 0x7B;
3368 var CHAR_VERTICAL_LINE = 0x7C;
3371 var CHAR_RIGHT_CURLY_BRACKET = 0x7D;
3374 var ESCAPE_SEQUENCES = {};
3375 ESCAPE_SEQUENCES[0x00] = '\\0';
3376 ESCAPE_SEQUENCES[0x07] = '\\a';
3377 ESCAPE_SEQUENCES[0x08] = '\\b';
3378 ESCAPE_SEQUENCES[0x09] = '\\t';
3379 ESCAPE_SEQUENCES[0x0A] = '\\n';
3380 ESCAPE_SEQUENCES[0x0B] = '\\v';
3381 ESCAPE_SEQUENCES[0x0C] = '\\f';
3382 ESCAPE_SEQUENCES[0x0D] = '\\r';
3383 ESCAPE_SEQUENCES[0x1B] = '\\e';
3384 ESCAPE_SEQUENCES[0x22] = '\\"';
3385 ESCAPE_SEQUENCES[0x5C] = '\\\\';
3386 ESCAPE_SEQUENCES[0x85] = '\\N';
3387 ESCAPE_SEQUENCES[0xA0] = '\\_';
3388 ESCAPE_SEQUENCES[0x2028] = '\\L';
3389 ESCAPE_SEQUENCES[0x2029] = '\\P';
3390 var DEPRECATED_BOOLEANS_SYNTAX = ['y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'];
3392 function compileStyleMap(schema, map) {
3393 var result, keys, index, length, tag, style, type;
3394 if (map === null) return {};
3396 keys = Object.keys(map);
3398 for (index = 0, length = keys.length; index < length; index += 1) {
3400 style = String(map[tag]);
3402 if (tag.slice(0, 2) === '!!') {
3403 tag = 'tag:yaml.org,2002:' + tag.slice(2);
3406 type = schema.compiledTypeMap['fallback'][tag];
3408 if (type && _hasOwnProperty$3.call(type.styleAliases, style)) {
3409 style = type.styleAliases[style];
3412 result[tag] = style;
3418 function encodeHex(character) {
3419 var string, handle, length;
3420 string = character.toString(16).toUpperCase();
3422 if (character <= 0xFF) {
3425 } else if (character <= 0xFFFF) {
3428 } else if (character <= 0xFFFFFFFF) {
3432 throw new exception('code point within a string may not be greater than 0xFFFFFFFF');
3435 return '\\' + handle + common.repeat('0', length - string.length) + string;
3438 function State$1(options) {
3439 this.schema = options['schema'] || default_full;
3440 this.indent = Math.max(1, options['indent'] || 2);
3441 this.noArrayIndent = options['noArrayIndent'] || false;
3442 this.skipInvalid = options['skipInvalid'] || false;
3443 this.flowLevel = common.isNothing(options['flowLevel']) ? -1 : options['flowLevel'];
3444 this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
3445 this.sortKeys = options['sortKeys'] || false;
3446 this.lineWidth = options['lineWidth'] || 80;
3447 this.noRefs = options['noRefs'] || false;
3448 this.noCompatMode = options['noCompatMode'] || false;
3449 this.condenseFlow = options['condenseFlow'] || false;
3450 this.implicitTypes = this.schema.compiledImplicit;
3451 this.explicitTypes = this.schema.compiledExplicit;
3454 this.duplicates = [];
3455 this.usedDuplicates = null;
3456 } // Indents every line in a string. Empty lines (\n only) are not indented.
3459 function indentString(string, spaces) {
3460 var ind = common.repeat(' ', spaces),
3465 length = string.length;
3467 while (position < length) {
3468 next = string.indexOf('\n', position);
3471 line = string.slice(position);
3474 line = string.slice(position, next + 1);
3475 position = next + 1;
3478 if (line.length && line !== '\n') result += ind;
3485 function generateNextLine(state, level) {
3486 return '\n' + common.repeat(' ', state.indent * level);
3489 function testImplicitResolving(state, str) {
3490 var index, length, type;
3492 for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
3493 type = state.implicitTypes[index];
3495 if (type.resolve(str)) {
3501 } // [33] s-white ::= s-space | s-tab
3504 function isWhitespace(c) {
3505 return c === CHAR_SPACE || c === CHAR_TAB;
3506 } // Returns true if the character can be printed without escaping.
3507 // From YAML 1.2: "any allowed characters known to be non-printable
3508 // should also be escaped. [However,] This isn’t mandatory"
3509 // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
3512 function isPrintable(c) {
3513 return 0x00020 <= c && c <= 0x00007E || 0x000A1 <= c && c <= 0x00D7FF && c !== 0x2028 && c !== 0x2029 || 0x0E000 <= c && c <= 0x00FFFD && c !== 0xFEFF
3515 || 0x10000 <= c && c <= 0x10FFFF;
3516 } // Simplified test for values allowed after the first character in plain style.
3519 function isPlainSafe(c) {
3520 // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
3521 // where nb-char ::= c-printable - b-char - c-byte-order-mark.
3522 return isPrintable(c) && c !== 0xFEFF // - c-flow-indicator
3523 && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // - ":" - "#"
3524 && c !== CHAR_COLON && c !== CHAR_SHARP;
3525 } // Simplified test for values allowed as the first character in plain style.
3528 function isPlainSafeFirst(c) {
3529 // Uses a subset of ns-char - c-indicator
3530 // where ns-char = nb-char - s-white.
3531 return isPrintable(c) && c !== 0xFEFF && !isWhitespace(c) // - s-white
3532 // - (c-indicator ::=
3533 // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
3534 && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
3535 && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE // | “%” | “@” | “`”)
3536 && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
3537 } // Determines whether block indentation indicator is required.
3540 function needIndentIndicator(string) {
3541 var leadingSpaceRe = /^\n* /;
3542 return leadingSpaceRe.test(string);
3545 var STYLE_PLAIN = 1,
3549 STYLE_DOUBLE = 5; // Determines which scalar styles are possible and returns the preferred style.
3550 // lineWidth = -1 => no limit.
3551 // Pre-conditions: str.length > 0.
3553 // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
3554 // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
3555 // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
3557 function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
3560 var hasLineBreak = false;
3561 var hasFoldableLine = false; // only checked if shouldTrackWidth
3563 var shouldTrackWidth = lineWidth !== -1;
3564 var previousLineBreak = -1; // count the first line correctly
3566 var plain = isPlainSafeFirst(string.charCodeAt(0)) && !isWhitespace(string.charCodeAt(string.length - 1));
3568 if (singleLineOnly) {
3569 // Case: no block styles.
3570 // Check for disallowed characters to rule out plain and single.
3571 for (i = 0; i < string.length; i++) {
3572 char = string.charCodeAt(i);
3574 if (!isPrintable(char)) {
3575 return STYLE_DOUBLE;
3578 plain = plain && isPlainSafe(char);
3581 // Case: block styles permitted.
3582 for (i = 0; i < string.length; i++) {
3583 char = string.charCodeAt(i);
3585 if (char === CHAR_LINE_FEED) {
3586 hasLineBreak = true; // Check if any line can be folded.
3588 if (shouldTrackWidth) {
3589 hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
3590 i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ';
3591 previousLineBreak = i;
3593 } else if (!isPrintable(char)) {
3594 return STYLE_DOUBLE;
3597 plain = plain && isPlainSafe(char);
3598 } // in case the end is missing a \n
3601 hasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ';
3602 } // Although every style can represent \n without escaping, prefer block styles
3603 // for multiline, since they're more readable and they don't add empty lines.
3604 // Also prefer folding a super-long line.
3607 if (!hasLineBreak && !hasFoldableLine) {
3608 // Strings interpretable as another type have to be quoted;
3609 // e.g. the string 'true' vs. the boolean true.
3610 return plain && !testAmbiguousType(string) ? STYLE_PLAIN : STYLE_SINGLE;
3611 } // Edge case: block indentation indicator can only have one digit.
3614 if (indentPerLevel > 9 && needIndentIndicator(string)) {
3615 return STYLE_DOUBLE;
3616 } // At this point we know block styles are valid.
3617 // Prefer literal style unless we want to fold.
3620 return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
3621 } // Note: line breaking/folding is implemented for only the folded style.
3622 // NB. We drop the last trailing newline (if any) of a returned block scalar
3623 // since the dumper adds its own newline. This always works:
3624 // • No ending newline => unaffected; already using strip "-" chomping.
3625 // • Ending newline => removed then restored.
3626 // Importantly, this keeps the "+" chomp indicator from gaining an extra line.
3629 function writeScalar(state, string, level, iskey) {
3630 state.dump = function () {
3631 if (string.length === 0) {
3635 if (!state.noCompatMode && DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
3636 return "'" + string + "'";
3639 var indent = state.indent * Math.max(1, level); // no 0-indent scalars
3640 // As indentation gets deeper, let the width decrease monotonically
3641 // to the lower bound min(state.lineWidth, 40).
3642 // Note that this implies
3643 // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
3644 // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
3645 // This behaves better than a constant minimum width which disallows narrower options,
3646 // or an indent threshold which causes the width to suddenly increase.
3648 var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); // Without knowing if keys are implicit/explicit, assume implicit for safety.
3650 var singleLineOnly = iskey // No block styles in flow mode.
3651 || state.flowLevel > -1 && level >= state.flowLevel;
3653 function testAmbiguity(string) {
3654 return testImplicitResolving(state, string);
3657 switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
3662 return "'" + string.replace(/'/g, "''") + "'";
3665 return '|' + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
3668 return '>' + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
3671 return '"' + escapeString(string) + '"';
3674 throw new exception('impossible error: invalid scalar style');
3677 } // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
3680 function blockHeader(string, indentPerLevel) {
3681 var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; // note the special case: the string '\n' counts as a "trailing" empty line.
3683 var clip = string[string.length - 1] === '\n';
3684 var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
3685 var chomp = keep ? '+' : clip ? '' : '-';
3686 return indentIndicator + chomp + '\n';
3687 } // (See the note for writeScalar.)
3690 function dropEndingNewline(string) {
3691 return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
3692 } // Note: a long line without a suitable break point will exceed the width limit.
3693 // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
3696 function foldString(string, width) {
3697 // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
3698 // unless they're before or after a more-indented line, or at the very
3699 // beginning or end, in which case $k$ maps to $k$.
3700 // Therefore, parse each chunk as newline(s) followed by a content line.
3701 var lineRe = /(\n+)([^\n]*)/g; // first line (possibly an empty line)
3703 var result = function () {
3704 var nextLF = string.indexOf('\n');
3705 nextLF = nextLF !== -1 ? nextLF : string.length;
3706 lineRe.lastIndex = nextLF;
3707 return foldLine(string.slice(0, nextLF), width);
3708 }(); // If we haven't reached the first content line yet, don't add an extra \n.
3711 var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
3712 var moreIndented; // rest of the lines
3716 while (match = lineRe.exec(string)) {
3717 var prefix = match[1],
3719 moreIndented = line[0] === ' ';
3720 result += prefix + (!prevMoreIndented && !moreIndented && line !== '' ? '\n' : '') + foldLine(line, width);
3721 prevMoreIndented = moreIndented;
3725 } // Greedy line breaking.
3726 // Picks the longest line under the limit each time,
3727 // otherwise settles for the shortest line over the limit.
3728 // NB. More-indented lines *cannot* be folded, as that would add an extra \n.
3731 function foldLine(line, width) {
3732 if (line === '' || line[0] === ' ') return line; // Since a more-indented line adds a \n, breaks can't be followed by a space.
3734 var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
3736 var match; // start is an inclusive index. end, curr, and next are exclusive.
3742 var result = ''; // Invariants: 0 <= start <= length-1.
3743 // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
3745 // A match implies length >= 2, so curr and next are <= length-2.
3747 while (match = breakRe.exec(line)) {
3748 next = match.index; // maintain invariant: curr - start <= width
3750 if (next - start > width) {
3751 end = curr > start ? curr : next; // derive end <= length-2
3753 result += '\n' + line.slice(start, end); // skip the space that was output as \n
3755 start = end + 1; // derive start <= length-1
3759 } // By the invariants, start <= length-1, so there is something left over.
3760 // It is either the whole string or a part starting from non-whitespace.
3763 result += '\n'; // Insert a break if the remainder is too long and there is a break available.
3765 if (line.length - start > width && curr > start) {
3766 result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
3768 result += line.slice(start);
3771 return result.slice(1); // drop extra \n joiner
3772 } // Escapes a double-quoted string.
3775 function escapeString(string) {
3780 for (var i = 0; i < string.length; i++) {
3781 char = string.charCodeAt(i); // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
3783 if (char >= 0xD800 && char <= 0xDBFF
3784 /* high surrogate */
3786 nextChar = string.charCodeAt(i + 1);
3788 if (nextChar >= 0xDC00 && nextChar <= 0xDFFF
3791 // Combine the surrogate pair and store it escaped.
3792 result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); // Advance index one extra since we already used that char here.
3799 escapeSeq = ESCAPE_SEQUENCES[char];
3800 result += !escapeSeq && isPrintable(char) ? string[i] : escapeSeq || encodeHex(char);
3806 function writeFlowSequence(state, level, object) {
3812 for (index = 0, length = object.length; index < length; index += 1) {
3813 // Write only valid elements.
3814 if (writeNode(state, level, object[index], false, false)) {
3815 if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
3816 _result += state.dump;
3821 state.dump = '[' + _result + ']';
3824 function writeBlockSequence(state, level, object, compact) {
3830 for (index = 0, length = object.length; index < length; index += 1) {
3831 // Write only valid elements.
3832 if (writeNode(state, level + 1, object[index], true, true)) {
3833 if (!compact || index !== 0) {
3834 _result += generateNextLine(state, level);
3837 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3843 _result += state.dump;
3848 state.dump = _result || '[]'; // Empty sequence if no valid values.
3851 function writeFlowMapping(state, level, object) {
3854 objectKeyList = Object.keys(object),
3861 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
3862 pairBuffer = state.condenseFlow ? '"' : '';
3863 if (index !== 0) pairBuffer += ', ';
3864 objectKey = objectKeyList[index];
3865 objectValue = object[objectKey];
3867 if (!writeNode(state, level, objectKey, false, false)) {
3868 continue; // Skip this pair because of invalid key;
3871 if (state.dump.length > 1024) pairBuffer += '? ';
3872 pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
3874 if (!writeNode(state, level, objectValue, false, false)) {
3875 continue; // Skip this pair because of invalid value.
3878 pairBuffer += state.dump; // Both key and value are valid.
3880 _result += pairBuffer;
3884 state.dump = '{' + _result + '}';
3887 function writeBlockMapping(state, level, object, compact) {
3890 objectKeyList = Object.keys(object),
3896 pairBuffer; // Allow sorting keys so that the output file is deterministic
3898 if (state.sortKeys === true) {
3900 objectKeyList.sort();
3901 } else if (typeof state.sortKeys === 'function') {
3902 // Custom sort function
3903 objectKeyList.sort(state.sortKeys);
3904 } else if (state.sortKeys) {
3905 // Something is wrong
3906 throw new exception('sortKeys must be a boolean or a function');
3909 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
3912 if (!compact || index !== 0) {
3913 pairBuffer += generateNextLine(state, level);
3916 objectKey = objectKeyList[index];
3917 objectValue = object[objectKey];
3919 if (!writeNode(state, level + 1, objectKey, true, true, true)) {
3920 continue; // Skip this pair because of invalid key.
3923 explicitPair = state.tag !== null && state.tag !== '?' || state.dump && state.dump.length > 1024;
3926 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3933 pairBuffer += state.dump;
3936 pairBuffer += generateNextLine(state, level);
3939 if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
3940 continue; // Skip this pair because of invalid value.
3943 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3949 pairBuffer += state.dump; // Both key and value are valid.
3951 _result += pairBuffer;
3955 state.dump = _result || '{}'; // Empty mapping if no valid pairs.
3958 function detectType(state, object, explicit) {
3959 var _result, typeList, index, length, type, style;
3961 typeList = explicit ? state.explicitTypes : state.implicitTypes;
3963 for (index = 0, length = typeList.length; index < length; index += 1) {
3964 type = typeList[index];
3966 if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === 'object' && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) {
3967 state.tag = explicit ? type.tag : '?';
3969 if (type.represent) {
3970 style = state.styleMap[type.tag] || type.defaultStyle;
3972 if (_toString$2.call(type.represent) === '[object Function]') {
3973 _result = type.represent(object, style);
3974 } else if (_hasOwnProperty$3.call(type.represent, style)) {
3975 _result = type.represent[style](object, style);
3977 throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
3980 state.dump = _result;
3988 } // Serializes `object` and writes it to global `result`.
3989 // Returns true on success, or false on invalid object.
3993 function writeNode(state, level, object, block, compact, iskey) {
3995 state.dump = object;
3997 if (!detectType(state, object, false)) {
3998 detectType(state, object, true);
4001 var type = _toString$2.call(state.dump);
4004 block = state.flowLevel < 0 || state.flowLevel > level;
4007 var objectOrArray = type === '[object Object]' || type === '[object Array]',
4011 if (objectOrArray) {
4012 duplicateIndex = state.duplicates.indexOf(object);
4013 duplicate = duplicateIndex !== -1;
4016 if (state.tag !== null && state.tag !== '?' || duplicate || state.indent !== 2 && level > 0) {
4020 if (duplicate && state.usedDuplicates[duplicateIndex]) {
4021 state.dump = '*ref_' + duplicateIndex;
4023 if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
4024 state.usedDuplicates[duplicateIndex] = true;
4027 if (type === '[object Object]') {
4028 if (block && Object.keys(state.dump).length !== 0) {
4029 writeBlockMapping(state, level, state.dump, compact);
4032 state.dump = '&ref_' + duplicateIndex + state.dump;
4035 writeFlowMapping(state, level, state.dump);
4038 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
4041 } else if (type === '[object Array]') {
4042 var arrayLevel = state.noArrayIndent && level > 0 ? level - 1 : level;
4044 if (block && state.dump.length !== 0) {
4045 writeBlockSequence(state, arrayLevel, state.dump, compact);
4048 state.dump = '&ref_' + duplicateIndex + state.dump;
4051 writeFlowSequence(state, arrayLevel, state.dump);
4054 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
4057 } else if (type === '[object String]') {
4058 if (state.tag !== '?') {
4059 writeScalar(state, state.dump, level, iskey);
4062 if (state.skipInvalid) return false;
4063 throw new exception('unacceptable kind of an object to dump ' + type);
4066 if (state.tag !== null && state.tag !== '?') {
4067 state.dump = '!<' + state.tag + '> ' + state.dump;
4074 function getDuplicateReferences(object, state) {
4076 duplicatesIndexes = [],
4079 inspectNode(object, objects, duplicatesIndexes);
4081 for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
4082 state.duplicates.push(objects[duplicatesIndexes[index]]);
4085 state.usedDuplicates = new Array(length);
4088 function inspectNode(object, objects, duplicatesIndexes) {
4089 var objectKeyList, index, length;
4091 if (object !== null && typeof object === 'object') {
4092 index = objects.indexOf(object);
4095 if (duplicatesIndexes.indexOf(index) === -1) {
4096 duplicatesIndexes.push(index);
4099 objects.push(object);
4101 if (Array.isArray(object)) {
4102 for (index = 0, length = object.length; index < length; index += 1) {
4103 inspectNode(object[index], objects, duplicatesIndexes);
4106 objectKeyList = Object.keys(object);
4108 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
4109 inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
4116 function dump(input, options) {
4117 options = options || {};
4118 var state = new State$1(options);
4119 if (!state.noRefs) getDuplicateReferences(input, state);
4120 if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
4124 function safeDump(input, options) {
4125 return dump(input, common.extend({
4126 schema: default_safe
4131 var safeDump_1 = safeDump;
4134 safeDump: safeDump_1
4137 function deprecated(name) {
4138 return function () {
4139 throw new Error('Function ' + name + ' is deprecated and cannot be used.');
4144 var Schema$1 = schema;
4145 var FAILSAFE_SCHEMA = failsafe;
4146 var JSON_SCHEMA = json;
4147 var CORE_SCHEMA = core;
4148 var DEFAULT_SAFE_SCHEMA = default_safe;
4149 var DEFAULT_FULL_SCHEMA = default_full;
4150 var load$1 = loader.load;
4151 var loadAll$1 = loader.loadAll;
4152 var safeLoad$1 = loader.safeLoad;
4153 var safeLoadAll$1 = loader.safeLoadAll;
4154 var dump$1 = dumper.dump;
4155 var safeDump$1 = dumper.safeDump;
4156 var YAMLException$1 = exception; // Deprecated schema names from JS-YAML 2.0.x
4158 var MINIMAL_SCHEMA = failsafe;
4159 var SAFE_SCHEMA = default_safe;
4160 var DEFAULT_SCHEMA = default_full; // Deprecated functions from JS-YAML 1.x.x
4162 var scan = deprecated('scan');
4163 var parse = deprecated('parse');
4164 var compose = deprecated('compose');
4165 var addConstructor = deprecated('addConstructor');
4169 FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,
4170 JSON_SCHEMA: JSON_SCHEMA,
4171 CORE_SCHEMA: CORE_SCHEMA,
4172 DEFAULT_SAFE_SCHEMA: DEFAULT_SAFE_SCHEMA,
4173 DEFAULT_FULL_SCHEMA: DEFAULT_FULL_SCHEMA,
4176 safeLoad: safeLoad$1,
4177 safeLoadAll: safeLoadAll$1,
4179 safeDump: safeDump$1,
4180 YAMLException: YAMLException$1,
4181 MINIMAL_SCHEMA: MINIMAL_SCHEMA,
4182 SAFE_SCHEMA: SAFE_SCHEMA,
4183 DEFAULT_SCHEMA: DEFAULT_SCHEMA,
4187 addConstructor: addConstructor
4190 var jsYaml$1 = jsYaml;
4192 var resolveFrom = function resolveFrom(fromDir, moduleId, silent) {
4193 if (typeof fromDir !== 'string') {
4194 throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDir}\``);
4197 if (typeof moduleId !== 'string') {
4198 throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
4201 fromDir = path.resolve(fromDir);
4202 var fromFile = path.join(fromDir, 'noop.js');
4204 var resolveFileName = function resolveFileName() {
4205 return module$1._resolveFilename(moduleId, {
4208 paths: module$1._nodeModulePaths(fromDir)
4214 return resolveFileName();
4220 return resolveFileName();
4223 var resolveFrom_1 = function resolveFrom_1(fromDir, moduleId) {
4224 return resolveFrom(fromDir, moduleId);
4227 var silent = function silent(fromDir, moduleId) {
4228 return resolveFrom(fromDir, moduleId, true);
4230 resolveFrom_1.silent = silent;
4232 var callsites = function callsites() {
4233 var _ = Error.prepareStackTrace;
4235 Error.prepareStackTrace = function (_, stack) {
4239 var stack = new Error().stack.slice(1);
4240 Error.prepareStackTrace = _;
4244 var callerCallsite = function callerCallsite() {
4245 var c = callsites();
4248 for (var i = 0; i < c.length; i++) {
4249 var hasReceiver = c[i].getTypeName() !== null;
4260 var callerPath = function callerPath() {
4261 return callerCallsite().getFileName();
4264 var importFresh = function importFresh(moduleId) {
4265 if (typeof moduleId !== 'string') {
4266 throw new TypeError('Expected a string');
4269 var filePath = resolveFrom_1(path.dirname(callerPath()), moduleId); // Delete itself from module parent
4271 if (require.cache[filePath] && require.cache[filePath].parent) {
4272 var i = require.cache[filePath].parent.children.length;
4275 if (require.cache[filePath].parent.children[i].id === filePath) {
4276 require.cache[filePath].parent.children.splice(i, 1);
4279 } // Delete module from cache
4282 delete require.cache[filePath]; // Return fresh module
4284 return require(filePath);
4287 function loadJs(filepath) {
4288 var result = importFresh(filepath);
4292 function loadJson(filepath, content) {
4294 return parseJson$1(content);
4296 err.message = `JSON Error in ${filepath}:\n${err.message}`;
4301 function loadYaml(filepath, content) {
4302 return jsYaml$1.safeLoad(content, {
4313 function readFile(filepath, options) {
4314 options = options || {};
4315 var throwNotFound = options.throwNotFound || false;
4316 return new Promise(function (resolve, reject) {
4317 fs.readFile(filepath, 'utf8', function (err, content) {
4318 if (err && err.code === 'ENOENT' && !throwNotFound) {
4319 return resolve(null);
4322 if (err) return reject(err);
4328 readFile.sync = function readFileSync(filepath, options) {
4329 options = options || {};
4330 var throwNotFound = options.throwNotFound || false;
4333 return fs.readFileSync(filepath, 'utf8');
4335 if (err.code === 'ENOENT' && !throwNotFound) {
4343 var readFile_1 = readFile;
4347 function cacheWrapper(cache, key, fn) {
4352 var cached = cache.get(key);
4354 if (cached !== undefined) {
4359 cache.set(key, result);
4363 var cacheWrapper_1 = cacheWrapper;
4370 function isDirectory(filepath, cb) {
4371 if (typeof cb !== 'function') {
4372 throw new Error('expected a callback function');
4375 if (typeof filepath !== 'string') {
4376 cb(new Error('expected filepath to be a string'));
4380 fs.stat(filepath, function (err, stats) {
4382 if (err.code === 'ENOENT') {
4391 cb(null, stats.isDirectory());
4399 isDirectory.sync = function isDirectorySync(filepath) {
4400 if (typeof filepath !== 'string') {
4401 throw new Error('expected filepath to be a string');
4405 var stat = fs.statSync(filepath);
4406 return stat.isDirectory();
4408 if (err.code === 'ENOENT') {
4418 * Expose `isDirectory`
4422 var isDirectory_1 = isDirectory;
4424 function getDirectory(filepath) {
4425 return new Promise(function (resolve, reject) {
4426 return isDirectory_1(filepath, function (err, filepathIsDirectory) {
4431 return resolve(filepathIsDirectory ? filepath : path.dirname(filepath));
4436 getDirectory.sync = function getDirectorySync(filepath) {
4437 return isDirectory_1.sync(filepath) ? filepath : path.dirname(filepath);
4440 var getDirectory_1 = getDirectory;
4443 // strings or arrays of strings. Property names that are found on the source
4444 // object are used directly (even if they include a period).
4445 // Nested property names that include periods, within a path, are only
4446 // understood in array paths.
4448 function getPropertyByPath(source, path) {
4449 if (typeof path === 'string' && source.hasOwnProperty(path)) {
4450 return source[path];
4453 var parsedPath = typeof path === 'string' ? path.split('.') : path;
4454 return parsedPath.reduce(function (previous, key) {
4455 if (previous === undefined) {
4459 return previous[key];
4463 var getPropertyByPath_1 = getPropertyByPath;
4465 var MODE_SYNC = 'sync'; // An object value represents a config object.
4466 // null represents that the loader did not find anything relevant.
4467 // undefined represents that the loader found something relevant
4468 // but it was empty.
4473 function Explorer(options) {
4474 _classCallCheck(this, Explorer);
4476 this.loadCache = options.cache ? new Map() : null;
4477 this.loadSyncCache = options.cache ? new Map() : null;
4478 this.searchCache = options.cache ? new Map() : null;
4479 this.searchSyncCache = options.cache ? new Map() : null;
4480 this.config = options;
4481 this.validateConfig();
4484 _createClass(Explorer, [{
4485 key: "clearLoadCache",
4486 value: function clearLoadCache() {
4487 if (this.loadCache) {
4488 this.loadCache.clear();
4491 if (this.loadSyncCache) {
4492 this.loadSyncCache.clear();
4496 key: "clearSearchCache",
4497 value: function clearSearchCache() {
4498 if (this.searchCache) {
4499 this.searchCache.clear();
4502 if (this.searchSyncCache) {
4503 this.searchSyncCache.clear();
4508 value: function clearCaches() {
4509 this.clearLoadCache();
4510 this.clearSearchCache();
4513 key: "validateConfig",
4514 value: function validateConfig() {
4515 var config = this.config;
4516 config.searchPlaces.forEach(function (place) {
4517 var loaderKey = path.extname(place) || 'noExt';
4518 var loader = config.loaders[loaderKey];
4521 throw new Error(`No loader specified for ${getExtensionDescription(place)}, so searchPlaces item "${place}" is invalid`);
4527 value: function search(searchFrom) {
4530 searchFrom = searchFrom || process.cwd();
4531 return getDirectory_1(searchFrom).then(function (dir) {
4532 return _this.searchFromDirectory(dir);
4536 key: "searchFromDirectory",
4537 value: function searchFromDirectory(dir) {
4540 var absoluteDir = path.resolve(process.cwd(), dir);
4542 var run = function run() {
4543 return _this2.searchDirectory(absoluteDir).then(function (result) {
4544 var nextDir = _this2.nextDirectoryToSearch(absoluteDir, result);
4547 return _this2.searchFromDirectory(nextDir);
4550 return _this2.config.transform(result);
4554 if (this.searchCache) {
4555 return cacheWrapper_1(this.searchCache, absoluteDir, run);
4562 value: function searchSync(searchFrom) {
4563 searchFrom = searchFrom || process.cwd();
4564 var dir = getDirectory_1.sync(searchFrom);
4565 return this.searchFromDirectorySync(dir);
4568 key: "searchFromDirectorySync",
4569 value: function searchFromDirectorySync(dir) {
4572 var absoluteDir = path.resolve(process.cwd(), dir);
4574 var run = function run() {
4575 var result = _this3.searchDirectorySync(absoluteDir);
4577 var nextDir = _this3.nextDirectoryToSearch(absoluteDir, result);
4580 return _this3.searchFromDirectorySync(nextDir);
4583 return _this3.config.transform(result);
4586 if (this.searchSyncCache) {
4587 return cacheWrapper_1(this.searchSyncCache, absoluteDir, run);
4593 key: "searchDirectory",
4594 value: function searchDirectory(dir) {
4597 return this.config.searchPlaces.reduce(function (prevResultPromise, place) {
4598 return prevResultPromise.then(function (prevResult) {
4599 if (_this4.shouldSearchStopWithResult(prevResult)) {
4603 return _this4.loadSearchPlace(dir, place);
4605 }, Promise.resolve(null));
4608 key: "searchDirectorySync",
4609 value: function searchDirectorySync(dir) {
4611 var _iteratorNormalCompletion = true;
4612 var _didIteratorError = false;
4613 var _iteratorError = undefined;
4616 for (var _iterator = this.config.searchPlaces[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
4617 var place = _step.value;
4618 result = this.loadSearchPlaceSync(dir, place);
4619 if (this.shouldSearchStopWithResult(result)) break;
4622 _didIteratorError = true;
4623 _iteratorError = err;
4626 if (!_iteratorNormalCompletion && _iterator.return != null) {
4630 if (_didIteratorError) {
4631 throw _iteratorError;
4639 key: "shouldSearchStopWithResult",
4640 value: function shouldSearchStopWithResult(result) {
4641 if (result === null) return false;
4642 if (result.isEmpty && this.config.ignoreEmptySearchPlaces) return false;
4646 key: "loadSearchPlace",
4647 value: function loadSearchPlace(dir, place) {
4650 var filepath = path.join(dir, place);
4651 return readFile_1(filepath).then(function (content) {
4652 return _this5.createCosmiconfigResult(filepath, content);
4656 key: "loadSearchPlaceSync",
4657 value: function loadSearchPlaceSync(dir, place) {
4658 var filepath = path.join(dir, place);
4659 var content = readFile_1.sync(filepath);
4660 return this.createCosmiconfigResultSync(filepath, content);
4663 key: "nextDirectoryToSearch",
4664 value: function nextDirectoryToSearch(currentDir, currentResult) {
4665 if (this.shouldSearchStopWithResult(currentResult)) {
4669 var nextDir = nextDirUp(currentDir);
4671 if (nextDir === currentDir || currentDir === this.config.stopDir) {
4678 key: "loadPackageProp",
4679 value: function loadPackageProp(filepath, content) {
4680 var parsedContent = loaders.loadJson(filepath, content);
4681 var packagePropValue = getPropertyByPath_1(parsedContent, this.config.packageProp);
4682 return packagePropValue || null;
4685 key: "getLoaderEntryForFile",
4686 value: function getLoaderEntryForFile(filepath) {
4687 if (path.basename(filepath) === 'package.json') {
4688 var loader = this.loadPackageProp.bind(this);
4695 var loaderKey = path.extname(filepath) || 'noExt';
4696 return this.config.loaders[loaderKey] || {};
4699 key: "getSyncLoaderForFile",
4700 value: function getSyncLoaderForFile(filepath) {
4701 var entry = this.getLoaderEntryForFile(filepath);
4704 throw new Error(`No sync loader specified for ${getExtensionDescription(filepath)}`);
4710 key: "getAsyncLoaderForFile",
4711 value: function getAsyncLoaderForFile(filepath) {
4712 var entry = this.getLoaderEntryForFile(filepath);
4713 var loader = entry.async || entry.sync;
4716 throw new Error(`No async loader specified for ${getExtensionDescription(filepath)}`);
4722 key: "loadFileContent",
4723 value: function loadFileContent(mode, filepath, content) {
4724 if (content === null) {
4728 if (content.trim() === '') {
4732 var loader = mode === MODE_SYNC ? this.getSyncLoaderForFile(filepath) : this.getAsyncLoaderForFile(filepath);
4733 return loader(filepath, content);
4736 key: "loadedContentToCosmiconfigResult",
4737 value: function loadedContentToCosmiconfigResult(filepath, loadedContent) {
4738 if (loadedContent === null) {
4742 if (loadedContent === undefined) {
4751 config: loadedContent,
4756 key: "createCosmiconfigResult",
4757 value: function createCosmiconfigResult(filepath, content) {
4760 return Promise.resolve().then(function () {
4761 return _this6.loadFileContent('async', filepath, content);
4762 }).then(function (loaderResult) {
4763 return _this6.loadedContentToCosmiconfigResult(filepath, loaderResult);
4767 key: "createCosmiconfigResultSync",
4768 value: function createCosmiconfigResultSync(filepath, content) {
4769 var loaderResult = this.loadFileContent('sync', filepath, content);
4770 return this.loadedContentToCosmiconfigResult(filepath, loaderResult);
4773 key: "validateFilePath",
4774 value: function validateFilePath(filepath) {
4776 throw new Error('load and loadSync must pass a non-empty string');
4781 value: function load(filepath) {
4784 return Promise.resolve().then(function () {
4785 _this7.validateFilePath(filepath);
4787 var absoluteFilePath = path.resolve(process.cwd(), filepath);
4788 return cacheWrapper_1(_this7.loadCache, absoluteFilePath, function () {
4789 return readFile_1(absoluteFilePath, {
4791 }).then(function (content) {
4792 return _this7.createCosmiconfigResult(absoluteFilePath, content);
4793 }).then(_this7.config.transform);
4799 value: function loadSync(filepath) {
4802 this.validateFilePath(filepath);
4803 var absoluteFilePath = path.resolve(process.cwd(), filepath);
4804 return cacheWrapper_1(this.loadSyncCache, absoluteFilePath, function () {
4805 var content = readFile_1.sync(absoluteFilePath, {
4809 var result = _this8.createCosmiconfigResultSync(absoluteFilePath, content);
4811 return _this8.config.transform(result);
4819 var createExplorer = function createExplorer(options) {
4820 var explorer = new Explorer(options);
4822 search: explorer.search.bind(explorer),
4823 searchSync: explorer.searchSync.bind(explorer),
4824 load: explorer.load.bind(explorer),
4825 loadSync: explorer.loadSync.bind(explorer),
4826 clearLoadCache: explorer.clearLoadCache.bind(explorer),
4827 clearSearchCache: explorer.clearSearchCache.bind(explorer),
4828 clearCaches: explorer.clearCaches.bind(explorer)
4832 function nextDirUp(dir) {
4833 return path.dirname(dir);
4836 function getExtensionDescription(filepath) {
4837 var ext = path.extname(filepath);
4838 return ext ? `extension "${ext}"` : 'files without extensions';
4841 var dist = cosmiconfig;
4843 function cosmiconfig(moduleName, options) {
4844 options = options || {};
4846 packageProp: moduleName,
4847 searchPlaces: ['package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.js`, `${moduleName}.config.js`],
4848 ignoreEmptySearchPlaces: true,
4849 stopDir: os.homedir(),
4853 var normalizedOptions = Object.assign({}, defaults, options, {
4854 loaders: normalizeLoaders(options.loaders)
4856 return createExplorer(normalizedOptions);
4859 cosmiconfig.loadJs = loaders.loadJs;
4860 cosmiconfig.loadJson = loaders.loadJson;
4861 cosmiconfig.loadYaml = loaders.loadYaml;
4863 function normalizeLoaders(rawLoaders) {
4866 sync: loaders.loadJs,
4867 async: loaders.loadJs
4870 sync: loaders.loadJson,
4871 async: loaders.loadJson
4874 sync: loaders.loadYaml,
4875 async: loaders.loadYaml
4878 sync: loaders.loadYaml,
4879 async: loaders.loadYaml
4882 sync: loaders.loadYaml,
4883 async: loaders.loadYaml
4891 return Object.keys(rawLoaders).reduce(function (result, ext) {
4892 var entry = rawLoaders && rawLoaders[ext];
4894 if (typeof entry === 'function') {
4900 result[ext] = entry;
4907 function identity(x) {
4911 var findParentDir = createCommonjsModule(function (module, exports) {
4913 var exists = fs.exists || path.exists,
4914 existsSync = fs.existsSync || path.existsSync;
4916 function splitPath(path) {
4917 var parts = path.split(/(\/|\\)/);
4918 if (!parts.length) return parts; // when path starts with a slash, the first part is empty string
4920 return !parts[0].length ? parts.slice(1) : parts;
4923 exports = module.exports = function (currentFullPath, clue, cb) {
4924 function testDir(parts) {
4925 if (parts.length === 0) return cb(null, null);
4926 var p = parts.join('');
4927 exists(path.join(p, clue), function (itdoes) {
4928 if (itdoes) return cb(null, p);
4929 testDir(parts.slice(0, -1));
4933 testDir(splitPath(currentFullPath));
4936 exports.sync = function (currentFullPath, clue) {
4937 function testDir(parts) {
4938 if (parts.length === 0) return null;
4939 var p = parts.join('');
4940 var itdoes = existsSync(path.join(p, clue));
4941 return itdoes ? p : testDir(parts.slice(0, -1));
4944 return testDir(splitPath(currentFullPath));
4947 var findParentDir_1 = findParentDir.sync;
4949 // Returns a wrapper function that returns a wrapped callback
4950 // The wrapper function should do some stuff, and return a
4951 // presumably different callback function.
4952 // This makes sure that own properties are retained, so that
4953 // decorations and such are not lost along the way.
4954 var wrappy_1 = wrappy;
4956 function wrappy(fn, cb) {
4957 if (fn && cb) return wrappy(fn)(cb);
4958 if (typeof fn !== 'function') throw new TypeError('need wrapper function');
4959 Object.keys(fn).forEach(function (k) {
4964 function wrapper() {
4965 var args = new Array(arguments.length);
4967 for (var i = 0; i < args.length; i++) {
4968 args[i] = arguments[i];
4971 var ret = fn.apply(this, args);
4972 var cb = args[args.length - 1];
4974 if (typeof ret === 'function' && ret !== cb) {
4975 Object.keys(cb).forEach(function (k) {
4984 var once_1 = wrappy_1(once);
4985 var strict = wrappy_1(onceStrict);
4986 once.proto = once(function () {
4987 Object.defineProperty(Function.prototype, 'once', {
4988 value: function value() {
4993 Object.defineProperty(Function.prototype, 'onceStrict', {
4994 value: function value() {
4995 return onceStrict(this);
5002 var f = function f() {
5003 if (f.called) return f.value;
5005 return f.value = fn.apply(this, arguments);
5012 function onceStrict(fn) {
5013 var f = function f() {
5014 if (f.called) throw new Error(f.onceError);
5016 return f.value = fn.apply(this, arguments);
5019 var name = fn.name || 'Function wrapped with `once`';
5020 f.onceError = name + " shouldn't be called more than once";
5024 once_1.strict = strict;
5026 var noop = function noop() {};
5028 var isRequest = function isRequest(stream) {
5029 return stream.setHeader && typeof stream.abort === 'function';
5032 var isChildProcess = function isChildProcess(stream) {
5033 return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3;
5036 var eos = function eos(stream, opts, callback) {
5037 if (typeof opts === 'function') return eos(stream, null, opts);
5038 if (!opts) opts = {};
5039 callback = once_1(callback || noop);
5040 var ws = stream._writableState;
5041 var rs = stream._readableState;
5042 var readable = opts.readable || opts.readable !== false && stream.readable;
5043 var writable = opts.writable || opts.writable !== false && stream.writable;
5045 var onlegacyfinish = function onlegacyfinish() {
5046 if (!stream.writable) onfinish();
5049 var onfinish = function onfinish() {
5051 if (!readable) callback.call(stream);
5054 var onend = function onend() {
5056 if (!writable) callback.call(stream);
5059 var onexit = function onexit(exitCode) {
5060 callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
5063 var onerror = function onerror(err) {
5064 callback.call(stream, err);
5067 var onclose = function onclose() {
5068 if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
5069 if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
5072 var onrequest = function onrequest() {
5073 stream.req.on('finish', onfinish);
5076 if (isRequest(stream)) {
5077 stream.on('complete', onfinish);
5078 stream.on('abort', onclose);
5079 if (stream.req) onrequest();else stream.on('request', onrequest);
5080 } else if (writable && !ws) {
5082 stream.on('end', onlegacyfinish);
5083 stream.on('close', onlegacyfinish);
5086 if (isChildProcess(stream)) stream.on('exit', onexit);
5087 stream.on('end', onend);
5088 stream.on('finish', onfinish);
5089 if (opts.error !== false) stream.on('error', onerror);
5090 stream.on('close', onclose);
5091 return function () {
5092 stream.removeListener('complete', onfinish);
5093 stream.removeListener('abort', onclose);
5094 stream.removeListener('request', onrequest);
5095 if (stream.req) stream.req.removeListener('finish', onfinish);
5096 stream.removeListener('end', onlegacyfinish);
5097 stream.removeListener('close', onlegacyfinish);
5098 stream.removeListener('finish', onfinish);
5099 stream.removeListener('exit', onexit);
5100 stream.removeListener('end', onend);
5101 stream.removeListener('error', onerror);
5102 stream.removeListener('close', onclose);
5106 var endOfStream = eos;
5108 var noop$1 = function noop() {};
5110 var ancient = /^v?\.0/.test(process.version);
5112 var isFn = function isFn(fn) {
5113 return typeof fn === 'function';
5116 var isFS = function isFS(stream) {
5117 if (!ancient) return false; // newer node version do not need to care about fs is a special way
5119 if (!fs) return false; // browser
5121 return (stream instanceof (fs.ReadStream || noop$1) || stream instanceof (fs.WriteStream || noop$1)) && isFn(stream.close);
5124 var isRequest$1 = function isRequest(stream) {
5125 return stream.setHeader && isFn(stream.abort);
5128 var destroyer = function destroyer(stream, reading, writing, callback) {
5129 callback = once_1(callback);
5131 stream.on('close', function () {
5134 endOfStream(stream, {
5138 if (err) return callback(err);
5142 var destroyed = false;
5143 return function (err) {
5145 if (destroyed) return;
5147 if (isFS(stream)) return stream.close(noop$1); // use close for fs streams to avoid fd leaks
5149 if (isRequest$1(stream)) return stream.abort(); // request.destroy just do .end - .abort is what we want
5151 if (isFn(stream.destroy)) return stream.destroy();
5152 callback(err || new Error('stream was destroyed'));
5156 var call = function call(fn) {
5160 var pipe = function pipe(from, to) {
5161 return from.pipe(to);
5164 var pump = function pump() {
5165 var streams = Array.prototype.slice.call(arguments);
5166 var callback = isFn(streams[streams.length - 1] || noop$1) && streams.pop() || noop$1;
5167 if (Array.isArray(streams[0])) streams = streams[0];
5168 if (streams.length < 2) throw new Error('pump requires two streams per minimum');
5170 var destroys = streams.map(function (stream, i) {
5171 var reading = i < streams.length - 1;
5172 var writing = i > 0;
5173 return destroyer(stream, reading, writing, function (err) {
5174 if (!error) error = err;
5175 if (err) destroys.forEach(call);
5176 if (reading) return;
5177 destroys.forEach(call);
5181 return streams.reduce(pipe);
5186 var PassThrough = stream.PassThrough;
5188 var bufferStream = function bufferStream(options) {
5189 options = Object.assign({}, options);
5190 var _options = options,
5191 array = _options.array;
5192 var _options2 = options,
5193 encoding = _options2.encoding;
5194 var buffer = encoding === 'buffer';
5195 var objectMode = false;
5198 objectMode = !(encoding || buffer);
5200 encoding = encoding || 'utf8';
5209 var stream = new PassThrough({
5214 stream.setEncoding(encoding);
5217 stream.on('data', function (chunk) {
5223 len += chunk.length;
5227 stream.getBufferedValue = function () {
5232 return buffer ? Buffer.concat(ret, len) : ret.join('');
5235 stream.getBufferedLength = function () {
5242 var MaxBufferError =
5245 _inherits(MaxBufferError, _Error);
5247 function MaxBufferError() {
5250 _classCallCheck(this, MaxBufferError);
5252 _this = _possibleConstructorReturn(this, _getPrototypeOf(MaxBufferError).call(this, 'maxBuffer exceeded'));
5253 _this.name = 'MaxBufferError';
5257 return MaxBufferError;
5258 }(_wrapNativeSuper(Error));
5260 function getStream(inputStream, options) {
5262 return Promise.reject(new Error('Expected a stream'));
5265 options = Object.assign({
5268 var _options = options,
5269 maxBuffer = _options.maxBuffer;
5271 return new Promise(function (resolve, reject) {
5272 var rejectPromise = function rejectPromise(error) {
5275 error.bufferedData = stream.getBufferedValue();
5281 stream = pump_1(inputStream, bufferStream(options), function (error) {
5283 rejectPromise(error);
5289 stream.on('data', function () {
5290 if (stream.getBufferedLength() > maxBuffer) {
5291 rejectPromise(new MaxBufferError());
5294 }).then(function () {
5295 return stream.getBufferedValue();
5299 var getStream_1 = getStream;
5301 var buffer = function buffer(stream, options) {
5302 return getStream(stream, Object.assign({}, options, {
5307 var array = function array(stream, options) {
5308 return getStream(stream, Object.assign({}, options, {
5313 var MaxBufferError_1 = MaxBufferError;
5314 getStream_1.buffer = buffer;
5315 getStream_1.array = array;
5316 getStream_1.MaxBufferError = MaxBufferError_1;
5321 constant: "APPVEYOR",
5323 pr: "APPVEYOR_PULL_REQUEST_NUMBER"
5326 name: "Azure Pipelines",
5327 constant: "AZURE_PIPELINES",
5328 env: "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI",
5329 pr: "SYSTEM_PULLREQUEST_PULLREQUESTID"
5334 env: "bamboo_planKey"
5337 name: "Bitbucket Pipelines",
5338 constant: "BITBUCKET",
5339 env: "BITBUCKET_COMMIT",
5340 pr: "BITBUCKET_PR_ID"
5344 constant: "BITRISE",
5346 pr: "BITRISE_PULL_REQUEST"
5351 env: "BUDDY_WORKSPACE_ID",
5352 pr: "BUDDY_EXECUTION_PULL_REQUEST_ID"
5356 constant: "BUILDKITE",
5359 env: "BUILDKITE_PULL_REQUEST",
5367 pr: "CIRCLE_PULL_REQUEST"
5376 name: "AWS CodeBuild",
5377 constant: "CODEBUILD",
5378 env: "CODEBUILD_BUILD_ARN"
5382 constant: "CODESHIP",
5392 DRONE_BUILD_EVENT: "pull_request"
5408 env: "GO_PIPELINE_LABEL"
5417 constant: "JENKINS",
5436 constant: "NETLIFY",
5437 env: "NETLIFY_BUILD_BASE",
5439 env: "PULL_REQUEST",
5447 pr: "SAIL_PULL_REQUEST_NUMBER"
5451 constant: "SEMAPHORE",
5453 pr: "PULL_REQUEST_NUMBER"
5457 constant: "SHIPPABLE",
5460 IS_PULL_REQUEST: "true"
5471 constant: "STRIDER",
5475 name: "TaskCluster",
5476 constant: "TASKCLUSTER",
5484 constant: "TEAMCITY",
5485 env: "TEAMCITY_VERSION"
5492 env: "TRAVIS_PULL_REQUEST",
5498 var vendors$1 = /*#__PURE__*/Object.freeze({
5503 var vendors$2 = getCjsExportFromNamespace(vendors$1);
5505 var ciInfo = createCommonjsModule(function (module, exports) {
5507 var env = process.env; // Used for testing only
5509 Object.defineProperty(exports, '_vendors', {
5510 value: vendors$2.map(function (v) {
5514 exports.name = null;
5515 exports.isPR = null;
5516 vendors$2.forEach(function (vendor) {
5517 var envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
5518 var isCI = envs.every(function (obj) {
5519 return checkEnv(obj);
5521 exports[vendor.constant] = isCI;
5524 exports.name = vendor.name;
5526 switch (typeof vendor.pr) {
5528 // "pr": "CIRRUS_PR"
5529 exports.isPR = !!env[vendor.pr];
5533 if ('env' in vendor.pr) {
5534 // "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" }
5535 exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne;
5536 } else if ('any' in vendor.pr) {
5537 // "pr": { "any": ["ghprbPullId", "CHANGE_ID"] }
5538 exports.isPR = vendor.pr.any.some(function (key) {
5542 // "pr": { "DRONE_BUILD_EVENT": "pull_request" }
5543 exports.isPR = checkEnv(vendor.pr);
5549 // PR detection not supported for this vendor
5550 exports.isPR = null;
5554 exports.isCI = !!(env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari
5555 env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
5556 env.BUILD_NUMBER || // Jenkins, TeamCity
5557 env.RUN_ID || // TaskCluster, dsari
5558 exports.name || false);
5560 function checkEnv(obj) {
5561 if (typeof obj === 'string') return !!env[obj];
5562 return Object.keys(obj).every(function (k) {
5563 return env[k] === obj[k];
5567 var ciInfo_1 = ciInfo.name;
5568 var ciInfo_2 = ciInfo.isPR;
5569 var ciInfo_3 = ciInfo.isCI;
5571 var isCi = ciInfo.isCI;
5575 findParentDir: findParentDir.sync,
5576 getStream: getStream_1,
5577 isCI: function isCI() {
5581 var thirdParty_1 = thirdParty.cosmiconfig;
5582 var thirdParty_2 = thirdParty.findParentDir;
5583 var thirdParty_3 = thirdParty.getStream;
5584 var thirdParty_4 = thirdParty.isCI;
5586 exports.cosmiconfig = thirdParty_1;
5587 exports.default = thirdParty;
5588 exports.findParentDir = thirdParty_2;
5589 exports.getStream = thirdParty_3;
5590 exports.isCI = thirdParty_4;