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

5590 lines
141 KiB

4 years ago
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  4. var os = _interopDefault(require('os'));
  5. var path = _interopDefault(require('path'));
  6. var util = _interopDefault(require('util'));
  7. var module$1 = _interopDefault(require('module'));
  8. var fs = _interopDefault(require('fs'));
  9. var stream = _interopDefault(require('stream'));
  10. function _classCallCheck(instance, Constructor) {
  11. if (!(instance instanceof Constructor)) {
  12. throw new TypeError("Cannot call a class as a function");
  13. }
  14. }
  15. function _defineProperties(target, props) {
  16. for (var i = 0; i < props.length; i++) {
  17. var descriptor = props[i];
  18. descriptor.enumerable = descriptor.enumerable || false;
  19. descriptor.configurable = true;
  20. if ("value" in descriptor) descriptor.writable = true;
  21. Object.defineProperty(target, descriptor.key, descriptor);
  22. }
  23. }
  24. function _createClass(Constructor, protoProps, staticProps) {
  25. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  26. if (staticProps) _defineProperties(Constructor, staticProps);
  27. return Constructor;
  28. }
  29. function _inherits(subClass, superClass) {
  30. if (typeof superClass !== "function" && superClass !== null) {
  31. throw new TypeError("Super expression must either be null or a function");
  32. }
  33. subClass.prototype = Object.create(superClass && superClass.prototype, {
  34. constructor: {
  35. value: subClass,
  36. writable: true,
  37. configurable: true
  38. }
  39. });
  40. if (superClass) _setPrototypeOf(subClass, superClass);
  41. }
  42. function _getPrototypeOf(o) {
  43. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  44. return o.__proto__ || Object.getPrototypeOf(o);
  45. };
  46. return _getPrototypeOf(o);
  47. }
  48. function _setPrototypeOf(o, p) {
  49. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  50. o.__proto__ = p;
  51. return o;
  52. };
  53. return _setPrototypeOf(o, p);
  54. }
  55. function isNativeReflectConstruct() {
  56. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  57. if (Reflect.construct.sham) return false;
  58. if (typeof Proxy === "function") return true;
  59. try {
  60. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  61. return true;
  62. } catch (e) {
  63. return false;
  64. }
  65. }
  66. function _construct(Parent, args, Class) {
  67. if (isNativeReflectConstruct()) {
  68. _construct = Reflect.construct;
  69. } else {
  70. _construct = function _construct(Parent, args, Class) {
  71. var a = [null];
  72. a.push.apply(a, args);
  73. var Constructor = Function.bind.apply(Parent, a);
  74. var instance = new Constructor();
  75. if (Class) _setPrototypeOf(instance, Class.prototype);
  76. return instance;
  77. };
  78. }
  79. return _construct.apply(null, arguments);
  80. }
  81. function _isNativeFunction(fn) {
  82. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  83. }
  84. function _wrapNativeSuper(Class) {
  85. var _cache = typeof Map === "function" ? new Map() : undefined;
  86. _wrapNativeSuper = function _wrapNativeSuper(Class) {
  87. if (Class === null || !_isNativeFunction(Class)) return Class;
  88. if (typeof Class !== "function") {
  89. throw new TypeError("Super expression must either be null or a function");
  90. }
  91. if (typeof _cache !== "undefined") {
  92. if (_cache.has(Class)) return _cache.get(Class);
  93. _cache.set(Class, Wrapper);
  94. }
  95. function Wrapper() {
  96. return _construct(Class, arguments, _getPrototypeOf(this).constructor);
  97. }
  98. Wrapper.prototype = Object.create(Class.prototype, {
  99. constructor: {
  100. value: Wrapper,
  101. enumerable: false,
  102. writable: true,
  103. configurable: true
  104. }
  105. });
  106. return _setPrototypeOf(Wrapper, Class);
  107. };
  108. return _wrapNativeSuper(Class);
  109. }
  110. function _assertThisInitialized(self) {
  111. if (self === void 0) {
  112. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  113. }
  114. return self;
  115. }
  116. function _possibleConstructorReturn(self, call) {
  117. if (call && (typeof call === "object" || typeof call === "function")) {
  118. return call;
  119. }
  120. return _assertThisInitialized(self);
  121. }
  122. var isArrayish = function isArrayish(obj) {
  123. if (!obj) {
  124. return false;
  125. }
  126. return obj instanceof Array || Array.isArray(obj) || obj.length >= 0 && obj.splice instanceof Function;
  127. };
  128. var errorEx = function errorEx(name, properties) {
  129. if (!name || name.constructor !== String) {
  130. properties = name || {};
  131. name = Error.name;
  132. }
  133. var errorExError = function ErrorEXError(message) {
  134. if (!this) {
  135. return new ErrorEXError(message);
  136. }
  137. message = message instanceof Error ? message.message : message || this.message;
  138. Error.call(this, message);
  139. Error.captureStackTrace(this, errorExError);
  140. this.name = name;
  141. Object.defineProperty(this, 'message', {
  142. configurable: true,
  143. enumerable: false,
  144. get: function get() {
  145. var newMessage = message.split(/\r?\n/g);
  146. for (var key in properties) {
  147. if (!properties.hasOwnProperty(key)) {
  148. continue;
  149. }
  150. var modifier = properties[key];
  151. if ('message' in modifier) {
  152. newMessage = modifier.message(this[key], newMessage) || newMessage;
  153. if (!isArrayish(newMessage)) {
  154. newMessage = [newMessage];
  155. }
  156. }
  157. }
  158. return newMessage.join('\n');
  159. },
  160. set: function set(v) {
  161. message = v;
  162. }
  163. });
  164. var overwrittenStack = null;
  165. var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
  166. var stackGetter = stackDescriptor.get;
  167. var stackValue = stackDescriptor.value;
  168. delete stackDescriptor.value;
  169. delete stackDescriptor.writable;
  170. stackDescriptor.set = function (newstack) {
  171. overwrittenStack = newstack;
  172. };
  173. stackDescriptor.get = function () {
  174. var stack = (overwrittenStack || (stackGetter ? stackGetter.call(this) : stackValue)).split(/\r?\n+/g); // starting in Node 7, the stack builder caches the message.
  175. // just replace it.
  176. if (!overwrittenStack) {
  177. stack[0] = this.name + ': ' + this.message;
  178. }
  179. var lineCount = 1;
  180. for (var key in properties) {
  181. if (!properties.hasOwnProperty(key)) {
  182. continue;
  183. }
  184. var modifier = properties[key];
  185. if ('line' in modifier) {
  186. var line = modifier.line(this[key]);
  187. if (line) {
  188. stack.splice(lineCount++, 0, ' ' + line);
  189. }
  190. }
  191. if ('stack' in modifier) {
  192. modifier.stack(this[key], stack);
  193. }
  194. }
  195. return stack.join('\n');
  196. };
  197. Object.defineProperty(this, 'stack', stackDescriptor);
  198. };
  199. if (Object.setPrototypeOf) {
  200. Object.setPrototypeOf(errorExError.prototype, Error.prototype);
  201. Object.setPrototypeOf(errorExError, Error);
  202. } else {
  203. util.inherits(errorExError, Error);
  204. }
  205. return errorExError;
  206. };
  207. errorEx.append = function (str, def) {
  208. return {
  209. message: function message(v, _message) {
  210. v = v || def;
  211. if (v) {
  212. _message[0] += ' ' + str.replace('%s', v.toString());
  213. }
  214. return _message;
  215. }
  216. };
  217. };
  218. errorEx.line = function (str, def) {
  219. return {
  220. line: function line(v) {
  221. v = v || def;
  222. if (v) {
  223. return str.replace('%s', v.toString());
  224. }
  225. return null;
  226. }
  227. };
  228. };
  229. var errorEx_1 = errorEx;
  230. var jsonParseBetterErrors = parseJson;
  231. function parseJson(txt, reviver, context) {
  232. context = context || 20;
  233. try {
  234. return JSON.parse(txt, reviver);
  235. } catch (e) {
  236. if (typeof txt !== 'string') {
  237. var isEmptyArray = Array.isArray(txt) && txt.length === 0;
  238. var errorMessage = 'Cannot parse ' + (isEmptyArray ? 'an empty array' : String(txt));
  239. throw new TypeError(errorMessage);
  240. }
  241. var syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i);
  242. var errIdx = syntaxErr ? +syntaxErr[1] : e.message.match(/^Unexpected end of JSON.*/i) ? txt.length - 1 : null;
  243. if (errIdx != null) {
  244. var start = errIdx <= context ? 0 : errIdx - context;
  245. var end = errIdx + context >= txt.length ? txt.length : errIdx + context;
  246. e.message += ` while parsing near '${start === 0 ? '' : '...'}${txt.slice(start, end)}${end === txt.length ? '' : '...'}'`;
  247. } else {
  248. e.message += ` while parsing '${txt.slice(0, context * 2)}'`;
  249. }
  250. throw e;
  251. }
  252. }
  253. var JSONError = errorEx_1('JSONError', {
  254. fileName: errorEx_1.append('in %s')
  255. });
  256. var parseJson$1 = function parseJson(input, reviver, filename) {
  257. if (typeof reviver === 'string') {
  258. filename = reviver;
  259. reviver = null;
  260. }
  261. try {
  262. try {
  263. return JSON.parse(input, reviver);
  264. } catch (err) {
  265. jsonParseBetterErrors(input, reviver);
  266. throw err;
  267. }
  268. } catch (err) {
  269. err.message = err.message.replace(/\n/g, '');
  270. var jsonErr = new JSONError(err);
  271. if (filename) {
  272. jsonErr.fileName = filename;
  273. }
  274. throw jsonErr;
  275. }
  276. };
  277. function isNothing(subject) {
  278. return typeof subject === 'undefined' || subject === null;
  279. }
  280. function isObject(subject) {
  281. return typeof subject === 'object' && subject !== null;
  282. }
  283. function toArray(sequence) {
  284. if (Array.isArray(sequence)) return sequence;else if (isNothing(sequence)) return [];
  285. return [sequence];
  286. }
  287. function extend(target, source) {
  288. var index, length, key, sourceKeys;
  289. if (source) {
  290. sourceKeys = Object.keys(source);
  291. for (index = 0, length = sourceKeys.length; index < length; index += 1) {
  292. key = sourceKeys[index];
  293. target[key] = source[key];
  294. }
  295. }
  296. return target;
  297. }
  298. function repeat(string, count) {
  299. var result = '',
  300. cycle;
  301. for (cycle = 0; cycle < count; cycle += 1) {
  302. result += string;
  303. }
  304. return result;
  305. }
  306. function isNegativeZero(number) {
  307. return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
  308. }
  309. var isNothing_1 = isNothing;
  310. var isObject_1 = isObject;
  311. var toArray_1 = toArray;
  312. var repeat_1 = repeat;
  313. var isNegativeZero_1 = isNegativeZero;
  314. var extend_1 = extend;
  315. var common = {
  316. isNothing: isNothing_1,
  317. isObject: isObject_1,
  318. toArray: toArray_1,
  319. repeat: repeat_1,
  320. isNegativeZero: isNegativeZero_1,
  321. extend: extend_1
  322. };
  323. // YAML error class. http://stackoverflow.com/questions/8458984
  324. function YAMLException(reason, mark) {
  325. // Super constructor
  326. Error.call(this);
  327. this.name = 'YAMLException';
  328. this.reason = reason;
  329. this.mark = mark;
  330. this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); // Include stack trace in error object
  331. if (Error.captureStackTrace) {
  332. // Chrome and NodeJS
  333. Error.captureStackTrace(this, this.constructor);
  334. } else {
  335. // FF, IE 10+ and Safari 6+. Fallback for others
  336. this.stack = new Error().stack || '';
  337. }
  338. } // Inherit from Error
  339. YAMLException.prototype = Object.create(Error.prototype);
  340. YAMLException.prototype.constructor = YAMLException;
  341. YAMLException.prototype.toString = function toString(compact) {
  342. var result = this.name + ': ';
  343. result += this.reason || '(unknown reason)';
  344. if (!compact && this.mark) {
  345. result += ' ' + this.mark.toString();
  346. }
  347. return result;
  348. };
  349. var exception = YAMLException;
  350. function Mark(name, buffer, position, line, column) {
  351. this.name = name;
  352. this.buffer = buffer;
  353. this.position = position;
  354. this.line = line;
  355. this.column = column;
  356. }
  357. Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
  358. var head, start, tail, end, snippet;
  359. if (!this.buffer) return null;
  360. indent = indent || 4;
  361. maxLength = maxLength || 75;
  362. head = '';
  363. start = this.position;
  364. while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
  365. start -= 1;
  366. if (this.position - start > maxLength / 2 - 1) {
  367. head = ' ... ';
  368. start += 5;
  369. break;
  370. }
  371. }
  372. tail = '';
  373. end = this.position;
  374. while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
  375. end += 1;
  376. if (end - this.position > maxLength / 2 - 1) {
  377. tail = ' ... ';
  378. end -= 5;
  379. break;
  380. }
  381. }
  382. snippet = this.buffer.slice(start, end);
  383. return common.repeat(' ', indent) + head + snippet + tail + '\n' + common.repeat(' ', indent + this.position - start + head.length) + '^';
  384. };
  385. Mark.prototype.toString = function toString(compact) {
  386. var snippet,
  387. where = '';
  388. if (this.name) {
  389. where += 'in "' + this.name + '" ';
  390. }
  391. where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
  392. if (!compact) {
  393. snippet = this.getSnippet();
  394. if (snippet) {
  395. where += ':\n' + snippet;
  396. }
  397. }
  398. return where;
  399. };
  400. var mark = Mark;
  401. var TYPE_CONSTRUCTOR_OPTIONS = ['kind', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'defaultStyle', 'styleAliases'];
  402. var YAML_NODE_KINDS = ['scalar', 'sequence', 'mapping'];
  403. function compileStyleAliases(map) {
  404. var result = {};
  405. if (map !== null) {
  406. Object.keys(map).forEach(function (style) {
  407. map[style].forEach(function (alias) {
  408. result[String(alias)] = style;
  409. });
  410. });
  411. }
  412. return result;
  413. }
  414. function Type(tag, options) {
  415. options = options || {};
  416. Object.keys(options).forEach(function (name) {
  417. if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
  418. throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
  419. }
  420. }); // TODO: Add tag format check.
  421. this.tag = tag;
  422. this.kind = options['kind'] || null;
  423. this.resolve = options['resolve'] || function () {
  424. return true;
  425. };
  426. this.construct = options['construct'] || function (data) {
  427. return data;
  428. };
  429. this.instanceOf = options['instanceOf'] || null;
  430. this.predicate = options['predicate'] || null;
  431. this.represent = options['represent'] || null;
  432. this.defaultStyle = options['defaultStyle'] || null;
  433. this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
  434. if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
  435. throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
  436. }
  437. }
  438. var type = Type;
  439. /*eslint-disable max-len*/
  440. function compileList(schema, name, result) {
  441. var exclude = [];
  442. schema.include.forEach(function (includedSchema) {
  443. result = compileList(includedSchema, name, result);
  444. });
  445. schema[name].forEach(function (currentType) {
  446. result.forEach(function (previousType, previousIndex) {
  447. if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
  448. exclude.push(previousIndex);
  449. }
  450. });
  451. result.push(currentType);
  452. });
  453. return result.filter(function (type, index) {
  454. return exclude.indexOf(index) === -1;
  455. });
  456. }
  457. function compileMap()
  458. /* lists... */
  459. {
  460. var result = {
  461. scalar: {},
  462. sequence: {},
  463. mapping: {},
  464. fallback: {}
  465. },
  466. index,
  467. length;
  468. function collectType(type) {
  469. result[type.kind][type.tag] = result['fallback'][type.tag] = type;
  470. }
  471. for (index = 0, length = arguments.length; index < length; index += 1) {
  472. arguments[index].forEach(collectType);
  473. }
  474. return result;
  475. }
  476. function Schema(definition) {
  477. this.include = definition.include || [];
  478. this.implicit = definition.implicit || [];
  479. this.explicit = definition.explicit || [];
  480. this.implicit.forEach(function (type) {
  481. if (type.loadKind && type.loadKind !== 'scalar') {
  482. throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
  483. }
  484. });
  485. this.compiledImplicit = compileList(this, 'implicit', []);
  486. this.compiledExplicit = compileList(this, 'explicit', []);
  487. this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
  488. }
  489. Schema.DEFAULT = null;
  490. Schema.create = function createSchema() {
  491. var schemas, types;
  492. switch (arguments.length) {
  493. case 1:
  494. schemas = Schema.DEFAULT;
  495. types = arguments[0];
  496. break;
  497. case 2:
  498. schemas = arguments[0];
  499. types = arguments[1];
  500. break;
  501. default:
  502. throw new exception('Wrong number of arguments for Schema.create function');
  503. }
  504. schemas = common.toArray(schemas);
  505. types = common.toArray(types);
  506. if (!schemas.every(function (schema) {
  507. return schema instanceof Schema;
  508. })) {
  509. throw new exception('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
  510. }
  511. if (!types.every(function (type$1) {
  512. return type$1 instanceof type;
  513. })) {
  514. throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
  515. }
  516. return new Schema({
  517. include: schemas,
  518. explicit: types
  519. });
  520. };
  521. var schema = Schema;
  522. var str = new type('tag:yaml.org,2002:str', {
  523. kind: 'scalar',
  524. construct: function construct(data) {
  525. return data !== null ? data : '';
  526. }
  527. });
  528. var seq = new type('tag:yaml.org,2002:seq', {
  529. kind: 'sequence',
  530. construct: function construct(data) {
  531. return data !== null ? data : [];
  532. }
  533. });
  534. var map = new type('tag:yaml.org,2002:map', {
  535. kind: 'mapping',
  536. construct: function construct(data) {
  537. return data !== null ? data : {};
  538. }
  539. });
  540. var failsafe = new schema({
  541. explicit: [str, seq, map]
  542. });
  543. function resolveYamlNull(data) {
  544. if (data === null) return true;
  545. var max = data.length;
  546. return max === 1 && data === '~' || max === 4 && (data === 'null' || data === 'Null' || data === 'NULL');
  547. }
  548. function constructYamlNull() {
  549. return null;
  550. }
  551. function isNull(object) {
  552. return object === null;
  553. }
  554. var _null = new type('tag:yaml.org,2002:null', {
  555. kind: 'scalar',
  556. resolve: resolveYamlNull,
  557. construct: constructYamlNull,
  558. predicate: isNull,
  559. represent: {
  560. canonical: function canonical() {
  561. return '~';
  562. },
  563. lowercase: function lowercase() {
  564. return 'null';
  565. },
  566. uppercase: function uppercase() {
  567. return 'NULL';
  568. },
  569. camelcase: function camelcase() {
  570. return 'Null';
  571. }
  572. },
  573. defaultStyle: 'lowercase'
  574. });
  575. function resolveYamlBoolean(data) {
  576. if (data === null) return false;
  577. var max = data.length;
  578. return max === 4 && (data === 'true' || data === 'True' || data === 'TRUE') || max === 5 && (data === 'false' || data === 'False' || data === 'FALSE');
  579. }
  580. function constructYamlBoolean(data) {
  581. return data === 'true' || data === 'True' || data === 'TRUE';
  582. }
  583. function isBoolean(object) {
  584. return Object.prototype.toString.call(object) === '[object Boolean]';
  585. }
  586. var bool = new type('tag:yaml.org,2002:bool', {
  587. kind: 'scalar',
  588. resolve: resolveYamlBoolean,
  589. construct: constructYamlBoolean,
  590. predicate: isBoolean,
  591. represent: {
  592. lowercase: function lowercase(object) {
  593. return object ? 'true' : 'false';
  594. },
  595. uppercase: function uppercase(object) {
  596. return object ? 'TRUE' : 'FALSE';
  597. },
  598. camelcase: function camelcase(object) {
  599. return object ? 'True' : 'False';
  600. }
  601. },
  602. defaultStyle: 'lowercase'
  603. });
  604. function isHexCode(c) {
  605. return 0x30
  606. /* 0 */
  607. <= c && c <= 0x39
  608. /* 9 */
  609. || 0x41
  610. /* A */
  611. <= c && c <= 0x46
  612. /* F */
  613. || 0x61
  614. /* a */
  615. <= c && c <= 0x66
  616. /* f */
  617. ;
  618. }
  619. function isOctCode(c) {
  620. return 0x30
  621. /* 0 */
  622. <= c && c <= 0x37
  623. /* 7 */
  624. ;
  625. }
  626. function isDecCode(c) {
  627. return 0x30
  628. /* 0 */
  629. <= c && c <= 0x39
  630. /* 9 */
  631. ;
  632. }
  633. function resolveYamlInteger(data) {
  634. if (data === null) return false;
  635. var max = data.length,
  636. index = 0,
  637. hasDigits = false,
  638. ch;
  639. if (!max) return false;
  640. ch = data[index]; // sign
  641. if (ch === '-' || ch === '+') {
  642. ch = data[++index];
  643. }
  644. if (ch === '0') {
  645. // 0
  646. if (index + 1 === max) return true;
  647. ch = data[++index]; // base 2, base 8, base 16
  648. if (ch === 'b') {
  649. // base 2
  650. index++;
  651. for (; index < max; index++) {
  652. ch = data[index];
  653. if (ch === '_') continue;
  654. if (ch !== '0' && ch !== '1') return false;
  655. hasDigits = true;
  656. }
  657. return hasDigits && ch !== '_';
  658. }
  659. if (ch === 'x') {
  660. // base 16
  661. index++;
  662. for (; index < max; index++) {
  663. ch = data[index];
  664. if (ch === '_') continue;
  665. if (!isHexCode(data.charCodeAt(index))) return false;
  666. hasDigits = true;
  667. }
  668. return hasDigits && ch !== '_';
  669. } // base 8
  670. for (; index < max; index++) {
  671. ch = data[index];
  672. if (ch === '_') continue;
  673. if (!isOctCode(data.charCodeAt(index))) return false;
  674. hasDigits = true;
  675. }
  676. return hasDigits && ch !== '_';
  677. } // base 10 (except 0) or base 60
  678. // value should not start with `_`;
  679. if (ch === '_') return false;
  680. for (; index < max; index++) {
  681. ch = data[index];
  682. if (ch === '_') continue;
  683. if (ch === ':') break;
  684. if (!isDecCode(data.charCodeAt(index))) {
  685. return false;
  686. }
  687. hasDigits = true;
  688. } // Should have digits and should not end with `_`
  689. if (!hasDigits || ch === '_') return false; // if !base60 - done;
  690. if (ch !== ':') return true; // base60 almost not used, no needs to optimize
  691. return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
  692. }
  693. function constructYamlInteger(data) {
  694. var value = data,
  695. sign = 1,
  696. ch,
  697. base,
  698. digits = [];
  699. if (value.indexOf('_') !== -1) {
  700. value = value.replace(/_/g, '');
  701. }
  702. ch = value[0];
  703. if (ch === '-' || ch === '+') {
  704. if (ch === '-') sign = -1;
  705. value = value.slice(1);
  706. ch = value[0];
  707. }
  708. if (value === '0') return 0;
  709. if (ch === '0') {
  710. if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
  711. if (value[1] === 'x') return sign * parseInt(value, 16);
  712. return sign * parseInt(value, 8);
  713. }
  714. if (value.indexOf(':') !== -1) {
  715. value.split(':').forEach(function (v) {
  716. digits.unshift(parseInt(v, 10));
  717. });
  718. value = 0;
  719. base = 1;
  720. digits.forEach(function (d) {
  721. value += d * base;
  722. base *= 60;
  723. });
  724. return sign * value;
  725. }
  726. return sign * parseInt(value, 10);
  727. }
  728. function isInteger(object) {
  729. return Object.prototype.toString.call(object) === '[object Number]' && object % 1 === 0 && !common.isNegativeZero(object);
  730. }
  731. var int_1 = new type('tag:yaml.org,2002:int', {
  732. kind: 'scalar',
  733. resolve: resolveYamlInteger,
  734. construct: constructYamlInteger,
  735. predicate: isInteger,
  736. represent: {
  737. binary: function binary(obj) {
  738. return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1);
  739. },
  740. octal: function octal(obj) {
  741. return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1);
  742. },
  743. decimal: function decimal(obj) {
  744. return obj.toString(10);
  745. },
  746. /* eslint-disable max-len */
  747. hexadecimal: function hexadecimal(obj) {
  748. return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1);
  749. }
  750. },
  751. defaultStyle: 'decimal',
  752. styleAliases: {
  753. binary: [2, 'bin'],
  754. octal: [8, 'oct'],
  755. decimal: [10, 'dec'],
  756. hexadecimal: [16, 'hex']
  757. }
  758. });
  759. var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers
  760. '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2
  761. // special case, seems not from spec
  762. '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + // 20:59
  763. '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + // .inf
  764. '|[-+]?\\.(?:inf|Inf|INF)' + // .nan
  765. '|\\.(?:nan|NaN|NAN))$');
  766. function resolveYamlFloat(data) {
  767. if (data === null) return false;
  768. if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`
  769. // Probably should update regexp & check speed
  770. data[data.length - 1] === '_') {
  771. return false;
  772. }
  773. return true;
  774. }
  775. function constructYamlFloat(data) {
  776. var value, sign, base, digits;
  777. value = data.replace(/_/g, '').toLowerCase();
  778. sign = value[0] === '-' ? -1 : 1;
  779. digits = [];
  780. if ('+-'.indexOf(value[0]) >= 0) {
  781. value = value.slice(1);
  782. }
  783. if (value === '.inf') {
  784. return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
  785. } else if (value === '.nan') {
  786. return NaN;
  787. } else if (value.indexOf(':') >= 0) {
  788. value.split(':').forEach(function (v) {
  789. digits.unshift(parseFloat(v, 10));
  790. });
  791. value = 0.0;
  792. base = 1;
  793. digits.forEach(function (d) {
  794. value += d * base;
  795. base *= 60;
  796. });
  797. return sign * value;
  798. }
  799. return sign * parseFloat(value, 10);
  800. }
  801. var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
  802. function representYamlFloat(object, style) {
  803. var res;
  804. if (isNaN(object)) {
  805. switch (style) {
  806. case 'lowercase':
  807. return '.nan';
  808. case 'uppercase':
  809. return '.NAN';
  810. case 'camelcase':
  811. return '.NaN';
  812. }
  813. } else if (Number.POSITIVE_INFINITY === object) {
  814. switch (style) {
  815. case 'lowercase':
  816. return '.inf';
  817. case 'uppercase':
  818. return '.INF';
  819. case 'camelcase':
  820. return '.Inf';
  821. }
  822. } else if (Number.NEGATIVE_INFINITY === object) {
  823. switch (style) {
  824. case 'lowercase':
  825. return '-.inf';
  826. case 'uppercase':
  827. return '-.INF';
  828. case 'camelcase':
  829. return '-.Inf';
  830. }
  831. } else if (common.isNegativeZero(object)) {
  832. return '-0.0';
  833. }
  834. res = object.toString(10); // JS stringifier can build scientific format without dots: 5e-100,
  835. // while YAML requres dot: 5.e-100. Fix it with simple hack
  836. return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
  837. }
  838. function isFloat(object) {
  839. return Object.prototype.toString.call(object) === '[object Number]' && (object % 1 !== 0 || common.isNegativeZero(object));
  840. }
  841. var float_1 = new type('tag:yaml.org,2002:float', {
  842. kind: 'scalar',
  843. resolve: resolveYamlFloat,
  844. construct: constructYamlFloat,
  845. predicate: isFloat,
  846. represent: representYamlFloat,
  847. defaultStyle: 'lowercase'
  848. });
  849. var json = new schema({
  850. include: [failsafe],
  851. implicit: [_null, bool, int_1, float_1]
  852. });
  853. var core = new schema({
  854. include: [json]
  855. });
  856. var YAML_DATE_REGEXP = new RegExp('^([0-9][0-9][0-9][0-9])' + // [1] year
  857. '-([0-9][0-9])' + // [2] month
  858. '-([0-9][0-9])$'); // [3] day
  859. var YAML_TIMESTAMP_REGEXP = new RegExp('^([0-9][0-9][0-9][0-9])' + // [1] year
  860. '-([0-9][0-9]?)' + // [2] month
  861. '-([0-9][0-9]?)' + // [3] day
  862. '(?:[Tt]|[ \\t]+)' + // ...
  863. '([0-9][0-9]?)' + // [4] hour
  864. ':([0-9][0-9])' + // [5] minute
  865. ':([0-9][0-9])' + // [6] second
  866. '(?:\\.([0-9]*))?' + // [7] fraction
  867. '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
  868. '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
  869. function resolveYamlTimestamp(data) {
  870. if (data === null) return false;
  871. if (YAML_DATE_REGEXP.exec(data) !== null) return true;
  872. if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
  873. return false;
  874. }
  875. function constructYamlTimestamp(data) {
  876. var match,
  877. year,
  878. month,
  879. day,
  880. hour,
  881. minute,
  882. second,
  883. fraction = 0,
  884. delta = null,
  885. tz_hour,
  886. tz_minute,
  887. date;
  888. match = YAML_DATE_REGEXP.exec(data);
  889. if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
  890. if (match === null) throw new Error('Date resolve error'); // match: [1] year [2] month [3] day
  891. year = +match[1];
  892. month = +match[2] - 1; // JS month starts with 0
  893. day = +match[3];
  894. if (!match[4]) {
  895. // no hour
  896. return new Date(Date.UTC(year, month, day));
  897. } // match: [4] hour [5] minute [6] second [7] fraction
  898. hour = +match[4];
  899. minute = +match[5];
  900. second = +match[6];
  901. if (match[7]) {
  902. fraction = match[7].slice(0, 3);
  903. while (fraction.length < 3) {
  904. // milli-seconds
  905. fraction += '0';
  906. }
  907. fraction = +fraction;
  908. } // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
  909. if (match[9]) {
  910. tz_hour = +match[10];
  911. tz_minute = +(match[11] || 0);
  912. delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
  913. if (match[9] === '-') delta = -delta;
  914. }
  915. date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
  916. if (delta) date.setTime(date.getTime() - delta);
  917. return date;
  918. }
  919. function representYamlTimestamp(object
  920. /*, style*/
  921. ) {
  922. return object.toISOString();
  923. }
  924. var timestamp = new type('tag:yaml.org,2002:timestamp', {
  925. kind: 'scalar',
  926. resolve: resolveYamlTimestamp,
  927. construct: constructYamlTimestamp,
  928. instanceOf: Date,
  929. represent: representYamlTimestamp
  930. });
  931. function resolveYamlMerge(data) {
  932. return data === '<<' || data === null;
  933. }
  934. var merge = new type('tag:yaml.org,2002:merge', {
  935. kind: 'scalar',
  936. resolve: resolveYamlMerge
  937. });
  938. function commonjsRequire () {
  939. throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
  940. }
  941. function createCommonjsModule(fn, module) {
  942. return module = { exports: {} }, fn(module, module.exports), module.exports;
  943. }
  944. function getCjsExportFromNamespace (n) {
  945. return n && n['default'] || n;
  946. }
  947. /*eslint-disable no-bitwise*/
  948. var NodeBuffer;
  949. try {
  950. // A trick for browserified version, to not include `Buffer` shim
  951. var _require = commonjsRequire;
  952. NodeBuffer = _require('buffer').Buffer;
  953. } catch (__) {} // [ 64, 65, 66 ] -> [ padding, CR, LF ]
  954. var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
  955. function resolveYamlBinary(data) {
  956. if (data === null) return false;
  957. var code,
  958. idx,
  959. bitlen = 0,
  960. max = data.length,
  961. map = BASE64_MAP; // Convert one by one.
  962. for (idx = 0; idx < max; idx++) {
  963. code = map.indexOf(data.charAt(idx)); // Skip CR/LF
  964. if (code > 64) continue; // Fail on illegal characters
  965. if (code < 0) return false;
  966. bitlen += 6;
  967. } // If there are any bits left, source was corrupted
  968. return bitlen % 8 === 0;
  969. }
  970. function constructYamlBinary(data) {
  971. var idx,
  972. tailbits,
  973. input = data.replace(/[\r\n=]/g, ''),
  974. // remove CR/LF & padding to simplify scan
  975. max = input.length,
  976. map = BASE64_MAP,
  977. bits = 0,
  978. result = []; // Collect by 6*4 bits (3 bytes)
  979. for (idx = 0; idx < max; idx++) {
  980. if (idx % 4 === 0 && idx) {
  981. result.push(bits >> 16 & 0xFF);
  982. result.push(bits >> 8 & 0xFF);
  983. result.push(bits & 0xFF);
  984. }
  985. bits = bits << 6 | map.indexOf(input.charAt(idx));
  986. } // Dump tail
  987. tailbits = max % 4 * 6;
  988. if (tailbits === 0) {
  989. result.push(bits >> 16 & 0xFF);
  990. result.push(bits >> 8 & 0xFF);
  991. result.push(bits & 0xFF);
  992. } else if (tailbits === 18) {
  993. result.push(bits >> 10 & 0xFF);
  994. result.push(bits >> 2 & 0xFF);
  995. } else if (tailbits === 12) {
  996. result.push(bits >> 4 & 0xFF);
  997. } // Wrap into Buffer for NodeJS and leave Array for browser
  998. if (NodeBuffer) {
  999. // Support node 6.+ Buffer API when available
  1000. return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
  1001. }
  1002. return result;
  1003. }
  1004. function representYamlBinary(object
  1005. /*, style*/
  1006. ) {
  1007. var result = '',
  1008. bits = 0,
  1009. idx,
  1010. tail,
  1011. max = object.length,
  1012. map = BASE64_MAP; // Convert every three bytes to 4 ASCII characters.
  1013. for (idx = 0; idx < max; idx++) {
  1014. if (idx % 3 === 0 && idx) {
  1015. result += map[bits >> 18 & 0x3F];
  1016. result += map[bits >> 12 & 0x3F];
  1017. result += map[bits >> 6 & 0x3F];
  1018. result += map[bits & 0x3F];
  1019. }
  1020. bits = (bits << 8) + object[idx];
  1021. } // Dump tail
  1022. tail = max % 3;
  1023. if (tail === 0) {
  1024. result += map[bits >> 18 & 0x3F];
  1025. result += map[bits >> 12 & 0x3F];
  1026. result += map[bits >> 6 & 0x3F];
  1027. result += map[bits & 0x3F];
  1028. } else if (tail === 2) {
  1029. result += map[bits >> 10 & 0x3F];
  1030. result += map[bits >> 4 & 0x3F];
  1031. result += map[bits << 2 & 0x3F];
  1032. result += map[64];
  1033. } else if (tail === 1) {
  1034. result += map[bits >> 2 & 0x3F];
  1035. result += map[bits << 4 & 0x3F];
  1036. result += map[64];
  1037. result += map[64];
  1038. }
  1039. return result;
  1040. }
  1041. function isBinary(object) {
  1042. return NodeBuffer && NodeBuffer.isBuffer(object);
  1043. }
  1044. var binary = new type('tag:yaml.org,2002:binary', {
  1045. kind: 'scalar',
  1046. resolve: resolveYamlBinary,
  1047. construct: constructYamlBinary,
  1048. predicate: isBinary,
  1049. represent: representYamlBinary
  1050. });
  1051. var _hasOwnProperty = Object.prototype.hasOwnProperty;
  1052. var _toString = Object.prototype.toString;
  1053. function resolveYamlOmap(data) {
  1054. if (data === null) return true;
  1055. var objectKeys = [],
  1056. index,
  1057. length,
  1058. pair,
  1059. pairKey,
  1060. pairHasKey,
  1061. object = data;
  1062. for (index = 0, length = object.length; index < length; index += 1) {
  1063. pair = object[index];
  1064. pairHasKey = false;
  1065. if (_toString.call(pair) !== '[object Object]') return false;
  1066. for (pairKey in pair) {
  1067. if (_hasOwnProperty.call(pair, pairKey)) {
  1068. if (!pairHasKey) pairHasKey = true;else return false;
  1069. }
  1070. }
  1071. if (!pairHasKey) return false;
  1072. if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);else return false;
  1073. }
  1074. return true;
  1075. }
  1076. function constructYamlOmap(data) {
  1077. return data !== null ? data : [];
  1078. }
  1079. var omap = new type('tag:yaml.org,2002:omap', {
  1080. kind: 'sequence',
  1081. resolve: resolveYamlOmap,
  1082. construct: constructYamlOmap
  1083. });
  1084. var _toString$1 = Object.prototype.toString;
  1085. function resolveYamlPairs(data) {
  1086. if (data === null) return true;
  1087. var index,
  1088. length,
  1089. pair,
  1090. keys,
  1091. result,
  1092. object = data;
  1093. result = new Array(object.length);
  1094. for (index = 0, length = object.length; index < length; index += 1) {
  1095. pair = object[index];
  1096. if (_toString$1.call(pair) !== '[object Object]') return false;
  1097. keys = Object.keys(pair);
  1098. if (keys.length !== 1) return false;
  1099. result[index] = [keys[0], pair[keys[0]]];
  1100. }
  1101. return true;
  1102. }
  1103. function constructYamlPairs(data) {
  1104. if (data === null) return [];
  1105. var index,
  1106. length,
  1107. pair,
  1108. keys,
  1109. result,
  1110. object = data;
  1111. result = new Array(object.length);
  1112. for (index = 0, length = object.length; index < length; index += 1) {
  1113. pair = object[index];
  1114. keys = Object.keys(pair);
  1115. result[index] = [keys[0], pair[keys[0]]];
  1116. }
  1117. return result;
  1118. }
  1119. var pairs = new type('tag:yaml.org,2002:pairs', {
  1120. kind: 'sequence',
  1121. resolve: resolveYamlPairs,
  1122. construct: constructYamlPairs
  1123. });
  1124. var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  1125. function resolveYamlSet(data) {
  1126. if (data === null) return true;
  1127. var key,
  1128. object = data;
  1129. for (key in object) {
  1130. if (_hasOwnProperty$1.call(object, key)) {
  1131. if (object[key] !== null) return false;
  1132. }
  1133. }
  1134. return true;
  1135. }
  1136. function constructYamlSet(data) {
  1137. return data !== null ? data : {};
  1138. }
  1139. var set = new type('tag:yaml.org,2002:set', {
  1140. kind: 'mapping',
  1141. resolve: resolveYamlSet,
  1142. construct: constructYamlSet
  1143. });
  1144. var default_safe = new schema({
  1145. include: [core],
  1146. implicit: [timestamp, merge],
  1147. explicit: [binary, omap, pairs, set]
  1148. });
  1149. function resolveJavascriptUndefined() {
  1150. return true;
  1151. }
  1152. function constructJavascriptUndefined() {
  1153. /*eslint-disable no-undefined*/
  1154. return undefined;
  1155. }
  1156. function representJavascriptUndefined() {
  1157. return '';
  1158. }
  1159. function isUndefined(object) {
  1160. return typeof object === 'undefined';
  1161. }
  1162. var _undefined = new type('tag:yaml.org,2002:js/undefined', {
  1163. kind: 'scalar',
  1164. resolve: resolveJavascriptUndefined,
  1165. construct: constructJavascriptUndefined,
  1166. predicate: isUndefined,
  1167. represent: representJavascriptUndefined
  1168. });
  1169. function resolveJavascriptRegExp(data) {
  1170. if (data === null) return false;
  1171. if (data.length === 0) return false;
  1172. var regexp = data,
  1173. tail = /\/([gim]*)$/.exec(data),
  1174. modifiers = ''; // if regexp starts with '/' it can have modifiers and must be properly closed
  1175. // `/foo/gim` - modifiers tail can be maximum 3 chars
  1176. if (regexp[0] === '/') {
  1177. if (tail) modifiers = tail[1];
  1178. if (modifiers.length > 3) return false; // if expression starts with /, is should be properly terminated
  1179. if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
  1180. }
  1181. return true;
  1182. }
  1183. function constructJavascriptRegExp(data) {
  1184. var regexp = data,
  1185. tail = /\/([gim]*)$/.exec(data),
  1186. modifiers = ''; // `/foo/gim` - tail can be maximum 4 chars
  1187. if (regexp[0] === '/') {
  1188. if (tail) modifiers = tail[1];
  1189. regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
  1190. }
  1191. return new RegExp(regexp, modifiers);
  1192. }
  1193. function representJavascriptRegExp(object
  1194. /*, style*/
  1195. ) {
  1196. var result = '/' + object.source + '/';
  1197. if (object.global) result += 'g';
  1198. if (object.multiline) result += 'm';
  1199. if (object.ignoreCase) result += 'i';
  1200. return result;
  1201. }
  1202. function isRegExp(object) {
  1203. return Object.prototype.toString.call(object) === '[object RegExp]';
  1204. }
  1205. var regexp = new type('tag:yaml.org,2002:js/regexp', {
  1206. kind: 'scalar',
  1207. resolve: resolveJavascriptRegExp,
  1208. construct: constructJavascriptRegExp,
  1209. predicate: isRegExp,
  1210. represent: representJavascriptRegExp
  1211. });
  1212. var esprima; // Browserified version does not have esprima
  1213. //
  1214. // 1. For node.js just require module as deps
  1215. // 2. For browser try to require mudule via external AMD system.
  1216. // If not found - try to fallback to window.esprima. If not
  1217. // found too - then fail to parse.
  1218. //
  1219. try {
  1220. // workaround to exclude package from browserify list.
  1221. var _require$1 = commonjsRequire;
  1222. esprima = _require$1('esprima');
  1223. } catch (_) {
  1224. /*global window */
  1225. if (typeof window !== 'undefined') esprima = window.esprima;
  1226. }
  1227. function resolveJavascriptFunction(data) {
  1228. if (data === null) return false;
  1229. try {
  1230. var source = '(' + data + ')',
  1231. ast = esprima.parse(source, {
  1232. range: true
  1233. });
  1234. 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') {
  1235. return false;
  1236. }
  1237. return true;
  1238. } catch (err) {
  1239. return false;
  1240. }
  1241. }
  1242. function constructJavascriptFunction(data) {
  1243. /*jslint evil:true*/
  1244. var source = '(' + data + ')',
  1245. ast = esprima.parse(source, {
  1246. range: true
  1247. }),
  1248. params = [],
  1249. body;
  1250. 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') {
  1251. throw new Error('Failed to resolve function');
  1252. }
  1253. ast.body[0].expression.params.forEach(function (param) {
  1254. params.push(param.name);
  1255. });
  1256. body = ast.body[0].expression.body.range; // Esprima's ranges include the first '{' and the last '}' characters on
  1257. // function expressions. So cut them out.
  1258. if (ast.body[0].expression.body.type === 'BlockStatement') {
  1259. /*eslint-disable no-new-func*/
  1260. return new Function(params, source.slice(body[0] + 1, body[1] - 1));
  1261. } // ES6 arrow functions can omit the BlockStatement. In that case, just return
  1262. // the body.
  1263. /*eslint-disable no-new-func*/
  1264. return new Function(params, 'return ' + source.slice(body[0], body[1]));
  1265. }
  1266. function representJavascriptFunction(object
  1267. /*, style*/
  1268. ) {
  1269. return object.toString();
  1270. }
  1271. function isFunction(object) {
  1272. return Object.prototype.toString.call(object) === '[object Function]';
  1273. }
  1274. var _function = new type('tag:yaml.org,2002:js/function', {
  1275. kind: 'scalar',
  1276. resolve: resolveJavascriptFunction,
  1277. construct: constructJavascriptFunction,
  1278. predicate: isFunction,
  1279. represent: representJavascriptFunction
  1280. });
  1281. var default_full = schema.DEFAULT = new schema({
  1282. include: [default_safe],
  1283. explicit: [_undefined, regexp, _function]
  1284. });
  1285. /*eslint-disable max-len,no-use-before-define*/
  1286. var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
  1287. var CONTEXT_FLOW_IN = 1;
  1288. var CONTEXT_FLOW_OUT = 2;
  1289. var CONTEXT_BLOCK_IN = 3;
  1290. var CONTEXT_BLOCK_OUT = 4;
  1291. var CHOMPING_CLIP = 1;
  1292. var CHOMPING_STRIP = 2;
  1293. var CHOMPING_KEEP = 3;
  1294. var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
  1295. var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
  1296. var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
  1297. var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
  1298. var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
  1299. function _class(obj) {
  1300. return Object.prototype.toString.call(obj);
  1301. }
  1302. function is_EOL(c) {
  1303. return c === 0x0A
  1304. /* LF */
  1305. || c === 0x0D
  1306. /* CR */
  1307. ;
  1308. }
  1309. function is_WHITE_SPACE(c) {
  1310. return c === 0x09
  1311. /* Tab */
  1312. || c === 0x20
  1313. /* Space */
  1314. ;
  1315. }
  1316. function is_WS_OR_EOL(c) {
  1317. return c === 0x09
  1318. /* Tab */
  1319. || c === 0x20
  1320. /* Space */
  1321. || c === 0x0A
  1322. /* LF */
  1323. || c === 0x0D
  1324. /* CR */
  1325. ;
  1326. }
  1327. function is_FLOW_INDICATOR(c) {
  1328. return c === 0x2C
  1329. /* , */
  1330. || c === 0x5B
  1331. /* [ */
  1332. || c === 0x5D
  1333. /* ] */
  1334. || c === 0x7B
  1335. /* { */
  1336. || c === 0x7D
  1337. /* } */
  1338. ;
  1339. }
  1340. function fromHexCode(c) {
  1341. var lc;
  1342. if (0x30
  1343. /* 0 */
  1344. <= c && c <= 0x39
  1345. /* 9 */
  1346. ) {
  1347. return c - 0x30;
  1348. }
  1349. /*eslint-disable no-bitwise*/
  1350. lc = c | 0x20;
  1351. if (0x61
  1352. /* a */
  1353. <= lc && lc <= 0x66
  1354. /* f */
  1355. ) {
  1356. return lc - 0x61 + 10;
  1357. }
  1358. return -1;
  1359. }
  1360. function escapedHexLen(c) {
  1361. if (c === 0x78
  1362. /* x */
  1363. ) {
  1364. return 2;
  1365. }
  1366. if (c === 0x75
  1367. /* u */
  1368. ) {
  1369. return 4;
  1370. }
  1371. if (c === 0x55
  1372. /* U */
  1373. ) {
  1374. return 8;
  1375. }
  1376. return 0;
  1377. }
  1378. function fromDecimalCode(c) {
  1379. if (0x30
  1380. /* 0 */
  1381. <= c && c <= 0x39
  1382. /* 9 */
  1383. ) {
  1384. return c - 0x30;
  1385. }
  1386. return -1;
  1387. }
  1388. function simpleEscapeSequence(c) {
  1389. /* eslint-disable indent */
  1390. return c === 0x30
  1391. /* 0 */
  1392. ? '\x00' : c === 0x61
  1393. /* a */
  1394. ? '\x07' : c === 0x62
  1395. /* b */
  1396. ? '\x08' : c === 0x74
  1397. /* t */
  1398. ? '\x09' : c === 0x09
  1399. /* Tab */
  1400. ? '\x09' : c === 0x6E
  1401. /* n */
  1402. ? '\x0A' : c === 0x76
  1403. /* v */
  1404. ? '\x0B' : c === 0x66
  1405. /* f */
  1406. ? '\x0C' : c === 0x72
  1407. /* r */
  1408. ? '\x0D' : c === 0x65
  1409. /* e */
  1410. ? '\x1B' : c === 0x20
  1411. /* Space */
  1412. ? ' ' : c === 0x22
  1413. /* " */
  1414. ? '\x22' : c === 0x2F
  1415. /* / */
  1416. ? '/' : c === 0x5C
  1417. /* \ */
  1418. ? '\x5C' : c === 0x4E
  1419. /* N */
  1420. ? '\x85' : c === 0x5F
  1421. /* _ */
  1422. ? '\xA0' : c === 0x4C
  1423. /* L */
  1424. ? '\u2028' : c === 0x50
  1425. /* P */
  1426. ? '\u2029' : '';
  1427. }
  1428. function charFromCodepoint(c) {
  1429. if (c <= 0xFFFF) {
  1430. return String.fromCharCode(c);
  1431. } // Encode UTF-16 surrogate pair
  1432. // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
  1433. return String.fromCharCode((c - 0x010000 >> 10) + 0xD800, (c - 0x010000 & 0x03FF) + 0xDC00);
  1434. }
  1435. var simpleEscapeCheck = new Array(256); // integer, for fast access
  1436. var simpleEscapeMap = new Array(256);
  1437. for (var i = 0; i < 256; i++) {
  1438. simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
  1439. simpleEscapeMap[i] = simpleEscapeSequence(i);
  1440. }
  1441. function State(input, options) {
  1442. this.input = input;
  1443. this.filename = options['filename'] || null;
  1444. this.schema = options['schema'] || default_full;
  1445. this.onWarning = options['onWarning'] || null;
  1446. this.legacy = options['legacy'] || false;
  1447. this.json = options['json'] || false;
  1448. this.listener = options['listener'] || null;
  1449. this.implicitTypes = this.schema.compiledImplicit;
  1450. this.typeMap = this.schema.compiledTypeMap;
  1451. this.length = input.length;
  1452. this.position = 0;
  1453. this.line = 0;
  1454. this.lineStart = 0;
  1455. this.lineIndent = 0;
  1456. this.documents = [];
  1457. /*
  1458. this.version;
  1459. this.checkLineBreaks;
  1460. this.tagMap;
  1461. this.anchorMap;
  1462. this.tag;
  1463. this.anchor;
  1464. this.kind;
  1465. this.result;*/
  1466. }
  1467. function generateError(state, message) {
  1468. return new exception(message, new mark(state.filename, state.input, state.position, state.line, state.position - state.lineStart));
  1469. }
  1470. function throwError(state, message) {
  1471. throw generateError(state, message);
  1472. }
  1473. function throwWarning(state, message) {
  1474. if (state.onWarning) {
  1475. state.onWarning.call(null, generateError(state, message));
  1476. }
  1477. }
  1478. var directiveHandlers = {
  1479. YAML: function handleYamlDirective(state, name, args) {
  1480. var match, major, minor;
  1481. if (state.version !== null) {
  1482. throwError(state, 'duplication of %YAML directive');
  1483. }
  1484. if (args.length !== 1) {
  1485. throwError(state, 'YAML directive accepts exactly one argument');
  1486. }
  1487. match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
  1488. if (match === null) {
  1489. throwError(state, 'ill-formed argument of the YAML directive');
  1490. }
  1491. major = parseInt(match[1], 10);
  1492. minor = parseInt(match[2], 10);
  1493. if (major !== 1) {
  1494. throwError(state, 'unacceptable YAML version of the document');
  1495. }
  1496. state.version = args[0];
  1497. state.checkLineBreaks = minor < 2;
  1498. if (minor !== 1 && minor !== 2) {
  1499. throwWarning(state, 'unsupported YAML version of the document');
  1500. }
  1501. },
  1502. TAG: function handleTagDirective(state, name, args) {
  1503. var handle, prefix;
  1504. if (args.length !== 2) {
  1505. throwError(state, 'TAG directive accepts exactly two arguments');
  1506. }
  1507. handle = args[0];
  1508. prefix = args[1];
  1509. if (!PATTERN_TAG_HANDLE.test(handle)) {
  1510. throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
  1511. }
  1512. if (_hasOwnProperty$2.call(state.tagMap, handle)) {
  1513. throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
  1514. }
  1515. if (!PATTERN_TAG_URI.test(prefix)) {
  1516. throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
  1517. }
  1518. state.tagMap[handle] = prefix;
  1519. }
  1520. };
  1521. function captureSegment(state, start, end, checkJson) {
  1522. var _position, _length, _character, _result;
  1523. if (start < end) {
  1524. _result = state.input.slice(start, end);
  1525. if (checkJson) {
  1526. for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
  1527. _character = _result.charCodeAt(_position);
  1528. if (!(_character === 0x09 || 0x20 <= _character && _character <= 0x10FFFF)) {
  1529. throwError(state, 'expected valid JSON character');
  1530. }
  1531. }
  1532. } else if (PATTERN_NON_PRINTABLE.test(_result)) {
  1533. throwError(state, 'the stream contains non-printable characters');
  1534. }
  1535. state.result += _result;
  1536. }
  1537. }
  1538. function mergeMappings(state, destination, source, overridableKeys) {
  1539. var sourceKeys, key, index, quantity;
  1540. if (!common.isObject(source)) {
  1541. throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
  1542. }
  1543. sourceKeys = Object.keys(source);
  1544. for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
  1545. key = sourceKeys[index];
  1546. if (!_hasOwnProperty$2.call(destination, key)) {
  1547. destination[key] = source[key];
  1548. overridableKeys[key] = true;
  1549. }
  1550. }
  1551. }
  1552. function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
  1553. var index, quantity; // The output is a plain object here, so keys can only be strings.
  1554. // We need to convert keyNode to a string, but doing so can hang the process
  1555. // (deeply nested arrays that explode exponentially using aliases).
  1556. if (Array.isArray(keyNode)) {
  1557. keyNode = Array.prototype.slice.call(keyNode);
  1558. for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
  1559. if (Array.isArray(keyNode[index])) {
  1560. throwError(state, 'nested arrays are not supported inside keys');
  1561. }
  1562. if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
  1563. keyNode[index] = '[object Object]';
  1564. }
  1565. }
  1566. } // Avoid code execution in load() via toString property
  1567. // (still use its own toString for arrays, timestamps,
  1568. // and whatever user schema extensions happen to have @@toStringTag)
  1569. if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
  1570. keyNode = '[object Object]';
  1571. }
  1572. keyNode = String(keyNode);
  1573. if (_result === null) {
  1574. _result = {};
  1575. }
  1576. if (keyTag === 'tag:yaml.org,2002:merge') {
  1577. if (Array.isArray(valueNode)) {
  1578. for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
  1579. mergeMappings(state, _result, valueNode[index], overridableKeys);
  1580. }
  1581. } else {
  1582. mergeMappings(state, _result, valueNode, overridableKeys);
  1583. }
  1584. } else {
  1585. if (!state.json && !_hasOwnProperty$2.call(overridableKeys, keyNode) && _hasOwnProperty$2.call(_result, keyNode)) {
  1586. state.line = startLine || state.line;
  1587. state.position = startPos || state.position;
  1588. throwError(state, 'duplicated mapping key');
  1589. }
  1590. _result[keyNode] = valueNode;
  1591. delete overridableKeys[keyNode];
  1592. }
  1593. return _result;
  1594. }
  1595. function readLineBreak(state) {
  1596. var ch;
  1597. ch = state.input.charCodeAt(state.position);
  1598. if (ch === 0x0A
  1599. /* LF */
  1600. ) {
  1601. state.position++;
  1602. } else if (ch === 0x0D
  1603. /* CR */
  1604. ) {
  1605. state.position++;
  1606. if (state.input.charCodeAt(state.position) === 0x0A
  1607. /* LF */
  1608. ) {
  1609. state.position++;
  1610. }
  1611. } else {
  1612. throwError(state, 'a line break is expected');
  1613. }
  1614. state.line += 1;
  1615. state.lineStart = state.position;
  1616. }
  1617. function skipSeparationSpace(state, allowComments, checkIndent) {
  1618. var lineBreaks = 0,
  1619. ch = state.input.charCodeAt(state.position);
  1620. while (ch !== 0) {
  1621. while (is_WHITE_SPACE(ch)) {
  1622. ch = state.input.charCodeAt(++state.position);
  1623. }
  1624. if (allowComments && ch === 0x23
  1625. /* # */
  1626. ) {
  1627. do {
  1628. ch = state.input.charCodeAt(++state.position);
  1629. } while (ch !== 0x0A
  1630. /* LF */
  1631. && ch !== 0x0D
  1632. /* CR */
  1633. && ch !== 0);
  1634. }
  1635. if (is_EOL(ch)) {
  1636. readLineBreak(state);
  1637. ch = state.input.charCodeAt(state.position);
  1638. lineBreaks++;
  1639. state.lineIndent = 0;
  1640. while (ch === 0x20
  1641. /* Space */
  1642. ) {
  1643. state.lineIndent++;
  1644. ch = state.input.charCodeAt(++state.position);
  1645. }
  1646. } else {
  1647. break;
  1648. }
  1649. }
  1650. if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
  1651. throwWarning(state, 'deficient indentation');
  1652. }
  1653. return lineBreaks;
  1654. }
  1655. function testDocumentSeparator(state) {
  1656. var _position = state.position,
  1657. ch;
  1658. ch = state.input.charCodeAt(_position); // Condition state.position === state.lineStart is tested
  1659. // in parent on each call, for efficiency. No needs to test here again.
  1660. if ((ch === 0x2D
  1661. /* - */
  1662. || ch === 0x2E
  1663. /* . */
  1664. ) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
  1665. _position += 3;
  1666. ch = state.input.charCodeAt(_position);
  1667. if (ch === 0 || is_WS_OR_EOL(ch)) {
  1668. return true;
  1669. }
  1670. }
  1671. return false;
  1672. }
  1673. function writeFoldedLines(state, count) {
  1674. if (count === 1) {
  1675. state.result += ' ';
  1676. } else if (count > 1) {
  1677. state.result += common.repeat('\n', count - 1);
  1678. }
  1679. }
  1680. function readPlainScalar(state, nodeIndent, withinFlowCollection) {
  1681. var preceding,
  1682. following,
  1683. captureStart,
  1684. captureEnd,
  1685. hasPendingContent,
  1686. _line,
  1687. _lineStart,
  1688. _lineIndent,
  1689. _kind = state.kind,
  1690. _result = state.result,
  1691. ch;
  1692. ch = state.input.charCodeAt(state.position);
  1693. if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 0x23
  1694. /* # */
  1695. || ch === 0x26
  1696. /* & */
  1697. || ch === 0x2A
  1698. /* * */
  1699. || ch === 0x21
  1700. /* ! */
  1701. || ch === 0x7C
  1702. /* | */
  1703. || ch === 0x3E
  1704. /* > */
  1705. || ch === 0x27
  1706. /* ' */
  1707. || ch === 0x22
  1708. /* " */
  1709. || ch === 0x25
  1710. /* % */
  1711. || ch === 0x40
  1712. /* @ */
  1713. || ch === 0x60
  1714. /* ` */
  1715. ) {
  1716. return false;
  1717. }
  1718. if (ch === 0x3F
  1719. /* ? */
  1720. || ch === 0x2D
  1721. /* - */
  1722. ) {
  1723. following = state.input.charCodeAt(state.position + 1);
  1724. if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
  1725. return false;
  1726. }
  1727. }
  1728. state.kind = 'scalar';
  1729. state.result = '';
  1730. captureStart = captureEnd = state.position;
  1731. hasPendingContent = false;
  1732. while (ch !== 0) {
  1733. if (ch === 0x3A
  1734. /* : */
  1735. ) {
  1736. following = state.input.charCodeAt(state.position + 1);
  1737. if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
  1738. break;
  1739. }
  1740. } else if (ch === 0x23
  1741. /* # */
  1742. ) {
  1743. preceding = state.input.charCodeAt(state.position - 1);
  1744. if (is_WS_OR_EOL(preceding)) {
  1745. break;
  1746. }
  1747. } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
  1748. break;
  1749. } else if (is_EOL(ch)) {
  1750. _line = state.line;
  1751. _lineStart = state.lineStart;
  1752. _lineIndent = state.lineIndent;
  1753. skipSeparationSpace(state, false, -1);
  1754. if (state.lineIndent >= nodeIndent) {
  1755. hasPendingContent = true;
  1756. ch = state.input.charCodeAt(state.position);
  1757. continue;
  1758. } else {
  1759. state.position = captureEnd;
  1760. state.line = _line;
  1761. state.lineStart = _lineStart;
  1762. state.lineIndent = _lineIndent;
  1763. break;
  1764. }
  1765. }
  1766. if (hasPendingContent) {
  1767. captureSegment(state, captureStart, captureEnd, false);
  1768. writeFoldedLines(state, state.line - _line);
  1769. captureStart = captureEnd = state.position;
  1770. hasPendingContent = false;
  1771. }
  1772. if (!is_WHITE_SPACE(ch)) {
  1773. captureEnd = state.position + 1;
  1774. }
  1775. ch = state.input.charCodeAt(++state.position);
  1776. }
  1777. captureSegment(state, captureStart, captureEnd, false);
  1778. if (state.result) {
  1779. return true;
  1780. }
  1781. state.kind = _kind;
  1782. state.result = _result;
  1783. return false;
  1784. }
  1785. function readSingleQuotedScalar(state, nodeIndent) {
  1786. var ch, captureStart, captureEnd;
  1787. ch = state.input.charCodeAt(state.position);
  1788. if (ch !== 0x27
  1789. /* ' */
  1790. ) {
  1791. return false;
  1792. }
  1793. state.kind = 'scalar';
  1794. state.result = '';
  1795. state.position++;
  1796. captureStart = captureEnd = state.position;
  1797. while ((ch = state.input.charCodeAt(state.position)) !== 0) {
  1798. if (ch === 0x27
  1799. /* ' */
  1800. ) {
  1801. captureSegment(state, captureStart, state.position, true);
  1802. ch = state.input.charCodeAt(++state.position);
  1803. if (ch === 0x27
  1804. /* ' */
  1805. ) {
  1806. captureStart = state.position;
  1807. state.position++;
  1808. captureEnd = state.position;
  1809. } else {
  1810. return true;
  1811. }
  1812. } else if (is_EOL(ch)) {
  1813. captureSegment(state, captureStart, captureEnd, true);
  1814. writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
  1815. captureStart = captureEnd = state.position;
  1816. } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
  1817. throwError(state, 'unexpected end of the document within a single quoted scalar');
  1818. } else {
  1819. state.position++;
  1820. captureEnd = state.position;
  1821. }
  1822. }
  1823. throwError(state, 'unexpected end of the stream within a single quoted scalar');
  1824. }
  1825. function readDoubleQuotedScalar(state, nodeIndent) {
  1826. var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
  1827. ch = state.input.charCodeAt(state.position);
  1828. if (ch !== 0x22
  1829. /* " */
  1830. ) {
  1831. return false;
  1832. }
  1833. state.kind = 'scalar';
  1834. state.result = '';
  1835. state.position++;
  1836. captureStart = captureEnd = state.position;
  1837. while ((ch = state.input.charCodeAt(state.position)) !== 0) {
  1838. if (ch === 0x22
  1839. /* " */
  1840. ) {
  1841. captureSegment(state, captureStart, state.position, true);
  1842. state.position++;
  1843. return true;
  1844. } else if (ch === 0x5C
  1845. /* \ */
  1846. ) {
  1847. captureSegment(state, captureStart, state.position, true);
  1848. ch = state.input.charCodeAt(++state.position);
  1849. if (is_EOL(ch)) {
  1850. skipSeparationSpace(state, false, nodeIndent); // TODO: rework to inline fn with no type cast?
  1851. } else if (ch < 256 && simpleEscapeCheck[ch]) {
  1852. state.result += simpleEscapeMap[ch];
  1853. state.position++;
  1854. } else if ((tmp = escapedHexLen(ch)) > 0) {
  1855. hexLength = tmp;
  1856. hexResult = 0;
  1857. for (; hexLength > 0; hexLength--) {
  1858. ch = state.input.charCodeAt(++state.position);
  1859. if ((tmp = fromHexCode(ch)) >= 0) {
  1860. hexResult = (hexResult << 4) + tmp;
  1861. } else {
  1862. throwError(state, 'expected hexadecimal character');
  1863. }
  1864. }
  1865. state.result += charFromCodepoint(hexResult);
  1866. state.position++;
  1867. } else {
  1868. throwError(state, 'unknown escape sequence');
  1869. }
  1870. captureStart = captureEnd = state.position;
  1871. } else if (is_EOL(ch)) {
  1872. captureSegment(state, captureStart, captureEnd, true);
  1873. writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
  1874. captureStart = captureEnd = state.position;
  1875. } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
  1876. throwError(state, 'unexpected end of the document within a double quoted scalar');
  1877. } else {
  1878. state.position++;
  1879. captureEnd = state.position;
  1880. }
  1881. }
  1882. throwError(state, 'unexpected end of the stream within a double quoted scalar');
  1883. }
  1884. function readFlowCollection(state, nodeIndent) {
  1885. var readNext = true,
  1886. _line,
  1887. _tag = state.tag,
  1888. _result,
  1889. _anchor = state.anchor,
  1890. following,
  1891. terminator,
  1892. isPair,
  1893. isExplicitPair,
  1894. isMapping,
  1895. overridableKeys = {},
  1896. keyNode,
  1897. keyTag,
  1898. valueNode,
  1899. ch;
  1900. ch = state.input.charCodeAt(state.position);
  1901. if (ch === 0x5B
  1902. /* [ */
  1903. ) {
  1904. terminator = 0x5D;
  1905. /* ] */
  1906. isMapping = false;
  1907. _result = [];
  1908. } else if (ch === 0x7B
  1909. /* { */
  1910. ) {
  1911. terminator = 0x7D;
  1912. /* } */
  1913. isMapping = true;
  1914. _result = {};
  1915. } else {
  1916. return false;
  1917. }
  1918. if (state.anchor !== null) {
  1919. state.anchorMap[state.anchor] = _result;
  1920. }
  1921. ch = state.input.charCodeAt(++state.position);
  1922. while (ch !== 0) {
  1923. skipSeparationSpace(state, true, nodeIndent);
  1924. ch = state.input.charCodeAt(state.position);
  1925. if (ch === terminator) {
  1926. state.position++;
  1927. state.tag = _tag;
  1928. state.anchor = _anchor;
  1929. state.kind = isMapping ? 'mapping' : 'sequence';
  1930. state.result = _result;
  1931. return true;
  1932. } else if (!readNext) {
  1933. throwError(state, 'missed comma between flow collection entries');
  1934. }
  1935. keyTag = keyNode = valueNode = null;
  1936. isPair = isExplicitPair = false;
  1937. if (ch === 0x3F
  1938. /* ? */
  1939. ) {
  1940. following = state.input.charCodeAt(state.position + 1);
  1941. if (is_WS_OR_EOL(following)) {
  1942. isPair = isExplicitPair = true;
  1943. state.position++;
  1944. skipSeparationSpace(state, true, nodeIndent);
  1945. }
  1946. }
  1947. _line = state.line;
  1948. composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
  1949. keyTag = state.tag;
  1950. keyNode = state.result;
  1951. skipSeparationSpace(state, true, nodeIndent);
  1952. ch = state.input.charCodeAt(state.position);
  1953. if ((isExplicitPair || state.line === _line) && ch === 0x3A
  1954. /* : */
  1955. ) {
  1956. isPair = true;
  1957. ch = state.input.charCodeAt(++state.position);
  1958. skipSeparationSpace(state, true, nodeIndent);
  1959. composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
  1960. valueNode = state.result;
  1961. }
  1962. if (isMapping) {
  1963. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
  1964. } else if (isPair) {
  1965. _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
  1966. } else {
  1967. _result.push(keyNode);
  1968. }
  1969. skipSeparationSpace(state, true, nodeIndent);
  1970. ch = state.input.charCodeAt(state.position);
  1971. if (ch === 0x2C
  1972. /* , */
  1973. ) {
  1974. readNext = true;
  1975. ch = state.input.charCodeAt(++state.position);
  1976. } else {
  1977. readNext = false;
  1978. }
  1979. }
  1980. throwError(state, 'unexpected end of the stream within a flow collection');
  1981. }
  1982. function readBlockScalar(state, nodeIndent) {
  1983. var captureStart,
  1984. folding,
  1985. chomping = CHOMPING_CLIP,
  1986. didReadContent = false,
  1987. detectedIndent = false,
  1988. textIndent = nodeIndent,
  1989. emptyLines = 0,
  1990. atMoreIndented = false,
  1991. tmp,
  1992. ch;
  1993. ch = state.input.charCodeAt(state.position);
  1994. if (ch === 0x7C
  1995. /* | */
  1996. ) {
  1997. folding = false;
  1998. } else if (ch === 0x3E
  1999. /* > */
  2000. ) {
  2001. folding = true;
  2002. } else {
  2003. return false;
  2004. }
  2005. state.kind = 'scalar';
  2006. state.result = '';
  2007. while (ch !== 0) {
  2008. ch = state.input.charCodeAt(++state.position);
  2009. if (ch === 0x2B
  2010. /* + */
  2011. || ch === 0x2D
  2012. /* - */
  2013. ) {
  2014. if (CHOMPING_CLIP === chomping) {
  2015. chomping = ch === 0x2B
  2016. /* + */
  2017. ? CHOMPING_KEEP : CHOMPING_STRIP;
  2018. } else {
  2019. throwError(state, 'repeat of a chomping mode identifier');
  2020. }
  2021. } else if ((tmp = fromDecimalCode(ch)) >= 0) {
  2022. if (tmp === 0) {
  2023. throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
  2024. } else if (!detectedIndent) {
  2025. textIndent = nodeIndent + tmp - 1;
  2026. detectedIndent = true;
  2027. } else {
  2028. throwError(state, 'repeat of an indentation width identifier');
  2029. }
  2030. } else {
  2031. break;
  2032. }
  2033. }
  2034. if (is_WHITE_SPACE(ch)) {
  2035. do {
  2036. ch = state.input.charCodeAt(++state.position);
  2037. } while (is_WHITE_SPACE(ch));
  2038. if (ch === 0x23
  2039. /* # */
  2040. ) {
  2041. do {
  2042. ch = state.input.charCodeAt(++state.position);
  2043. } while (!is_EOL(ch) && ch !== 0);
  2044. }
  2045. }
  2046. while (ch !== 0) {
  2047. readLineBreak(state);
  2048. state.lineIndent = 0;
  2049. ch = state.input.charCodeAt(state.position);
  2050. while ((!detectedIndent || state.lineIndent < textIndent) && ch === 0x20
  2051. /* Space */
  2052. ) {
  2053. state.lineIndent++;
  2054. ch = state.input.charCodeAt(++state.position);
  2055. }
  2056. if (!detectedIndent && state.lineIndent > textIndent) {
  2057. textIndent = state.lineIndent;
  2058. }
  2059. if (is_EOL(ch)) {
  2060. emptyLines++;
  2061. continue;
  2062. } // End of the scalar.
  2063. if (state.lineIndent < textIndent) {
  2064. // Perform the chomping.
  2065. if (chomping === CHOMPING_KEEP) {
  2066. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
  2067. } else if (chomping === CHOMPING_CLIP) {
  2068. if (didReadContent) {
  2069. // i.e. only if the scalar is not empty.
  2070. state.result += '\n';
  2071. }
  2072. } // Break this `while` cycle and go to the funciton's epilogue.
  2073. break;
  2074. } // Folded style: use fancy rules to handle line breaks.
  2075. if (folding) {
  2076. // Lines starting with white space characters (more-indented lines) are not folded.
  2077. if (is_WHITE_SPACE(ch)) {
  2078. atMoreIndented = true; // except for the first content line (cf. Example 8.1)
  2079. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); // End of more-indented block.
  2080. } else if (atMoreIndented) {
  2081. atMoreIndented = false;
  2082. state.result += common.repeat('\n', emptyLines + 1); // Just one line break - perceive as the same line.
  2083. } else if (emptyLines === 0) {
  2084. if (didReadContent) {
  2085. // i.e. only if we have already read some scalar content.
  2086. state.result += ' ';
  2087. } // Several line breaks - perceive as different lines.
  2088. } else {
  2089. state.result += common.repeat('\n', emptyLines);
  2090. } // Literal style: just add exact number of line breaks between content lines.
  2091. } else {
  2092. // Keep all line breaks except the header line break.
  2093. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
  2094. }
  2095. didReadContent = true;
  2096. detectedIndent = true;
  2097. emptyLines = 0;
  2098. captureStart = state.position;
  2099. while (!is_EOL(ch) && ch !== 0) {
  2100. ch = state.input.charCodeAt(++state.position);
  2101. }
  2102. captureSegment(state, captureStart, state.position, false);
  2103. }
  2104. return true;
  2105. }
  2106. function readBlockSequence(state, nodeIndent) {
  2107. var _line,
  2108. _tag = state.tag,
  2109. _anchor = state.anchor,
  2110. _result = [],
  2111. following,
  2112. detected = false,
  2113. ch;
  2114. if (state.anchor !== null) {
  2115. state.anchorMap[state.anchor] = _result;
  2116. }
  2117. ch = state.input.charCodeAt(state.position);
  2118. while (ch !== 0) {
  2119. if (ch !== 0x2D
  2120. /* - */
  2121. ) {
  2122. break;
  2123. }
  2124. following = state.input.charCodeAt(state.position + 1);
  2125. if (!is_WS_OR_EOL(following)) {
  2126. break;
  2127. }
  2128. detected = true;
  2129. state.position++;
  2130. if (skipSeparationSpace(state, true, -1)) {
  2131. if (state.lineIndent <= nodeIndent) {
  2132. _result.push(null);
  2133. ch = state.input.charCodeAt(state.position);
  2134. continue;
  2135. }
  2136. }
  2137. _line = state.line;
  2138. composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
  2139. _result.push(state.result);
  2140. skipSeparationSpace(state, true, -1);
  2141. ch = state.input.charCodeAt(state.position);
  2142. if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
  2143. throwError(state, 'bad indentation of a sequence entry');
  2144. } else if (state.lineIndent < nodeIndent) {
  2145. break;
  2146. }
  2147. }
  2148. if (detected) {
  2149. state.tag = _tag;
  2150. state.anchor = _anchor;
  2151. state.kind = 'sequence';
  2152. state.result = _result;
  2153. return true;
  2154. }
  2155. return false;
  2156. }
  2157. function readBlockMapping(state, nodeIndent, flowIndent) {
  2158. var following,
  2159. allowCompact,
  2160. _line,
  2161. _pos,
  2162. _tag = state.tag,
  2163. _anchor = state.anchor,
  2164. _result = {},
  2165. overridableKeys = {},
  2166. keyTag = null,
  2167. keyNode = null,
  2168. valueNode = null,
  2169. atExplicitKey = false,
  2170. detected = false,
  2171. ch;
  2172. if (state.anchor !== null) {
  2173. state.anchorMap[state.anchor] = _result;
  2174. }
  2175. ch = state.input.charCodeAt(state.position);
  2176. while (ch !== 0) {
  2177. following = state.input.charCodeAt(state.position + 1);
  2178. _line = state.line; // Save the current line.
  2179. _pos = state.position; //
  2180. // Explicit notation case. There are two separate blocks:
  2181. // first for the key (denoted by "?") and second for the value (denoted by ":")
  2182. //
  2183. if ((ch === 0x3F
  2184. /* ? */
  2185. || ch === 0x3A
  2186. /* : */
  2187. ) && is_WS_OR_EOL(following)) {
  2188. if (ch === 0x3F
  2189. /* ? */
  2190. ) {
  2191. if (atExplicitKey) {
  2192. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
  2193. keyTag = keyNode = valueNode = null;
  2194. }
  2195. detected = true;
  2196. atExplicitKey = true;
  2197. allowCompact = true;
  2198. } else if (atExplicitKey) {
  2199. // i.e. 0x3A/* : */ === character after the explicit key.
  2200. atExplicitKey = false;
  2201. allowCompact = true;
  2202. } else {
  2203. throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
  2204. }
  2205. state.position += 1;
  2206. ch = following; //
  2207. // Implicit notation case. Flow-style node as the key first, then ":", and the value.
  2208. //
  2209. } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
  2210. if (state.line === _line) {
  2211. ch = state.input.charCodeAt(state.position);
  2212. while (is_WHITE_SPACE(ch)) {
  2213. ch = state.input.charCodeAt(++state.position);
  2214. }
  2215. if (ch === 0x3A
  2216. /* : */
  2217. ) {
  2218. ch = state.input.charCodeAt(++state.position);
  2219. if (!is_WS_OR_EOL(ch)) {
  2220. throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
  2221. }
  2222. if (atExplicitKey) {
  2223. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
  2224. keyTag = keyNode = valueNode = null;
  2225. }
  2226. detected = true;
  2227. atExplicitKey = false;
  2228. allowCompact = false;
  2229. keyTag = state.tag;
  2230. keyNode = state.result;
  2231. } else if (detected) {
  2232. throwError(state, 'can not read an implicit mapping pair; a colon is missed');
  2233. } else {
  2234. state.tag = _tag;
  2235. state.anchor = _anchor;
  2236. return true; // Keep the result of `composeNode`.
  2237. }
  2238. } else if (detected) {
  2239. throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
  2240. } else {
  2241. state.tag = _tag;
  2242. state.anchor = _anchor;
  2243. return true; // Keep the result of `composeNode`.
  2244. }
  2245. } else {
  2246. break; // Reading is done. Go to the epilogue.
  2247. } //
  2248. // Common reading code for both explicit and implicit notations.
  2249. //
  2250. if (state.line === _line || state.lineIndent > nodeIndent) {
  2251. if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
  2252. if (atExplicitKey) {
  2253. keyNode = state.result;
  2254. } else {
  2255. valueNode = state.result;
  2256. }
  2257. }
  2258. if (!atExplicitKey) {
  2259. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
  2260. keyTag = keyNode = valueNode = null;
  2261. }
  2262. skipSeparationSpace(state, true, -1);
  2263. ch = state.input.charCodeAt(state.position);
  2264. }
  2265. if (state.lineIndent > nodeIndent && ch !== 0) {
  2266. throwError(state, 'bad indentation of a mapping entry');
  2267. } else if (state.lineIndent < nodeIndent) {
  2268. break;
  2269. }
  2270. } //
  2271. // Epilogue.
  2272. //
  2273. // Special case: last mapping's node contains only the key in explicit notation.
  2274. if (atExplicitKey) {
  2275. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
  2276. } // Expose the resulting mapping.
  2277. if (detected) {
  2278. state.tag = _tag;
  2279. state.anchor = _anchor;
  2280. state.kind = 'mapping';
  2281. state.result = _result;
  2282. }
  2283. return detected;
  2284. }
  2285. function readTagProperty(state) {
  2286. var _position,
  2287. isVerbatim = false,
  2288. isNamed = false,
  2289. tagHandle,
  2290. tagName,
  2291. ch;
  2292. ch = state.input.charCodeAt(state.position);
  2293. if (ch !== 0x21
  2294. /* ! */
  2295. ) return false;
  2296. if (state.tag !== null) {
  2297. throwError(state, 'duplication of a tag property');
  2298. }
  2299. ch = state.input.charCodeAt(++state.position);
  2300. if (ch === 0x3C
  2301. /* < */
  2302. ) {
  2303. isVerbatim = true;
  2304. ch = state.input.charCodeAt(++state.position);
  2305. } else if (ch === 0x21
  2306. /* ! */
  2307. ) {
  2308. isNamed = true;
  2309. tagHandle = '!!';
  2310. ch = state.input.charCodeAt(++state.position);
  2311. } else {
  2312. tagHandle = '!';
  2313. }
  2314. _position = state.position;
  2315. if (isVerbatim) {
  2316. do {
  2317. ch = state.input.charCodeAt(++state.position);
  2318. } while (ch !== 0 && ch !== 0x3E
  2319. /* > */
  2320. );
  2321. if (state.position < state.length) {
  2322. tagName = state.input.slice(_position, state.position);
  2323. ch = state.input.charCodeAt(++state.position);
  2324. } else {
  2325. throwError(state, 'unexpected end of the stream within a verbatim tag');
  2326. }
  2327. } else {
  2328. while (ch !== 0 && !is_WS_OR_EOL(ch)) {
  2329. if (ch === 0x21
  2330. /* ! */
  2331. ) {
  2332. if (!isNamed) {
  2333. tagHandle = state.input.slice(_position - 1, state.position + 1);
  2334. if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
  2335. throwError(state, 'named tag handle cannot contain such characters');
  2336. }
  2337. isNamed = true;
  2338. _position = state.position + 1;
  2339. } else {
  2340. throwError(state, 'tag suffix cannot contain exclamation marks');
  2341. }
  2342. }
  2343. ch = state.input.charCodeAt(++state.position);
  2344. }
  2345. tagName = state.input.slice(_position, state.position);
  2346. if (PATTERN_FLOW_INDICATORS.test(tagName)) {
  2347. throwError(state, 'tag suffix cannot contain flow indicator characters');
  2348. }
  2349. }
  2350. if (tagName && !PATTERN_TAG_URI.test(tagName)) {
  2351. throwError(state, 'tag name cannot contain such characters: ' + tagName);
  2352. }
  2353. if (isVerbatim) {
  2354. state.tag = tagName;
  2355. } else if (_hasOwnProperty$2.call(state.tagMap, tagHandle)) {
  2356. state.tag = state.tagMap[tagHandle] + tagName;
  2357. } else if (tagHandle === '!') {
  2358. state.tag = '!' + tagName;
  2359. } else if (tagHandle === '!!') {
  2360. state.tag = 'tag:yaml.org,2002:' + tagName;
  2361. } else {
  2362. throwError(state, 'undeclared tag handle "' + tagHandle + '"');
  2363. }
  2364. return true;
  2365. }
  2366. function readAnchorProperty(state) {
  2367. var _position, ch;
  2368. ch = state.input.charCodeAt(state.position);
  2369. if (ch !== 0x26
  2370. /* & */
  2371. ) return false;
  2372. if (state.anchor !== null) {
  2373. throwError(state, 'duplication of an anchor property');
  2374. }
  2375. ch = state.input.charCodeAt(++state.position);
  2376. _position = state.position;
  2377. while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
  2378. ch = state.input.charCodeAt(++state.position);
  2379. }
  2380. if (state.position === _position) {
  2381. throwError(state, 'name of an anchor node must contain at least one character');
  2382. }
  2383. state.anchor = state.input.slice(_position, state.position);
  2384. return true;
  2385. }
  2386. function readAlias(state) {
  2387. var _position, alias, ch;
  2388. ch = state.input.charCodeAt(state.position);
  2389. if (ch !== 0x2A
  2390. /* * */
  2391. ) return false;
  2392. ch = state.input.charCodeAt(++state.position);
  2393. _position = state.position;
  2394. while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
  2395. ch = state.input.charCodeAt(++state.position);
  2396. }
  2397. if (state.position === _position) {
  2398. throwError(state, 'name of an alias node must contain at least one character');
  2399. }
  2400. alias = state.input.slice(_position, state.position);
  2401. if (!state.anchorMap.hasOwnProperty(alias)) {
  2402. throwError(state, 'unidentified alias "' + alias + '"');
  2403. }
  2404. state.result = state.anchorMap[alias];
  2405. skipSeparationSpace(state, true, -1);
  2406. return true;
  2407. }
  2408. function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
  2409. var allowBlockStyles,
  2410. allowBlockScalars,
  2411. allowBlockCollections,
  2412. indentStatus = 1,
  2413. // 1: this>parent, 0: this=parent, -1: this<parent
  2414. atNewLine = false,
  2415. hasContent = false,
  2416. typeIndex,
  2417. typeQuantity,
  2418. type,
  2419. flowIndent,
  2420. blockIndent;
  2421. if (state.listener !== null) {
  2422. state.listener('open', state);
  2423. }
  2424. state.tag = null;
  2425. state.anchor = null;
  2426. state.kind = null;
  2427. state.result = null;
  2428. allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
  2429. if (allowToSeek) {
  2430. if (skipSeparationSpace(state, true, -1)) {
  2431. atNewLine = true;
  2432. if (state.lineIndent > parentIndent) {
  2433. indentStatus = 1;
  2434. } else if (state.lineIndent === parentIndent) {
  2435. indentStatus = 0;
  2436. } else if (state.lineIndent < parentIndent) {
  2437. indentStatus = -1;
  2438. }
  2439. }
  2440. }
  2441. if (indentStatus === 1) {
  2442. while (readTagProperty(state) || readAnchorProperty(state)) {
  2443. if (skipSeparationSpace(state, true, -1)) {
  2444. atNewLine = true;
  2445. allowBlockCollections = allowBlockStyles;
  2446. if (state.lineIndent > parentIndent) {
  2447. indentStatus = 1;
  2448. } else if (state.lineIndent === parentIndent) {
  2449. indentStatus = 0;
  2450. } else if (state.lineIndent < parentIndent) {
  2451. indentStatus = -1;
  2452. }
  2453. } else {
  2454. allowBlockCollections = false;
  2455. }
  2456. }
  2457. }
  2458. if (allowBlockCollections) {
  2459. allowBlockCollections = atNewLine || allowCompact;
  2460. }
  2461. if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
  2462. if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
  2463. flowIndent = parentIndent;
  2464. } else {
  2465. flowIndent = parentIndent + 1;
  2466. }
  2467. blockIndent = state.position - state.lineStart;
  2468. if (indentStatus === 1) {
  2469. if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
  2470. hasContent = true;
  2471. } else {
  2472. if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
  2473. hasContent = true;
  2474. } else if (readAlias(state)) {
  2475. hasContent = true;
  2476. if (state.tag !== null || state.anchor !== null) {
  2477. throwError(state, 'alias node should not have any properties');
  2478. }
  2479. } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
  2480. hasContent = true;
  2481. if (state.tag === null) {
  2482. state.tag = '?';
  2483. }
  2484. }
  2485. if (state.anchor !== null) {
  2486. state.anchorMap[state.anchor] = state.result;
  2487. }
  2488. }
  2489. } else if (indentStatus === 0) {
  2490. // Special case: block sequences are allowed to have same indentation level as the parent.
  2491. // http://www.yaml.org/spec/1.2/spec.html#id2799784
  2492. hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
  2493. }
  2494. }
  2495. if (state.tag !== null && state.tag !== '!') {
  2496. if (state.tag === '?') {
  2497. for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
  2498. type = state.implicitTypes[typeIndex]; // Implicit resolving is not allowed for non-scalar types, and '?'
  2499. // non-specific tag is only assigned to plain scalars. So, it isn't
  2500. // needed to check for 'kind' conformity.
  2501. if (type.resolve(state.result)) {
  2502. // `state.result` updated in resolver if matched
  2503. state.result = type.construct(state.result);
  2504. state.tag = type.tag;
  2505. if (state.anchor !== null) {
  2506. state.anchorMap[state.anchor] = state.result;
  2507. }
  2508. break;
  2509. }
  2510. }
  2511. } else if (_hasOwnProperty$2.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
  2512. type = state.typeMap[state.kind || 'fallback'][state.tag];
  2513. if (state.result !== null && type.kind !== state.kind) {
  2514. throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
  2515. }
  2516. if (!type.resolve(state.result)) {
  2517. // `state.result` updated in resolver if matched
  2518. throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
  2519. } else {
  2520. state.result = type.construct(state.result);
  2521. if (state.anchor !== null) {
  2522. state.anchorMap[state.anchor] = state.result;
  2523. }
  2524. }
  2525. } else {
  2526. throwError(state, 'unknown tag !<' + state.tag + '>');
  2527. }
  2528. }
  2529. if (state.listener !== null) {
  2530. state.listener('close', state);
  2531. }
  2532. return state.tag !== null || state.anchor !== null || hasContent;
  2533. }
  2534. function readDocument(state) {
  2535. var documentStart = state.position,
  2536. _position,
  2537. directiveName,
  2538. directiveArgs,
  2539. hasDirectives = false,
  2540. ch;
  2541. state.version = null;
  2542. state.checkLineBreaks = state.legacy;
  2543. state.tagMap = {};
  2544. state.anchorMap = {};
  2545. while ((ch = state.input.charCodeAt(state.position)) !== 0) {
  2546. skipSeparationSpace(state, true, -1);
  2547. ch = state.input.charCodeAt(state.position);
  2548. if (state.lineIndent > 0 || ch !== 0x25
  2549. /* % */
  2550. ) {
  2551. break;
  2552. }
  2553. hasDirectives = true;
  2554. ch = state.input.charCodeAt(++state.position);
  2555. _position = state.position;
  2556. while (ch !== 0 && !is_WS_OR_EOL(ch)) {
  2557. ch = state.input.charCodeAt(++state.position);
  2558. }
  2559. directiveName = state.input.slice(_position, state.position);
  2560. directiveArgs = [];
  2561. if (directiveName.length < 1) {
  2562. throwError(state, 'directive name must not be less than one character in length');
  2563. }
  2564. while (ch !== 0) {
  2565. while (is_WHITE_SPACE(ch)) {
  2566. ch = state.input.charCodeAt(++state.position);
  2567. }
  2568. if (ch === 0x23
  2569. /* # */
  2570. ) {
  2571. do {
  2572. ch = state.input.charCodeAt(++state.position);
  2573. } while (ch !== 0 && !is_EOL(ch));
  2574. break;
  2575. }
  2576. if (is_EOL(ch)) break;
  2577. _position = state.position;
  2578. while (ch !== 0 && !is_WS_OR_EOL(ch)) {
  2579. ch = state.input.charCodeAt(++state.position);
  2580. }
  2581. directiveArgs.push(state.input.slice(_position, state.position));
  2582. }
  2583. if (ch !== 0) readLineBreak(state);
  2584. if (_hasOwnProperty$2.call(directiveHandlers, directiveName)) {
  2585. directiveHandlers[directiveName](state, directiveName, directiveArgs);
  2586. } else {
  2587. throwWarning(state, 'unknown document directive "' + directiveName + '"');
  2588. }
  2589. }
  2590. skipSeparationSpace(state, true, -1);
  2591. if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D
  2592. /* - */
  2593. && state.input.charCodeAt(state.position + 1) === 0x2D
  2594. /* - */
  2595. && state.input.charCodeAt(state.position + 2) === 0x2D
  2596. /* - */
  2597. ) {
  2598. state.position += 3;
  2599. skipSeparationSpace(state, true, -1);
  2600. } else if (hasDirectives) {
  2601. throwError(state, 'directives end mark is expected');
  2602. }
  2603. composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
  2604. skipSeparationSpace(state, true, -1);
  2605. if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
  2606. throwWarning(state, 'non-ASCII line breaks are interpreted as content');
  2607. }
  2608. state.documents.push(state.result);
  2609. if (state.position === state.lineStart && testDocumentSeparator(state)) {
  2610. if (state.input.charCodeAt(state.position) === 0x2E
  2611. /* . */
  2612. ) {
  2613. state.position += 3;
  2614. skipSeparationSpace(state, true, -1);
  2615. }
  2616. return;
  2617. }
  2618. if (state.position < state.length - 1) {
  2619. throwError(state, 'end of the stream or a document separator is expected');
  2620. } else {
  2621. return;
  2622. }
  2623. }
  2624. function loadDocuments(input, options) {
  2625. input = String(input);
  2626. options = options || {};
  2627. if (input.length !== 0) {
  2628. // Add tailing `\n` if not exists
  2629. if (input.charCodeAt(input.length - 1) !== 0x0A
  2630. /* LF */
  2631. && input.charCodeAt(input.length - 1) !== 0x0D
  2632. /* CR */
  2633. ) {
  2634. input += '\n';
  2635. } // Strip BOM
  2636. if (input.charCodeAt(0) === 0xFEFF) {
  2637. input = input.slice(1);
  2638. }
  2639. }
  2640. var state = new State(input, options); // Use 0 as string terminator. That significantly simplifies bounds check.
  2641. state.input += '\0';
  2642. while (state.input.charCodeAt(state.position) === 0x20
  2643. /* Space */
  2644. ) {
  2645. state.lineIndent += 1;
  2646. state.position += 1;
  2647. }
  2648. while (state.position < state.length - 1) {
  2649. readDocument(state);
  2650. }
  2651. return state.documents;
  2652. }
  2653. function loadAll(input, iterator, options) {
  2654. var documents = loadDocuments(input, options),
  2655. index,
  2656. length;
  2657. if (typeof iterator !== 'function') {
  2658. return documents;
  2659. }
  2660. for (index = 0, length = documents.length; index < length; index += 1) {
  2661. iterator(documents[index]);
  2662. }
  2663. }
  2664. function load(input, options) {
  2665. var documents = loadDocuments(input, options);
  2666. if (documents.length === 0) {
  2667. /*eslint-disable no-undefined*/
  2668. return undefined;
  2669. } else if (documents.length === 1) {
  2670. return documents[0];
  2671. }
  2672. throw new exception('expected a single document in the stream, but found more');
  2673. }
  2674. function safeLoadAll(input, output, options) {
  2675. if (typeof output === 'function') {
  2676. loadAll(input, output, common.extend({
  2677. schema: default_safe
  2678. }, options));
  2679. } else {
  2680. return loadAll(input, common.extend({
  2681. schema: default_safe
  2682. }, options));
  2683. }
  2684. }
  2685. function safeLoad(input, options) {
  2686. return load(input, common.extend({
  2687. schema: default_safe
  2688. }, options));
  2689. }
  2690. var loadAll_1 = loadAll;
  2691. var load_1 = load;
  2692. var safeLoadAll_1 = safeLoadAll;
  2693. var safeLoad_1 = safeLoad;
  2694. var loader = {
  2695. loadAll: loadAll_1,
  2696. load: load_1,
  2697. safeLoadAll: safeLoadAll_1,
  2698. safeLoad: safeLoad_1
  2699. };
  2700. /*eslint-disable no-use-before-define*/
  2701. var _toString$2 = Object.prototype.toString;
  2702. var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
  2703. var CHAR_TAB = 0x09;
  2704. /* Tab */
  2705. var CHAR_LINE_FEED = 0x0A;
  2706. /* LF */
  2707. var CHAR_SPACE = 0x20;
  2708. /* Space */
  2709. var CHAR_EXCLAMATION = 0x21;
  2710. /* ! */
  2711. var CHAR_DOUBLE_QUOTE = 0x22;
  2712. /* " */
  2713. var CHAR_SHARP = 0x23;
  2714. /* # */
  2715. var CHAR_PERCENT = 0x25;
  2716. /* % */
  2717. var CHAR_AMPERSAND = 0x26;
  2718. /* & */
  2719. var CHAR_SINGLE_QUOTE = 0x27;
  2720. /* ' */
  2721. var CHAR_ASTERISK = 0x2A;
  2722. /* * */
  2723. var CHAR_COMMA = 0x2C;
  2724. /* , */
  2725. var CHAR_MINUS = 0x2D;
  2726. /* - */
  2727. var CHAR_COLON = 0x3A;
  2728. /* : */
  2729. var CHAR_GREATER_THAN = 0x3E;
  2730. /* > */
  2731. var CHAR_QUESTION = 0x3F;
  2732. /* ? */
  2733. var CHAR_COMMERCIAL_AT = 0x40;
  2734. /* @ */
  2735. var CHAR_LEFT_SQUARE_BRACKET = 0x5B;
  2736. /* [ */
  2737. var CHAR_RIGHT_SQUARE_BRACKET = 0x5D;
  2738. /* ] */
  2739. var CHAR_GRAVE_ACCENT = 0x60;
  2740. /* ` */
  2741. var CHAR_LEFT_CURLY_BRACKET = 0x7B;
  2742. /* { */
  2743. var CHAR_VERTICAL_LINE = 0x7C;
  2744. /* | */
  2745. var CHAR_RIGHT_CURLY_BRACKET = 0x7D;
  2746. /* } */
  2747. var ESCAPE_SEQUENCES = {};
  2748. ESCAPE_SEQUENCES[0x00] = '\\0';
  2749. ESCAPE_SEQUENCES[0x07] = '\\a';
  2750. ESCAPE_SEQUENCES[0x08] = '\\b';
  2751. ESCAPE_SEQUENCES[0x09] = '\\t';
  2752. ESCAPE_SEQUENCES[0x0A] = '\\n';
  2753. ESCAPE_SEQUENCES[0x0B] = '\\v';
  2754. ESCAPE_SEQUENCES[0x0C] = '\\f';
  2755. ESCAPE_SEQUENCES[0x0D] = '\\r';
  2756. ESCAPE_SEQUENCES[0x1B] = '\\e';
  2757. ESCAPE_SEQUENCES[0x22] = '\\"';
  2758. ESCAPE_SEQUENCES[0x5C] = '\\\\';
  2759. ESCAPE_SEQUENCES[0x85] = '\\N';
  2760. ESCAPE_SEQUENCES[0xA0] = '\\_';
  2761. ESCAPE_SEQUENCES[0x2028] = '\\L';
  2762. ESCAPE_SEQUENCES[0x2029] = '\\P';
  2763. var DEPRECATED_BOOLEANS_SYNTAX = ['y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'];
  2764. function compileStyleMap(schema, map) {
  2765. var result, keys, index, length, tag, style, type;
  2766. if (map === null) return {};
  2767. result = {};
  2768. keys = Object.keys(map);
  2769. for (index = 0, length = keys.length; index < length; index += 1) {
  2770. tag = keys[index];
  2771. style = String(map[tag]);
  2772. if (tag.slice(0, 2) === '!!') {
  2773. tag = 'tag:yaml.org,2002:' + tag.slice(2);
  2774. }
  2775. type = schema.compiledTypeMap['fallback'][tag];
  2776. if (type && _hasOwnProperty$3.call(type.styleAliases, style)) {
  2777. style = type.styleAliases[style];
  2778. }
  2779. result[tag] = style;
  2780. }
  2781. return result;
  2782. }
  2783. function encodeHex(character) {
  2784. var string, handle, length;
  2785. string = character.toString(16).toUpperCase();
  2786. if (character <= 0xFF) {
  2787. handle = 'x';
  2788. length = 2;
  2789. } else if (character <= 0xFFFF) {
  2790. handle = 'u';
  2791. length = 4;
  2792. } else if (character <= 0xFFFFFFFF) {
  2793. handle = 'U';
  2794. length = 8;
  2795. } else {
  2796. throw new exception('code point within a string may not be greater than 0xFFFFFFFF');
  2797. }
  2798. return '\\' + handle + common.repeat('0', length - string.length) + string;
  2799. }
  2800. function State$1(options) {
  2801. this.schema = options['schema'] || default_full;
  2802. this.indent = Math.max(1, options['indent'] || 2);
  2803. this.noArrayIndent = options['noArrayIndent'] || false;
  2804. this.skipInvalid = options['skipInvalid'] || false;
  2805. this.flowLevel = common.isNothing(options['flowLevel']) ? -1 : options['flowLevel'];
  2806. this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
  2807. this.sortKeys = options['sortKeys'] || false;
  2808. this.lineWidth = options['lineWidth'] || 80;
  2809. this.noRefs = options['noRefs'] || false;
  2810. this.noCompatMode = options['noCompatMode'] || false;
  2811. this.condenseFlow = options['condenseFlow'] || false;
  2812. this.implicitTypes = this.schema.compiledImplicit;
  2813. this.explicitTypes = this.schema.compiledExplicit;
  2814. this.tag = null;
  2815. this.result = '';
  2816. this.duplicates = [];
  2817. this.usedDuplicates = null;
  2818. } // Indents every line in a string. Empty lines (\n only) are not indented.
  2819. function indentString(string, spaces) {
  2820. var ind = common.repeat(' ', spaces),
  2821. position = 0,
  2822. next = -1,
  2823. result = '',
  2824. line,
  2825. length = string.length;
  2826. while (position < length) {
  2827. next = string.indexOf('\n', position);
  2828. if (next === -1) {
  2829. line = string.slice(position);
  2830. position = length;
  2831. } else {
  2832. line = string.slice(position, next + 1);
  2833. position = next + 1;
  2834. }
  2835. if (line.length && line !== '\n') result += ind;
  2836. result += line;
  2837. }
  2838. return result;
  2839. }
  2840. function generateNextLine(state, level) {
  2841. return '\n' + common.repeat(' ', state.indent * level);
  2842. }
  2843. function testImplicitResolving(state, str) {
  2844. var index, length, type;
  2845. for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
  2846. type = state.implicitTypes[index];
  2847. if (type.resolve(str)) {
  2848. return true;
  2849. }
  2850. }
  2851. return false;
  2852. } // [33] s-white ::= s-space | s-tab
  2853. function isWhitespace(c) {
  2854. return c === CHAR_SPACE || c === CHAR_TAB;
  2855. } // Returns true if the character can be printed without escaping.
  2856. // From YAML 1.2: "any allowed characters known to be non-printable
  2857. // should also be escaped. [However,] This isn’t mandatory"
  2858. // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
  2859. function isPrintable(c) {
  2860. return 0x00020 <= c && c <= 0x00007E || 0x000A1 <= c && c <= 0x00D7FF && c !== 0x2028 && c !== 0x2029 || 0x0E000 <= c && c <= 0x00FFFD && c !== 0xFEFF
  2861. /* BOM */
  2862. || 0x10000 <= c && c <= 0x10FFFF;
  2863. } // Simplified test for values allowed after the first character in plain style.
  2864. function isPlainSafe(c) {
  2865. // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
  2866. // where nb-char ::= c-printable - b-char - c-byte-order-mark.
  2867. return isPrintable(c) && c !== 0xFEFF // - c-flow-indicator
  2868. && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // - ":" - "#"
  2869. && c !== CHAR_COLON && c !== CHAR_SHARP;
  2870. } // Simplified test for values allowed as the first character in plain style.
  2871. function isPlainSafeFirst(c) {
  2872. // Uses a subset of ns-char - c-indicator
  2873. // where ns-char = nb-char - s-white.
  2874. return isPrintable(c) && c !== 0xFEFF && !isWhitespace(c) // - s-white
  2875. // - (c-indicator ::=
  2876. // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
  2877. && 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 // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
  2878. && 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 // | “%” | “@” | “`”)
  2879. && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
  2880. } // Determines whether block indentation indicator is required.
  2881. function needIndentIndicator(string) {
  2882. var leadingSpaceRe = /^\n* /;
  2883. return leadingSpaceRe.test(string);
  2884. }
  2885. var STYLE_PLAIN = 1,
  2886. STYLE_SINGLE = 2,
  2887. STYLE_LITERAL = 3,
  2888. STYLE_FOLDED = 4,
  2889. STYLE_DOUBLE = 5; // Determines which scalar styles are possible and returns the preferred style.
  2890. // lineWidth = -1 => no limit.
  2891. // Pre-conditions: str.length > 0.
  2892. // Post-conditions:
  2893. // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
  2894. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
  2895. // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
  2896. function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
  2897. var i;
  2898. var char;
  2899. var hasLineBreak = false;
  2900. var hasFoldableLine = false; // only checked if shouldTrackWidth
  2901. var shouldTrackWidth = lineWidth !== -1;
  2902. var previousLineBreak = -1; // count the first line correctly
  2903. var plain = isPlainSafeFirst(string.charCodeAt(0)) && !isWhitespace(string.charCodeAt(string.length - 1));
  2904. if (singleLineOnly) {
  2905. // Case: no block styles.
  2906. // Check for disallowed characters to rule out plain and single.
  2907. for (i = 0; i < string.length; i++) {
  2908. char = string.charCodeAt(i);
  2909. if (!isPrintable(char)) {
  2910. return STYLE_DOUBLE;
  2911. }
  2912. plain = plain && isPlainSafe(char);
  2913. }
  2914. } else {
  2915. // Case: block styles permitted.
  2916. for (i = 0; i < string.length; i++) {
  2917. char = string.charCodeAt(i);
  2918. if (char === CHAR_LINE_FEED) {
  2919. hasLineBreak = true; // Check if any line can be folded.
  2920. if (shouldTrackWidth) {
  2921. hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
  2922. i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ';
  2923. previousLineBreak = i;
  2924. }
  2925. } else if (!isPrintable(char)) {
  2926. return STYLE_DOUBLE;
  2927. }
  2928. plain = plain && isPlainSafe(char);
  2929. } // in case the end is missing a \n
  2930. hasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ';
  2931. } // Although every style can represent \n without escaping, prefer block styles
  2932. // for multiline, since they're more readable and they don't add empty lines.
  2933. // Also prefer folding a super-long line.
  2934. if (!hasLineBreak && !hasFoldableLine) {
  2935. // Strings interpretable as another type have to be quoted;
  2936. // e.g. the string 'true' vs. the boolean true.
  2937. return plain && !testAmbiguousType(string) ? STYLE_PLAIN : STYLE_SINGLE;
  2938. } // Edge case: block indentation indicator can only have one digit.
  2939. if (indentPerLevel > 9 && needIndentIndicator(string)) {
  2940. return STYLE_DOUBLE;
  2941. } // At this point we know block styles are valid.
  2942. // Prefer literal style unless we want to fold.
  2943. return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
  2944. } // Note: line breaking/folding is implemented for only the folded style.
  2945. // NB. We drop the last trailing newline (if any) of a returned block scalar
  2946. // since the dumper adds its own newline. This always works:
  2947. // • No ending newline => unaffected; already using strip "-" chomping.
  2948. // • Ending newline => removed then restored.
  2949. // Importantly, this keeps the "+" chomp indicator from gaining an extra line.
  2950. function writeScalar(state, string, level, iskey) {
  2951. state.dump = function () {
  2952. if (string.length === 0) {
  2953. return "''";
  2954. }
  2955. if (!state.noCompatMode && DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
  2956. return "'" + string + "'";
  2957. }
  2958. var indent = state.indent * Math.max(1, level); // no 0-indent scalars
  2959. // As indentation gets deeper, let the width decrease monotonically
  2960. // to the lower bound min(state.lineWidth, 40).
  2961. // Note that this implies
  2962. // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
  2963. // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
  2964. // This behaves better than a constant minimum width which disallows narrower options,
  2965. // or an indent threshold which causes the width to suddenly increase.
  2966. 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.
  2967. var singleLineOnly = iskey // No block styles in flow mode.
  2968. || state.flowLevel > -1 && level >= state.flowLevel;
  2969. function testAmbiguity(string) {
  2970. return testImplicitResolving(state, string);
  2971. }
  2972. switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
  2973. case STYLE_PLAIN:
  2974. return string;
  2975. case STYLE_SINGLE:
  2976. return "'" + string.replace(/'/g, "''") + "'";
  2977. case STYLE_LITERAL:
  2978. return '|' + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
  2979. case STYLE_FOLDED:
  2980. return '>' + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
  2981. case STYLE_DOUBLE:
  2982. return '"' + escapeString(string) + '"';
  2983. default:
  2984. throw new exception('impossible error: invalid scalar style');
  2985. }
  2986. }();
  2987. } // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
  2988. function blockHeader(string, indentPerLevel) {
  2989. var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; // note the special case: the string '\n' counts as a "trailing" empty line.
  2990. var clip = string[string.length - 1] === '\n';
  2991. var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
  2992. var chomp = keep ? '+' : clip ? '' : '-';
  2993. return indentIndicator + chomp + '\n';
  2994. } // (See the note for writeScalar.)
  2995. function dropEndingNewline(string) {
  2996. return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
  2997. } // Note: a long line without a suitable break point will exceed the width limit.
  2998. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
  2999. function foldString(string, width) {
  3000. // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
  3001. // unless they're before or after a more-indented line, or at the very
  3002. // beginning or end, in which case $k$ maps to $k$.
  3003. // Therefore, parse each chunk as newline(s) followed by a content line.
  3004. var lineRe = /(\n+)([^\n]*)/g; // first line (possibly an empty line)
  3005. var result = function () {
  3006. var nextLF = string.indexOf('\n');
  3007. nextLF = nextLF !== -1 ? nextLF : string.length;
  3008. lineRe.lastIndex = nextLF;
  3009. return foldLine(string.slice(0, nextLF), width);
  3010. }(); // If we haven't reached the first content line yet, don't add an extra \n.
  3011. var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
  3012. var moreIndented; // rest of the lines
  3013. var match;
  3014. while (match = lineRe.exec(string)) {
  3015. var prefix = match[1],
  3016. line = match[2];
  3017. moreIndented = line[0] === ' ';
  3018. result += prefix + (!prevMoreIndented && !moreIndented && line !== '' ? '\n' : '') + foldLine(line, width);
  3019. prevMoreIndented = moreIndented;
  3020. }
  3021. return result;
  3022. } // Greedy line breaking.
  3023. // Picks the longest line under the limit each time,
  3024. // otherwise settles for the shortest line over the limit.
  3025. // NB. More-indented lines *cannot* be folded, as that would add an extra \n.
  3026. function foldLine(line, width) {
  3027. if (line === '' || line[0] === ' ') return line; // Since a more-indented line adds a \n, breaks can't be followed by a space.
  3028. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
  3029. var match; // start is an inclusive index. end, curr, and next are exclusive.
  3030. var start = 0,
  3031. end,
  3032. curr = 0,
  3033. next = 0;
  3034. var result = ''; // Invariants: 0 <= start <= length-1.
  3035. // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
  3036. // Inside the loop:
  3037. // A match implies length >= 2, so curr and next are <= length-2.
  3038. while (match = breakRe.exec(line)) {
  3039. next = match.index; // maintain invariant: curr - start <= width
  3040. if (next - start > width) {
  3041. end = curr > start ? curr : next; // derive end <= length-2
  3042. result += '\n' + line.slice(start, end); // skip the space that was output as \n
  3043. start = end + 1; // derive start <= length-1
  3044. }
  3045. curr = next;
  3046. } // By the invariants, start <= length-1, so there is something left over.
  3047. // It is either the whole string or a part starting from non-whitespace.
  3048. result += '\n'; // Insert a break if the remainder is too long and there is a break available.
  3049. if (line.length - start > width && curr > start) {
  3050. result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
  3051. } else {
  3052. result += line.slice(start);
  3053. }
  3054. return result.slice(1); // drop extra \n joiner
  3055. } // Escapes a double-quoted string.
  3056. function escapeString(string) {
  3057. var result = '';
  3058. var char, nextChar;
  3059. var escapeSeq;
  3060. for (var i = 0; i < string.length; i++) {
  3061. char = string.charCodeAt(i); // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
  3062. if (char >= 0xD800 && char <= 0xDBFF
  3063. /* high surrogate */
  3064. ) {
  3065. nextChar = string.charCodeAt(i + 1);
  3066. if (nextChar >= 0xDC00 && nextChar <= 0xDFFF
  3067. /* low surrogate */
  3068. ) {
  3069. // Combine the surrogate pair and store it escaped.
  3070. result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); // Advance index one extra since we already used that char here.
  3071. i++;
  3072. continue;
  3073. }
  3074. }
  3075. escapeSeq = ESCAPE_SEQUENCES[char];
  3076. result += !escapeSeq && isPrintable(char) ? string[i] : escapeSeq || encodeHex(char);
  3077. }
  3078. return result;
  3079. }
  3080. function writeFlowSequence(state, level, object) {
  3081. var _result = '',
  3082. _tag = state.tag,
  3083. index,
  3084. length;
  3085. for (index = 0, length = object.length; index < length; index += 1) {
  3086. // Write only valid elements.
  3087. if (writeNode(state, level, object[index], false, false)) {
  3088. if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
  3089. _result += state.dump;
  3090. }
  3091. }
  3092. state.tag = _tag;
  3093. state.dump = '[' + _result + ']';
  3094. }
  3095. function writeBlockSequence(state, level, object, compact) {
  3096. var _result = '',
  3097. _tag = state.tag,
  3098. index,
  3099. length;
  3100. for (index = 0, length = object.length; index < length; index += 1) {
  3101. // Write only valid elements.
  3102. if (writeNode(state, level + 1, object[index], true, true)) {
  3103. if (!compact || index !== 0) {
  3104. _result += generateNextLine(state, level);
  3105. }
  3106. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  3107. _result += '-';
  3108. } else {
  3109. _result += '- ';
  3110. }
  3111. _result += state.dump;
  3112. }
  3113. }
  3114. state.tag = _tag;
  3115. state.dump = _result || '[]'; // Empty sequence if no valid values.
  3116. }
  3117. function writeFlowMapping(state, level, object) {
  3118. var _result = '',
  3119. _tag = state.tag,
  3120. objectKeyList = Object.keys(object),
  3121. index,
  3122. length,
  3123. objectKey,
  3124. objectValue,
  3125. pairBuffer;
  3126. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  3127. pairBuffer = state.condenseFlow ? '"' : '';
  3128. if (index !== 0) pairBuffer += ', ';
  3129. objectKey = objectKeyList[index];
  3130. objectValue = object[objectKey];
  3131. if (!writeNode(state, level, objectKey, false, false)) {
  3132. continue; // Skip this pair because of invalid key;
  3133. }
  3134. if (state.dump.length > 1024) pairBuffer += '? ';
  3135. pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
  3136. if (!writeNode(state, level, objectValue, false, false)) {
  3137. continue; // Skip this pair because of invalid value.
  3138. }
  3139. pairBuffer += state.dump; // Both key and value are valid.
  3140. _result += pairBuffer;
  3141. }
  3142. state.tag = _tag;
  3143. state.dump = '{' + _result + '}';
  3144. }
  3145. function writeBlockMapping(state, level, object, compact) {
  3146. var _result = '',
  3147. _tag = state.tag,
  3148. objectKeyList = Object.keys(object),
  3149. index,
  3150. length,
  3151. objectKey,
  3152. objectValue,
  3153. explicitPair,
  3154. pairBuffer; // Allow sorting keys so that the output file is deterministic
  3155. if (state.sortKeys === true) {
  3156. // Default sorting
  3157. objectKeyList.sort();
  3158. } else if (typeof state.sortKeys === 'function') {
  3159. // Custom sort function
  3160. objectKeyList.sort(state.sortKeys);
  3161. } else if (state.sortKeys) {
  3162. // Something is wrong
  3163. throw new exception('sortKeys must be a boolean or a function');
  3164. }
  3165. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  3166. pairBuffer = '';
  3167. if (!compact || index !== 0) {
  3168. pairBuffer += generateNextLine(state, level);
  3169. }
  3170. objectKey = objectKeyList[index];
  3171. objectValue = object[objectKey];
  3172. if (!writeNode(state, level + 1, objectKey, true, true, true)) {
  3173. continue; // Skip this pair because of invalid key.
  3174. }
  3175. explicitPair = state.tag !== null && state.tag !== '?' || state.dump && state.dump.length > 1024;
  3176. if (explicitPair) {
  3177. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  3178. pairBuffer += '?';
  3179. } else {
  3180. pairBuffer += '? ';
  3181. }
  3182. }
  3183. pairBuffer += state.dump;
  3184. if (explicitPair) {
  3185. pairBuffer += generateNextLine(state, level);
  3186. }
  3187. if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
  3188. continue; // Skip this pair because of invalid value.
  3189. }
  3190. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  3191. pairBuffer += ':';
  3192. } else {
  3193. pairBuffer += ': ';
  3194. }
  3195. pairBuffer += state.dump; // Both key and value are valid.
  3196. _result += pairBuffer;
  3197. }
  3198. state.tag = _tag;
  3199. state.dump = _result || '{}'; // Empty mapping if no valid pairs.
  3200. }
  3201. function detectType(state, object, explicit) {
  3202. var _result, typeList, index, length, type, style;
  3203. typeList = explicit ? state.explicitTypes : state.implicitTypes;
  3204. for (index = 0, length = typeList.length; index < length; index += 1) {
  3205. type = typeList[index];
  3206. if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === 'object' && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) {
  3207. state.tag = explicit ? type.tag : '?';
  3208. if (type.represent) {
  3209. style = state.styleMap[type.tag] || type.defaultStyle;
  3210. if (_toString$2.call(type.represent) === '[object Function]') {
  3211. _result = type.represent(object, style);
  3212. } else if (_hasOwnProperty$3.call(type.represent, style)) {
  3213. _result = type.represent[style](object, style);
  3214. } else {
  3215. throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
  3216. }
  3217. state.dump = _result;
  3218. }
  3219. return true;
  3220. }
  3221. }
  3222. return false;
  3223. } // Serializes `object` and writes it to global `result`.
  3224. // Returns true on success, or false on invalid object.
  3225. //
  3226. function writeNode(state, level, object, block, compact, iskey) {
  3227. state.tag = null;
  3228. state.dump = object;
  3229. if (!detectType(state, object, false)) {
  3230. detectType(state, object, true);
  3231. }
  3232. var type = _toString$2.call(state.dump);
  3233. if (block) {
  3234. block = state.flowLevel < 0 || state.flowLevel > level;
  3235. }
  3236. var objectOrArray = type === '[object Object]' || type === '[object Array]',
  3237. duplicateIndex,
  3238. duplicate;
  3239. if (objectOrArray) {
  3240. duplicateIndex = state.duplicates.indexOf(object);
  3241. duplicate = duplicateIndex !== -1;
  3242. }
  3243. if (state.tag !== null && state.tag !== '?' || duplicate || state.indent !== 2 && level > 0) {
  3244. compact = false;
  3245. }
  3246. if (duplicate && state.usedDuplicates[duplicateIndex]) {
  3247. state.dump = '*ref_' + duplicateIndex;
  3248. } else {
  3249. if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
  3250. state.usedDuplicates[duplicateIndex] = true;
  3251. }
  3252. if (type === '[object Object]') {
  3253. if (block && Object.keys(state.dump).length !== 0) {
  3254. writeBlockMapping(state, level, state.dump, compact);
  3255. if (duplicate) {
  3256. state.dump = '&ref_' + duplicateIndex + state.dump;
  3257. }
  3258. } else {
  3259. writeFlowMapping(state, level, state.dump);
  3260. if (duplicate) {
  3261. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  3262. }
  3263. }
  3264. } else if (type === '[object Array]') {
  3265. var arrayLevel = state.noArrayIndent && level > 0 ? level - 1 : level;
  3266. if (block && state.dump.length !== 0) {
  3267. writeBlockSequence(state, arrayLevel, state.dump, compact);
  3268. if (duplicate) {
  3269. state.dump = '&ref_' + duplicateIndex + state.dump;
  3270. }
  3271. } else {
  3272. writeFlowSequence(state, arrayLevel, state.dump);
  3273. if (duplicate) {
  3274. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  3275. }
  3276. }
  3277. } else if (type === '[object String]') {
  3278. if (state.tag !== '?') {
  3279. writeScalar(state, state.dump, level, iskey);
  3280. }
  3281. } else {
  3282. if (state.skipInvalid) return false;
  3283. throw new exception('unacceptable kind of an object to dump ' + type);
  3284. }
  3285. if (state.tag !== null && state.tag !== '?') {
  3286. state.dump = '!<' + state.tag + '> ' + state.dump;
  3287. }
  3288. }
  3289. return true;
  3290. }
  3291. function getDuplicateReferences(object, state) {
  3292. var objects = [],
  3293. duplicatesIndexes = [],
  3294. index,
  3295. length;
  3296. inspectNode(object, objects, duplicatesIndexes);
  3297. for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
  3298. state.duplicates.push(objects[duplicatesIndexes[index]]);
  3299. }
  3300. state.usedDuplicates = new Array(length);
  3301. }
  3302. function inspectNode(object, objects, duplicatesIndexes) {
  3303. var objectKeyList, index, length;
  3304. if (object !== null && typeof object === 'object') {
  3305. index = objects.indexOf(object);
  3306. if (index !== -1) {
  3307. if (duplicatesIndexes.indexOf(index) === -1) {
  3308. duplicatesIndexes.push(index);
  3309. }
  3310. } else {
  3311. objects.push(object);
  3312. if (Array.isArray(object)) {
  3313. for (index = 0, length = object.length; index < length; index += 1) {
  3314. inspectNode(object[index], objects, duplicatesIndexes);
  3315. }
  3316. } else {
  3317. objectKeyList = Object.keys(object);
  3318. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  3319. inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
  3320. }
  3321. }
  3322. }
  3323. }
  3324. }
  3325. function dump(input, options) {
  3326. options = options || {};
  3327. var state = new State$1(options);
  3328. if (!state.noRefs) getDuplicateReferences(input, state);
  3329. if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
  3330. return '';
  3331. }
  3332. function safeDump(input, options) {
  3333. return dump(input, common.extend({
  3334. schema: default_safe
  3335. }, options));
  3336. }
  3337. var dump_1 = dump;
  3338. var safeDump_1 = safeDump;
  3339. var dumper = {
  3340. dump: dump_1,
  3341. safeDump: safeDump_1
  3342. };
  3343. function deprecated(name) {
  3344. return function () {
  3345. throw new Error('Function ' + name + ' is deprecated and cannot be used.');
  3346. };
  3347. }
  3348. var Type$1 = type;
  3349. var Schema$1 = schema;
  3350. var FAILSAFE_SCHEMA = failsafe;
  3351. var JSON_SCHEMA = json;
  3352. var CORE_SCHEMA = core;
  3353. var DEFAULT_SAFE_SCHEMA = default_safe;
  3354. var DEFAULT_FULL_SCHEMA = default_full;
  3355. var load$1 = loader.load;
  3356. var loadAll$1 = loader.loadAll;
  3357. var safeLoad$1 = loader.safeLoad;
  3358. var safeLoadAll$1 = loader.safeLoadAll;
  3359. var dump$1 = dumper.dump;
  3360. var safeDump$1 = dumper.safeDump;
  3361. var YAMLException$1 = exception; // Deprecated schema names from JS-YAML 2.0.x
  3362. var MINIMAL_SCHEMA = failsafe;
  3363. var SAFE_SCHEMA = default_safe;
  3364. var DEFAULT_SCHEMA = default_full; // Deprecated functions from JS-YAML 1.x.x
  3365. var scan = deprecated('scan');
  3366. var parse = deprecated('parse');
  3367. var compose = deprecated('compose');
  3368. var addConstructor = deprecated('addConstructor');
  3369. var jsYaml = {
  3370. Type: Type$1,
  3371. Schema: Schema$1,
  3372. FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,
  3373. JSON_SCHEMA: JSON_SCHEMA,
  3374. CORE_SCHEMA: CORE_SCHEMA,
  3375. DEFAULT_SAFE_SCHEMA: DEFAULT_SAFE_SCHEMA,
  3376. DEFAULT_FULL_SCHEMA: DEFAULT_FULL_SCHEMA,
  3377. load: load$1,
  3378. loadAll: loadAll$1,
  3379. safeLoad: safeLoad$1,
  3380. safeLoadAll: safeLoadAll$1,
  3381. dump: dump$1,
  3382. safeDump: safeDump$1,
  3383. YAMLException: YAMLException$1,
  3384. MINIMAL_SCHEMA: MINIMAL_SCHEMA,
  3385. SAFE_SCHEMA: SAFE_SCHEMA,
  3386. DEFAULT_SCHEMA: DEFAULT_SCHEMA,
  3387. scan: scan,
  3388. parse: parse,
  3389. compose: compose,
  3390. addConstructor: addConstructor
  3391. };
  3392. var jsYaml$1 = jsYaml;
  3393. var resolveFrom = function resolveFrom(fromDir, moduleId, silent) {
  3394. if (typeof fromDir !== 'string') {
  3395. throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDir}\``);
  3396. }
  3397. if (typeof moduleId !== 'string') {
  3398. throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
  3399. }
  3400. fromDir = path.resolve(fromDir);
  3401. var fromFile = path.join(fromDir, 'noop.js');
  3402. var resolveFileName = function resolveFileName() {
  3403. return module$1._resolveFilename(moduleId, {
  3404. id: fromFile,
  3405. filename: fromFile,
  3406. paths: module$1._nodeModulePaths(fromDir)
  3407. });
  3408. };
  3409. if (silent) {
  3410. try {
  3411. return resolveFileName();
  3412. } catch (err) {
  3413. return null;
  3414. }
  3415. }
  3416. return resolveFileName();
  3417. };
  3418. var resolveFrom_1 = function resolveFrom_1(fromDir, moduleId) {
  3419. return resolveFrom(fromDir, moduleId);
  3420. };
  3421. var silent = function silent(fromDir, moduleId) {
  3422. return resolveFrom(fromDir, moduleId, true);
  3423. };
  3424. resolveFrom_1.silent = silent;
  3425. var callsites = function callsites() {
  3426. var _ = Error.prepareStackTrace;
  3427. Error.prepareStackTrace = function (_, stack) {
  3428. return stack;
  3429. };
  3430. var stack = new Error().stack.slice(1);
  3431. Error.prepareStackTrace = _;
  3432. return stack;
  3433. };
  3434. var callerCallsite = function callerCallsite() {
  3435. var c = callsites();
  3436. var caller;
  3437. for (var i = 0; i < c.length; i++) {
  3438. var hasReceiver = c[i].getTypeName() !== null;
  3439. if (hasReceiver) {
  3440. caller = i;
  3441. break;
  3442. }
  3443. }
  3444. return c[caller];
  3445. };
  3446. var callerPath = function callerPath() {
  3447. return callerCallsite().getFileName();
  3448. };
  3449. var importFresh = function importFresh(moduleId) {
  3450. if (typeof moduleId !== 'string') {
  3451. throw new TypeError('Expected a string');
  3452. }
  3453. var filePath = resolveFrom_1(path.dirname(callerPath()), moduleId); // Delete itself from module parent
  3454. if (require.cache[filePath] && require.cache[filePath].parent) {
  3455. var i = require.cache[filePath].parent.children.length;
  3456. while (i--) {
  3457. if (require.cache[filePath].parent.children[i].id === filePath) {
  3458. require.cache[filePath].parent.children.splice(i, 1);
  3459. }
  3460. }
  3461. } // Delete module from cache
  3462. delete require.cache[filePath]; // Return fresh module
  3463. return require(filePath);
  3464. };
  3465. function loadJs(filepath) {
  3466. var result = importFresh(filepath);
  3467. return result;
  3468. }
  3469. function loadJson(filepath, content) {
  3470. try {
  3471. return parseJson$1(content);
  3472. } catch (err) {
  3473. err.message = `JSON Error in ${filepath}:\n${err.message}`;
  3474. throw err;
  3475. }
  3476. }
  3477. function loadYaml(filepath, content) {
  3478. return jsYaml$1.safeLoad(content, {
  3479. filename: filepath
  3480. });
  3481. }
  3482. var loaders = {
  3483. loadJs,
  3484. loadJson,
  3485. loadYaml
  3486. };
  3487. function readFile(filepath, options) {
  3488. options = options || {};
  3489. var throwNotFound = options.throwNotFound || false;
  3490. return new Promise(function (resolve, reject) {
  3491. fs.readFile(filepath, 'utf8', function (err, content) {
  3492. if (err && err.code === 'ENOENT' && !throwNotFound) {
  3493. return resolve(null);
  3494. }
  3495. if (err) return reject(err);
  3496. resolve(content);
  3497. });
  3498. });
  3499. }
  3500. readFile.sync = function readFileSync(filepath, options) {
  3501. options = options || {};
  3502. var throwNotFound = options.throwNotFound || false;
  3503. try {
  3504. return fs.readFileSync(filepath, 'utf8');
  3505. } catch (err) {
  3506. if (err.code === 'ENOENT' && !throwNotFound) {
  3507. return null;
  3508. }
  3509. throw err;
  3510. }
  3511. };
  3512. var readFile_1 = readFile;
  3513. //
  3514. function cacheWrapper(cache, key, fn) {
  3515. if (!cache) {
  3516. return fn();
  3517. }
  3518. var cached = cache.get(key);
  3519. if (cached !== undefined) {
  3520. return cached;
  3521. }
  3522. var result = fn();
  3523. cache.set(key, result);
  3524. return result;
  3525. }
  3526. var cacheWrapper_1 = cacheWrapper;
  3527. /**
  3528. * async
  3529. */
  3530. function isDirectory(filepath, cb) {
  3531. if (typeof cb !== 'function') {
  3532. throw new Error('expected a callback function');
  3533. }
  3534. if (typeof filepath !== 'string') {
  3535. cb(new Error('expected filepath to be a string'));
  3536. return;
  3537. }
  3538. fs.stat(filepath, function (err, stats) {
  3539. if (err) {
  3540. if (err.code === 'ENOENT') {
  3541. cb(null, false);
  3542. return;
  3543. }
  3544. cb(err);
  3545. return;
  3546. }
  3547. cb(null, stats.isDirectory());
  3548. });
  3549. }
  3550. /**
  3551. * sync
  3552. */
  3553. isDirectory.sync = function isDirectorySync(filepath) {
  3554. if (typeof filepath !== 'string') {
  3555. throw new Error('expected filepath to be a string');
  3556. }
  3557. try {
  3558. var stat = fs.statSync(filepath);
  3559. return stat.isDirectory();
  3560. } catch (err) {
  3561. if (err.code === 'ENOENT') {
  3562. return false;
  3563. } else {
  3564. throw err;
  3565. }
  3566. }
  3567. return false;
  3568. };
  3569. /**
  3570. * Expose `isDirectory`
  3571. */
  3572. var isDirectory_1 = isDirectory;
  3573. function getDirectory(filepath) {
  3574. return new Promise(function (resolve, reject) {
  3575. return isDirectory_1(filepath, function (err, filepathIsDirectory) {
  3576. if (err) {
  3577. return reject(err);
  3578. }
  3579. return resolve(filepathIsDirectory ? filepath : path.dirname(filepath));
  3580. });
  3581. });
  3582. }
  3583. getDirectory.sync = function getDirectorySync(filepath) {
  3584. return isDirectory_1.sync(filepath) ? filepath : path.dirname(filepath);
  3585. };
  3586. var getDirectory_1 = getDirectory;
  3587. //
  3588. // strings or arrays of strings. Property names that are found on the source
  3589. // object are used directly (even if they include a period).
  3590. // Nested property names that include periods, within a path, are only
  3591. // understood in array paths.
  3592. function getPropertyByPath(source, path) {
  3593. if (typeof path === 'string' && source.hasOwnProperty(path)) {
  3594. return source[path];
  3595. }
  3596. var parsedPath = typeof path === 'string' ? path.split('.') : path;
  3597. return parsedPath.reduce(function (previous, key) {
  3598. if (previous === undefined) {
  3599. return previous;
  3600. }
  3601. return previous[key];
  3602. }, source);
  3603. }
  3604. var getPropertyByPath_1 = getPropertyByPath;
  3605. var MODE_SYNC = 'sync'; // An object value represents a config object.
  3606. // null represents that the loader did not find anything relevant.
  3607. // undefined represents that the loader found something relevant
  3608. // but it was empty.
  3609. var Explorer =
  3610. /*#__PURE__*/
  3611. function () {
  3612. function Explorer(options) {
  3613. _classCallCheck(this, Explorer);
  3614. this.loadCache = options.cache ? new Map() : null;
  3615. this.loadSyncCache = options.cache ? new Map() : null;
  3616. this.searchCache = options.cache ? new Map() : null;
  3617. this.searchSyncCache = options.cache ? new Map() : null;
  3618. this.config = options;
  3619. this.validateConfig();
  3620. }
  3621. _createClass(Explorer, [{
  3622. key: "clearLoadCache",
  3623. value: function clearLoadCache() {
  3624. if (this.loadCache) {
  3625. this.loadCache.clear();
  3626. }
  3627. if (this.loadSyncCache) {
  3628. this.loadSyncCache.clear();
  3629. }
  3630. }
  3631. }, {
  3632. key: "clearSearchCache",
  3633. value: function clearSearchCache() {
  3634. if (this.searchCache) {
  3635. this.searchCache.clear();
  3636. }
  3637. if (this.searchSyncCache) {
  3638. this.searchSyncCache.clear();
  3639. }
  3640. }
  3641. }, {
  3642. key: "clearCaches",
  3643. value: function clearCaches() {
  3644. this.clearLoadCache();
  3645. this.clearSearchCache();
  3646. }
  3647. }, {
  3648. key: "validateConfig",
  3649. value: function validateConfig() {
  3650. var config = this.config;
  3651. config.searchPlaces.forEach(function (place) {
  3652. var loaderKey = path.extname(place) || 'noExt';
  3653. var loader = config.loaders[loaderKey];
  3654. if (!loader) {
  3655. throw new Error(`No loader specified for ${getExtensionDescription(place)}, so searchPlaces item "${place}" is invalid`);
  3656. }
  3657. });
  3658. }
  3659. }, {
  3660. key: "search",
  3661. value: function search(searchFrom) {
  3662. var _this = this;
  3663. searchFrom = searchFrom || process.cwd();
  3664. return getDirectory_1(searchFrom).then(function (dir) {
  3665. return _this.searchFromDirectory(dir);
  3666. });
  3667. }
  3668. }, {
  3669. key: "searchFromDirectory",
  3670. value: function searchFromDirectory(dir) {
  3671. var _this2 = this;
  3672. var absoluteDir = path.resolve(process.cwd(), dir);
  3673. var run = function run() {
  3674. return _this2.searchDirectory(absoluteDir).then(function (result) {
  3675. var nextDir = _this2.nextDirectoryToSearch(absoluteDir, result);
  3676. if (nextDir) {
  3677. return _this2.searchFromDirectory(nextDir);
  3678. }
  3679. return _this2.config.transform(result);
  3680. });
  3681. };
  3682. if (this.searchCache) {
  3683. return cacheWrapper_1(this.searchCache, absoluteDir, run);
  3684. }
  3685. return run();
  3686. }
  3687. }, {
  3688. key: "searchSync",
  3689. value: function searchSync(searchFrom) {
  3690. searchFrom = searchFrom || process.cwd();
  3691. var dir = getDirectory_1.sync(searchFrom);
  3692. return this.searchFromDirectorySync(dir);
  3693. }
  3694. }, {
  3695. key: "searchFromDirectorySync",
  3696. value: function searchFromDirectorySync(dir) {
  3697. var _this3 = this;
  3698. var absoluteDir = path.resolve(process.cwd(), dir);
  3699. var run = function run() {
  3700. var result = _this3.searchDirectorySync(absoluteDir);
  3701. var nextDir = _this3.nextDirectoryToSearch(absoluteDir, result);
  3702. if (nextDir) {
  3703. return _this3.searchFromDirectorySync(nextDir);
  3704. }
  3705. return _this3.config.transform(result);
  3706. };
  3707. if (this.searchSyncCache) {
  3708. return cacheWrapper_1(this.searchSyncCache, absoluteDir, run);
  3709. }
  3710. return run();
  3711. }
  3712. }, {
  3713. key: "searchDirectory",
  3714. value: function searchDirectory(dir) {
  3715. var _this4 = this;
  3716. return this.config.searchPlaces.reduce(function (prevResultPromise, place) {
  3717. return prevResultPromise.then(function (prevResult) {
  3718. if (_this4.shouldSearchStopWithResult(prevResult)) {
  3719. return prevResult;
  3720. }
  3721. return _this4.loadSearchPlace(dir, place);
  3722. });
  3723. }, Promise.resolve(null));
  3724. }
  3725. }, {
  3726. key: "searchDirectorySync",
  3727. value: function searchDirectorySync(dir) {
  3728. var result = null;
  3729. var _iteratorNormalCompletion = true;
  3730. var _didIteratorError = false;
  3731. var _iteratorError = undefined;
  3732. try {
  3733. for (var _iterator = this.config.searchPlaces[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  3734. var place = _step.value;
  3735. result = this.loadSearchPlaceSync(dir, place);
  3736. if (this.shouldSearchStopWithResult(result)) break;
  3737. }
  3738. } catch (err) {
  3739. _didIteratorError = true;
  3740. _iteratorError = err;
  3741. } finally {
  3742. try {
  3743. if (!_iteratorNormalCompletion && _iterator.return != null) {
  3744. _iterator.return();
  3745. }
  3746. } finally {
  3747. if (_didIteratorError) {
  3748. throw _iteratorError;
  3749. }
  3750. }
  3751. }
  3752. return result;
  3753. }
  3754. }, {
  3755. key: "shouldSearchStopWithResult",
  3756. value: function shouldSearchStopWithResult(result) {
  3757. if (result === null) return false;
  3758. if (result.isEmpty && this.config.ignoreEmptySearchPlaces) return false;
  3759. return true;
  3760. }
  3761. }, {
  3762. key: "loadSearchPlace",
  3763. value: function loadSearchPlace(dir, place) {
  3764. var _this5 = this;
  3765. var filepath = path.join(dir, place);
  3766. return readFile_1(filepath).then(function (content) {
  3767. return _this5.createCosmiconfigResult(filepath, content);
  3768. });
  3769. }
  3770. }, {
  3771. key: "loadSearchPlaceSync",
  3772. value: function loadSearchPlaceSync(dir, place) {
  3773. var filepath = path.join(dir, place);
  3774. var content = readFile_1.sync(filepath);
  3775. return this.createCosmiconfigResultSync(filepath, content);
  3776. }
  3777. }, {
  3778. key: "nextDirectoryToSearch",
  3779. value: function nextDirectoryToSearch(currentDir, currentResult) {
  3780. if (this.shouldSearchStopWithResult(currentResult)) {
  3781. return null;
  3782. }
  3783. var nextDir = nextDirUp(currentDir);
  3784. if (nextDir === currentDir || currentDir === this.config.stopDir) {
  3785. return null;
  3786. }
  3787. return nextDir;
  3788. }
  3789. }, {
  3790. key: "loadPackageProp",
  3791. value: function loadPackageProp(filepath, content) {
  3792. var parsedContent = loaders.loadJson(filepath, content);
  3793. var packagePropValue = getPropertyByPath_1(parsedContent, this.config.packageProp);
  3794. return packagePropValue || null;
  3795. }
  3796. }, {
  3797. key: "getLoaderEntryForFile",
  3798. value: function getLoaderEntryForFile(filepath) {
  3799. if (path.basename(filepath) === 'package.json') {
  3800. var loader = this.loadPackageProp.bind(this);
  3801. return {
  3802. sync: loader,
  3803. async: loader
  3804. };
  3805. }
  3806. var loaderKey = path.extname(filepath) || 'noExt';
  3807. return this.config.loaders[loaderKey] || {};
  3808. }
  3809. }, {
  3810. key: "getSyncLoaderForFile",
  3811. value: function getSyncLoaderForFile(filepath) {
  3812. var entry = this.getLoaderEntryForFile(filepath);
  3813. if (!entry.sync) {
  3814. throw new Error(`No sync loader specified for ${getExtensionDescription(filepath)}`);
  3815. }
  3816. return entry.sync;
  3817. }
  3818. }, {
  3819. key: "getAsyncLoaderForFile",
  3820. value: function getAsyncLoaderForFile(filepath) {
  3821. var entry = this.getLoaderEntryForFile(filepath);
  3822. var loader = entry.async || entry.sync;
  3823. if (!loader) {
  3824. throw new Error(`No async loader specified for ${getExtensionDescription(filepath)}`);
  3825. }
  3826. return loader;
  3827. }
  3828. }, {
  3829. key: "loadFileContent",
  3830. value: function loadFileContent(mode, filepath, content) {
  3831. if (content === null) {
  3832. return null;
  3833. }
  3834. if (content.trim() === '') {
  3835. return undefined;
  3836. }
  3837. var loader = mode === MODE_SYNC ? this.getSyncLoaderForFile(filepath) : this.getAsyncLoaderForFile(filepath);
  3838. return loader(filepath, content);
  3839. }
  3840. }, {
  3841. key: "loadedContentToCosmiconfigResult",
  3842. value: function loadedContentToCosmiconfigResult(filepath, loadedContent) {
  3843. if (loadedContent === null) {
  3844. return null;
  3845. }
  3846. if (loadedContent === undefined) {
  3847. return {
  3848. filepath,
  3849. config: undefined,
  3850. isEmpty: true
  3851. };
  3852. }
  3853. return {
  3854. config: loadedContent,
  3855. filepath
  3856. };
  3857. }
  3858. }, {
  3859. key: "createCosmiconfigResult",
  3860. value: function createCosmiconfigResult(filepath, content) {
  3861. var _this6 = this;
  3862. return Promise.resolve().then(function () {
  3863. return _this6.loadFileContent('async', filepath, content);
  3864. }).then(function (loaderResult) {
  3865. return _this6.loadedContentToCosmiconfigResult(filepath, loaderResult);
  3866. });
  3867. }
  3868. }, {
  3869. key: "createCosmiconfigResultSync",
  3870. value: function createCosmiconfigResultSync(filepath, content) {
  3871. var loaderResult = this.loadFileContent('sync', filepath, content);
  3872. return this.loadedContentToCosmiconfigResult(filepath, loaderResult);
  3873. }
  3874. }, {
  3875. key: "validateFilePath",
  3876. value: function validateFilePath(filepath) {
  3877. if (!filepath) {
  3878. throw new Error('load and loadSync must pass a non-empty string');
  3879. }
  3880. }
  3881. }, {
  3882. key: "load",
  3883. value: function load(filepath) {
  3884. var _this7 = this;
  3885. return Promise.resolve().then(function () {
  3886. _this7.validateFilePath(filepath);
  3887. var absoluteFilePath = path.resolve(process.cwd(), filepath);
  3888. return cacheWrapper_1(_this7.loadCache, absoluteFilePath, function () {
  3889. return readFile_1(absoluteFilePath, {
  3890. throwNotFound: true
  3891. }).then(function (content) {
  3892. return _this7.createCosmiconfigResult(absoluteFilePath, content);
  3893. }).then(_this7.config.transform);
  3894. });
  3895. });
  3896. }
  3897. }, {
  3898. key: "loadSync",
  3899. value: function loadSync(filepath) {
  3900. var _this8 = this;
  3901. this.validateFilePath(filepath);
  3902. var absoluteFilePath = path.resolve(process.cwd(), filepath);
  3903. return cacheWrapper_1(this.loadSyncCache, absoluteFilePath, function () {
  3904. var content = readFile_1.sync(absoluteFilePath, {
  3905. throwNotFound: true
  3906. });
  3907. var result = _this8.createCosmiconfigResultSync(absoluteFilePath, content);
  3908. return _this8.config.transform(result);
  3909. });
  3910. }
  3911. }]);
  3912. return Explorer;
  3913. }();
  3914. var createExplorer = function createExplorer(options) {
  3915. var explorer = new Explorer(options);
  3916. return {
  3917. search: explorer.search.bind(explorer),
  3918. searchSync: explorer.searchSync.bind(explorer),
  3919. load: explorer.load.bind(explorer),
  3920. loadSync: explorer.loadSync.bind(explorer),
  3921. clearLoadCache: explorer.clearLoadCache.bind(explorer),
  3922. clearSearchCache: explorer.clearSearchCache.bind(explorer),
  3923. clearCaches: explorer.clearCaches.bind(explorer)
  3924. };
  3925. };
  3926. function nextDirUp(dir) {
  3927. return path.dirname(dir);
  3928. }
  3929. function getExtensionDescription(filepath) {
  3930. var ext = path.extname(filepath);
  3931. return ext ? `extension "${ext}"` : 'files without extensions';
  3932. }
  3933. var dist = cosmiconfig;
  3934. function cosmiconfig(moduleName, options) {
  3935. options = options || {};
  3936. var defaults = {
  3937. packageProp: moduleName,
  3938. searchPlaces: ['package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.js`, `${moduleName}.config.js`],
  3939. ignoreEmptySearchPlaces: true,
  3940. stopDir: os.homedir(),
  3941. cache: true,
  3942. transform: identity
  3943. };
  3944. var normalizedOptions = Object.assign({}, defaults, options, {
  3945. loaders: normalizeLoaders(options.loaders)
  3946. });
  3947. return createExplorer(normalizedOptions);
  3948. }
  3949. cosmiconfig.loadJs = loaders.loadJs;
  3950. cosmiconfig.loadJson = loaders.loadJson;
  3951. cosmiconfig.loadYaml = loaders.loadYaml;
  3952. function normalizeLoaders(rawLoaders) {
  3953. var defaults = {
  3954. '.js': {
  3955. sync: loaders.loadJs,
  3956. async: loaders.loadJs
  3957. },
  3958. '.json': {
  3959. sync: loaders.loadJson,
  3960. async: loaders.loadJson
  3961. },
  3962. '.yaml': {
  3963. sync: loaders.loadYaml,
  3964. async: loaders.loadYaml
  3965. },
  3966. '.yml': {
  3967. sync: loaders.loadYaml,
  3968. async: loaders.loadYaml
  3969. },
  3970. noExt: {
  3971. sync: loaders.loadYaml,
  3972. async: loaders.loadYaml
  3973. }
  3974. };
  3975. if (!rawLoaders) {
  3976. return defaults;
  3977. }
  3978. return Object.keys(rawLoaders).reduce(function (result, ext) {
  3979. var entry = rawLoaders && rawLoaders[ext];
  3980. if (typeof entry === 'function') {
  3981. result[ext] = {
  3982. sync: entry,
  3983. async: entry
  3984. };
  3985. } else {
  3986. result[ext] = entry;
  3987. }
  3988. return result;
  3989. }, defaults);
  3990. }
  3991. function identity(x) {
  3992. return x;
  3993. }
  3994. var findParentDir = createCommonjsModule(function (module, exports) {
  3995. var exists = fs.exists || path.exists,
  3996. existsSync = fs.existsSync || path.existsSync;
  3997. function splitPath(path) {
  3998. var parts = path.split(/(\/|\\)/);
  3999. if (!parts.length) return parts; // when path starts with a slash, the first part is empty string
  4000. return !parts[0].length ? parts.slice(1) : parts;
  4001. }
  4002. exports = module.exports = function (currentFullPath, clue, cb) {
  4003. function testDir(parts) {
  4004. if (parts.length === 0) return cb(null, null);
  4005. var p = parts.join('');
  4006. exists(path.join(p, clue), function (itdoes) {
  4007. if (itdoes) return cb(null, p);
  4008. testDir(parts.slice(0, -1));
  4009. });
  4010. }
  4011. testDir(splitPath(currentFullPath));
  4012. };
  4013. exports.sync = function (currentFullPath, clue) {
  4014. function testDir(parts) {
  4015. if (parts.length === 0) return null;
  4016. var p = parts.join('');
  4017. var itdoes = existsSync(path.join(p, clue));
  4018. return itdoes ? p : testDir(parts.slice(0, -1));
  4019. }
  4020. return testDir(splitPath(currentFullPath));
  4021. };
  4022. });
  4023. var findParentDir_1 = findParentDir.sync;
  4024. // Returns a wrapper function that returns a wrapped callback
  4025. // The wrapper function should do some stuff, and return a
  4026. // presumably different callback function.
  4027. // This makes sure that own properties are retained, so that
  4028. // decorations and such are not lost along the way.
  4029. var wrappy_1 = wrappy;
  4030. function wrappy(fn, cb) {
  4031. if (fn && cb) return wrappy(fn)(cb);
  4032. if (typeof fn !== 'function') throw new TypeError('need wrapper function');
  4033. Object.keys(fn).forEach(function (k) {
  4034. wrapper[k] = fn[k];
  4035. });
  4036. return wrapper;
  4037. function wrapper() {
  4038. var args = new Array(arguments.length);
  4039. for (var i = 0; i < args.length; i++) {
  4040. args[i] = arguments[i];
  4041. }
  4042. var ret = fn.apply(this, args);
  4043. var cb = args[args.length - 1];
  4044. if (typeof ret === 'function' && ret !== cb) {
  4045. Object.keys(cb).forEach(function (k) {
  4046. ret[k] = cb[k];
  4047. });
  4048. }
  4049. return ret;
  4050. }
  4051. }
  4052. var once_1 = wrappy_1(once);
  4053. var strict = wrappy_1(onceStrict);
  4054. once.proto = once(function () {
  4055. Object.defineProperty(Function.prototype, 'once', {
  4056. value: function value() {
  4057. return once(this);
  4058. },
  4059. configurable: true
  4060. });
  4061. Object.defineProperty(Function.prototype, 'onceStrict', {
  4062. value: function value() {
  4063. return onceStrict(this);
  4064. },
  4065. configurable: true
  4066. });
  4067. });
  4068. function once(fn) {
  4069. var f = function f() {
  4070. if (f.called) return f.value;
  4071. f.called = true;
  4072. return f.value = fn.apply(this, arguments);
  4073. };
  4074. f.called = false;
  4075. return f;
  4076. }
  4077. function onceStrict(fn) {
  4078. var f = function f() {
  4079. if (f.called) throw new Error(f.onceError);
  4080. f.called = true;
  4081. return f.value = fn.apply(this, arguments);
  4082. };
  4083. var name = fn.name || 'Function wrapped with `once`';
  4084. f.onceError = name + " shouldn't be called more than once";
  4085. f.called = false;
  4086. return f;
  4087. }
  4088. once_1.strict = strict;
  4089. var noop = function noop() {};
  4090. var isRequest = function isRequest(stream) {
  4091. return stream.setHeader && typeof stream.abort === 'function';
  4092. };
  4093. var isChildProcess = function isChildProcess(stream) {
  4094. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3;
  4095. };
  4096. var eos = function eos(stream, opts, callback) {
  4097. if (typeof opts === 'function') return eos(stream, null, opts);
  4098. if (!opts) opts = {};
  4099. callback = once_1(callback || noop);
  4100. var ws = stream._writableState;
  4101. var rs = stream._readableState;
  4102. var readable = opts.readable || opts.readable !== false && stream.readable;
  4103. var writable = opts.writable || opts.writable !== false && stream.writable;
  4104. var onlegacyfinish = function onlegacyfinish() {
  4105. if (!stream.writable) onfinish();
  4106. };
  4107. var onfinish = function onfinish() {
  4108. writable = false;
  4109. if (!readable) callback.call(stream);
  4110. };
  4111. var onend = function onend() {
  4112. readable = false;
  4113. if (!writable) callback.call(stream);
  4114. };
  4115. var onexit = function onexit(exitCode) {
  4116. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  4117. };
  4118. var onerror = function onerror(err) {
  4119. callback.call(stream, err);
  4120. };
  4121. var onclose = function onclose() {
  4122. if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
  4123. if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
  4124. };
  4125. var onrequest = function onrequest() {
  4126. stream.req.on('finish', onfinish);
  4127. };
  4128. if (isRequest(stream)) {
  4129. stream.on('complete', onfinish);
  4130. stream.on('abort', onclose);
  4131. if (stream.req) onrequest();else stream.on('request', onrequest);
  4132. } else if (writable && !ws) {
  4133. // legacy streams
  4134. stream.on('end', onlegacyfinish);
  4135. stream.on('close', onlegacyfinish);
  4136. }
  4137. if (isChildProcess(stream)) stream.on('exit', onexit);
  4138. stream.on('end', onend);
  4139. stream.on('finish', onfinish);
  4140. if (opts.error !== false) stream.on('error', onerror);
  4141. stream.on('close', onclose);
  4142. return function () {
  4143. stream.removeListener('complete', onfinish);
  4144. stream.removeListener('abort', onclose);
  4145. stream.removeListener('request', onrequest);
  4146. if (stream.req) stream.req.removeListener('finish', onfinish);
  4147. stream.removeListener('end', onlegacyfinish);
  4148. stream.removeListener('close', onlegacyfinish);
  4149. stream.removeListener('finish', onfinish);
  4150. stream.removeListener('exit', onexit);
  4151. stream.removeListener('end', onend);
  4152. stream.removeListener('error', onerror);
  4153. stream.removeListener('close', onclose);
  4154. };
  4155. };
  4156. var endOfStream = eos;
  4157. var noop$1 = function noop() {};
  4158. var ancient = /^v?\.0/.test(process.version);
  4159. var isFn = function isFn(fn) {
  4160. return typeof fn === 'function';
  4161. };
  4162. var isFS = function isFS(stream) {
  4163. if (!ancient) return false; // newer node version do not need to care about fs is a special way
  4164. if (!fs) return false; // browser
  4165. return (stream instanceof (fs.ReadStream || noop$1) || stream instanceof (fs.WriteStream || noop$1)) && isFn(stream.close);
  4166. };
  4167. var isRequest$1 = function isRequest(stream) {
  4168. return stream.setHeader && isFn(stream.abort);
  4169. };
  4170. var destroyer = function destroyer(stream, reading, writing, callback) {
  4171. callback = once_1(callback);
  4172. var closed = false;
  4173. stream.on('close', function () {
  4174. closed = true;
  4175. });
  4176. endOfStream(stream, {
  4177. readable: reading,
  4178. writable: writing
  4179. }, function (err) {
  4180. if (err) return callback(err);
  4181. closed = true;
  4182. callback();
  4183. });
  4184. var destroyed = false;
  4185. return function (err) {
  4186. if (closed) return;
  4187. if (destroyed) return;
  4188. destroyed = true;
  4189. if (isFS(stream)) return stream.close(noop$1); // use close for fs streams to avoid fd leaks
  4190. if (isRequest$1(stream)) return stream.abort(); // request.destroy just do .end - .abort is what we want
  4191. if (isFn(stream.destroy)) return stream.destroy();
  4192. callback(err || new Error('stream was destroyed'));
  4193. };
  4194. };
  4195. var call = function call(fn) {
  4196. fn();
  4197. };
  4198. var pipe = function pipe(from, to) {
  4199. return from.pipe(to);
  4200. };
  4201. var pump = function pump() {
  4202. var streams = Array.prototype.slice.call(arguments);
  4203. var callback = isFn(streams[streams.length - 1] || noop$1) && streams.pop() || noop$1;
  4204. if (Array.isArray(streams[0])) streams = streams[0];
  4205. if (streams.length < 2) throw new Error('pump requires two streams per minimum');
  4206. var error;
  4207. var destroys = streams.map(function (stream, i) {
  4208. var reading = i < streams.length - 1;
  4209. var writing = i > 0;
  4210. return destroyer(stream, reading, writing, function (err) {
  4211. if (!error) error = err;
  4212. if (err) destroys.forEach(call);
  4213. if (reading) return;
  4214. destroys.forEach(call);
  4215. callback(error);
  4216. });
  4217. });
  4218. return streams.reduce(pipe);
  4219. };
  4220. var pump_1 = pump;
  4221. var PassThrough = stream.PassThrough;
  4222. var bufferStream = function bufferStream(options) {
  4223. options = Object.assign({}, options);
  4224. var _options = options,
  4225. array = _options.array;
  4226. var _options2 = options,
  4227. encoding = _options2.encoding;
  4228. var buffer = encoding === 'buffer';
  4229. var objectMode = false;
  4230. if (array) {
  4231. objectMode = !(encoding || buffer);
  4232. } else {
  4233. encoding = encoding || 'utf8';
  4234. }
  4235. if (buffer) {
  4236. encoding = null;
  4237. }
  4238. var len = 0;
  4239. var ret = [];
  4240. var stream = new PassThrough({
  4241. objectMode
  4242. });
  4243. if (encoding) {
  4244. stream.setEncoding(encoding);
  4245. }
  4246. stream.on('data', function (chunk) {
  4247. ret.push(chunk);
  4248. if (objectMode) {
  4249. len = ret.length;
  4250. } else {
  4251. len += chunk.length;
  4252. }
  4253. });
  4254. stream.getBufferedValue = function () {
  4255. if (array) {
  4256. return ret;
  4257. }
  4258. return buffer ? Buffer.concat(ret, len) : ret.join('');
  4259. };
  4260. stream.getBufferedLength = function () {
  4261. return len;
  4262. };
  4263. return stream;
  4264. };
  4265. var MaxBufferError =
  4266. /*#__PURE__*/
  4267. function (_Error) {
  4268. _inherits(MaxBufferError, _Error);
  4269. function MaxBufferError() {
  4270. var _this;
  4271. _classCallCheck(this, MaxBufferError);
  4272. _this = _possibleConstructorReturn(this, _getPrototypeOf(MaxBufferError).call(this, 'maxBuffer exceeded'));
  4273. _this.name = 'MaxBufferError';
  4274. return _this;
  4275. }
  4276. return MaxBufferError;
  4277. }(_wrapNativeSuper(Error));
  4278. function getStream(inputStream, options) {
  4279. if (!inputStream) {
  4280. return Promise.reject(new Error('Expected a stream'));
  4281. }
  4282. options = Object.assign({
  4283. maxBuffer: Infinity
  4284. }, options);
  4285. var _options = options,
  4286. maxBuffer = _options.maxBuffer;
  4287. var stream;
  4288. return new Promise(function (resolve, reject) {
  4289. var rejectPromise = function rejectPromise(error) {
  4290. if (error) {
  4291. // A null check
  4292. error.bufferedData = stream.getBufferedValue();
  4293. }
  4294. reject(error);
  4295. };
  4296. stream = pump_1(inputStream, bufferStream(options), function (error) {
  4297. if (error) {
  4298. rejectPromise(error);
  4299. return;
  4300. }
  4301. resolve();
  4302. });
  4303. stream.on('data', function () {
  4304. if (stream.getBufferedLength() > maxBuffer) {
  4305. rejectPromise(new MaxBufferError());
  4306. }
  4307. });
  4308. }).then(function () {
  4309. return stream.getBufferedValue();
  4310. });
  4311. }
  4312. var getStream_1 = getStream;
  4313. var buffer = function buffer(stream, options) {
  4314. return getStream(stream, Object.assign({}, options, {
  4315. encoding: 'buffer'
  4316. }));
  4317. };
  4318. var array = function array(stream, options) {
  4319. return getStream(stream, Object.assign({}, options, {
  4320. array: true
  4321. }));
  4322. };
  4323. var MaxBufferError_1 = MaxBufferError;
  4324. getStream_1.buffer = buffer;
  4325. getStream_1.array = array;
  4326. getStream_1.MaxBufferError = MaxBufferError_1;
  4327. var vendors = [
  4328. {
  4329. name: "AppVeyor",
  4330. constant: "APPVEYOR",
  4331. env: "APPVEYOR",
  4332. pr: "APPVEYOR_PULL_REQUEST_NUMBER"
  4333. },
  4334. {
  4335. name: "Azure Pipelines",
  4336. constant: "AZURE_PIPELINES",
  4337. env: "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI",
  4338. pr: "SYSTEM_PULLREQUEST_PULLREQUESTID"
  4339. },
  4340. {
  4341. name: "Bamboo",
  4342. constant: "BAMBOO",
  4343. env: "bamboo_planKey"
  4344. },
  4345. {
  4346. name: "Bitbucket Pipelines",
  4347. constant: "BITBUCKET",
  4348. env: "BITBUCKET_COMMIT",
  4349. pr: "BITBUCKET_PR_ID"
  4350. },
  4351. {
  4352. name: "Bitrise",
  4353. constant: "BITRISE",
  4354. env: "BITRISE_IO",
  4355. pr: "BITRISE_PULL_REQUEST"
  4356. },
  4357. {
  4358. name: "Buddy",
  4359. constant: "BUDDY",
  4360. env: "BUDDY_WORKSPACE_ID",
  4361. pr: "BUDDY_EXECUTION_PULL_REQUEST_ID"
  4362. },
  4363. {
  4364. name: "Buildkite",
  4365. constant: "BUILDKITE",
  4366. env: "BUILDKITE",
  4367. pr: {
  4368. env: "BUILDKITE_PULL_REQUEST",
  4369. ne: "false"
  4370. }
  4371. },
  4372. {
  4373. name: "CircleCI",
  4374. constant: "CIRCLE",
  4375. env: "CIRCLECI",
  4376. pr: "CIRCLE_PULL_REQUEST"
  4377. },
  4378. {
  4379. name: "Cirrus CI",
  4380. constant: "CIRRUS",
  4381. env: "CIRRUS_CI",
  4382. pr: "CIRRUS_PR"
  4383. },
  4384. {
  4385. name: "AWS CodeBuild",
  4386. constant: "CODEBUILD",
  4387. env: "CODEBUILD_BUILD_ARN"
  4388. },
  4389. {
  4390. name: "Codeship",
  4391. constant: "CODESHIP",
  4392. env: {
  4393. CI_NAME: "codeship"
  4394. }
  4395. },
  4396. {
  4397. name: "Drone",
  4398. constant: "DRONE",
  4399. env: "DRONE",
  4400. pr: {
  4401. DRONE_BUILD_EVENT: "pull_request"
  4402. }
  4403. },
  4404. {
  4405. name: "dsari",
  4406. constant: "DSARI",
  4407. env: "DSARI"
  4408. },
  4409. {
  4410. name: "GitLab CI",
  4411. constant: "GITLAB",
  4412. env: "GITLAB_CI"
  4413. },
  4414. {
  4415. name: "GoCD",
  4416. constant: "GOCD",
  4417. env: "GO_PIPELINE_LABEL"
  4418. },
  4419. {
  4420. name: "Hudson",
  4421. constant: "HUDSON",
  4422. env: "HUDSON_URL"
  4423. },
  4424. {
  4425. name: "Jenkins",
  4426. constant: "JENKINS",
  4427. env: [
  4428. "JENKINS_URL",
  4429. "BUILD_ID"
  4430. ],
  4431. pr: {
  4432. any: [
  4433. "ghprbPullId",
  4434. "CHANGE_ID"
  4435. ]
  4436. }
  4437. },
  4438. {
  4439. name: "Magnum CI",
  4440. constant: "MAGNUM",
  4441. env: "MAGNUM"
  4442. },
  4443. {
  4444. name: "Netlify CI",
  4445. constant: "NETLIFY",
  4446. env: "NETLIFY_BUILD_BASE",
  4447. pr: {
  4448. env: "PULL_REQUEST",
  4449. ne: "false"
  4450. }
  4451. },
  4452. {
  4453. name: "Sail CI",
  4454. constant: "SAIL",
  4455. env: "SAILCI",
  4456. pr: "SAIL_PULL_REQUEST_NUMBER"
  4457. },
  4458. {
  4459. name: "Semaphore",
  4460. constant: "SEMAPHORE",
  4461. env: "SEMAPHORE",
  4462. pr: "PULL_REQUEST_NUMBER"
  4463. },
  4464. {
  4465. name: "Shippable",
  4466. constant: "SHIPPABLE",
  4467. env: "SHIPPABLE",
  4468. pr: {
  4469. IS_PULL_REQUEST: "true"
  4470. }
  4471. },
  4472. {
  4473. name: "Solano CI",
  4474. constant: "SOLANO",
  4475. env: "TDDIUM",
  4476. pr: "TDDIUM_PR_ID"
  4477. },
  4478. {
  4479. name: "Strider CD",
  4480. constant: "STRIDER",
  4481. env: "STRIDER"
  4482. },
  4483. {
  4484. name: "TaskCluster",
  4485. constant: "TASKCLUSTER",
  4486. env: [
  4487. "TASK_ID",
  4488. "RUN_ID"
  4489. ]
  4490. },
  4491. {
  4492. name: "TeamCity",
  4493. constant: "TEAMCITY",
  4494. env: "TEAMCITY_VERSION"
  4495. },
  4496. {
  4497. name: "Travis CI",
  4498. constant: "TRAVIS",
  4499. env: "TRAVIS",
  4500. pr: {
  4501. env: "TRAVIS_PULL_REQUEST",
  4502. ne: "false"
  4503. }
  4504. }
  4505. ];
  4506. var vendors$1 = /*#__PURE__*/Object.freeze({
  4507. __proto__: null,
  4508. 'default': vendors
  4509. });
  4510. var vendors$2 = getCjsExportFromNamespace(vendors$1);
  4511. var ciInfo = createCommonjsModule(function (module, exports) {
  4512. var env = process.env; // Used for testing only
  4513. Object.defineProperty(exports, '_vendors', {
  4514. value: vendors$2.map(function (v) {
  4515. return v.constant;
  4516. })
  4517. });
  4518. exports.name = null;
  4519. exports.isPR = null;
  4520. vendors$2.forEach(function (vendor) {
  4521. var envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
  4522. var isCI = envs.every(function (obj) {
  4523. return checkEnv(obj);
  4524. });
  4525. exports[vendor.constant] = isCI;
  4526. if (isCI) {
  4527. exports.name = vendor.name;
  4528. switch (typeof vendor.pr) {
  4529. case 'string':
  4530. // "pr": "CIRRUS_PR"
  4531. exports.isPR = !!env[vendor.pr];
  4532. break;
  4533. case 'object':
  4534. if ('env' in vendor.pr) {
  4535. // "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" }
  4536. exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne;
  4537. } else if ('any' in vendor.pr) {
  4538. // "pr": { "any": ["ghprbPullId", "CHANGE_ID"] }
  4539. exports.isPR = vendor.pr.any.some(function (key) {
  4540. return !!env[key];
  4541. });
  4542. } else {
  4543. // "pr": { "DRONE_BUILD_EVENT": "pull_request" }
  4544. exports.isPR = checkEnv(vendor.pr);
  4545. }
  4546. break;
  4547. default:
  4548. // PR detection not supported for this vendor
  4549. exports.isPR = null;
  4550. }
  4551. }
  4552. });
  4553. exports.isCI = !!(env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari
  4554. env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
  4555. env.BUILD_NUMBER || // Jenkins, TeamCity
  4556. env.RUN_ID || // TaskCluster, dsari
  4557. exports.name || false);
  4558. function checkEnv(obj) {
  4559. if (typeof obj === 'string') return !!env[obj];
  4560. return Object.keys(obj).every(function (k) {
  4561. return env[k] === obj[k];
  4562. });
  4563. }
  4564. });
  4565. var ciInfo_1 = ciInfo.name;
  4566. var ciInfo_2 = ciInfo.isPR;
  4567. var ciInfo_3 = ciInfo.isCI;
  4568. var isCi = ciInfo.isCI;
  4569. var thirdParty = {
  4570. cosmiconfig: dist,
  4571. findParentDir: findParentDir.sync,
  4572. getStream: getStream_1,
  4573. isCI: function isCI() {
  4574. return isCi;
  4575. }
  4576. };
  4577. var thirdParty_1 = thirdParty.cosmiconfig;
  4578. var thirdParty_2 = thirdParty.findParentDir;
  4579. var thirdParty_3 = thirdParty.getStream;
  4580. var thirdParty_4 = thirdParty.isCI;
  4581. exports.cosmiconfig = thirdParty_1;
  4582. exports.default = thirdParty;
  4583. exports.findParentDir = thirdParty_2;
  4584. exports.getStream = thirdParty_3;
  4585. exports.isCI = thirdParty_4;