3 var os = require('os');
4 var path = require('path');
5 var Module = require('module');
6 var fs = require('fs');
7 var util = require('util');
9 function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
11 var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
12 var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
13 var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module);
14 var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
15 var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
17 function createCommonjsModule(fn, basedir, module) {
21 require: function (path, base) {
22 return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
24 }, fn(module, module.exports), module.exports;
27 function commonjsRequire () {
28 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
31 const resolveFrom = (fromDir, moduleId, silent) => {
32 if (typeof fromDir !== 'string') {
33 throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDir}\``);
36 if (typeof moduleId !== 'string') {
37 throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
41 fromDir = fs__default['default'].realpathSync(fromDir);
43 if (err.code === 'ENOENT') {
44 fromDir = path__default['default'].resolve(fromDir);
52 const fromFile = path__default['default'].join(fromDir, 'noop.js');
54 const resolveFileName = () => Module__default['default']._resolveFilename(moduleId, {
57 paths: Module__default['default']._nodeModulePaths(fromDir)
62 return resolveFileName();
68 return resolveFileName();
71 var resolveFrom_1 = (fromDir, moduleId) => resolveFrom(fromDir, moduleId);
73 var silent = (fromDir, moduleId) => resolveFrom(fromDir, moduleId, true);
74 resolveFrom_1.silent = silent;
76 var importFresh = moduleId => {
77 if (typeof moduleId !== 'string') {
78 throw new TypeError('Expected a string');
81 const parentPath = __filename;
82 const filePath = resolveFrom_1(path__default['default'].dirname(parentPath), moduleId);
83 const oldModule = eval('require').cache[filePath]; // Delete itself from module parent
85 if (oldModule && oldModule.parent) {
86 let i = oldModule.parent.children.length;
89 if (oldModule.parent.children[i].id === filePath) {
90 oldModule.parent.children.splice(i, 1);
95 delete eval('require').cache[filePath]; // Delete module from cache
97 const parent = eval('require').cache[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step
99 return parent === undefined ? eval('require')(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require
102 var isArrayish = function isArrayish(obj) {
107 return obj instanceof Array || Array.isArray(obj) || obj.length >= 0 && obj.splice instanceof Function;
110 var errorEx = function errorEx(name, properties) {
111 if (!name || name.constructor !== String) {
112 properties = name || {};
116 var errorExError = function ErrorEXError(message) {
118 return new ErrorEXError(message);
121 message = message instanceof Error ? message.message : message || this.message;
122 Error.call(this, message);
123 Error.captureStackTrace(this, errorExError);
125 Object.defineProperty(this, 'message', {
129 var newMessage = message.split(/\r?\n/g);
131 for (var key in properties) {
132 if (!properties.hasOwnProperty(key)) {
136 var modifier = properties[key];
138 if ('message' in modifier) {
139 newMessage = modifier.message(this[key], newMessage) || newMessage;
141 if (!isArrayish(newMessage)) {
142 newMessage = [newMessage];
147 return newMessage.join('\n');
153 var overwrittenStack = null;
154 var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
155 var stackGetter = stackDescriptor.get;
156 var stackValue = stackDescriptor.value;
157 delete stackDescriptor.value;
158 delete stackDescriptor.writable;
160 stackDescriptor.set = function (newstack) {
161 overwrittenStack = newstack;
164 stackDescriptor.get = function () {
165 var stack = (overwrittenStack || (stackGetter ? stackGetter.call(this) : stackValue)).split(/\r?\n+/g); // starting in Node 7, the stack builder caches the message.
168 if (!overwrittenStack) {
169 stack[0] = this.name + ': ' + this.message;
174 for (var key in properties) {
175 if (!properties.hasOwnProperty(key)) {
179 var modifier = properties[key];
181 if ('line' in modifier) {
182 var line = modifier.line(this[key]);
185 stack.splice(lineCount++, 0, ' ' + line);
189 if ('stack' in modifier) {
190 modifier.stack(this[key], stack);
194 return stack.join('\n');
197 Object.defineProperty(this, 'stack', stackDescriptor);
200 if (Object.setPrototypeOf) {
201 Object.setPrototypeOf(errorExError.prototype, Error.prototype);
202 Object.setPrototypeOf(errorExError, Error);
204 util__default['default'].inherits(errorExError, Error);
210 errorEx.append = function (str, def) {
212 message: function (v, message) {
216 message[0] += ' ' + str.replace('%s', v.toString());
224 errorEx.line = function (str, def) {
230 return str.replace('%s', v.toString());
238 var errorEx_1 = errorEx;
240 var jsonParseBetterErrors = parseJson;
242 function parseJson(txt, reviver, context) {
243 context = context || 20;
246 return JSON.parse(txt, reviver);
248 if (typeof txt !== 'string') {
249 const isEmptyArray = Array.isArray(txt) && txt.length === 0;
250 const errorMessage = 'Cannot parse ' + (isEmptyArray ? 'an empty array' : String(txt));
251 throw new TypeError(errorMessage);
254 const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i);
255 const errIdx = syntaxErr ? +syntaxErr[1] : e.message.match(/^Unexpected end of JSON.*/i) ? txt.length - 1 : null;
257 if (errIdx != null) {
258 const start = errIdx <= context ? 0 : errIdx - context;
259 const end = errIdx + context >= txt.length ? txt.length : errIdx + context;
260 e.message += ` while parsing near '${start === 0 ? '' : '...'}${txt.slice(start, end)}${end === txt.length ? '' : '...'}'`;
262 e.message += ` while parsing '${txt.slice(0, context * 2)}'`;
269 var dist = createCommonjsModule(function (module, exports) {
274 var LinesAndColumns = function () {
275 function LinesAndColumns(string) {
276 this.string = string;
279 for (var offset = 0; offset < string.length;) {
280 switch (string[offset]) {
283 offsets.push(offset);
289 if (string[offset] === LF) {
293 offsets.push(offset);
302 this.offsets = offsets;
305 LinesAndColumns.prototype.locationForIndex = function (index) {
306 if (index < 0 || index > this.string.length) {
311 var offsets = this.offsets;
313 while (offsets[line + 1] <= index) {
317 var column = index - offsets[line];
324 LinesAndColumns.prototype.indexForLocation = function (location) {
325 var line = location.line,
326 column = location.column;
328 if (line < 0 || line >= this.offsets.length) {
332 if (column < 0 || column > this.lengthOfLine(line)) {
336 return this.offsets[line] + column;
339 LinesAndColumns.prototype.lengthOfLine = function (line) {
340 var offset = this.offsets[line];
341 var nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1];
342 return nextOffset - offset;
345 return LinesAndColumns;
348 exports.__esModule = true;
349 exports["default"] = LinesAndColumns;
352 var jsTokens = createCommonjsModule(function (module, exports) {
353 // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
354 // License: MIT. (See LICENSE.)
355 Object.defineProperty(exports, "__esModule", {
357 }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
358 // (run `npm run build`).
360 exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g;
362 exports.matchToToken = function (match) {
368 if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace";
373 var identifier = createCommonjsModule(function (module, exports) {
375 Object.defineProperty(exports, "__esModule", {
378 exports.isIdentifierStart = isIdentifierStart;
379 exports.isIdentifierChar = isIdentifierChar;
380 exports.isIdentifierName = isIdentifierName;
381 let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
382 let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
383 const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
384 const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
385 nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
386 const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
387 const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
389 function isInAstralSet(code, set) {
392 for (let i = 0, length = set.length; i < length; i += 2) {
394 if (pos > code) return false;
396 if (pos >= code) return true;
402 function isIdentifierStart(code) {
403 if (code < 65) return code === 36;
404 if (code <= 90) return true;
405 if (code < 97) return code === 95;
406 if (code <= 122) return true;
408 if (code <= 0xffff) {
409 return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
412 return isInAstralSet(code, astralIdentifierStartCodes);
415 function isIdentifierChar(code) {
416 if (code < 48) return code === 36;
417 if (code < 58) return true;
418 if (code < 65) return false;
419 if (code <= 90) return true;
420 if (code < 97) return code === 95;
421 if (code <= 122) return true;
423 if (code <= 0xffff) {
424 return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
427 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
430 function isIdentifierName(name) {
433 for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) {
434 const char = _Array$from[_i];
435 const cp = char.codePointAt(0);
438 if (!isIdentifierStart(cp)) {
443 } else if (!isIdentifierChar(cp)) {
452 var keyword = createCommonjsModule(function (module, exports) {
454 Object.defineProperty(exports, "__esModule", {
457 exports.isReservedWord = isReservedWord;
458 exports.isStrictReservedWord = isStrictReservedWord;
459 exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
460 exports.isStrictBindReservedWord = isStrictBindReservedWord;
461 exports.isKeyword = isKeyword;
462 const reservedWords = {
463 keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
464 strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
465 strictBind: ["eval", "arguments"]
467 const keywords = new Set(reservedWords.keyword);
468 const reservedWordsStrictSet = new Set(reservedWords.strict);
469 const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
471 function isReservedWord(word, inModule) {
472 return inModule && word === "await" || word === "enum";
475 function isStrictReservedWord(word, inModule) {
476 return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
479 function isStrictBindOnlyReservedWord(word) {
480 return reservedWordsStrictBindSet.has(word);
483 function isStrictBindReservedWord(word, inModule) {
484 return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
487 function isKeyword(word) {
488 return keywords.has(word);
492 var lib = createCommonjsModule(function (module, exports) {
494 Object.defineProperty(exports, "__esModule", {
497 Object.defineProperty(exports, "isIdentifierName", {
500 return identifier.isIdentifierName;
503 Object.defineProperty(exports, "isIdentifierChar", {
506 return identifier.isIdentifierChar;
509 Object.defineProperty(exports, "isIdentifierStart", {
512 return identifier.isIdentifierStart;
515 Object.defineProperty(exports, "isReservedWord", {
518 return keyword.isReservedWord;
521 Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
524 return keyword.isStrictBindOnlyReservedWord;
527 Object.defineProperty(exports, "isStrictBindReservedWord", {
530 return keyword.isStrictBindReservedWord;
533 Object.defineProperty(exports, "isStrictReservedWord", {
536 return keyword.isStrictReservedWord;
539 Object.defineProperty(exports, "isKeyword", {
542 return keyword.isKeyword;
547 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
549 var escapeStringRegexp = function (str) {
550 if (typeof str !== 'string') {
551 throw new TypeError('Expected a string');
554 return str.replace(matchOperatorsRe, '\\$&');
558 "aliceblue": [240, 248, 255],
559 "antiquewhite": [250, 235, 215],
560 "aqua": [0, 255, 255],
561 "aquamarine": [127, 255, 212],
562 "azure": [240, 255, 255],
563 "beige": [245, 245, 220],
564 "bisque": [255, 228, 196],
566 "blanchedalmond": [255, 235, 205],
568 "blueviolet": [138, 43, 226],
569 "brown": [165, 42, 42],
570 "burlywood": [222, 184, 135],
571 "cadetblue": [95, 158, 160],
572 "chartreuse": [127, 255, 0],
573 "chocolate": [210, 105, 30],
574 "coral": [255, 127, 80],
575 "cornflowerblue": [100, 149, 237],
576 "cornsilk": [255, 248, 220],
577 "crimson": [220, 20, 60],
578 "cyan": [0, 255, 255],
579 "darkblue": [0, 0, 139],
580 "darkcyan": [0, 139, 139],
581 "darkgoldenrod": [184, 134, 11],
582 "darkgray": [169, 169, 169],
583 "darkgreen": [0, 100, 0],
584 "darkgrey": [169, 169, 169],
585 "darkkhaki": [189, 183, 107],
586 "darkmagenta": [139, 0, 139],
587 "darkolivegreen": [85, 107, 47],
588 "darkorange": [255, 140, 0],
589 "darkorchid": [153, 50, 204],
590 "darkred": [139, 0, 0],
591 "darksalmon": [233, 150, 122],
592 "darkseagreen": [143, 188, 143],
593 "darkslateblue": [72, 61, 139],
594 "darkslategray": [47, 79, 79],
595 "darkslategrey": [47, 79, 79],
596 "darkturquoise": [0, 206, 209],
597 "darkviolet": [148, 0, 211],
598 "deeppink": [255, 20, 147],
599 "deepskyblue": [0, 191, 255],
600 "dimgray": [105, 105, 105],
601 "dimgrey": [105, 105, 105],
602 "dodgerblue": [30, 144, 255],
603 "firebrick": [178, 34, 34],
604 "floralwhite": [255, 250, 240],
605 "forestgreen": [34, 139, 34],
606 "fuchsia": [255, 0, 255],
607 "gainsboro": [220, 220, 220],
608 "ghostwhite": [248, 248, 255],
609 "gold": [255, 215, 0],
610 "goldenrod": [218, 165, 32],
611 "gray": [128, 128, 128],
612 "green": [0, 128, 0],
613 "greenyellow": [173, 255, 47],
614 "grey": [128, 128, 128],
615 "honeydew": [240, 255, 240],
616 "hotpink": [255, 105, 180],
617 "indianred": [205, 92, 92],
618 "indigo": [75, 0, 130],
619 "ivory": [255, 255, 240],
620 "khaki": [240, 230, 140],
621 "lavender": [230, 230, 250],
622 "lavenderblush": [255, 240, 245],
623 "lawngreen": [124, 252, 0],
624 "lemonchiffon": [255, 250, 205],
625 "lightblue": [173, 216, 230],
626 "lightcoral": [240, 128, 128],
627 "lightcyan": [224, 255, 255],
628 "lightgoldenrodyellow": [250, 250, 210],
629 "lightgray": [211, 211, 211],
630 "lightgreen": [144, 238, 144],
631 "lightgrey": [211, 211, 211],
632 "lightpink": [255, 182, 193],
633 "lightsalmon": [255, 160, 122],
634 "lightseagreen": [32, 178, 170],
635 "lightskyblue": [135, 206, 250],
636 "lightslategray": [119, 136, 153],
637 "lightslategrey": [119, 136, 153],
638 "lightsteelblue": [176, 196, 222],
639 "lightyellow": [255, 255, 224],
641 "limegreen": [50, 205, 50],
642 "linen": [250, 240, 230],
643 "magenta": [255, 0, 255],
644 "maroon": [128, 0, 0],
645 "mediumaquamarine": [102, 205, 170],
646 "mediumblue": [0, 0, 205],
647 "mediumorchid": [186, 85, 211],
648 "mediumpurple": [147, 112, 219],
649 "mediumseagreen": [60, 179, 113],
650 "mediumslateblue": [123, 104, 238],
651 "mediumspringgreen": [0, 250, 154],
652 "mediumturquoise": [72, 209, 204],
653 "mediumvioletred": [199, 21, 133],
654 "midnightblue": [25, 25, 112],
655 "mintcream": [245, 255, 250],
656 "mistyrose": [255, 228, 225],
657 "moccasin": [255, 228, 181],
658 "navajowhite": [255, 222, 173],
660 "oldlace": [253, 245, 230],
661 "olive": [128, 128, 0],
662 "olivedrab": [107, 142, 35],
663 "orange": [255, 165, 0],
664 "orangered": [255, 69, 0],
665 "orchid": [218, 112, 214],
666 "palegoldenrod": [238, 232, 170],
667 "palegreen": [152, 251, 152],
668 "paleturquoise": [175, 238, 238],
669 "palevioletred": [219, 112, 147],
670 "papayawhip": [255, 239, 213],
671 "peachpuff": [255, 218, 185],
672 "peru": [205, 133, 63],
673 "pink": [255, 192, 203],
674 "plum": [221, 160, 221],
675 "powderblue": [176, 224, 230],
676 "purple": [128, 0, 128],
677 "rebeccapurple": [102, 51, 153],
679 "rosybrown": [188, 143, 143],
680 "royalblue": [65, 105, 225],
681 "saddlebrown": [139, 69, 19],
682 "salmon": [250, 128, 114],
683 "sandybrown": [244, 164, 96],
684 "seagreen": [46, 139, 87],
685 "seashell": [255, 245, 238],
686 "sienna": [160, 82, 45],
687 "silver": [192, 192, 192],
688 "skyblue": [135, 206, 235],
689 "slateblue": [106, 90, 205],
690 "slategray": [112, 128, 144],
691 "slategrey": [112, 128, 144],
692 "snow": [255, 250, 250],
693 "springgreen": [0, 255, 127],
694 "steelblue": [70, 130, 180],
695 "tan": [210, 180, 140],
696 "teal": [0, 128, 128],
697 "thistle": [216, 191, 216],
698 "tomato": [255, 99, 71],
699 "turquoise": [64, 224, 208],
700 "violet": [238, 130, 238],
701 "wheat": [245, 222, 179],
702 "white": [255, 255, 255],
703 "whitesmoke": [245, 245, 245],
704 "yellow": [255, 255, 0],
705 "yellowgreen": [154, 205, 50]
708 var conversions = createCommonjsModule(function (module) {
710 // NOTE: conversions should only return primitive values (i.e. arrays, or
711 // values that give correct `typeof` results).
712 // do not use box values types (i.e. Number(), String(), etc.)
713 var reverseKeywords = {};
715 for (var key in colorName) {
716 if (colorName.hasOwnProperty(key)) {
717 reverseKeywords[colorName[key]] = key;
721 var convert = module.exports = {
772 labels: ['h', 'c', 'g']
776 labels: ['r16', 'g16', 'b16']
782 }; // hide .channels and .labels properties
784 for (var model in convert) {
785 if (convert.hasOwnProperty(model)) {
786 if (!('channels' in convert[model])) {
787 throw new Error('missing channels property: ' + model);
790 if (!('labels' in convert[model])) {
791 throw new Error('missing channel labels property: ' + model);
794 if (convert[model].labels.length !== convert[model].channels) {
795 throw new Error('channel and label counts mismatch: ' + model);
798 var channels = convert[model].channels;
799 var labels = convert[model].labels;
800 delete convert[model].channels;
801 delete convert[model].labels;
802 Object.defineProperty(convert[model], 'channels', {
805 Object.defineProperty(convert[model], 'labels', {
811 convert.rgb.hsl = function (rgb) {
812 var r = rgb[0] / 255;
813 var g = rgb[1] / 255;
814 var b = rgb[2] / 255;
815 var min = Math.min(r, g, b);
816 var max = Math.max(r, g, b);
817 var delta = max - min;
824 } else if (r === max) {
826 } else if (g === max) {
827 h = 2 + (b - r) / delta;
828 } else if (b === max) {
829 h = 4 + (r - g) / delta;
832 h = Math.min(h * 60, 360);
842 } else if (l <= 0.5) {
843 s = delta / (max + min);
845 s = delta / (2 - max - min);
848 return [h, s * 100, l * 100];
851 convert.rgb.hsv = function (rgb) {
857 var r = rgb[0] / 255;
858 var g = rgb[1] / 255;
859 var b = rgb[2] / 255;
860 var v = Math.max(r, g, b);
861 var diff = v - Math.min(r, g, b);
863 var diffc = function (c) {
864 return (v - c) / 6 / diff + 1 / 2;
877 } else if (g === v) {
878 h = 1 / 3 + rdif - bdif;
879 } else if (b === v) {
880 h = 2 / 3 + gdif - rdif;
890 return [h * 360, s * 100, v * 100];
893 convert.rgb.hwb = function (rgb) {
897 var h = convert.rgb.hsl(rgb)[0];
898 var w = 1 / 255 * Math.min(r, Math.min(g, b));
899 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
900 return [h, w * 100, b * 100];
903 convert.rgb.cmyk = function (rgb) {
904 var r = rgb[0] / 255;
905 var g = rgb[1] / 255;
906 var b = rgb[2] / 255;
911 k = Math.min(1 - r, 1 - g, 1 - b);
912 c = (1 - r - k) / (1 - k) || 0;
913 m = (1 - g - k) / (1 - k) || 0;
914 y = (1 - b - k) / (1 - k) || 0;
915 return [c * 100, m * 100, y * 100, k * 100];
918 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
922 function comparativeDistance(x, y) {
923 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
926 convert.rgb.keyword = function (rgb) {
927 var reversed = reverseKeywords[rgb];
933 var currentClosestDistance = Infinity;
934 var currentClosestKeyword;
936 for (var keyword in colorName) {
937 if (colorName.hasOwnProperty(keyword)) {
938 var value = colorName[keyword]; // Compute comparative distance
940 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
942 if (distance < currentClosestDistance) {
943 currentClosestDistance = distance;
944 currentClosestKeyword = keyword;
949 return currentClosestKeyword;
952 convert.keyword.rgb = function (keyword) {
953 return colorName[keyword];
956 convert.rgb.xyz = function (rgb) {
957 var r = rgb[0] / 255;
958 var g = rgb[1] / 255;
959 var b = rgb[2] / 255; // assume sRGB
961 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
962 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
963 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
964 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
965 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
966 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
967 return [x * 100, y * 100, z * 100];
970 convert.rgb.lab = function (rgb) {
971 var xyz = convert.rgb.xyz(rgb);
981 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
982 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
983 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
990 convert.hsl.rgb = function (hsl) {
991 var h = hsl[0] / 360;
992 var s = hsl[1] / 100;
993 var l = hsl[2] / 100;
1002 return [val, val, val];
1014 for (var i = 0; i < 3; i++) {
1015 t3 = h + 1 / 3 * -(i - 1);
1026 val = t1 + (t2 - t1) * 6 * t3;
1027 } else if (2 * t3 < 1) {
1029 } else if (3 * t3 < 2) {
1030 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
1041 convert.hsl.hsv = function (hsl) {
1043 var s = hsl[1] / 100;
1044 var l = hsl[2] / 100;
1046 var lmin = Math.max(l, 0.01);
1050 s *= l <= 1 ? l : 2 - l;
1051 smin *= lmin <= 1 ? lmin : 2 - lmin;
1053 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
1054 return [h, sv * 100, v * 100];
1057 convert.hsv.rgb = function (hsv) {
1058 var h = hsv[0] / 60;
1059 var s = hsv[1] / 100;
1060 var v = hsv[2] / 100;
1061 var hi = Math.floor(h) % 6;
1062 var f = h - Math.floor(h);
1063 var p = 255 * v * (1 - s);
1064 var q = 255 * v * (1 - s * f);
1065 var t = 255 * v * (1 - s * (1 - f));
1089 convert.hsv.hsl = function (hsv) {
1091 var s = hsv[1] / 100;
1092 var v = hsv[2] / 100;
1093 var vmin = Math.max(v, 0.01);
1098 lmin = (2 - s) * vmin;
1100 sl /= lmin <= 1 ? lmin : 2 - lmin;
1103 return [h, sl * 100, l * 100];
1104 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
1107 convert.hwb.rgb = function (hwb) {
1108 var h = hwb[0] / 360;
1109 var wh = hwb[1] / 100;
1110 var bl = hwb[2] / 100;
1111 var ratio = wh + bl;
1115 var n; // wh + bl cant be > 1
1122 i = Math.floor(6 * h);
1126 if ((i & 0x01) !== 0) {
1130 n = wh + f * (v - wh); // linear interpolation
1176 return [r * 255, g * 255, b * 255];
1179 convert.cmyk.rgb = function (cmyk) {
1180 var c = cmyk[0] / 100;
1181 var m = cmyk[1] / 100;
1182 var y = cmyk[2] / 100;
1183 var k = cmyk[3] / 100;
1187 r = 1 - Math.min(1, c * (1 - k) + k);
1188 g = 1 - Math.min(1, m * (1 - k) + k);
1189 b = 1 - Math.min(1, y * (1 - k) + k);
1190 return [r * 255, g * 255, b * 255];
1193 convert.xyz.rgb = function (xyz) {
1194 var x = xyz[0] / 100;
1195 var y = xyz[1] / 100;
1196 var z = xyz[2] / 100;
1200 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
1201 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
1202 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
1204 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
1205 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
1206 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
1207 r = Math.min(Math.max(0, r), 1);
1208 g = Math.min(Math.max(0, g), 1);
1209 b = Math.min(Math.max(0, b), 1);
1210 return [r * 255, g * 255, b * 255];
1213 convert.xyz.lab = function (xyz) {
1223 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
1224 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
1225 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
1232 convert.lab.xyz = function (lab) {
1242 var y2 = Math.pow(y, 3);
1243 var x2 = Math.pow(x, 3);
1244 var z2 = Math.pow(z, 3);
1245 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
1246 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
1247 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
1254 convert.lab.lch = function (lab) {
1261 hr = Math.atan2(b, a);
1262 h = hr * 360 / 2 / Math.PI;
1268 c = Math.sqrt(a * a + b * b);
1272 convert.lch.lab = function (lch) {
1279 hr = h / 360 * 2 * Math.PI;
1280 a = c * Math.cos(hr);
1281 b = c * Math.sin(hr);
1285 convert.rgb.ansi16 = function (args) {
1289 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
1291 value = Math.round(value / 50);
1297 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
1306 convert.hsv.ansi16 = function (args) {
1307 // optimization here; we already know the value and don't need to get
1308 // it converted for us.
1309 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
1312 convert.rgb.ansi256 = function (args) {
1315 var b = args[2]; // we use the extended greyscale palette here, with the exception of
1316 // black and white. normal palette only has 4 greyscale shades.
1318 if (r === g && g === b) {
1327 return Math.round((r - 8) / 247 * 24) + 232;
1330 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
1334 convert.ansi16.rgb = function (args) {
1335 var color = args % 10; // handle greyscale
1337 if (color === 0 || color === 7) {
1342 color = color / 10.5 * 255;
1343 return [color, color, color];
1346 var mult = (~~(args > 50) + 1) * 0.5;
1347 var r = (color & 1) * mult * 255;
1348 var g = (color >> 1 & 1) * mult * 255;
1349 var b = (color >> 2 & 1) * mult * 255;
1353 convert.ansi256.rgb = function (args) {
1356 var c = (args - 232) * 10 + 8;
1362 var r = Math.floor(args / 36) / 5 * 255;
1363 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
1364 var b = rem % 6 / 5 * 255;
1368 convert.rgb.hex = function (args) {
1369 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
1370 var string = integer.toString(16).toUpperCase();
1371 return '000000'.substring(string.length) + string;
1374 convert.hex.rgb = function (args) {
1375 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
1381 var colorString = match[0];
1383 if (match[0].length === 3) {
1384 colorString = colorString.split('').map(function (char) {
1389 var integer = parseInt(colorString, 16);
1390 var r = integer >> 16 & 0xFF;
1391 var g = integer >> 8 & 0xFF;
1392 var b = integer & 0xFF;
1396 convert.rgb.hcg = function (rgb) {
1397 var r = rgb[0] / 255;
1398 var g = rgb[1] / 255;
1399 var b = rgb[2] / 255;
1400 var max = Math.max(Math.max(r, g), b);
1401 var min = Math.min(Math.min(r, g), b);
1402 var chroma = max - min;
1407 grayscale = min / (1 - chroma);
1414 } else if (max === r) {
1415 hue = (g - b) / chroma % 6;
1416 } else if (max === g) {
1417 hue = 2 + (b - r) / chroma;
1419 hue = 4 + (r - g) / chroma + 4;
1424 return [hue * 360, chroma * 100, grayscale * 100];
1427 convert.hsl.hcg = function (hsl) {
1428 var s = hsl[1] / 100;
1429 var l = hsl[2] / 100;
1436 c = 2.0 * s * (1.0 - l);
1440 f = (l - 0.5 * c) / (1.0 - c);
1443 return [hsl[0], c * 100, f * 100];
1446 convert.hsv.hcg = function (hsv) {
1447 var s = hsv[1] / 100;
1448 var v = hsv[2] / 100;
1453 f = (v - c) / (1 - c);
1456 return [hsv[0], c * 100, f * 100];
1459 convert.hcg.rgb = function (hcg) {
1460 var h = hcg[0] / 360;
1461 var c = hcg[1] / 100;
1462 var g = hcg[2] / 100;
1465 return [g * 255, g * 255, g * 255];
1468 var pure = [0, 0, 0];
1474 switch (Math.floor(hi)) {
1512 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
1515 convert.hcg.hsv = function (hcg) {
1516 var c = hcg[1] / 100;
1517 var g = hcg[2] / 100;
1518 var v = c + g * (1.0 - c);
1525 return [hcg[0], f * 100, v * 100];
1528 convert.hcg.hsl = function (hcg) {
1529 var c = hcg[1] / 100;
1530 var g = hcg[2] / 100;
1531 var l = g * (1.0 - c) + 0.5 * c;
1534 if (l > 0.0 && l < 0.5) {
1536 } else if (l >= 0.5 && l < 1.0) {
1537 s = c / (2 * (1 - l));
1540 return [hcg[0], s * 100, l * 100];
1543 convert.hcg.hwb = function (hcg) {
1544 var c = hcg[1] / 100;
1545 var g = hcg[2] / 100;
1546 var v = c + g * (1.0 - c);
1547 return [hcg[0], (v - c) * 100, (1 - v) * 100];
1550 convert.hwb.hcg = function (hwb) {
1551 var w = hwb[1] / 100;
1552 var b = hwb[2] / 100;
1558 g = (v - c) / (1 - c);
1561 return [hwb[0], c * 100, g * 100];
1564 convert.apple.rgb = function (apple) {
1565 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
1568 convert.rgb.apple = function (rgb) {
1569 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
1572 convert.gray.rgb = function (args) {
1573 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
1576 convert.gray.hsl = convert.gray.hsv = function (args) {
1577 return [0, 0, args[0]];
1580 convert.gray.hwb = function (gray) {
1581 return [0, 100, gray[0]];
1584 convert.gray.cmyk = function (gray) {
1585 return [0, 0, 0, gray[0]];
1588 convert.gray.lab = function (gray) {
1589 return [gray[0], 0, 0];
1592 convert.gray.hex = function (gray) {
1593 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
1594 var integer = (val << 16) + (val << 8) + val;
1595 var string = integer.toString(16).toUpperCase();
1596 return '000000'.substring(string.length) + string;
1599 convert.rgb.gray = function (rgb) {
1600 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
1601 return [val / 255 * 100];
1606 this function routes a model to all other models.
1608 all functions that are routed have a property `.conversion` attached
1609 to the returned synthetic function. This property is an array
1610 of strings, each with the steps in between the 'from' and 'to'
1611 color models (inclusive).
1613 conversions that are not possible simply are not included.
1616 function buildGraph() {
1617 var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
1619 var models = Object.keys(conversions);
1621 for (var len = models.length, i = 0; i < len; i++) {
1622 graph[models[i]] = {
1623 // http://jsperf.com/1-vs-infinity
1624 // micro-opt, but this is simple.
1631 } // https://en.wikipedia.org/wiki/Breadth-first_search
1634 function deriveBFS(fromModel) {
1635 var graph = buildGraph();
1636 var queue = [fromModel]; // unshift -> queue -> pop
1638 graph[fromModel].distance = 0;
1640 while (queue.length) {
1641 var current = queue.pop();
1642 var adjacents = Object.keys(conversions[current]);
1644 for (var len = adjacents.length, i = 0; i < len; i++) {
1645 var adjacent = adjacents[i];
1646 var node = graph[adjacent];
1648 if (node.distance === -1) {
1649 node.distance = graph[current].distance + 1;
1650 node.parent = current;
1651 queue.unshift(adjacent);
1659 function link(from, to) {
1660 return function (args) {
1661 return to(from(args));
1665 function wrapConversion(toModel, graph) {
1666 var path = [graph[toModel].parent, toModel];
1667 var fn = conversions[graph[toModel].parent][toModel];
1668 var cur = graph[toModel].parent;
1670 while (graph[cur].parent) {
1671 path.unshift(graph[cur].parent);
1672 fn = link(conversions[graph[cur].parent][cur], fn);
1673 cur = graph[cur].parent;
1676 fn.conversion = path;
1680 var route = function (fromModel) {
1681 var graph = deriveBFS(fromModel);
1682 var conversion = {};
1683 var models = Object.keys(graph);
1685 for (var len = models.length, i = 0; i < len; i++) {
1686 var toModel = models[i];
1687 var node = graph[toModel];
1689 if (node.parent === null) {
1690 // no possible conversion, or this node is the source model.
1694 conversion[toModel] = wrapConversion(toModel, graph);
1701 var models = Object.keys(conversions);
1703 function wrapRaw(fn) {
1704 var wrappedFn = function (args) {
1705 if (args === undefined || args === null) {
1709 if (arguments.length > 1) {
1710 args = Array.prototype.slice.call(arguments);
1714 }; // preserve .conversion property if there is one
1717 if ('conversion' in fn) {
1718 wrappedFn.conversion = fn.conversion;
1724 function wrapRounded(fn) {
1725 var wrappedFn = function (args) {
1726 if (args === undefined || args === null) {
1730 if (arguments.length > 1) {
1731 args = Array.prototype.slice.call(arguments);
1734 var result = fn(args); // we're assuming the result is an array here.
1735 // see notice in conversions.js; don't use box types
1736 // in conversion functions.
1738 if (typeof result === 'object') {
1739 for (var len = result.length, i = 0; i < len; i++) {
1740 result[i] = Math.round(result[i]);
1745 }; // preserve .conversion property if there is one
1748 if ('conversion' in fn) {
1749 wrappedFn.conversion = fn.conversion;
1755 models.forEach(function (fromModel) {
1756 convert[fromModel] = {};
1757 Object.defineProperty(convert[fromModel], 'channels', {
1758 value: conversions[fromModel].channels
1760 Object.defineProperty(convert[fromModel], 'labels', {
1761 value: conversions[fromModel].labels
1763 var routes = route(fromModel);
1764 var routeModels = Object.keys(routes);
1765 routeModels.forEach(function (toModel) {
1766 var fn = routes[toModel];
1767 convert[fromModel][toModel] = wrapRounded(fn);
1768 convert[fromModel][toModel].raw = wrapRaw(fn);
1771 var colorConvert = convert;
1773 var ansiStyles = createCommonjsModule(function (module) {
1775 const wrapAnsi16 = (fn, offset) => function () {
1776 const code = fn.apply(colorConvert, arguments);
1777 return `\u001B[${code + offset}m`;
1780 const wrapAnsi256 = (fn, offset) => function () {
1781 const code = fn.apply(colorConvert, arguments);
1782 return `\u001B[${38 + offset};5;${code}m`;
1785 const wrapAnsi16m = (fn, offset) => function () {
1786 const rgb = fn.apply(colorConvert, arguments);
1787 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
1790 function assembleStyles() {
1791 const codes = new Map();
1795 // 21 isn't widely supported and 22 does the same thing
1802 strikethrough: [9, 29]
1815 redBright: [91, 39],
1816 greenBright: [92, 39],
1817 yellowBright: [93, 39],
1818 blueBright: [94, 39],
1819 magentaBright: [95, 39],
1820 cyanBright: [96, 39],
1821 whiteBright: [97, 39]
1829 bgMagenta: [45, 49],
1833 bgBlackBright: [100, 49],
1834 bgRedBright: [101, 49],
1835 bgGreenBright: [102, 49],
1836 bgYellowBright: [103, 49],
1837 bgBlueBright: [104, 49],
1838 bgMagentaBright: [105, 49],
1839 bgCyanBright: [106, 49],
1840 bgWhiteBright: [107, 49]
1844 styles.color.grey = styles.color.gray;
1846 for (const groupName of Object.keys(styles)) {
1847 const group = styles[groupName];
1849 for (const styleName of Object.keys(group)) {
1850 const style = group[styleName];
1851 styles[styleName] = {
1852 open: `\u001B[${style[0]}m`,
1853 close: `\u001B[${style[1]}m`
1855 group[styleName] = styles[styleName];
1856 codes.set(style[0], style[1]);
1859 Object.defineProperty(styles, groupName, {
1863 Object.defineProperty(styles, 'codes', {
1869 const ansi2ansi = n => n;
1871 const rgb2rgb = (r, g, b) => [r, g, b];
1873 styles.color.close = '\u001B[39m';
1874 styles.bgColor.close = '\u001B[49m';
1875 styles.color.ansi = {
1876 ansi: wrapAnsi16(ansi2ansi, 0)
1878 styles.color.ansi256 = {
1879 ansi256: wrapAnsi256(ansi2ansi, 0)
1881 styles.color.ansi16m = {
1882 rgb: wrapAnsi16m(rgb2rgb, 0)
1884 styles.bgColor.ansi = {
1885 ansi: wrapAnsi16(ansi2ansi, 10)
1887 styles.bgColor.ansi256 = {
1888 ansi256: wrapAnsi256(ansi2ansi, 10)
1890 styles.bgColor.ansi16m = {
1891 rgb: wrapAnsi16m(rgb2rgb, 10)
1894 for (let key of Object.keys(colorConvert)) {
1895 if (typeof colorConvert[key] !== 'object') {
1899 const suite = colorConvert[key];
1901 if (key === 'ansi16') {
1905 if ('ansi16' in suite) {
1906 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
1907 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
1910 if ('ansi256' in suite) {
1911 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
1912 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
1915 if ('rgb' in suite) {
1916 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
1917 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
1922 } // Make the export immutable
1925 Object.defineProperty(module, 'exports', {
1931 var hasFlag = (flag, argv) => {
1932 argv = argv || process.argv;
1933 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
1934 const pos = argv.indexOf(prefix + flag);
1935 const terminatorPos = argv.indexOf('--');
1936 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
1939 const env = process.env;
1942 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
1944 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
1948 if ('FORCE_COLOR' in env) {
1949 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
1952 function translateLevel(level) {
1965 function supportsColor(stream) {
1966 if (forceColor === false) {
1970 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
1974 if (hasFlag('color=256')) {
1978 if (stream && !stream.isTTY && forceColor !== true) {
1982 const min = forceColor ? 1 : 0;
1984 if (process.platform === 'win32') {
1985 // Node.js 7.5.0 is the first version of Node.js to include a patch to
1986 // libuv that enables 256 color output on Windows. Anything earlier and it
1987 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
1988 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
1989 // release that supports 256 colors. Windows 10 build 14931 is the first release
1990 // that supports 16m/TrueColor.
1991 const osRelease = os__default['default'].release().split('.');
1993 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
1994 return Number(osRelease[2]) >= 14931 ? 3 : 2;
2001 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
2008 if ('TEAMCITY_VERSION' in env) {
2009 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2012 if (env.COLORTERM === 'truecolor') {
2016 if ('TERM_PROGRAM' in env) {
2017 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
2019 switch (env.TERM_PROGRAM) {
2021 return version >= 3 ? 3 : 2;
2023 case 'Apple_Terminal':
2029 if (/-256(color)?$/i.test(env.TERM)) {
2033 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2037 if ('COLORTERM' in env) {
2041 if (env.TERM === 'dumb') {
2048 function getSupportLevel(stream) {
2049 const level = supportsColor(stream);
2050 return translateLevel(level);
2053 var supportsColor_1 = {
2054 supportsColor: getSupportLevel,
2055 stdout: getSupportLevel(process.stdout),
2056 stderr: getSupportLevel(process.stderr)
2059 const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
2060 const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
2061 const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
2062 const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
2063 const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
2065 function unescape(c) {
2066 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
2067 return String.fromCharCode(parseInt(c.slice(1), 16));
2070 return ESCAPES.get(c) || c;
2073 function parseArguments(name, args) {
2075 const chunks = args.trim().split(/\s*,\s*/g);
2078 for (const chunk of chunks) {
2079 if (!isNaN(chunk)) {
2080 results.push(Number(chunk));
2081 } else if (matches = chunk.match(STRING_REGEX)) {
2082 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
2084 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
2091 function parseStyle(style) {
2092 STYLE_REGEX.lastIndex = 0;
2096 while ((matches = STYLE_REGEX.exec(style)) !== null) {
2097 const name = matches[1];
2100 const args = parseArguments(name, matches[2]);
2101 results.push([name].concat(args));
2103 results.push([name]);
2110 function buildStyle(chalk, styles) {
2113 for (const layer of styles) {
2114 for (const style of layer.styles) {
2115 enabled[style[0]] = layer.inverse ? null : style.slice(1);
2119 let current = chalk;
2121 for (const styleName of Object.keys(enabled)) {
2122 if (Array.isArray(enabled[styleName])) {
2123 if (!(styleName in current)) {
2124 throw new Error(`Unknown Chalk style: ${styleName}`);
2127 if (enabled[styleName].length > 0) {
2128 current = current[styleName].apply(current, enabled[styleName]);
2130 current = current[styleName];
2138 var templates = (chalk, tmp) => {
2141 let chunk = []; // eslint-disable-next-line max-params
2143 tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
2145 chunk.push(unescape(escapeChar));
2147 const str = chunk.join('');
2149 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
2152 styles: parseStyle(style)
2155 if (styles.length === 0) {
2156 throw new Error('Found extraneous } in Chalk template literal');
2159 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
2166 chunks.push(chunk.join(''));
2168 if (styles.length > 0) {
2169 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
2170 throw new Error(errMsg);
2173 return chunks.join('');
2176 var chalk = createCommonjsModule(function (module) {
2178 const stdoutColor = supportsColor_1.stdout;
2179 const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
2181 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
2183 const skipModels = new Set(['gray']);
2184 const styles = Object.create(null);
2186 function applyOptions(obj, options) {
2187 options = options || {}; // Detect level if not set manually
2189 const scLevel = stdoutColor ? stdoutColor.level : 0;
2190 obj.level = options.level === undefined ? scLevel : options.level;
2191 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
2194 function Chalk(options) {
2195 // We check for this.template here since calling `chalk.constructor()`
2196 // by itself will have a `this` of a previously constructed chalk object
2197 if (!this || !(this instanceof Chalk) || this.template) {
2199 applyOptions(chalk, options);
2201 chalk.template = function () {
2202 const args = [].slice.call(arguments);
2203 return chalkTag.apply(null, [chalk.template].concat(args));
2206 Object.setPrototypeOf(chalk, Chalk.prototype);
2207 Object.setPrototypeOf(chalk.template, chalk);
2208 chalk.template.constructor = Chalk;
2209 return chalk.template;
2212 applyOptions(this, options);
2213 } // Use bright blue on Windows as the normal blue color is illegible
2216 if (isSimpleWindowsTerm) {
2217 ansiStyles.blue.open = '\u001B[94m';
2220 for (const key of Object.keys(ansiStyles)) {
2221 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
2224 const codes = ansiStyles[key];
2225 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
2233 return build.call(this, this._styles || [], true, 'visible');
2237 ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
2239 for (const model of Object.keys(ansiStyles.color.ansi)) {
2240 if (skipModels.has(model)) {
2246 const level = this.level;
2247 return function () {
2248 const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
2251 close: ansiStyles.color.close,
2252 closeRe: ansiStyles.color.closeRe
2254 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
2261 ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
2263 for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
2264 if (skipModels.has(model)) {
2268 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
2271 const level = this.level;
2272 return function () {
2273 const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
2276 close: ansiStyles.bgColor.close,
2277 closeRe: ansiStyles.bgColor.closeRe
2279 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
2286 const proto = Object.defineProperties(() => {}, styles);
2288 function build(_styles, _empty, key) {
2289 const builder = function () {
2290 return applyStyle.apply(builder, arguments);
2293 builder._styles = _styles;
2294 builder._empty = _empty;
2296 Object.defineProperty(builder, 'level', {
2308 Object.defineProperty(builder, 'enabled', {
2312 return self.enabled;
2316 self.enabled = enabled;
2319 }); // See below for fix regarding invisible grey/dim combination on Windows
2321 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
2322 // no way to create a function with a different prototype
2324 builder.__proto__ = proto; // eslint-disable-line no-proto
2329 function applyStyle() {
2330 // Support varags, but simply cast to string in case there's only one arg
2331 const args = arguments;
2332 const argsLen = args.length;
2333 let str = String(arguments[0]);
2335 if (argsLen === 0) {
2340 // Don't slice `arguments`, it prevents V8 optimizations
2341 for (let a = 1; a < argsLen; a++) {
2342 str += ' ' + args[a];
2346 if (!this.enabled || this.level <= 0 || !str) {
2347 return this._empty ? '' : str;
2348 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
2349 // see https://github.com/chalk/chalk/issues/58
2350 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
2353 const originalDim = ansiStyles.dim.open;
2355 if (isSimpleWindowsTerm && this.hasGrey) {
2356 ansiStyles.dim.open = '';
2359 for (const code of this._styles.slice().reverse()) {
2360 // Replace any instances already present with a re-opening code
2361 // otherwise only the part of the string until said closing code
2362 // will be colored, and the rest will simply be 'plain'.
2363 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
2364 // after next line to fix a bleed issue on macOS
2365 // https://github.com/chalk/chalk/pull/92
2367 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
2368 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
2371 ansiStyles.dim.open = originalDim;
2375 function chalkTag(chalk, strings) {
2376 if (!Array.isArray(strings)) {
2377 // If chalk() was called by itself or with a string,
2378 // return the string itself as a string.
2379 return [].slice.call(arguments, 1).join(' ');
2382 const args = [].slice.call(arguments, 2);
2383 const parts = [strings.raw[0]];
2385 for (let i = 1; i < strings.length; i++) {
2386 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
2387 parts.push(String(strings.raw[i]));
2390 return templates(chalk, parts.join(''));
2393 Object.defineProperties(Chalk.prototype, styles);
2394 module.exports = Chalk(); // eslint-disable-line new-cap
2396 module.exports.supportsColor = stdoutColor;
2397 module.exports.default = module.exports; // For TypeScript
2400 var lib$1 = createCommonjsModule(function (module, exports) {
2402 Object.defineProperty(exports, "__esModule", {
2405 exports.shouldHighlight = shouldHighlight;
2406 exports.getChalk = getChalk;
2407 exports.default = highlight;
2409 var _jsTokens = _interopRequireWildcard(jsTokens);
2411 var _chalk = _interopRequireDefault(chalk);
2413 function _interopRequireDefault(obj) {
2414 return obj && obj.__esModule ? obj : {
2419 function _getRequireWildcardCache() {
2420 if (typeof WeakMap !== "function") return null;
2421 var cache = new WeakMap();
2423 _getRequireWildcardCache = function () {
2430 function _interopRequireWildcard(obj) {
2431 if (obj && obj.__esModule) {
2435 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
2441 var cache = _getRequireWildcardCache();
2443 if (cache && cache.has(obj)) {
2444 return cache.get(obj);
2448 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
2450 for (var key in obj) {
2451 if (Object.prototype.hasOwnProperty.call(obj, key)) {
2452 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
2454 if (desc && (desc.get || desc.set)) {
2455 Object.defineProperty(newObj, key, desc);
2457 newObj[key] = obj[key];
2462 newObj.default = obj;
2465 cache.set(obj, newObj);
2471 function getDefs(chalk) {
2473 keyword: chalk.cyan,
2474 capitalized: chalk.yellow,
2475 jsx_tag: chalk.yellow,
2476 punctuator: chalk.yellow,
2477 number: chalk.magenta,
2478 string: chalk.green,
2479 regex: chalk.magenta,
2480 comment: chalk.grey,
2481 invalid: chalk.white.bgRed.bold
2485 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
2486 const JSX_TAG = /^[a-z][\w-]*$/i;
2487 const BRACKET = /^[()[\]{}]$/;
2489 function getTokenType(match) {
2490 const [offset, text] = match.slice(-2);
2491 const token = (0, _jsTokens.matchToToken)(match);
2493 if (token.type === "name") {
2494 if ((0, lib.isKeyword)(token.value) || (0, lib.isReservedWord)(token.value)) {
2498 if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
2502 if (token.value[0] !== token.value[0].toLowerCase()) {
2503 return "capitalized";
2507 if (token.type === "punctuator" && BRACKET.test(token.value)) {
2511 if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
2512 return "punctuator";
2518 function highlightTokens(defs, text) {
2519 return text.replace(_jsTokens.default, function (...args) {
2520 const type = getTokenType(args);
2521 const colorize = defs[type];
2524 return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
2531 function shouldHighlight(options) {
2532 return _chalk.default.supportsColor || options.forceColor;
2535 function getChalk(options) {
2536 let chalk = _chalk.default;
2538 if (options.forceColor) {
2539 chalk = new _chalk.default.constructor({
2548 function highlight(code, options = {}) {
2549 if (shouldHighlight(options)) {
2550 const chalk = getChalk(options);
2551 const defs = getDefs(chalk);
2552 return highlightTokens(defs, code);
2559 var lib$2 = createCommonjsModule(function (module, exports) {
2561 Object.defineProperty(exports, "__esModule", {
2564 exports.codeFrameColumns = codeFrameColumns;
2565 exports.default = _default;
2567 var _highlight = _interopRequireWildcard(lib$1);
2569 function _getRequireWildcardCache() {
2570 if (typeof WeakMap !== "function") return null;
2571 var cache = new WeakMap();
2573 _getRequireWildcardCache = function () {
2580 function _interopRequireWildcard(obj) {
2581 if (obj && obj.__esModule) {
2585 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
2591 var cache = _getRequireWildcardCache();
2593 if (cache && cache.has(obj)) {
2594 return cache.get(obj);
2598 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
2600 for (var key in obj) {
2601 if (Object.prototype.hasOwnProperty.call(obj, key)) {
2602 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
2604 if (desc && (desc.get || desc.set)) {
2605 Object.defineProperty(newObj, key, desc);
2607 newObj[key] = obj[key];
2612 newObj.default = obj;
2615 cache.set(obj, newObj);
2621 let deprecationWarningShown = false;
2623 function getDefs(chalk) {
2626 marker: chalk.red.bold,
2627 message: chalk.red.bold
2631 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
2633 function getMarkerLines(loc, source, opts) {
2634 const startLoc = Object.assign({
2638 const endLoc = Object.assign({}, startLoc, loc.end);
2643 const startLine = startLoc.line;
2644 const startColumn = startLoc.column;
2645 const endLine = endLoc.line;
2646 const endColumn = endLoc.column;
2647 let start = Math.max(startLine - (linesAbove + 1), 0);
2648 let end = Math.min(source.length, endLine + linesBelow);
2650 if (startLine === -1) {
2654 if (endLine === -1) {
2655 end = source.length;
2658 const lineDiff = endLine - startLine;
2659 const markerLines = {};
2662 for (let i = 0; i <= lineDiff; i++) {
2663 const lineNumber = i + startLine;
2666 markerLines[lineNumber] = true;
2667 } else if (i === 0) {
2668 const sourceLength = source[lineNumber - 1].length;
2669 markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
2670 } else if (i === lineDiff) {
2671 markerLines[lineNumber] = [0, endColumn];
2673 const sourceLength = source[lineNumber - i].length;
2674 markerLines[lineNumber] = [0, sourceLength];
2678 if (startColumn === endColumn) {
2680 markerLines[startLine] = [startColumn, 0];
2682 markerLines[startLine] = true;
2685 markerLines[startLine] = [startColumn, endColumn - startColumn];
2696 function codeFrameColumns(rawLines, loc, opts = {}) {
2697 const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
2698 const chalk = (0, _highlight.getChalk)(opts);
2699 const defs = getDefs(chalk);
2701 const maybeHighlight = (chalkFn, string) => {
2702 return highlighted ? chalkFn(string) : string;
2705 const lines = rawLines.split(NEWLINE);
2710 } = getMarkerLines(loc, lines, opts);
2711 const hasColumns = loc.start && typeof loc.start.column === "number";
2712 const numberMaxWidth = String(end).length;
2713 const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
2714 let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
2715 const number = start + 1 + index;
2716 const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
2717 const gutter = ` ${paddedNumber} | `;
2718 const hasMarker = markerLines[number];
2719 const lastMarkerLine = !markerLines[number + 1];
2722 let markerLine = "";
2724 if (Array.isArray(hasMarker)) {
2725 const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
2726 const numberOfMarkers = hasMarker[1] || 1;
2727 markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
2729 if (lastMarkerLine && opts.message) {
2730 markerLine += " " + maybeHighlight(defs.message, opts.message);
2734 return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
2736 return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
2740 if (opts.message && !hasColumns) {
2741 frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
2745 return chalk.reset(frame);
2751 function _default(rawLines, lineNumber, colNumber, opts = {}) {
2752 if (!deprecationWarningShown) {
2753 deprecationWarningShown = true;
2754 const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
2756 if (process.emitWarning) {
2757 process.emitWarning(message, "DeprecationWarning");
2759 const deprecationError = new Error(message);
2760 deprecationError.name = "DeprecationWarning";
2761 console.warn(new Error(message));
2765 colNumber = Math.max(colNumber, 0);
2772 return codeFrameColumns(rawLines, location, opts);
2777 default: LinesAndColumns
2782 const JSONError = errorEx_1('JSONError', {
2783 fileName: errorEx_1.append('in %s'),
2784 codeFrame: errorEx_1.append('\n\n%s\n')
2787 var parseJson$1 = (string, reviver, filename) => {
2788 if (typeof reviver === 'string') {
2795 return JSON.parse(string, reviver);
2797 jsonParseBetterErrors(string, reviver);
2801 error.message = error.message.replace(/\n/g, '');
2802 const indexMatch = error.message.match(/in JSON at position (\d+) while parsing near/);
2803 const jsonError = new JSONError(error);
2806 jsonError.fileName = filename;
2809 if (indexMatch && indexMatch.length > 0) {
2810 const lines = new LinesAndColumns(string);
2811 const index = Number(indexMatch[1]);
2812 const location = lines.locationForIndex(index);
2813 const codeFrame = codeFrameColumns(string, {
2815 line: location.line + 1,
2816 column: location.column + 1
2821 jsonError.codeFrame = codeFrame;
2832 DIRECTIVES_END: '-',
2837 BLANK_LINE: 'BLANK_LINE',
2838 BLOCK_FOLDED: 'BLOCK_FOLDED',
2839 BLOCK_LITERAL: 'BLOCK_LITERAL',
2841 DIRECTIVE: 'DIRECTIVE',
2842 DOCUMENT: 'DOCUMENT',
2843 FLOW_MAP: 'FLOW_MAP',
2844 FLOW_SEQ: 'FLOW_SEQ',
2847 MAP_VALUE: 'MAP_VALUE',
2849 QUOTE_DOUBLE: 'QUOTE_DOUBLE',
2850 QUOTE_SINGLE: 'QUOTE_SINGLE',
2852 SEQ_ITEM: 'SEQ_ITEM'
2854 const defaultTagPrefix = 'tag:yaml.org,2002:';
2855 const defaultTags = {
2856 MAP: 'tag:yaml.org,2002:map',
2857 SEQ: 'tag:yaml.org,2002:seq',
2858 STR: 'tag:yaml.org,2002:str'
2861 function findLineStarts(src) {
2863 let offset = src.indexOf('\n');
2865 while (offset !== -1) {
2868 offset = src.indexOf('\n', offset);
2874 function getSrcInfo(cst) {
2875 let lineStarts, src;
2877 if (typeof cst === 'string') {
2878 lineStarts = findLineStarts(cst);
2881 if (Array.isArray(cst)) cst = cst[0];
2883 if (cst && cst.context) {
2884 if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src);
2885 lineStarts = cst.lineStarts;
2886 src = cst.context.src;
2896 * @typedef {Object} LinePos - One-indexed position in the source
2897 * @property {number} line
2898 * @property {number} col
2902 * Determine the line/col position matching a character offset.
2904 * Accepts a source string or a CST document as the second parameter. With
2905 * the latter, starting indices for lines are cached in the document as
2906 * `lineStarts: number[]`.
2908 * Returns a one-indexed `{ line, col }` location if found, or
2909 * `undefined` otherwise.
2911 * @param {number} offset
2912 * @param {string|Document|Document[]} cst
2913 * @returns {?LinePos}
2917 function getLinePos(offset, cst) {
2918 if (typeof offset !== 'number' || offset < 0) return null;
2922 } = getSrcInfo(cst);
2923 if (!lineStarts || !src || offset > src.length) return null;
2925 for (let i = 0; i < lineStarts.length; ++i) {
2926 const start = lineStarts[i];
2928 if (offset < start) {
2931 col: offset - lineStarts[i - 1] + 1
2935 if (offset === start) return {
2941 const line = lineStarts.length;
2944 col: offset - lineStarts[line - 1] + 1
2948 * Get a specified line from the source.
2950 * Accepts a source string or a CST document as the second parameter. With
2951 * the latter, starting indices for lines are cached in the document as
2952 * `lineStarts: number[]`.
2954 * Returns the line as a string if found, or `null` otherwise.
2956 * @param {number} line One-indexed line number
2957 * @param {string|Document|Document[]} cst
2958 * @returns {?string}
2962 function getLine(line, cst) {
2966 } = getSrcInfo(cst);
2967 if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null;
2968 const start = lineStarts[line - 1];
2969 let end = lineStarts[line]; // undefined for last line; that's ok for slice()
2971 while (end && end > start && src[end - 1] === '\n') --end;
2973 return src.slice(start, end);
2976 * Pretty-print the starting line from the source indicated by the range `pos`
2978 * Trims output to `maxWidth` chars while keeping the starting column visible,
2979 * using `…` at either end to indicate dropped characters.
2981 * Returns a two-line string (or `null`) with `\n` as separator; the second line
2982 * will hold appropriately indented `^` marks indicating the column range.
2984 * @param {Object} pos
2985 * @param {LinePos} pos.start
2986 * @param {LinePos} [pos.end]
2987 * @param {string|Document|Document[]*} cst
2988 * @param {number} [maxWidth=80]
2989 * @returns {?string}
2993 function getPrettyContext({
2996 }, cst, maxWidth = 80) {
2997 let src = getLine(start.line, cst);
2998 if (!src) return null;
3003 if (src.length > maxWidth) {
3004 if (col <= maxWidth - 10) {
3005 src = src.substr(0, maxWidth - 1) + '…';
3007 const halfWidth = Math.round(maxWidth / 2);
3008 if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…';
3009 col -= src.length - maxWidth;
3010 src = '…' + src.substr(1 - maxWidth);
3018 if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) {
3019 errLen = end.col - start.col;
3021 errLen = Math.min(src.length + 1, maxWidth) - col;
3026 const offset = col > 1 ? ' '.repeat(col - 1) : '';
3027 const err = '^'.repeat(errLen);
3028 return `${src}\n${offset}${err}${errEnd}`;
3033 return new Range(orig.start, orig.end);
3036 constructor(start, end) {
3038 this.end = end || start;
3042 return typeof this.start !== 'number' || !this.end || this.end <= this.start;
3045 * Set `origStart` and `origEnd` to point to the original source range for
3046 * this node, which may differ due to dropped CR characters.
3048 * @param {number[]} cr - Positions of dropped CR characters
3049 * @param {number} offset - Starting index of `cr` from the last call
3050 * @returns {number} - The next offset, matching the one found for `origStart`
3054 setOrigRange(cr, offset) {
3060 if (cr.length === 0 || end <= cr[0]) {
3061 this.origStart = start;
3068 while (i < cr.length) {
3069 if (cr[i] > start) break;else ++i;
3072 this.origStart = start + i;
3073 const nextOffset = i;
3075 while (i < cr.length) {
3076 // if end was at \n, it should now be at \r
3077 if (cr[i] >= end) break;else ++i;
3080 this.origEnd = end + i;
3085 /** Root class of all nodes */
3089 static addStringTerminator(src, offset, str) {
3090 if (str[str.length - 1] === '\n') return str;
3091 const next = Node.endOfWhiteSpace(src, offset);
3092 return next >= src.length || src[next] === '\n' ? str + '\n' : str;
3096 static atDocumentBoundary(src, offset, sep) {
3097 const ch0 = src[offset];
3098 if (!ch0) return true;
3099 const prev = src[offset - 1];
3100 if (prev && prev !== '\n') return false;
3103 if (ch0 !== sep) return false;
3105 if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false;
3108 const ch1 = src[offset + 1];
3109 const ch2 = src[offset + 2];
3110 if (ch1 !== ch0 || ch2 !== ch0) return false;
3111 const ch3 = src[offset + 3];
3112 return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' ';
3115 static endOfIdentifier(src, offset) {
3116 let ch = src[offset];
3117 const isVerbatim = ch === '<';
3118 const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ','];
3120 while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1];
3122 if (isVerbatim && ch === '>') offset += 1;
3126 static endOfIndent(src, offset) {
3127 let ch = src[offset];
3129 while (ch === ' ') ch = src[offset += 1];
3134 static endOfLine(src, offset) {
3135 let ch = src[offset];
3137 while (ch && ch !== '\n') ch = src[offset += 1];
3142 static endOfWhiteSpace(src, offset) {
3143 let ch = src[offset];
3145 while (ch === '\t' || ch === ' ') ch = src[offset += 1];
3150 static startOfLine(src, offset) {
3151 let ch = src[offset - 1];
3152 if (ch === '\n') return offset;
3154 while (ch && ch !== '\n') ch = src[offset -= 1];
3159 * End of indentation, or null if the line's indent level is not more
3162 * @param {string} src
3163 * @param {number} indent
3164 * @param {number} lineStart
3165 * @returns {?number}
3169 static endOfBlockIndent(src, indent, lineStart) {
3170 const inEnd = Node.endOfIndent(src, lineStart);
3172 if (inEnd > lineStart + indent) {
3175 const wsEnd = Node.endOfWhiteSpace(src, inEnd);
3176 const ch = src[wsEnd];
3177 if (!ch || ch === '\n') return wsEnd;
3183 static atBlank(src, offset, endAsBlank) {
3184 const ch = src[offset];
3185 return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch;
3188 static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) {
3189 if (!ch || indentDiff < 0) return false;
3190 if (indentDiff > 0) return true;
3191 return indicatorAsIndent && ch === '-';
3192 } // should be at line or string end, or at next non-whitespace char
3195 static normalizeOffset(src, offset) {
3196 const ch = src[offset];
3197 return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node.endOfWhiteSpace(src, offset);
3198 } // fold single newline into space, multiple newlines to N - 1 newlines
3199 // presumes src[offset] === '\n'
3202 static foldNewline(src, offset, indent) {
3206 let ch = src[offset + 1];
3208 while (ch === ' ' || ch === '\t' || ch === '\n') {
3217 if (inCount <= indent) error = true;
3218 offset = Node.endOfWhiteSpace(src, offset + 2) - 1;
3227 ch = src[offset + 1];
3230 if (!fold) fold = ' ';
3231 if (ch && inCount <= indent) error = true;
3239 constructor(type, props, context) {
3240 Object.defineProperty(this, 'context', {
3241 value: context || null,
3246 this.valueRange = null;
3247 this.props = props || [];
3252 getPropValue(idx, key, skipKey) {
3253 if (!this.context) return null;
3257 const prop = this.props[idx];
3258 return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null;
3262 for (let i = 0; i < this.props.length; ++i) {
3263 const anchor = this.getPropValue(i, Char.ANCHOR, true);
3264 if (anchor != null) return anchor;
3271 const comments = [];
3273 for (let i = 0; i < this.props.length; ++i) {
3274 const comment = this.getPropValue(i, Char.COMMENT, true);
3275 if (comment != null) comments.push(comment);
3278 return comments.length > 0 ? comments.join('\n') : null;
3281 commentHasRequiredWhitespace(start) {
3285 if (this.header && start === this.header.end) return false;
3286 if (!this.valueRange) return false;
3289 } = this.valueRange;
3290 return start !== end || Node.atBlank(src, end - 1);
3299 for (let i = 0; i < this.props.length; ++i) {
3300 if (src[this.props[i].start] === Char.COMMENT) return true;
3313 for (let i = 0; i < this.props.length; ++i) {
3314 if (src[this.props[i].start] !== Char.COMMENT) return true;
3321 get includesTrailingLines() {
3326 const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE];
3327 return jsonLikeTypes.indexOf(this.type) !== -1;
3330 get rangeAsLinePos() {
3331 if (!this.range || !this.context) return undefined;
3332 const start = getLinePos(this.range.start, this.context.root);
3333 if (!start) return undefined;
3334 const end = getLinePos(this.range.end, this.context.root);
3342 if (!this.valueRange || !this.context) return null;
3346 } = this.valueRange;
3347 return this.context.src.slice(start, end);
3351 for (let i = 0; i < this.props.length; ++i) {
3352 const tag = this.getPropValue(i, Char.TAG, false);
3355 if (tag[1] === '<') {
3357 verbatim: tag.slice(2, -1)
3360 // eslint-disable-next-line no-unused-vars
3361 const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/);
3373 get valueRangeContainsNewline() {
3374 if (!this.valueRange || !this.context) return false;
3378 } = this.valueRange;
3383 for (let i = start; i < end; ++i) {
3384 if (src[i] === '\n') return true;
3390 parseComment(start) {
3395 if (src[start] === Char.COMMENT) {
3396 const end = Node.endOfLine(src, start + 1);
3397 const commentRange = new Range(start, end);
3398 this.props.push(commentRange);
3405 * Populates the `origStart` and `origEnd` values of all ranges for this
3406 * node. Extended by child classes to handle descendant nodes.
3408 * @param {number[]} cr - Positions of dropped CR characters
3409 * @param {number} offset - Starting index of `cr` from the last call
3410 * @returns {number} - The next offset, matching the one found for `origStart`
3414 setOrigRanges(cr, offset) {
3415 if (this.range) offset = this.range.setOrigRange(cr, offset);
3416 if (this.valueRange) this.valueRange.setOrigRange(cr, offset);
3417 this.props.forEach(prop => prop.setOrigRange(cr, offset));
3429 if (value != null) return value;
3430 const str = src.slice(range.start, range.end);
3431 return Node.addStringTerminator(src, range.end, str);
3436 class YAMLError extends Error {
3437 constructor(name, source, message) {
3438 if (!message || !(source instanceof Node)) throw new Error(`Invalid arguments for new ${name}`);
3441 this.message = message;
3442 this.source = source;
3446 if (!this.source) return;
3447 this.nodeType = this.source.type;
3448 const cst = this.source.context && this.source.context.root;
3450 if (typeof this.offset === 'number') {
3451 this.range = new Range(this.offset, this.offset + 1);
3452 const start = cst && getLinePos(this.offset, cst);
3467 this.range = this.source.range;
3468 this.linePos = this.source.rangeAsLinePos;
3475 } = this.linePos.start;
3476 this.message += ` at line ${line}, column ${col}`;
3477 const ctx = cst && getPrettyContext(this.linePos, cst);
3478 if (ctx) this.message += `:\n\n${ctx}\n`;
3486 class YAMLReferenceError extends YAMLError {
3487 constructor(source, message) {
3488 super('YAMLReferenceError', source, message);
3493 class YAMLSemanticError extends YAMLError {
3494 constructor(source, message) {
3495 super('YAMLSemanticError', source, message);
3500 class YAMLSyntaxError extends YAMLError {
3501 constructor(source, message) {
3502 super('YAMLSyntaxError', source, message);
3507 class YAMLWarning extends YAMLError {
3508 constructor(source, message) {
3509 super('YAMLWarning', source, message);
3514 function _defineProperty(obj, key, value) {
3516 Object.defineProperty(obj, key, {
3529 class PlainValue extends Node {
3530 static endOfLine(src, start, inFlow) {
3531 let ch = src[start];
3534 while (ch && ch !== '\n') {
3535 if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break;
3536 const next = src[offset + 1];
3537 if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break;
3538 if ((ch === ' ' || ch === '\t') && next === '#') break;
3547 if (!this.valueRange || !this.context) return null;
3551 } = this.valueRange;
3555 let ch = src[end - 1];
3557 while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1];
3561 for (let i = start; i < end; ++i) {
3568 } = Node.foldNewline(src, i, -1);
3571 } else if (ch === ' ' || ch === '\t') {
3572 // trim trailing whitespace
3574 let next = src[i + 1];
3576 while (i < end && (next === ' ' || next === '\t')) {
3581 if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
3587 const ch0 = src[start];
3592 const msg = 'Plain value cannot start with a tab character';
3593 const errors = [new YAMLSemanticError(this, msg)];
3603 const msg = `Plain value cannot start with reserved character ${ch0}`;
3604 const errors = [new YAMLSemanticError(this, msg)];
3616 parseBlockValue(start) {
3623 let valueEnd = start;
3625 for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
3626 if (Node.atDocumentBoundary(src, offset + 1)) break;
3627 const end = Node.endOfBlockIndent(src, indent, offset + 1);
3628 if (end === null || src[end] === '#') break;
3630 if (src[end] === '\n') {
3633 valueEnd = PlainValue.endOfLine(src, end, inFlow);
3638 if (this.valueRange.isEmpty()) this.valueRange.start = start;
3639 this.valueRange.end = valueEnd;
3643 * Parses a plain value from the source
3645 * Accepted forms are:
3651 * first line #comment
3661 * where block lines are empty or have an indent level greater than `indent`.
3663 * @param {ParseContext} context
3664 * @param {number} start - Index of first character
3665 * @returns {number} - Index of the character after this scalar, may be `\n`
3669 parse(context, start) {
3670 this.context = context;
3676 const ch = src[offset];
3678 if (ch && ch !== '#' && ch !== '\n') {
3679 offset = PlainValue.endOfLine(src, start, inFlow);
3682 this.valueRange = new Range(start, offset);
3683 offset = Node.endOfWhiteSpace(src, offset);
3684 offset = this.parseComment(offset);
3686 if (!this.hasComment || this.valueRange.isEmpty()) {
3687 offset = this.parseBlockValue(offset);
3697 var PlainValue_1 = PlainValue;
3698 var Range_1 = Range;
3700 var YAMLError_1 = YAMLError;
3701 var YAMLReferenceError_1 = YAMLReferenceError;
3702 var YAMLSemanticError_1 = YAMLSemanticError;
3703 var YAMLSyntaxError_1 = YAMLSyntaxError;
3704 var YAMLWarning_1 = YAMLWarning;
3705 var _defineProperty_1 = _defineProperty;
3706 var defaultTagPrefix_1 = defaultTagPrefix;
3707 var defaultTags_1 = defaultTags;
3708 var PlainValueEc8e588e = {
3711 PlainValue: PlainValue_1,
3714 YAMLError: YAMLError_1,
3715 YAMLReferenceError: YAMLReferenceError_1,
3716 YAMLSemanticError: YAMLSemanticError_1,
3717 YAMLSyntaxError: YAMLSyntaxError_1,
3718 YAMLWarning: YAMLWarning_1,
3719 _defineProperty: _defineProperty_1,
3720 defaultTagPrefix: defaultTagPrefix_1,
3721 defaultTags: defaultTags_1
3724 class BlankLine extends PlainValueEc8e588e.Node {
3726 super(PlainValueEc8e588e.Type.BLANK_LINE);
3728 /* istanbul ignore next */
3731 get includesTrailingLines() {
3732 // This is never called from anywhere, but if it were,
3733 // this is the value it should return.
3737 * Parses a blank line from the source
3739 * @param {ParseContext} context
3740 * @param {number} start - Index of first \n character
3741 * @returns {number} - Index of the character after this
3745 parse(context, start) {
3746 this.context = context;
3747 this.range = new PlainValueEc8e588e.Range(start, start + 1);
3753 class CollectionItem extends PlainValueEc8e588e.Node {
3754 constructor(type, props) {
3759 get includesTrailingLines() {
3760 return !!this.node && this.node.includesTrailingLines;
3763 * @param {ParseContext} context
3764 * @param {number} start - Index of first character
3765 * @returns {number} - Index of the character after this
3769 parse(context, start) {
3770 this.context = context;
3779 if (!atLineStart && this.type === PlainValueEc8e588e.Type.SEQ_ITEM) this.error = new PlainValueEc8e588e.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line');
3780 const indent = atLineStart ? start - lineStart : context.indent;
3781 let offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, start + 1);
3782 let ch = src[offset];
3783 const inlineComment = ch === '#';
3784 const comments = [];
3785 let blankLine = null;
3787 while (ch === '\n' || ch === '#') {
3789 const end = PlainValueEc8e588e.Node.endOfLine(src, offset + 1);
3790 comments.push(new PlainValueEc8e588e.Range(offset, end));
3794 lineStart = offset + 1;
3795 const wsEnd = PlainValueEc8e588e.Node.endOfWhiteSpace(src, lineStart);
3797 if (src[wsEnd] === '\n' && comments.length === 0) {
3798 blankLine = new BlankLine();
3799 lineStart = blankLine.parse({
3804 offset = PlainValueEc8e588e.Node.endOfIndent(src, lineStart);
3810 if (PlainValueEc8e588e.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValueEc8e588e.Type.SEQ_ITEM)) {
3811 this.node = parseNode({
3813 inCollection: false,
3818 } else if (ch && lineStart > start + 1) {
3819 offset = lineStart - 1;
3824 // Only blank lines preceding non-empty nodes are captured. Note that
3825 // this means that collection item range start indices do not always
3826 // increase monotonically. -- eemeli/yaml#126
3827 const items = context.parent.items || context.parent.contents;
3828 if (items) items.push(blankLine);
3831 if (comments.length) Array.prototype.push.apply(this.props, comments);
3832 offset = this.node.range.end;
3834 if (inlineComment) {
3835 const c = comments[0];
3839 offset = PlainValueEc8e588e.Node.endOfLine(src, start + 1);
3843 const end = this.node ? this.node.valueRange.end : offset;
3844 this.valueRange = new PlainValueEc8e588e.Range(start, end);
3848 setOrigRanges(cr, offset) {
3849 offset = super.setOrigRanges(cr, offset);
3850 return this.node ? this.node.setOrigRanges(cr, offset) : offset;
3862 if (value != null) return value;
3863 const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end);
3864 return PlainValueEc8e588e.Node.addStringTerminator(src, range.end, str);
3869 class Comment extends PlainValueEc8e588e.Node {
3871 super(PlainValueEc8e588e.Type.COMMENT);
3874 * Parses a comment line from the source
3876 * @param {ParseContext} context
3877 * @param {number} start - Index of first character
3878 * @returns {number} - Index of the character after this scalar
3882 parse(context, start) {
3883 this.context = context;
3884 const offset = this.parseComment(start);
3885 this.range = new PlainValueEc8e588e.Range(start, offset);
3891 function grabCollectionEndComments(node) {
3894 while (cnode instanceof CollectionItem) cnode = cnode.node;
3896 if (!(cnode instanceof Collection)) return null;
3897 const len = cnode.items.length;
3900 for (let i = len - 1; i >= 0; --i) {
3901 const n = cnode.items[i];
3903 if (n.type === PlainValueEc8e588e.Type.COMMENT) {
3904 // Keep sufficiently indented comments with preceding node
3909 if (indent > 0 && n.range.start >= lineStart + indent) break;
3911 } else if (n.type === PlainValueEc8e588e.Type.BLANK_LINE) ci = i;else break;
3914 if (ci === -1) return null;
3915 const ca = cnode.items.splice(ci, len - ci);
3916 const prevEnd = ca[0].range.start;
3919 cnode.range.end = prevEnd;
3920 if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd;
3921 if (cnode === node) break;
3922 cnode = cnode.context.parent;
3928 class Collection extends PlainValueEc8e588e.Node {
3929 static nextContentHasIndent(src, offset, indent) {
3930 const lineStart = PlainValueEc8e588e.Node.endOfLine(src, offset) + 1;
3931 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, lineStart);
3932 const ch = src[offset];
3933 if (!ch) return false;
3934 if (offset >= lineStart + indent) return true;
3935 if (ch !== '#' && ch !== '\n') return false;
3936 return Collection.nextContentHasIndent(src, offset, indent);
3939 constructor(firstItem) {
3940 super(firstItem.type === PlainValueEc8e588e.Type.SEQ_ITEM ? PlainValueEc8e588e.Type.SEQ : PlainValueEc8e588e.Type.MAP);
3942 for (let i = firstItem.props.length - 1; i >= 0; --i) {
3943 if (firstItem.props[i].start < firstItem.context.lineStart) {
3944 // props on previous line are assumed by the collection
3945 this.props = firstItem.props.slice(0, i + 1);
3946 firstItem.props = firstItem.props.slice(i + 1);
3947 const itemRange = firstItem.props[0] || firstItem.valueRange;
3948 firstItem.range.start = itemRange.start;
3953 this.items = [firstItem];
3954 const ec = grabCollectionEndComments(firstItem);
3955 if (ec) Array.prototype.push.apply(this.items, ec);
3958 get includesTrailingLines() {
3959 return this.items.length > 0;
3962 * @param {ParseContext} context
3963 * @param {number} start - Index of first character
3964 * @returns {number} - Index of the character after this
3968 parse(context, start) {
3969 this.context = context;
3973 } = context; // It's easier to recalculate lineStart here rather than tracking down the
3974 // last context from which to read it -- eemeli/yaml#2
3976 let lineStart = PlainValueEc8e588e.Node.startOfLine(src, start);
3977 const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling
3978 // -- eemeli/yaml#17
3980 firstItem.context.parent = this;
3981 this.valueRange = PlainValueEc8e588e.Range.copy(firstItem.valueRange);
3982 const indent = firstItem.range.start - firstItem.context.lineStart;
3984 offset = PlainValueEc8e588e.Node.normalizeOffset(src, offset);
3985 let ch = src[offset];
3986 let atLineStart = PlainValueEc8e588e.Node.endOfWhiteSpace(src, lineStart) === offset;
3987 let prevIncludesTrailingLines = false;
3990 while (ch === '\n' || ch === '#') {
3991 if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) {
3992 const blankLine = new BlankLine();
3993 offset = blankLine.parse({
3996 this.valueRange.end = offset;
3998 if (offset >= src.length) {
4003 this.items.push(blankLine);
4004 offset -= 1; // blankLine.parse() consumes terminal newline
4005 } else if (ch === '#') {
4006 if (offset < lineStart + indent && !Collection.nextContentHasIndent(src, offset, indent)) {
4010 const comment = new Comment();
4011 offset = comment.parse({
4016 this.items.push(comment);
4017 this.valueRange.end = offset;
4019 if (offset >= src.length) {
4025 lineStart = offset + 1;
4026 offset = PlainValueEc8e588e.Node.endOfIndent(src, lineStart);
4028 if (PlainValueEc8e588e.Node.atBlank(src, offset)) {
4029 const wsEnd = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4030 const next = src[wsEnd];
4032 if (!next || next === '\n' || next === '#') {
4045 if (offset !== lineStart + indent && (atLineStart || ch !== ':')) {
4046 if (offset < lineStart + indent) {
4047 if (lineStart > start) offset = lineStart;
4049 } else if (!this.error) {
4050 const msg = 'All collection items must start at the same column';
4051 this.error = new PlainValueEc8e588e.YAMLSyntaxError(this, msg);
4055 if (firstItem.type === PlainValueEc8e588e.Type.SEQ_ITEM) {
4057 if (lineStart > start) offset = lineStart;
4060 } else if (ch === '-' && !this.error) {
4061 // map key may start with -, as long as it's followed by a non-whitespace char
4062 const next = src[offset + 1];
4064 if (!next || next === '\n' || next === '\t' || next === ' ') {
4065 const msg = 'A collection cannot be both a mapping and a sequence';
4066 this.error = new PlainValueEc8e588e.YAMLSyntaxError(this, msg);
4070 const node = parseNode({
4077 if (!node) return offset; // at next document start
4079 this.items.push(node);
4080 this.valueRange.end = node.valueRange.end;
4081 offset = PlainValueEc8e588e.Node.normalizeOffset(src, node.range.end);
4083 atLineStart = false;
4084 prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range
4085 // has advanced to check the current line's indentation level
4086 // -- eemeli/yaml#10 & eemeli/yaml#38
4089 let ls = offset - 1;
4092 while (prev === ' ' || prev === '\t') prev = src[--ls];
4094 if (prev === '\n') {
4100 const ec = grabCollectionEndComments(node);
4101 if (ec) Array.prototype.push.apply(this.items, ec);
4107 setOrigRanges(cr, offset) {
4108 offset = super.setOrigRanges(cr, offset);
4109 this.items.forEach(node => {
4110 offset = node.setOrigRanges(cr, offset);
4124 if (value != null) return value;
4125 let str = src.slice(range.start, items[0].range.start) + String(items[0]);
4127 for (let i = 1; i < items.length; ++i) {
4128 const item = items[i];
4133 if (atLineStart) for (let i = 0; i < indent; ++i) str += ' ';
4134 str += String(item);
4137 return PlainValueEc8e588e.Node.addStringTerminator(src, range.end, str);
4142 class Directive extends PlainValueEc8e588e.Node {
4144 super(PlainValueEc8e588e.Type.DIRECTIVE);
4149 const raw = this.rawValue;
4150 return raw ? raw.trim().split(/[ \t]+/) : [];
4158 let ch = src[offset];
4160 while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1];
4162 this.name = src.slice(start, offset);
4166 parseParameters(start) {
4171 let ch = src[offset];
4173 while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1];
4175 this.valueRange = new PlainValueEc8e588e.Range(start, offset);
4179 parse(context, start) {
4180 this.context = context;
4181 let offset = this.parseName(start + 1);
4182 offset = this.parseParameters(offset);
4183 offset = this.parseComment(offset);
4184 this.range = new PlainValueEc8e588e.Range(start, offset);
4190 class Document extends PlainValueEc8e588e.Node {
4191 static startCommentOrEndBlankLine(src, start) {
4192 const offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, start);
4193 const ch = src[offset];
4194 return ch === '#' || ch === '\n' ? offset : start;
4198 super(PlainValueEc8e588e.Type.DOCUMENT);
4199 this.directives = null;
4200 this.contents = null;
4201 this.directivesEndMarker = null;
4202 this.documentEndMarker = null;
4205 parseDirectives(start) {
4209 this.directives = [];
4210 let atLineStart = true;
4211 let hasDirectives = false;
4214 while (!PlainValueEc8e588e.Node.atDocumentBoundary(src, offset, PlainValueEc8e588e.Char.DIRECTIVES_END)) {
4215 offset = Document.startCommentOrEndBlankLine(src, offset);
4217 switch (src[offset]) {
4220 const blankLine = new BlankLine();
4221 offset = blankLine.parse({
4225 if (offset < src.length) {
4226 this.directives.push(blankLine);
4237 const comment = new Comment();
4238 offset = comment.parse({
4241 this.directives.push(comment);
4242 atLineStart = false;
4248 const directive = new Directive();
4249 offset = directive.parse({
4253 this.directives.push(directive);
4254 hasDirectives = true;
4255 atLineStart = false;
4260 if (hasDirectives) {
4261 this.error = new PlainValueEc8e588e.YAMLSemanticError(this, 'Missing directives-end indicator line');
4262 } else if (this.directives.length > 0) {
4263 this.contents = this.directives;
4264 this.directives = [];
4272 this.directivesEndMarker = new PlainValueEc8e588e.Range(offset, offset + 3);
4276 if (hasDirectives) {
4277 this.error = new PlainValueEc8e588e.YAMLSemanticError(this, 'Missing directives-end indicator line');
4278 } else if (this.directives.length > 0) {
4279 this.contents = this.directives;
4280 this.directives = [];
4286 parseContents(start) {
4291 if (!this.contents) this.contents = [];
4292 let lineStart = start;
4294 while (src[lineStart - 1] === '-') lineStart -= 1;
4296 let offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, start);
4297 let atLineStart = lineStart === start;
4298 this.valueRange = new PlainValueEc8e588e.Range(offset);
4300 while (!PlainValueEc8e588e.Node.atDocumentBoundary(src, offset, PlainValueEc8e588e.Char.DOCUMENT_END)) {
4301 switch (src[offset]) {
4304 const blankLine = new BlankLine();
4305 offset = blankLine.parse({
4309 if (offset < src.length) {
4310 this.contents.push(blankLine);
4322 const comment = new Comment();
4323 offset = comment.parse({
4326 this.contents.push(comment);
4327 atLineStart = false;
4333 const iEnd = PlainValueEc8e588e.Node.endOfIndent(src, offset);
4338 inCollection: false,
4342 const node = parseNode(context, iEnd);
4343 if (!node) return this.valueRange.end = iEnd; // at next document start
4345 this.contents.push(node);
4346 offset = node.range.end;
4347 atLineStart = false;
4348 const ec = grabCollectionEndComments(node);
4349 if (ec) Array.prototype.push.apply(this.contents, ec);
4353 offset = Document.startCommentOrEndBlankLine(src, offset);
4356 this.valueRange.end = offset;
4359 this.documentEndMarker = new PlainValueEc8e588e.Range(offset, offset + 3);
4363 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4365 if (src[offset] === '#') {
4366 const comment = new Comment();
4367 offset = comment.parse({
4370 this.contents.push(comment);
4373 switch (src[offset]) {
4382 this.error = new PlainValueEc8e588e.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix');
4390 * @param {ParseContext} context
4391 * @param {number} start - Index of first character
4392 * @returns {number} - Index of the character after this
4396 parse(context, start) {
4397 context.root = this;
4398 this.context = context;
4402 let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM
4404 offset = this.parseDirectives(offset);
4405 offset = this.parseContents(offset);
4409 setOrigRanges(cr, offset) {
4410 offset = super.setOrigRanges(cr, offset);
4411 this.directives.forEach(node => {
4412 offset = node.setOrigRanges(cr, offset);
4414 if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset);
4415 this.contents.forEach(node => {
4416 offset = node.setOrigRanges(cr, offset);
4418 if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset);
4428 if (value != null) return value;
4429 let str = directives.join('');
4431 if (contents.length > 0) {
4432 if (directives.length > 0 || contents[0].type === PlainValueEc8e588e.Type.COMMENT) str += '---\n';
4433 str += contents.join('');
4436 if (str[str.length - 1] !== '\n') str += '\n';
4442 class Alias extends PlainValueEc8e588e.Node {
4444 * Parses an *alias from the source
4446 * @param {ParseContext} context
4447 * @param {number} start - Index of first character
4448 * @returns {number} - Index of the character after this scalar
4450 parse(context, start) {
4451 this.context = context;
4455 let offset = PlainValueEc8e588e.Node.endOfIdentifier(src, start + 1);
4456 this.valueRange = new PlainValueEc8e588e.Range(start + 1, offset);
4457 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4458 offset = this.parseComment(offset);
4470 class BlockValue extends PlainValueEc8e588e.Node {
4471 constructor(type, props) {
4473 this.blockIndent = null;
4474 this.chomping = Chomp.CLIP;
4478 get includesTrailingLines() {
4479 return this.chomping === Chomp.KEEP;
4483 if (!this.valueRange || !this.context) return null;
4487 } = this.valueRange;
4492 if (this.valueRange.isEmpty()) return '';
4493 let lastNewLine = null;
4494 let ch = src[end - 1];
4496 while (ch === '\n' || ch === '\t' || ch === ' ') {
4500 if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens
4503 if (ch === '\n') lastNewLine = end;
4507 let keepStart = end + 1;
4510 if (this.chomping === Chomp.KEEP) {
4511 keepStart = lastNewLine;
4512 end = this.valueRange.end;
4518 const bi = indent + this.blockIndent;
4519 const folded = this.type === PlainValueEc8e588e.Type.BLOCK_FOLDED;
4523 let prevMoreIndented = false;
4525 for (let i = start; i < end; ++i) {
4526 for (let j = 0; j < bi; ++j) {
4527 if (src[i] !== ' ') break;
4534 if (sep === '\n') str += '\n';else sep = '\n';
4536 const lineEnd = PlainValueEc8e588e.Node.endOfLine(src, i);
4537 const line = src.slice(i, lineEnd);
4540 if (folded && (ch === ' ' || ch === '\t') && i < keepStart) {
4541 if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n';
4542 str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '')
4544 sep = lineEnd < end && src[lineEnd] || '';
4545 prevMoreIndented = true;
4548 sep = folded && i < keepStart ? ' ' : '\n';
4549 prevMoreIndented = false;
4552 if (atStart && line !== '') atStart = false;
4556 return this.chomping === Chomp.STRIP ? str : str + '\n';
4559 parseBlockHeader(start) {
4563 let offset = start + 1;
4567 const ch = src[offset];
4571 this.chomping = Chomp.STRIP;
4575 this.chomping = Chomp.KEEP;
4592 this.blockIndent = Number(bi) || null;
4593 this.header = new PlainValueEc8e588e.Range(start, offset);
4601 parseBlockValue(start) {
4606 const explicit = !!this.blockIndent;
4608 let valueEnd = start;
4609 let minBlockIndent = 1;
4611 for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
4613 if (PlainValueEc8e588e.Node.atDocumentBoundary(src, offset)) break;
4614 const end = PlainValueEc8e588e.Node.endOfBlockIndent(src, indent, offset); // should not include tab?
4616 if (end === null) break;
4617 const ch = src[end];
4618 const lineIndent = end - (offset + indent);
4620 if (!this.blockIndent) {
4621 // no explicit block indent, none yet detected
4622 if (src[end] !== '\n') {
4623 // first line with non-whitespace content
4624 if (lineIndent < minBlockIndent) {
4625 const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
4626 this.error = new PlainValueEc8e588e.YAMLSemanticError(this, msg);
4629 this.blockIndent = lineIndent;
4630 } else if (lineIndent > minBlockIndent) {
4631 // empty line with more whitespace
4632 minBlockIndent = lineIndent;
4634 } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) {
4635 if (src[end] === '#') break;
4638 const src = explicit ? 'explicit indentation indicator' : 'first line';
4639 const msg = `Block scalars must not be less indented than their ${src}`;
4640 this.error = new PlainValueEc8e588e.YAMLSemanticError(this, msg);
4644 if (src[end] === '\n') {
4647 offset = valueEnd = PlainValueEc8e588e.Node.endOfLine(src, end);
4651 if (this.chomping !== Chomp.KEEP) {
4652 offset = src[valueEnd] ? valueEnd + 1 : valueEnd;
4655 this.valueRange = new PlainValueEc8e588e.Range(start + 1, offset);
4659 * Parses a block value from the source
4661 * Accepted forms are:
4671 * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines
4672 * are empty or have an indent level greater than `indent`.
4674 * @param {ParseContext} context
4675 * @param {number} start - Index of first character
4676 * @returns {number} - Index of the character after this block
4680 parse(context, start) {
4681 this.context = context;
4685 let offset = this.parseBlockHeader(start);
4686 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4687 offset = this.parseComment(offset);
4688 offset = this.parseBlockValue(offset);
4692 setOrigRanges(cr, offset) {
4693 offset = super.setOrigRanges(cr, offset);
4694 return this.header ? this.header.setOrigRange(cr, offset) : offset;
4699 class FlowCollection extends PlainValueEc8e588e.Node {
4700 constructor(type, props) {
4705 prevNodeIsJsonLike(idx = this.items.length) {
4706 const node = this.items[idx - 1];
4707 return !!node && (node.jsonLike || node.type === PlainValueEc8e588e.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1));
4710 * @param {ParseContext} context
4711 * @param {number} start - Index of first character
4712 * @returns {number} - Index of the character after this
4716 parse(context, start) {
4717 this.context = context;
4726 let char = src[start]; // { or [
4732 let offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, start + 1);
4735 while (char && char !== ']' && char !== '}') {
4739 lineStart = offset + 1;
4740 const wsEnd = PlainValueEc8e588e.Node.endOfWhiteSpace(src, lineStart);
4742 if (src[wsEnd] === '\n') {
4743 const blankLine = new BlankLine();
4744 lineStart = blankLine.parse({
4747 this.items.push(blankLine);
4750 offset = PlainValueEc8e588e.Node.endOfIndent(src, lineStart);
4752 if (offset <= lineStart + indent) {
4755 if (offset < lineStart + indent || char !== ']' && char !== '}') {
4756 const msg = 'Insufficient indentation in flow collection';
4757 this.error = new PlainValueEc8e588e.YAMLSemanticError(this, msg);
4775 const comment = new Comment();
4776 offset = comment.parse({
4779 this.items.push(comment);
4786 const next = src[offset + 1];
4788 if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace
4789 char === ':' && this.prevNodeIsJsonLike()) {
4802 const node = parseNode({
4804 inCollection: false,
4812 // at next document start
4813 this.valueRange = new PlainValueEc8e588e.Range(start, offset);
4817 this.items.push(node);
4818 offset = PlainValueEc8e588e.Node.normalizeOffset(src, node.range.end);
4822 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
4826 this.valueRange = new PlainValueEc8e588e.Range(start, offset + 1);
4833 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset + 1);
4834 offset = this.parseComment(offset);
4840 setOrigRanges(cr, offset) {
4841 offset = super.setOrigRanges(cr, offset);
4842 this.items.forEach(node => {
4843 if (node instanceof PlainValueEc8e588e.Node) {
4844 offset = node.setOrigRanges(cr, offset);
4845 } else if (cr.length === 0) {
4846 node.origOffset = node.offset;
4850 while (i < cr.length) {
4851 if (cr[i] > node.offset) break;else ++i;
4854 node.origOffset = node.offset + i;
4870 if (value != null) return value;
4871 const nodes = items.filter(item => item instanceof PlainValueEc8e588e.Node);
4873 let prevEnd = range.start;
4874 nodes.forEach(node => {
4875 const prefix = src.slice(prevEnd, node.range.start);
4876 prevEnd = node.range.end;
4877 str += prefix + String(node);
4879 if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') {
4880 // Comment range does not include the terminal newline, but its
4881 // stringified value does. Without this fix, newlines at comment ends
4886 str += src.slice(prevEnd, range.end);
4887 return PlainValueEc8e588e.Node.addStringTerminator(src, range.end, str);
4892 class QuoteDouble extends PlainValueEc8e588e.Node {
4893 static endOfQuote(src, offset) {
4894 let ch = src[offset];
4896 while (ch && ch !== '"') {
4897 offset += ch === '\\' ? 2 : 1;
4904 * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
4909 if (!this.valueRange || !this.context) return null;
4914 } = this.valueRange;
4919 if (src[end - 1] !== '"') errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by
4920 // escaped backslashes; also, this should be faster.
4924 for (let i = start + 1; i < end - 1; ++i) {
4928 if (PlainValueEc8e588e.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValueEc8e588e.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
4933 } = PlainValueEc8e588e.Node.foldNewline(src, i, indent);
4936 if (error) errors.push(new PlainValueEc8e588e.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented'));
4937 } else if (ch === '\\') {
4989 // Unicode next line
4994 // Unicode non-breaking space
4999 // Unicode line separator
5004 // Unicode paragraph separator
5027 str += this.parseCharCode(i + 1, 2, errors);
5032 str += this.parseCharCode(i + 1, 4, errors);
5037 str += this.parseCharCode(i + 1, 8, errors);
5042 // skip escaped newlines, but still trim the following line
5043 while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1;
5048 errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`));
5049 str += '\\' + src[i];
5051 } else if (ch === ' ' || ch === '\t') {
5052 // trim trailing whitespace
5054 let next = src[i + 1];
5056 while (next === ' ' || next === '\t') {
5061 if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
5067 return errors.length > 0 ? {
5073 parseCharCode(offset, length, errors) {
5077 const cc = src.substr(offset, length);
5078 const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
5079 const code = ok ? parseInt(cc, 16) : NaN;
5082 errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`));
5083 return src.substr(offset - 2, length + 2);
5086 return String.fromCodePoint(code);
5089 * Parses a "double quoted" value from the source
5091 * @param {ParseContext} context
5092 * @param {number} start - Index of first character
5093 * @returns {number} - Index of the character after this scalar
5097 parse(context, start) {
5098 this.context = context;
5102 let offset = QuoteDouble.endOfQuote(src, start + 1);
5103 this.valueRange = new PlainValueEc8e588e.Range(start, offset);
5104 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
5105 offset = this.parseComment(offset);
5111 class QuoteSingle extends PlainValueEc8e588e.Node {
5112 static endOfQuote(src, offset) {
5113 let ch = src[offset];
5117 if (src[offset + 1] !== "'") break;
5118 ch = src[offset += 2];
5120 ch = src[offset += 1];
5127 * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
5132 if (!this.valueRange || !this.context) return null;
5137 } = this.valueRange;
5142 if (src[end - 1] !== "'") errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, "Missing closing 'quote"));
5145 for (let i = start + 1; i < end - 1; ++i) {
5149 if (PlainValueEc8e588e.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValueEc8e588e.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
5154 } = PlainValueEc8e588e.Node.foldNewline(src, i, indent);
5157 if (error) errors.push(new PlainValueEc8e588e.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented'));
5158 } else if (ch === "'") {
5161 if (src[i] !== "'") errors.push(new PlainValueEc8e588e.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.'));
5162 } else if (ch === ' ' || ch === '\t') {
5163 // trim trailing whitespace
5165 let next = src[i + 1];
5167 while (next === ' ' || next === '\t') {
5172 if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
5178 return errors.length > 0 ? {
5184 * Parses a 'single quoted' value from the source
5186 * @param {ParseContext} context
5187 * @param {number} start - Index of first character
5188 * @returns {number} - Index of the character after this scalar
5192 parse(context, start) {
5193 this.context = context;
5197 let offset = QuoteSingle.endOfQuote(src, start + 1);
5198 this.valueRange = new PlainValueEc8e588e.Range(start, offset);
5199 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
5200 offset = this.parseComment(offset);
5206 function createNewNode(type, props) {
5208 case PlainValueEc8e588e.Type.ALIAS:
5209 return new Alias(type, props);
5211 case PlainValueEc8e588e.Type.BLOCK_FOLDED:
5212 case PlainValueEc8e588e.Type.BLOCK_LITERAL:
5213 return new BlockValue(type, props);
5215 case PlainValueEc8e588e.Type.FLOW_MAP:
5216 case PlainValueEc8e588e.Type.FLOW_SEQ:
5217 return new FlowCollection(type, props);
5219 case PlainValueEc8e588e.Type.MAP_KEY:
5220 case PlainValueEc8e588e.Type.MAP_VALUE:
5221 case PlainValueEc8e588e.Type.SEQ_ITEM:
5222 return new CollectionItem(type, props);
5224 case PlainValueEc8e588e.Type.COMMENT:
5225 case PlainValueEc8e588e.Type.PLAIN:
5226 return new PlainValueEc8e588e.PlainValue(type, props);
5228 case PlainValueEc8e588e.Type.QUOTE_DOUBLE:
5229 return new QuoteDouble(type, props);
5231 case PlainValueEc8e588e.Type.QUOTE_SINGLE:
5232 return new QuoteSingle(type, props);
5234 /* istanbul ignore next */
5238 // should never happen
5242 * @param {boolean} atLineStart - Node starts at beginning of line
5243 * @param {boolean} inFlow - true if currently in a flow context
5244 * @param {boolean} inCollection - true if currently in a collection context
5245 * @param {number} indent - Current level of indentation
5246 * @param {number} lineStart - Start of the current line
5247 * @param {Node} parent - The parent of the node
5248 * @param {string} src - Source of the YAML document
5252 class ParseContext {
5253 static parseType(src, offset, inFlow) {
5254 switch (src[offset]) {
5256 return PlainValueEc8e588e.Type.ALIAS;
5259 return PlainValueEc8e588e.Type.BLOCK_FOLDED;
5262 return PlainValueEc8e588e.Type.BLOCK_LITERAL;
5265 return PlainValueEc8e588e.Type.FLOW_MAP;
5268 return PlainValueEc8e588e.Type.FLOW_SEQ;
5271 return !inFlow && PlainValueEc8e588e.Node.atBlank(src, offset + 1, true) ? PlainValueEc8e588e.Type.MAP_KEY : PlainValueEc8e588e.Type.PLAIN;
5274 return !inFlow && PlainValueEc8e588e.Node.atBlank(src, offset + 1, true) ? PlainValueEc8e588e.Type.MAP_VALUE : PlainValueEc8e588e.Type.PLAIN;
5277 return !inFlow && PlainValueEc8e588e.Node.atBlank(src, offset + 1, true) ? PlainValueEc8e588e.Type.SEQ_ITEM : PlainValueEc8e588e.Type.PLAIN;
5280 return PlainValueEc8e588e.Type.QUOTE_DOUBLE;
5283 return PlainValueEc8e588e.Type.QUOTE_SINGLE;
5286 return PlainValueEc8e588e.Type.PLAIN;
5290 constructor(orig = {}, {
5298 PlainValueEc8e588e._defineProperty(this, "parseNode", (overlay, start) => {
5299 if (PlainValueEc8e588e.Node.atDocumentBoundary(this.src, start)) return null;
5300 const context = new ParseContext(this, overlay);
5305 } = context.parseProps(start);
5306 const node = createNewNode(type, props);
5307 let offset = node.parse(context, valueStart);
5308 node.range = new PlainValueEc8e588e.Range(start, offset);
5309 /* istanbul ignore if */
5311 if (offset <= start) {
5312 // This should never happen, but if it does, let's make sure to at least
5313 // step one character forward to avoid a busy loop.
5314 node.error = new Error(`Node#parse consumed no characters`);
5315 node.error.parseEnd = offset;
5316 node.error.source = node;
5317 node.range.end = start + 1;
5320 if (context.nodeStartsCollection(node)) {
5321 if (!node.error && !context.atLineStart && context.parent.type === PlainValueEc8e588e.Type.DOCUMENT) {
5322 node.error = new PlainValueEc8e588e.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)');
5325 const collection = new Collection(node);
5326 offset = collection.parse(new ParseContext(context), offset);
5327 collection.range = new PlainValueEc8e588e.Range(start, offset);
5334 this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false;
5335 this.inCollection = inCollection != null ? inCollection : orig.inCollection || false;
5336 this.inFlow = inFlow != null ? inFlow : orig.inFlow || false;
5337 this.indent = indent != null ? indent : orig.indent;
5338 this.lineStart = lineStart != null ? lineStart : orig.lineStart;
5339 this.parent = parent != null ? parent : orig.parent || {};
5340 this.root = orig.root;
5341 this.src = orig.src;
5344 nodeStartsCollection(node) {
5350 if (inCollection || inFlow) return false;
5351 if (node instanceof CollectionItem) return true; // check for implicit key
5353 let offset = node.range.end;
5354 if (src[offset] === '\n' || src[offset - 1] === '\n') return false;
5355 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
5356 return src[offset] === ':';
5357 } // Anchor and tag are before type, which determines the node implementation
5358 // class; hence this intermediate step.
5361 parseProps(offset) {
5368 let lineHasProps = false;
5369 offset = this.atLineStart ? PlainValueEc8e588e.Node.endOfIndent(src, offset) : PlainValueEc8e588e.Node.endOfWhiteSpace(src, offset);
5370 let ch = src[offset];
5372 while (ch === PlainValueEc8e588e.Char.ANCHOR || ch === PlainValueEc8e588e.Char.COMMENT || ch === PlainValueEc8e588e.Char.TAG || ch === '\n') {
5374 const lineStart = offset + 1;
5375 const inEnd = PlainValueEc8e588e.Node.endOfIndent(src, lineStart);
5376 const indentDiff = inEnd - (lineStart + this.indent);
5377 const noIndicatorAsIndent = parent.type === PlainValueEc8e588e.Type.SEQ_ITEM && parent.context.atLineStart;
5378 if (!PlainValueEc8e588e.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break;
5379 this.atLineStart = true;
5380 this.lineStart = lineStart;
5381 lineHasProps = false;
5383 } else if (ch === PlainValueEc8e588e.Char.COMMENT) {
5384 const end = PlainValueEc8e588e.Node.endOfLine(src, offset + 1);
5385 props.push(new PlainValueEc8e588e.Range(offset, end));
5388 let end = PlainValueEc8e588e.Node.endOfIdentifier(src, offset + 1);
5390 if (ch === PlainValueEc8e588e.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) {
5391 // Let's presume we're dealing with a YAML 1.0 domain tag here, rather
5392 // than an empty but 'foo.bar' private-tagged node in a flow collection
5393 // followed without whitespace by a plain string starting with a year
5394 // or date divided by something.
5395 end = PlainValueEc8e588e.Node.endOfIdentifier(src, end + 5);
5398 props.push(new PlainValueEc8e588e.Range(offset, end));
5399 lineHasProps = true;
5400 offset = PlainValueEc8e588e.Node.endOfWhiteSpace(src, end);
5404 } // '- &a : b' has an anchor on an empty node
5407 if (lineHasProps && ch === ':' && PlainValueEc8e588e.Node.atBlank(src, offset + 1, true)) offset -= 1;
5408 const type = ParseContext.parseType(src, offset, inFlow);
5416 * Parses a node from the source
5417 * @param {ParseContext} overlay
5418 * @param {number} start - Index of first non-whitespace character for the node
5419 * @returns {?Node} - null if at a document boundary
5423 } // Published as 'yaml/parse-cst'
5426 function parse(src) {
5429 if (src.indexOf('\r') !== -1) {
5430 src = src.replace(/\r\n?/g, (match, offset) => {
5431 if (match.length > 1) cr.push(offset);
5436 const documents = [];
5440 const doc = new Document();
5441 const context = new ParseContext({
5444 offset = doc.parse(context, offset);
5445 documents.push(doc);
5446 } while (offset < src.length);
5448 documents.setOrigRanges = () => {
5449 if (cr.length === 0) return false;
5451 for (let i = 1; i < cr.length; ++i) cr[i] -= i;
5455 for (let i = 0; i < documents.length; ++i) {
5456 crOffset = documents[i].setOrigRanges(cr, crOffset);
5459 cr.splice(0, cr.length);
5463 documents.toString = () => documents.join('...\n');
5468 var parse_1 = parse;
5473 function addCommentBefore(str, indent, comment) {
5474 if (!comment) return str;
5475 const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`);
5476 return `#${cc}\n${indent}${str}`;
5479 function addComment(str, indent, comment) {
5480 return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`);
5485 function toJSON(value, arg, ctx) {
5486 if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx));
5488 if (value && typeof value.toJSON === 'function') {
5489 const anchor = ctx && ctx.anchors && ctx.anchors.get(value);
5490 if (anchor) ctx.onCreate = res => {
5492 delete ctx.onCreate;
5494 const res = value.toJSON(arg, ctx);
5495 if (anchor && ctx.onCreate) ctx.onCreate(res);
5499 if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value);
5503 class Scalar extends Node$1 {
5504 constructor(value) {
5510 return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx);
5514 return String(this.value);
5519 function collectionFromPath(schema, path, value) {
5522 for (let i = path.length - 1; i >= 0; --i) {
5524 const o = Number.isInteger(k) && k >= 0 ? [] : {};
5529 return schema.createNode(v, false);
5530 } // null, undefined, or an empty non-string iterable (e.g. [])
5533 const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done;
5535 class Collection$1 extends Node$1 {
5536 constructor(schema) {
5539 PlainValueEc8e588e._defineProperty(this, "items", []);
5541 this.schema = schema;
5544 addIn(path, value) {
5545 if (isEmptyPath(path)) this.add(value);else {
5546 const [key, ...rest] = path;
5547 const node = this.get(key, true);
5548 if (node instanceof Collection$1) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
5552 deleteIn([key, ...rest]) {
5553 if (rest.length === 0) return this.delete(key);
5554 const node = this.get(key, true);
5555 if (node instanceof Collection$1) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
5558 getIn([key, ...rest], keepScalar) {
5559 const node = this.get(key, true);
5560 if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection$1 ? node.getIn(rest, keepScalar) : undefined;
5563 hasAllNullValues() {
5564 return this.items.every(node => {
5565 if (!node || node.type !== 'PAIR') return false;
5566 const n = node.value;
5567 return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag;
5571 hasIn([key, ...rest]) {
5572 if (rest.length === 0) return this.has(key);
5573 const node = this.get(key, true);
5574 return node instanceof Collection$1 ? node.hasIn(rest) : false;
5577 setIn([key, ...rest], value) {
5578 if (rest.length === 0) {
5579 this.set(key, value);
5581 const node = this.get(key, true);
5582 if (node instanceof Collection$1) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
5584 } // overridden in implementations
5586 /* istanbul ignore next */
5598 }, onComment, onChompKeep) {
5604 const inFlow = this.type === PlainValueEc8e588e.Type.FLOW_MAP || this.type === PlainValueEc8e588e.Type.FLOW_SEQ || ctx.inFlow;
5605 if (inFlow) itemIndent += indentStep;
5606 const allNullValues = isMap && this.hasAllNullValues();
5607 ctx = Object.assign({}, ctx, {
5613 let chompKeep = false;
5614 let hasItemWithNewLine = false;
5615 const nodes = this.items.reduce((nodes, item, i) => {
5619 if (!chompKeep && item.spaceBefore) nodes.push({
5623 if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => {
5629 if (item.comment) comment = item.comment;
5630 if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true;
5634 let str = stringify(item, ctx, () => comment = null, () => chompKeep = true);
5635 if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true;
5636 if (inFlow && i < this.items.length - 1) str += ',';
5637 str = addComment(str, itemIndent, comment);
5638 if (chompKeep && (comment || inFlow)) chompKeep = false;
5647 if (nodes.length === 0) {
5648 str = flowChars.start + flowChars.end;
5649 } else if (inFlow) {
5654 const strings = nodes.map(n => n.str);
5656 if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection$1.maxFlowStringSingleLineLength) {
5659 for (const s of strings) {
5660 str += s ? `\n${indentStep}${indent}${s}` : '\n';
5663 str += `\n${indent}${end}`;
5665 str = `${start} ${strings.join(' ')} ${end}`;
5668 const strings = nodes.map(blockItem);
5669 str = strings.shift();
5671 for (const s of strings) str += s ? `\n${indent}${s}` : '\n';
5675 str += '\n' + this.comment.replace(/^/gm, `${indent}#`);
5676 if (onComment) onComment();
5677 } else if (chompKeep && onChompKeep) onChompKeep();
5684 PlainValueEc8e588e._defineProperty(Collection$1, "maxFlowStringSingleLineLength", 60);
5686 function asItemIndex(key) {
5687 let idx = key instanceof Scalar ? key.value : key;
5688 if (idx && typeof idx === 'string') idx = Number(idx);
5689 return Number.isInteger(idx) && idx >= 0 ? idx : null;
5692 class YAMLSeq extends Collection$1 {
5694 this.items.push(value);
5698 const idx = asItemIndex(key);
5699 if (typeof idx !== 'number') return false;
5700 const del = this.items.splice(idx, 1);
5701 return del.length > 0;
5704 get(key, keepScalar) {
5705 const idx = asItemIndex(key);
5706 if (typeof idx !== 'number') return undefined;
5707 const it = this.items[idx];
5708 return !keepScalar && it instanceof Scalar ? it.value : it;
5712 const idx = asItemIndex(key);
5713 return typeof idx === 'number' && idx < this.items.length;
5717 const idx = asItemIndex(key);
5718 if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`);
5719 this.items[idx] = value;
5724 if (ctx && ctx.onCreate) ctx.onCreate(seq);
5727 for (const item of this.items) seq.push(toJSON(item, String(i++), ctx));
5732 toString(ctx, onComment, onChompKeep) {
5733 if (!ctx) return JSON.stringify(this);
5734 return super.toString(ctx, {
5735 blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`,
5741 itemIndent: (ctx.indent || '') + ' '
5742 }, onComment, onChompKeep);
5747 const stringifyKey = (key, jsKey, ctx) => {
5748 if (jsKey === null) return '';
5749 if (typeof jsKey !== 'object') return String(jsKey);
5750 if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({
5754 indentStep: ctx.indentStep,
5756 inStringifyKey: true,
5757 stringify: ctx.stringify
5759 return JSON.stringify(jsKey);
5762 class Pair extends Node$1 {
5763 constructor(key, value = null) {
5767 this.type = Pair.Type.PAIR;
5770 get commentBefore() {
5771 return this.key instanceof Node$1 ? this.key.commentBefore : undefined;
5774 set commentBefore(cb) {
5775 if (this.key == null) this.key = new Scalar(null);
5776 if (this.key instanceof Node$1) this.key.commentBefore = cb;else {
5777 const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.';
5778 throw new Error(msg);
5782 addToJSMap(ctx, map) {
5783 const key = toJSON(this.key, '', ctx);
5785 if (map instanceof Map) {
5786 const value = toJSON(this.value, key, ctx);
5787 map.set(key, value);
5788 } else if (map instanceof Set) {
5791 const stringKey = stringifyKey(this.key, key, ctx);
5792 map[stringKey] = toJSON(this.value, stringKey, ctx);
5799 const pair = ctx && ctx.mapAsMap ? new Map() : {};
5800 return this.addToJSMap(ctx, pair);
5803 toString(ctx, onComment, onChompKeep) {
5804 if (!ctx || !ctx.doc) return JSON.stringify(this);
5809 } = ctx.doc.options;
5814 let keyComment = key instanceof Node$1 && key.comment;
5818 throw new Error('With simple keys, key nodes cannot have comments');
5821 if (key instanceof Collection$1) {
5822 const msg = 'With simple keys, collection cannot be used as a key value';
5823 throw new Error(msg);
5827 const explicitKey = !simpleKeys && (!key || keyComment || key instanceof Collection$1 || key.type === PlainValueEc8e588e.Type.BLOCK_FOLDED || key.type === PlainValueEc8e588e.Type.BLOCK_LITERAL);
5834 ctx = Object.assign({}, ctx, {
5835 implicitKey: !explicitKey,
5836 indent: indent + indentStep
5838 let chompKeep = false;
5839 let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true);
5840 str = addComment(str, ctx.indent, keyComment);
5842 if (ctx.allNullValues && !simpleKeys) {
5844 str = addComment(str, ctx.indent, this.comment);
5845 if (onComment) onComment();
5846 } else if (chompKeep && !keyComment && onChompKeep) onChompKeep();
5848 return ctx.inFlow ? str : `? ${str}`;
5851 str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`;
5854 // expected (but not strictly required) to be a single-line comment
5855 str = addComment(str, ctx.indent, this.comment);
5856 if (onComment) onComment();
5860 let valueComment = null;
5862 if (value instanceof Node$1) {
5863 if (value.spaceBefore) vcb = '\n';
5865 if (value.commentBefore) {
5866 const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`);
5870 valueComment = value.comment;
5871 } else if (value && typeof value === 'object') {
5872 value = doc.schema.createNode(value, true);
5875 ctx.implicitKey = false;
5876 if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1;
5879 if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValueEc8e588e.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) {
5880 // If indentSeq === false, consider '- ' as part of indentation where possible
5881 ctx.indent = ctx.indent.substr(2);
5884 const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true);
5887 if (vcb || this.comment) {
5888 ws = `${vcb}\n${ctx.indent}`;
5889 } else if (!explicitKey && value instanceof Collection$1) {
5890 const flow = valueStr[0] === '[' || valueStr[0] === '{';
5891 if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`;
5894 if (chompKeep && !valueComment && onChompKeep) onChompKeep();
5895 return addComment(str + ws + valueStr, ctx.indent, valueComment);
5900 PlainValueEc8e588e._defineProperty(Pair, "Type", {
5902 MERGE_PAIR: 'MERGE_PAIR'
5905 const getAliasCount = (node, anchors) => {
5906 if (node instanceof Alias$1) {
5907 const anchor = anchors.get(node.source);
5908 return anchor.count * anchor.aliasCount;
5909 } else if (node instanceof Collection$1) {
5912 for (const item of node.items) {
5913 const c = getAliasCount(item, anchors);
5914 if (c > count) count = c;
5918 } else if (node instanceof Pair) {
5919 const kc = getAliasCount(node.key, anchors);
5920 const vc = getAliasCount(node.value, anchors);
5921 return Math.max(kc, vc);
5927 class Alias$1 extends Node$1 {
5937 let anchor = Object.keys(anchors).find(a => anchors[a] === source);
5938 if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName();
5939 if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`;
5940 const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node';
5941 throw new Error(`${msg} [${range}]`);
5944 constructor(source) {
5946 this.source = source;
5947 this.type = PlainValueEc8e588e.Type.ALIAS;
5951 throw new Error('Alias nodes cannot have tags');
5955 if (!ctx) return toJSON(this.source, arg, ctx);
5960 const anchor = anchors.get(this.source);
5961 /* istanbul ignore if */
5963 if (!anchor || anchor.res === undefined) {
5964 const msg = 'This should not happen: Alias anchor was not resolved?';
5965 if (this.cstNode) throw new PlainValueEc8e588e.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
5968 if (maxAliasCount >= 0) {
5970 if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors);
5972 if (anchor.count * anchor.aliasCount > maxAliasCount) {
5973 const msg = 'Excessive alias count indicates a resource exhaustion attack';
5974 if (this.cstNode) throw new PlainValueEc8e588e.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
5979 } // Only called when stringifying an alias mapping key while constructing
5984 return Alias$1.stringify(this, ctx);
5989 PlainValueEc8e588e._defineProperty(Alias$1, "default", true);
5991 function findPair(items, key) {
5992 const k = key instanceof Scalar ? key.value : key;
5994 for (const it of items) {
5995 if (it instanceof Pair) {
5996 if (it.key === key || it.key === k) return it;
5997 if (it.key && it.key.value === k) return it;
6004 class YAMLMap extends Collection$1 {
6005 add(pair, overwrite) {
6006 if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value);
6007 const prev = findPair(this.items, pair.key);
6008 const sortEntries = this.schema && this.schema.sortMapEntries;
6011 if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`);
6012 } else if (sortEntries) {
6013 const i = this.items.findIndex(item => sortEntries(pair, item) < 0);
6014 if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair);
6016 this.items.push(pair);
6021 const it = findPair(this.items, key);
6022 if (!it) return false;
6023 const del = this.items.splice(this.items.indexOf(it), 1);
6024 return del.length > 0;
6027 get(key, keepScalar) {
6028 const it = findPair(this.items, key);
6029 const node = it && it.value;
6030 return !keepScalar && node instanceof Scalar ? node.value : node;
6034 return !!findPair(this.items, key);
6038 this.add(new Pair(key, value), true);
6041 * @param {*} arg ignored
6042 * @param {*} ctx Conversion context, originally set in Document#toJSON()
6043 * @param {Class} Type If set, forces the returned collection type
6044 * @returns {*} Instance of Type, Map, or Object
6048 toJSON(_, ctx, Type) {
6049 const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {};
6050 if (ctx && ctx.onCreate) ctx.onCreate(map);
6052 for (const item of this.items) item.addToJSMap(ctx, map);
6057 toString(ctx, onComment, onChompKeep) {
6058 if (!ctx) return JSON.stringify(this);
6060 for (const item of this.items) {
6061 if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
6064 return super.toString(ctx, {
6065 blockItem: n => n.str,
6071 itemIndent: ctx.indent || ''
6072 }, onComment, onChompKeep);
6077 const MERGE_KEY = '<<';
6079 class Merge extends Pair {
6081 if (pair instanceof Pair) {
6082 let seq = pair.value;
6084 if (!(seq instanceof YAMLSeq)) {
6085 seq = new YAMLSeq();
6086 seq.items.push(pair.value);
6087 seq.range = pair.value.range;
6090 super(pair.key, seq);
6091 this.range = pair.range;
6093 super(new Scalar(MERGE_KEY), new YAMLSeq());
6096 this.type = Pair.Type.MERGE_PAIR;
6097 } // If the value associated with a merge key is a single mapping node, each of
6098 // its key/value pairs is inserted into the current mapping, unless the key
6099 // already exists in it. If the value associated with the merge key is a
6100 // sequence, then this sequence is expected to contain mapping nodes and each
6101 // of these nodes is merged in turn according to its order in the sequence.
6102 // Keys in mapping nodes earlier in the sequence override keys specified in
6103 // later mapping nodes. -- http://yaml.org/type/merge.html
6106 addToJSMap(ctx, map) {
6109 } of this.value.items) {
6110 if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps');
6111 const srcMap = source.toJSON(null, ctx, Map);
6113 for (const [key, value] of srcMap) {
6114 if (map instanceof Map) {
6115 if (!map.has(key)) map.set(key, value);
6116 } else if (map instanceof Set) {
6119 if (!Object.prototype.hasOwnProperty.call(map, key)) map[key] = value;
6127 toString(ctx, onComment) {
6128 const seq = this.value;
6129 if (seq.items.length > 1) return super.toString(ctx, onComment);
6130 this.value = seq.items[0];
6131 const str = super.toString(ctx, onComment);
6138 const binaryOptions = {
6139 defaultType: PlainValueEc8e588e.Type.BLOCK_LITERAL,
6142 const boolOptions = {
6146 const intOptions = {
6149 const nullOptions = {
6152 const strOptions = {
6153 defaultType: PlainValueEc8e588e.Type.PLAIN,
6155 jsonEncoding: false,
6156 minMultiLineLength: 40
6164 function resolveScalar(str, tags, scalarFallback) {
6171 const match = str.match(test);
6174 let res = resolve.apply(null, match);
6175 if (!(res instanceof Scalar)) res = new Scalar(res);
6176 if (format) res.format = format;
6182 if (scalarFallback) str = scalarFallback(str);
6183 return new Scalar(str);
6186 const FOLD_FLOW = 'flow';
6187 const FOLD_BLOCK = 'block';
6188 const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line
6189 // returns index of last newline in more-indented block
6191 const consumeMoreIndentedLines = (text, i) => {
6192 let ch = text[i + 1];
6194 while (ch === ' ' || ch === '\t') {
6197 } while (ch && ch !== '\n');
6205 * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
6206 * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
6207 * terminated with `\n` and started with `indent`.
6209 * @param {string} text
6210 * @param {string} indent
6211 * @param {string} [mode='flow'] `'block'` prevents more-indented lines
6212 * from being folded; `'quoted'` allows for `\` escapes, including escaped
6214 * @param {Object} options
6215 * @param {number} [options.indentAtStart] Accounts for leading contents on
6216 * the first line, defaulting to `indent.length`
6217 * @param {number} [options.lineWidth=80]
6218 * @param {number} [options.minContentWidth=20] Allow highly indented lines to
6219 * stretch the line width
6220 * @param {function} options.onFold Called once if the text is folded
6221 * @param {function} options.onFold Called once if any line of text exceeds
6222 * lineWidth characters
6226 function foldFlowLines(text, indent, mode, {
6229 minContentWidth = 20,
6233 if (!lineWidth || lineWidth < 0) return text;
6234 const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
6235 if (text.length <= endStep) return text;
6237 const escapedFolds = {};
6238 let end = lineWidth - (typeof indentAtStart === 'number' ? indentAtStart : indent.length);
6239 let split = undefined;
6240 let prev = undefined;
6241 let overflow = false;
6244 if (mode === FOLD_BLOCK) {
6245 i = consumeMoreIndentedLines(text, i);
6246 if (i !== -1) end = i + endStep;
6249 for (let ch; ch = text[i += 1];) {
6250 if (mode === FOLD_QUOTED && ch === '\\') {
6251 switch (text[i + 1]) {
6270 if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i);
6274 if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') {
6275 // space surrounded by non-space can be replaced with newline + indent
6276 const next = text[i + 1];
6277 if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i;
6283 end = split + endStep;
6285 } else if (mode === FOLD_QUOTED) {
6286 // white-space collected at end may stretch past lineWidth
6287 while (prev === ' ' || prev === '\t') {
6291 } // i - 2 accounts for not-dropped last char + newline-escaping \
6295 escapedFolds[i - 2] = true;
6296 end = i - 2 + endStep;
6307 if (overflow && onOverflow) onOverflow();
6308 if (folds.length === 0) return text;
6309 if (onFold) onFold();
6310 let res = text.slice(0, folds[0]);
6312 for (let i = 0; i < folds.length; ++i) {
6313 const fold = folds[i];
6314 const end = folds[i + 1] || text.length;
6315 if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`;
6316 res += `\n${indent}${text.slice(fold + 1, end)}`;
6322 const getFoldOptions = ({
6324 }) => indentAtStart ? Object.assign({
6326 }, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will
6327 // presume that's starting a new document.
6330 const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str);
6332 function lineLengthOverLimit(str, limit) {
6333 const strLen = str.length;
6334 if (strLen <= limit) return false;
6336 for (let i = 0, start = 0; i < strLen; ++i) {
6337 if (str[i] === '\n') {
6338 if (i - start > limit) return true;
6340 if (strLen - start <= limit) return false;
6347 function doubleQuotedString(value, ctx) {
6354 } = strOptions.doubleQuoted;
6355 const json = JSON.stringify(value);
6356 if (jsonEncoding) return json;
6357 const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
6361 for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
6362 if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
6363 // space before newline needs to be escaped to not be folded
6364 str += json.slice(start, i) + '\\ ';
6370 if (ch === '\\') switch (json[i + 1]) {
6373 str += json.slice(start, i);
6374 const code = json.substr(i + 2, 4);
6410 if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6);
6419 if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
6422 // folding will eat first newline
6423 str += json.slice(start, i) + '\n\n';
6425 while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') {
6430 str += indent; // space after newline needs to be escaped to not be folded
6432 if (json[i + 2] === ' ') str += '\\';
6444 str = start ? str + json.slice(start) : json;
6445 return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
6448 function singleQuotedString(value, ctx) {
6449 if (ctx.implicitKey) {
6450 if (/\n/.test(value)) return doubleQuotedString(value, ctx);
6452 // single quoted string can't have leading or trailing whitespace around newline
6453 if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx);
6456 const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
6457 const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
6458 return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
6461 function blockString({
6465 }, ctx, onComment, onChompKeep) {
6466 // 1. Block can't end in whitespace unless the last line is non-empty.
6467 // 2. Strings consisting of only whitespace are best rendered explicitly.
6468 if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
6469 return doubleQuotedString(value, ctx);
6472 const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');
6473 const indentSize = indent ? '2' : '1'; // root is at -1
6475 const literal = type === PlainValueEc8e588e.Type.BLOCK_FOLDED ? false : type === PlainValueEc8e588e.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth - indent.length);
6476 let header = literal ? '|' : '>';
6477 if (!value) return header + '\n';
6480 value = value.replace(/[\n\t ]*$/, ws => {
6481 const n = ws.indexOf('\n');
6484 header += '-'; // strip
6485 } else if (value === ws || n !== ws.length - 1) {
6486 header += '+'; // keep
6488 if (onChompKeep) onChompKeep();
6491 wsEnd = ws.replace(/\n$/, '');
6493 }).replace(/^[\n ]*/, ws => {
6494 if (ws.indexOf(' ') !== -1) header += indentSize;
6495 const m = ws.match(/ +$/);
6498 wsStart = ws.slice(0, -m[0].length);
6505 if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`);
6506 if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`);
6509 header += ' #' + comment.replace(/ ?[\r\n]+/g, ' ');
6510 if (onComment) onComment();
6513 if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`;
6516 value = value.replace(/\n+/g, `$&${indent}`);
6517 return `${header}\n${indent}${wsStart}${value}${wsEnd}`;
6520 value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
6521 // ^ ind.line ^ empty ^ capture next empty lines only at end of indent
6522 .replace(/\n+/g, `$&${indent}`);
6523 const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold);
6524 return `${header}\n${indent}${body}`;
6527 function plainString(item, ctx, onComment, onChompKeep) {
6540 if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) {
6541 return doubleQuotedString(value, ctx);
6544 if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
6546 // - empty string, '-' or '?'
6547 // - start with an indicator character (except [?:-]) or /[?-] /
6548 // - '\n ', ': ' or ' \n' anywhere
6549 // - '#' not preceded by a non-space char
6550 // - end with ' ' or ':'
6551 return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
6554 if (!implicitKey && !inFlow && type !== PlainValueEc8e588e.Type.PLAIN && value.indexOf('\n') !== -1) {
6555 // Where allowed & type not set explicitly, prefer block style for multiline strings
6556 return blockString(item, ctx, onComment, onChompKeep);
6559 if (indent === '' && containsDocumentMarker(value)) {
6560 ctx.forceBlockIndent = true;
6561 return blockString(item, ctx, onComment, onChompKeep);
6564 const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and
6565 // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
6566 // and others in v1.1.
6572 const resolved = resolveScalar(str, tags, tags.scalarFallback).value;
6573 if (typeof resolved !== 'string') return doubleQuotedString(value, ctx);
6576 const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
6578 if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) {
6579 if (onComment) onComment();
6580 return addCommentBefore(body, indent, comment);
6586 function stringifyString(item, ctx, onComment, onChompKeep) {
6599 if (typeof value !== 'string') {
6600 value = String(value);
6601 item = Object.assign({}, item, {
6606 const _stringify = _type => {
6608 case PlainValueEc8e588e.Type.BLOCK_FOLDED:
6609 case PlainValueEc8e588e.Type.BLOCK_LITERAL:
6610 return blockString(item, ctx, onComment, onChompKeep);
6612 case PlainValueEc8e588e.Type.QUOTE_DOUBLE:
6613 return doubleQuotedString(value, ctx);
6615 case PlainValueEc8e588e.Type.QUOTE_SINGLE:
6616 return singleQuotedString(value, ctx);
6618 case PlainValueEc8e588e.Type.PLAIN:
6619 return plainString(item, ctx, onComment, onChompKeep);
6626 if (type !== PlainValueEc8e588e.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) {
6627 // force double quotes on control characters
6628 type = PlainValueEc8e588e.Type.QUOTE_DOUBLE;
6629 } else if ((implicitKey || inFlow) && (type === PlainValueEc8e588e.Type.BLOCK_FOLDED || type === PlainValueEc8e588e.Type.BLOCK_LITERAL)) {
6630 // should not happen; blocks are not valid inside flow containers
6631 type = PlainValueEc8e588e.Type.QUOTE_DOUBLE;
6634 let res = _stringify(type);
6637 res = _stringify(defaultType);
6638 if (res === null) throw new Error(`Unsupported default string type ${defaultType}`);
6644 function stringifyNumber({
6650 if (typeof value === 'bigint') return String(value);
6651 if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf';
6652 let n = JSON.stringify(value);
6654 if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) {
6655 let i = n.indexOf('.');
6662 let d = minFractionDigits - (n.length - i - 1);
6664 while (d-- > 0) n += '0';
6670 function checkFlowCollectionEnd(errors, cst) {
6674 case PlainValueEc8e588e.Type.FLOW_MAP:
6679 case PlainValueEc8e588e.Type.FLOW_SEQ:
6681 name = 'flow sequence';
6685 errors.push(new PlainValueEc8e588e.YAMLSemanticError(cst, 'Not a flow collection!?'));
6691 for (let i = cst.items.length - 1; i >= 0; --i) {
6692 const item = cst.items[i];
6694 if (!item || item.type !== PlainValueEc8e588e.Type.COMMENT) {
6700 if (lastItem && lastItem.char !== char) {
6701 const msg = `Expected ${name} to end with ${char}`;
6704 if (typeof lastItem.offset === 'number') {
6705 err = new PlainValueEc8e588e.YAMLSemanticError(cst, msg);
6706 err.offset = lastItem.offset + 1;
6708 err = new PlainValueEc8e588e.YAMLSemanticError(lastItem, msg);
6709 if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start;
6716 function checkFlowCommentSpace(errors, comment) {
6717 const prev = comment.context.src[comment.range.start - 1];
6719 if (prev !== '\n' && prev !== '\t' && prev !== ' ') {
6720 const msg = 'Comments must be separated from other tokens by white space characters';
6721 errors.push(new PlainValueEc8e588e.YAMLSemanticError(comment, msg));
6725 function getLongKeyError(source, key) {
6726 const sk = String(key);
6727 const k = sk.substr(0, 8) + '...' + sk.substr(-8);
6728 return new PlainValueEc8e588e.YAMLSemanticError(source, `The "${k}" key is too long`);
6731 function resolveComments(collection, comments) {
6737 let item = collection.items[before];
6740 if (comment !== undefined) {
6741 if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment;
6744 if (afterKey && item.value) item = item.value;
6746 if (comment === undefined) {
6747 if (afterKey || !item.commentBefore) item.spaceBefore = true;
6749 if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment;
6753 } // on error, will return { str: string, errors: Error[] }
6756 function resolveString(doc, node) {
6757 const res = node.strValue;
6758 if (!res) return '';
6759 if (typeof res === 'string') return res;
6760 res.errors.forEach(error => {
6761 if (!error.source) error.source = node;
6762 doc.errors.push(error);
6767 function resolveTagHandle(doc, node) {
6772 let prefix = doc.tagPrefixes.find(p => p.handle === handle);
6775 const dtp = doc.getDefaults().tagPrefixes;
6776 if (dtp) prefix = dtp.find(p => p.handle === handle);
6777 if (!prefix) throw new PlainValueEc8e588e.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`);
6780 if (!suffix) throw new PlainValueEc8e588e.YAMLSemanticError(node, `The ${handle} tag has no suffix.`);
6782 if (handle === '!' && (doc.version || doc.options.version) === '1.0') {
6783 if (suffix[0] === '^') {
6784 doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported'));
6788 if (/[:/]/.test(suffix)) {
6789 // word/foo -> tag:word.yaml.org,2002:foo
6790 const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i);
6791 return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`;
6795 return prefix.prefix + decodeURIComponent(suffix);
6798 function resolveTagName(doc, node) {
6803 let nonSpecific = false;
6813 if (verbatim !== '!' && verbatim !== '!!') return verbatim;
6814 const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`;
6815 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
6816 } else if (handle === '!' && !suffix) {
6820 return resolveTagHandle(doc, node);
6822 doc.errors.push(error);
6828 case PlainValueEc8e588e.Type.BLOCK_FOLDED:
6829 case PlainValueEc8e588e.Type.BLOCK_LITERAL:
6830 case PlainValueEc8e588e.Type.QUOTE_DOUBLE:
6831 case PlainValueEc8e588e.Type.QUOTE_SINGLE:
6832 return PlainValueEc8e588e.defaultTags.STR;
6834 case PlainValueEc8e588e.Type.FLOW_MAP:
6835 case PlainValueEc8e588e.Type.MAP:
6836 return PlainValueEc8e588e.defaultTags.MAP;
6838 case PlainValueEc8e588e.Type.FLOW_SEQ:
6839 case PlainValueEc8e588e.Type.SEQ:
6840 return PlainValueEc8e588e.defaultTags.SEQ;
6842 case PlainValueEc8e588e.Type.PLAIN:
6843 return nonSpecific ? PlainValueEc8e588e.defaultTags.STR : null;
6850 function resolveByTagName(doc, node, tagName) {
6854 const matchWithTest = [];
6856 for (const tag of tags) {
6857 if (tag.tag === tagName) {
6858 if (tag.test) matchWithTest.push(tag);else {
6859 const res = tag.resolve(doc, node);
6860 return res instanceof Collection$1 ? res : new Scalar(res);
6865 const str = resolveString(doc, node);
6866 if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback);
6870 function getFallbackTagName({
6874 case PlainValueEc8e588e.Type.FLOW_MAP:
6875 case PlainValueEc8e588e.Type.MAP:
6876 return PlainValueEc8e588e.defaultTags.MAP;
6878 case PlainValueEc8e588e.Type.FLOW_SEQ:
6879 case PlainValueEc8e588e.Type.SEQ:
6880 return PlainValueEc8e588e.defaultTags.SEQ;
6883 return PlainValueEc8e588e.defaultTags.STR;
6887 function resolveTag(doc, node, tagName) {
6889 const res = resolveByTagName(doc, node, tagName);
6892 if (tagName && node.tag) res.tag = tagName;
6896 /* istanbul ignore if */
6897 if (!error.source) error.source = node;
6898 doc.errors.push(error);
6903 const fallback = getFallbackTagName(node);
6904 if (!fallback) throw new Error(`The tag ${tagName} is unavailable`);
6905 const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`;
6906 doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(node, msg));
6907 const res = resolveByTagName(doc, node, fallback);
6911 const refError = new PlainValueEc8e588e.YAMLReferenceError(node, error.message);
6912 refError.stack = error.stack;
6913 doc.errors.push(refError);
6918 const isCollectionItem = node => {
6919 if (!node) return false;
6923 return type === PlainValueEc8e588e.Type.MAP_KEY || type === PlainValueEc8e588e.Type.MAP_VALUE || type === PlainValueEc8e588e.Type.SEQ_ITEM;
6926 function resolveNodeProps(errors, node) {
6931 let hasAnchor = false;
6933 const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props;
6939 switch (node.context.src[start]) {
6940 case PlainValueEc8e588e.Char.COMMENT:
6942 if (!node.commentHasRequiredWhitespace(start)) {
6943 const msg = 'Comments must be separated from other tokens by white space characters';
6944 errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
6951 const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before;
6952 cc.push(node.context.src.slice(start + 1, end));
6955 // Actual anchor & tag resolution is handled by schema, here we just complain
6957 case PlainValueEc8e588e.Char.ANCHOR:
6959 const msg = 'A node can have at most one anchor';
6960 errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
6966 case PlainValueEc8e588e.Char.TAG:
6968 const msg = 'A node can have at most one tag';
6969 errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
6984 function resolveNodeValue(doc, node) {
6991 if (node.type === PlainValueEc8e588e.Type.ALIAS) {
6992 const name = node.rawValue;
6993 const src = anchors.getNode(name);
6996 const msg = `Aliased anchor not found: ${name}`;
6997 errors.push(new PlainValueEc8e588e.YAMLReferenceError(node, msg));
6999 } // Lazy resolution for circular references
7002 const res = new Alias$1(src);
7004 anchors._cstAliases.push(res);
7009 const tagName = resolveTagName(doc, node);
7010 if (tagName) return resolveTag(doc, node, tagName);
7012 if (node.type !== PlainValueEc8e588e.Type.PLAIN) {
7013 const msg = `Failed to resolve ${node.type} node here`;
7014 errors.push(new PlainValueEc8e588e.YAMLSyntaxError(node, msg));
7019 const str = resolveString(doc, node);
7020 return resolveScalar(str, schema.tags, schema.tags.scalarFallback);
7022 if (!error.source) error.source = node;
7026 } // sets node.resolved on success
7029 function resolveNode(doc, node) {
7030 if (!node) return null;
7031 if (node.error) doc.errors.push(node.error);
7036 } = resolveNodeProps(doc.errors, node);
7042 const name = node.anchor;
7043 const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor
7044 // name have already been resolved, so it may safely be renamed.
7046 if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as
7047 // anchors need to be available during resolution to allow for
7048 // circular references.
7050 anchors.map[name] = node;
7053 if (node.type === PlainValueEc8e588e.Type.ALIAS && (hasAnchor || hasTag)) {
7054 const msg = 'An alias node must not specify any properties';
7055 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(node, msg));
7058 const res = resolveNodeValue(doc, node);
7061 res.range = [node.range.start, node.range.end];
7062 if (doc.options.keepCstNodes) res.cstNode = node;
7063 if (doc.options.keepNodeTypes) res.type = node.type;
7064 const cb = comments.before.join('\n');
7067 res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb;
7070 const ca = comments.after.join('\n');
7071 if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca;
7074 return node.resolved = res;
7077 function resolveMap(doc, cst) {
7078 if (cst.type !== PlainValueEc8e588e.Type.MAP && cst.type !== PlainValueEc8e588e.Type.FLOW_MAP) {
7079 const msg = `A ${cst.type} node cannot be resolved as a mapping`;
7080 doc.errors.push(new PlainValueEc8e588e.YAMLSyntaxError(cst, msg));
7087 } = cst.type === PlainValueEc8e588e.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst);
7088 const map = new YAMLMap();
7090 resolveComments(map, comments);
7091 let hasCollectionKey = false;
7093 for (let i = 0; i < items.length; ++i) {
7097 if (iKey instanceof Collection$1) hasCollectionKey = true;
7099 if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) {
7100 items[i] = new Merge(items[i]);
7101 const sources = items[i].value.items;
7103 sources.some(node => {
7104 if (node instanceof Alias$1) {
7105 // During parsing, alias sources are CST nodes; to account for
7106 // circular references their resolved values can't be used here.
7110 if (type === PlainValueEc8e588e.Type.MAP || type === PlainValueEc8e588e.Type.FLOW_MAP) return false;
7111 return error = 'Merge nodes aliases can only point to maps';
7114 return error = 'Merge nodes can only have Alias nodes as values';
7116 if (error) doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(cst, error));
7118 for (let j = i + 1; j < items.length; ++j) {
7123 if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) {
7124 const msg = `Map keys must be unique; "${iKey}" is repeated`;
7125 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(cst, msg));
7132 if (hasCollectionKey && !doc.options.mapAsMap) {
7133 const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
7134 doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(cst, warn));
7141 const valueHasPairComment = ({
7149 if (props.length === 0) return false;
7153 if (node && start > node.valueRange.start) return false;
7154 if (src[start] !== PlainValueEc8e588e.Char.COMMENT) return false;
7156 for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false;
7161 function resolvePairComment(item, pair) {
7162 if (!valueHasPairComment(item)) return;
7163 const comment = item.getPropValue(0, PlainValueEc8e588e.Char.COMMENT, true);
7165 const cb = pair.value.commentBefore;
7167 if (cb && cb.startsWith(comment)) {
7168 pair.value.commentBefore = cb.substr(comment.length + 1);
7171 const cc = pair.value.comment;
7173 if (!item.node && cc && cc.startsWith(comment)) {
7174 pair.value.comment = cc.substr(comment.length + 1);
7179 if (found) pair.comment = comment;
7182 function resolveBlockMapItems(doc, cst) {
7183 const comments = [];
7185 let key = undefined;
7186 let keyStart = null;
7188 for (let i = 0; i < cst.items.length; ++i) {
7189 const item = cst.items[i];
7191 switch (item.type) {
7192 case PlainValueEc8e588e.Type.BLANK_LINE:
7195 before: items.length
7199 case PlainValueEc8e588e.Type.COMMENT:
7202 before: items.length,
7203 comment: item.comment
7207 case PlainValueEc8e588e.Type.MAP_KEY:
7208 if (key !== undefined) items.push(new Pair(key));
7209 if (item.error) doc.errors.push(item.error);
7210 key = resolveNode(doc, item.node);
7214 case PlainValueEc8e588e.Type.MAP_VALUE:
7216 if (key === undefined) key = null;
7217 if (item.error) doc.errors.push(item.error);
7219 if (!item.context.atLineStart && item.node && item.node.type === PlainValueEc8e588e.Type.MAP && !item.node.context.atLineStart) {
7220 const msg = 'Nested mappings are not allowed in compact mappings';
7221 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item.node, msg));
7224 let valueNode = item.node;
7226 if (!valueNode && item.props.length > 0) {
7227 // Comments on an empty mapping value need to be preserved, so we
7228 // need to construct a minimal empty node here to use instead of the
7229 // missing `item.node`. -- eemeli/yaml#19
7230 valueNode = new PlainValueEc8e588e.PlainValue(PlainValueEc8e588e.Type.PLAIN, []);
7231 valueNode.context = {
7233 src: item.context.src
7235 const pos = item.range.start + 1;
7240 valueNode.valueRange = {
7245 if (typeof item.range.origStart === 'number') {
7246 const origPos = item.range.origStart + 1;
7247 valueNode.range.origStart = valueNode.range.origEnd = origPos;
7248 valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos;
7252 const pair = new Pair(key, resolveNode(doc, valueNode));
7253 resolvePairComment(item, pair);
7256 if (key && typeof keyStart === 'number') {
7257 if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
7266 if (key !== undefined) items.push(new Pair(key));
7267 key = resolveNode(doc, item);
7268 keyStart = item.range.start;
7269 if (item.error) doc.errors.push(item.error);
7271 next: for (let j = i + 1;; ++j) {
7272 const nextItem = cst.items[j];
7274 switch (nextItem && nextItem.type) {
7275 case PlainValueEc8e588e.Type.BLANK_LINE:
7276 case PlainValueEc8e588e.Type.COMMENT:
7279 case PlainValueEc8e588e.Type.MAP_VALUE:
7284 const msg = 'Implicit map keys need to be followed by map values';
7285 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, msg));
7291 if (item.valueRangeContainsNewline) {
7292 const msg = 'Implicit map keys need to be on a single line';
7293 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, msg));
7299 if (key !== undefined) items.push(new Pair(key));
7306 function resolveFlowMapItems(doc, cst) {
7307 const comments = [];
7309 let key = undefined;
7310 let explicitKey = false;
7313 for (let i = 0; i < cst.items.length; ++i) {
7314 const item = cst.items[i];
7316 if (typeof item.char === 'string') {
7322 if (char === '?' && key === undefined && !explicitKey) {
7329 if (key === undefined) key = null;
7337 if (key === undefined && char !== ',') key = null;
7338 explicitKey = false;
7341 if (key !== undefined) {
7342 items.push(new Pair(key));
7353 if (i === cst.items.length - 1) continue;
7354 } else if (char === next) {
7359 const msg = `Flow map contains an unexpected ${char}`;
7360 const err = new PlainValueEc8e588e.YAMLSyntaxError(cst, msg);
7361 err.offset = offset;
7362 doc.errors.push(err);
7363 } else if (item.type === PlainValueEc8e588e.Type.BLANK_LINE) {
7366 before: items.length
7368 } else if (item.type === PlainValueEc8e588e.Type.COMMENT) {
7369 checkFlowCommentSpace(doc.errors, item);
7372 before: items.length,
7373 comment: item.comment
7375 } else if (key === undefined) {
7376 if (next === ',') doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, 'Separator , missing in flow map'));
7377 key = resolveNode(doc, item);
7379 if (next !== ',') doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, 'Indicator : missing in flow map entry'));
7380 items.push(new Pair(key, resolveNode(doc, item)));
7382 explicitKey = false;
7386 checkFlowCollectionEnd(doc.errors, cst);
7387 if (key !== undefined) items.push(new Pair(key));
7394 function resolveSeq(doc, cst) {
7395 if (cst.type !== PlainValueEc8e588e.Type.SEQ && cst.type !== PlainValueEc8e588e.Type.FLOW_SEQ) {
7396 const msg = `A ${cst.type} node cannot be resolved as a sequence`;
7397 doc.errors.push(new PlainValueEc8e588e.YAMLSyntaxError(cst, msg));
7404 } = cst.type === PlainValueEc8e588e.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst);
7405 const seq = new YAMLSeq();
7407 resolveComments(seq, comments);
7409 if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection$1)) {
7410 const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
7411 doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(cst, warn));
7418 function resolveBlockSeqItems(doc, cst) {
7419 const comments = [];
7422 for (let i = 0; i < cst.items.length; ++i) {
7423 const item = cst.items[i];
7425 switch (item.type) {
7426 case PlainValueEc8e588e.Type.BLANK_LINE:
7428 before: items.length
7432 case PlainValueEc8e588e.Type.COMMENT:
7434 comment: item.comment,
7435 before: items.length
7439 case PlainValueEc8e588e.Type.SEQ_ITEM:
7440 if (item.error) doc.errors.push(item.error);
7441 items.push(resolveNode(doc, item.node));
7443 if (item.hasProps) {
7444 const msg = 'Sequence items cannot have tags or anchors before the - indicator';
7445 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, msg));
7451 if (item.error) doc.errors.push(item.error);
7452 doc.errors.push(new PlainValueEc8e588e.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`));
7462 function resolveFlowSeqItems(doc, cst) {
7463 const comments = [];
7465 let explicitKey = false;
7466 let key = undefined;
7467 let keyStart = null;
7469 let prevItem = null;
7471 for (let i = 0; i < cst.items.length; ++i) {
7472 const item = cst.items[i];
7474 if (typeof item.char === 'string') {
7480 if (char !== ':' && (explicitKey || key !== undefined)) {
7481 if (explicitKey && key === undefined) key = next ? items.pop() : null;
7482 items.push(new Pair(key));
7483 explicitKey = false;
7488 if (char === next) {
7490 } else if (!next && char === '?') {
7492 } else if (next !== '[' && char === ':' && key === undefined) {
7496 if (key instanceof Pair) {
7497 const msg = 'Chaining flow sequence pairs is invalid';
7498 const err = new PlainValueEc8e588e.YAMLSemanticError(cst, msg);
7499 err.offset = offset;
7500 doc.errors.push(err);
7503 if (!explicitKey && typeof keyStart === 'number') {
7504 const keyEnd = item.range ? item.range.start : item.offset;
7505 if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
7508 } = prevItem.context;
7510 for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') {
7511 const msg = 'Implicit keys of flow sequence pairs need to be on a single line';
7512 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(prevItem, msg));
7521 explicitKey = false;
7523 } else if (next === '[' || char !== ']' || i < cst.items.length - 1) {
7524 const msg = `Flow sequence contains an unexpected ${char}`;
7525 const err = new PlainValueEc8e588e.YAMLSyntaxError(cst, msg);
7526 err.offset = offset;
7527 doc.errors.push(err);
7529 } else if (item.type === PlainValueEc8e588e.Type.BLANK_LINE) {
7531 before: items.length
7533 } else if (item.type === PlainValueEc8e588e.Type.COMMENT) {
7534 checkFlowCommentSpace(doc.errors, item);
7536 comment: item.comment,
7537 before: items.length
7541 const msg = `Expected a ${next} in flow sequence`;
7542 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(item, msg));
7545 const value = resolveNode(doc, item);
7547 if (key === undefined) {
7551 items.push(new Pair(key, value));
7555 keyStart = item.range.start;
7560 checkFlowCollectionEnd(doc.errors, cst);
7561 if (key !== undefined) items.push(new Pair(key));
7568 var Alias_1 = Alias$1;
7569 var Collection_1 = Collection$1;
7570 var Merge_1 = Merge;
7571 var Node_1$1 = Node$1;
7573 var Scalar_1 = Scalar;
7574 var YAMLMap_1 = YAMLMap;
7575 var YAMLSeq_1 = YAMLSeq;
7576 var addComment_1 = addComment;
7577 var binaryOptions_1 = binaryOptions;
7578 var boolOptions_1 = boolOptions;
7579 var findPair_1 = findPair;
7580 var intOptions_1 = intOptions;
7581 var isEmptyPath_1 = isEmptyPath;
7582 var nullOptions_1 = nullOptions;
7583 var resolveMap_1 = resolveMap;
7584 var resolveNode_1 = resolveNode;
7585 var resolveSeq_1 = resolveSeq;
7586 var resolveString_1 = resolveString;
7587 var strOptions_1 = strOptions;
7588 var stringifyNumber_1 = stringifyNumber;
7589 var stringifyString_1 = stringifyString;
7590 var toJSON_1 = toJSON;
7591 var resolveSeq4a68b39b = {
7593 Collection: Collection_1,
7600 addComment: addComment_1,
7601 binaryOptions: binaryOptions_1,
7602 boolOptions: boolOptions_1,
7603 findPair: findPair_1,
7604 intOptions: intOptions_1,
7605 isEmptyPath: isEmptyPath_1,
7606 nullOptions: nullOptions_1,
7607 resolveMap: resolveMap_1,
7608 resolveNode: resolveNode_1,
7609 resolveSeq: resolveSeq_1,
7610 resolveString: resolveString_1,
7611 strOptions: strOptions_1,
7612 stringifyNumber: stringifyNumber_1,
7613 stringifyString: stringifyString_1,
7617 /* global atob, btoa, Buffer */
7621 identify: value => value instanceof Uint8Array,
7622 // Buffer inherits from Uint8Array
7624 tag: 'tag:yaml.org,2002:binary',
7627 * Returns a Buffer in node and an Uint8Array in browsers
7629 * To use the resulting buffer as an image, you'll want to do something like:
7631 * const blob = new Blob([buffer], { type: 'image/jpeg' })
7632 * document.querySelector('#photo').src = URL.createObjectURL(blob)
7634 resolve: (doc, node) => {
7635 const src = resolveSeq4a68b39b.resolveString(doc, node);
7637 if (typeof Buffer === 'function') {
7638 return Buffer.from(src, 'base64');
7639 } else if (typeof atob === 'function') {
7640 // On IE 11, atob() can't handle newlines
7641 const str = atob(src.replace(/[\n\r]/g, ''));
7642 const buffer = new Uint8Array(str.length);
7644 for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i);
7648 const msg = 'This environment does not support reading binary tags; either Buffer or atob is required';
7649 doc.errors.push(new PlainValueEc8e588e.YAMLReferenceError(node, msg));
7653 options: resolveSeq4a68b39b.binaryOptions,
7658 }, ctx, onComment, onChompKeep) => {
7661 if (typeof Buffer === 'function') {
7662 src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64');
7663 } else if (typeof btoa === 'function') {
7666 for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]);
7670 throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
7673 if (!type) type = resolveSeq4a68b39b.binaryOptions.defaultType;
7675 if (type === PlainValueEc8e588e.Type.QUOTE_DOUBLE) {
7680 } = resolveSeq4a68b39b.binaryOptions;
7681 const n = Math.ceil(src.length / lineWidth);
7682 const lines = new Array(n);
7684 for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
7685 lines[i] = src.substr(o, lineWidth);
7688 value = lines.join(type === PlainValueEc8e588e.Type.BLOCK_LITERAL ? '\n' : ' ');
7691 return resolveSeq4a68b39b.stringifyString({
7695 }, ctx, onComment, onChompKeep);
7699 function parsePairs(doc, cst) {
7700 const seq = resolveSeq4a68b39b.resolveSeq(doc, cst);
7702 for (let i = 0; i < seq.items.length; ++i) {
7703 let item = seq.items[i];
7704 if (item instanceof resolveSeq4a68b39b.Pair) continue;else if (item instanceof resolveSeq4a68b39b.YAMLMap) {
7705 if (item.items.length > 1) {
7706 const msg = 'Each pair must have its own sequence indicator';
7707 throw new PlainValueEc8e588e.YAMLSemanticError(cst, msg);
7710 const pair = item.items[0] || new resolveSeq4a68b39b.Pair();
7711 if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore;
7712 if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment;
7715 seq.items[i] = item instanceof resolveSeq4a68b39b.Pair ? item : new resolveSeq4a68b39b.Pair(item);
7721 function createPairs(schema, iterable, ctx) {
7722 const pairs = new resolveSeq4a68b39b.YAMLSeq(schema);
7723 pairs.tag = 'tag:yaml.org,2002:pairs';
7725 for (const it of iterable) {
7728 if (Array.isArray(it)) {
7729 if (it.length === 2) {
7732 } else throw new TypeError(`Expected [key, value] tuple: ${it}`);
7733 } else if (it && it instanceof Object) {
7734 const keys = Object.keys(it);
7736 if (keys.length === 1) {
7739 } else throw new TypeError(`Expected { key: value } tuple: ${it}`);
7744 const pair = schema.createPair(key, value, ctx);
7745 pairs.items.push(pair);
7753 tag: 'tag:yaml.org,2002:pairs',
7754 resolve: parsePairs,
7755 createNode: createPairs
7758 class YAMLOMap extends resolveSeq4a68b39b.YAMLSeq {
7762 PlainValueEc8e588e._defineProperty(this, "add", resolveSeq4a68b39b.YAMLMap.prototype.add.bind(this));
7764 PlainValueEc8e588e._defineProperty(this, "delete", resolveSeq4a68b39b.YAMLMap.prototype.delete.bind(this));
7766 PlainValueEc8e588e._defineProperty(this, "get", resolveSeq4a68b39b.YAMLMap.prototype.get.bind(this));
7768 PlainValueEc8e588e._defineProperty(this, "has", resolveSeq4a68b39b.YAMLMap.prototype.has.bind(this));
7770 PlainValueEc8e588e._defineProperty(this, "set", resolveSeq4a68b39b.YAMLMap.prototype.set.bind(this));
7772 this.tag = YAMLOMap.tag;
7776 const map = new Map();
7777 if (ctx && ctx.onCreate) ctx.onCreate(map);
7779 for (const pair of this.items) {
7782 if (pair instanceof resolveSeq4a68b39b.Pair) {
7783 key = resolveSeq4a68b39b.toJSON(pair.key, '', ctx);
7784 value = resolveSeq4a68b39b.toJSON(pair.value, key, ctx);
7786 key = resolveSeq4a68b39b.toJSON(pair, '', ctx);
7789 if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys');
7790 map.set(key, value);
7798 PlainValueEc8e588e._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap');
7800 function parseOMap(doc, cst) {
7801 const pairs = parsePairs(doc, cst);
7802 const seenKeys = [];
7807 if (key instanceof resolveSeq4a68b39b.Scalar) {
7808 if (seenKeys.includes(key.value)) {
7809 const msg = 'Ordered maps must not include duplicate keys';
7810 throw new PlainValueEc8e588e.YAMLSemanticError(cst, msg);
7812 seenKeys.push(key.value);
7817 return Object.assign(new YAMLOMap(), pairs);
7820 function createOMap(schema, iterable, ctx) {
7821 const pairs = createPairs(schema, iterable, ctx);
7822 const omap = new YAMLOMap();
7823 omap.items = pairs.items;
7828 identify: value => value instanceof Map,
7829 nodeClass: YAMLOMap,
7831 tag: 'tag:yaml.org,2002:omap',
7833 createNode: createOMap
7836 class YAMLSet extends resolveSeq4a68b39b.YAMLMap {
7839 this.tag = YAMLSet.tag;
7843 const pair = key instanceof resolveSeq4a68b39b.Pair ? key : new resolveSeq4a68b39b.Pair(key);
7844 const prev = resolveSeq4a68b39b.findPair(this.items, pair.key);
7845 if (!prev) this.items.push(pair);
7848 get(key, keepPair) {
7849 const pair = resolveSeq4a68b39b.findPair(this.items, key);
7850 return !keepPair && pair instanceof resolveSeq4a68b39b.Pair ? pair.key instanceof resolveSeq4a68b39b.Scalar ? pair.key.value : pair.key : pair;
7854 if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
7855 const prev = resolveSeq4a68b39b.findPair(this.items, key);
7857 if (prev && !value) {
7858 this.items.splice(this.items.indexOf(prev), 1);
7859 } else if (!prev && value) {
7860 this.items.push(new resolveSeq4a68b39b.Pair(key));
7865 return super.toJSON(_, ctx, Set);
7868 toString(ctx, onComment, onChompKeep) {
7869 if (!ctx) return JSON.stringify(this);
7870 if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values');
7875 PlainValueEc8e588e._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set');
7877 function parseSet(doc, cst) {
7878 const map = resolveSeq4a68b39b.resolveMap(doc, cst);
7879 if (!map.hasAllNullValues()) throw new PlainValueEc8e588e.YAMLSemanticError(cst, 'Set items must all have null values');
7880 return Object.assign(new YAMLSet(), map);
7883 function createSet(schema, iterable, ctx) {
7884 const set = new YAMLSet();
7886 for (const value of iterable) set.items.push(schema.createPair(value, null, ctx));
7892 identify: value => value instanceof Set,
7895 tag: 'tag:yaml.org,2002:set',
7897 createNode: createSet
7900 const parseSexagesimal = (sign, parts) => {
7901 const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0);
7902 return sign === '-' ? -n : n;
7903 }; // hhhh:mm:ss.sss
7906 const stringifySexagesimal = ({
7909 if (isNaN(value) || !isFinite(value)) return resolveSeq4a68b39b.stringifyNumber(value);
7914 value = Math.abs(value);
7917 const parts = [value % 60]; // seconds, including ms
7920 parts.unshift(0); // at least one : is required
7922 value = Math.round((value - parts[0]) / 60);
7923 parts.unshift(value % 60); // minutes
7926 value = Math.round((value - parts[0]) / 60);
7927 parts.unshift(value); // hours
7931 return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error
7936 identify: value => typeof value === 'number',
7938 tag: 'tag:yaml.org,2002:int',
7940 test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,
7941 resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
7942 stringify: stringifySexagesimal
7945 identify: value => typeof value === 'number',
7947 tag: 'tag:yaml.org,2002:float',
7949 test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,
7950 resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
7951 stringify: stringifySexagesimal
7954 identify: value => value instanceof Date,
7956 tag: 'tag:yaml.org,2002:timestamp',
7957 // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
7958 // may be omitted altogether, resulting in a date format. In such a case, the time part is
7959 // assumed to be 00:00:00Z (start of day, UTC).
7960 test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
7961 '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace
7962 '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
7963 '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
7965 resolve: (str, year, month, day, hour, minute, second, millisec, tz) => {
7966 if (millisec) millisec = (millisec + '00').substr(1, 3);
7967 let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0);
7969 if (tz && tz !== 'Z') {
7970 let d = parseSexagesimal(tz[0], tz.slice(1));
7971 if (Math.abs(d) < 30) d *= 60;
7975 return new Date(date);
7979 }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '')
7981 /* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */
7983 function shouldWarn(deprecation) {
7984 const env = typeof process !== 'undefined' && process.env || {};
7987 if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS;
7988 return !env.YAML_SILENCE_DEPRECATION_WARNINGS;
7991 if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS;
7992 return !env.YAML_SILENCE_WARNINGS;
7995 function warn(warning, type) {
7996 if (shouldWarn(false)) {
7997 const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to
7998 // https://github.com/facebook/jest/issues/2549
8000 if (emit) emit(warning, type);else {
8001 // eslint-disable-next-line no-console
8002 console.warn(type ? `${type}: ${warning}` : warning);
8007 function warnFileDeprecation(filename) {
8008 if (shouldWarn(true)) {
8009 const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/');
8010 warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning');
8016 function warnOptionDeprecation(name, alternative) {
8017 if (!warned[name] && shouldWarn(true)) {
8018 warned[name] = true;
8019 let msg = `The option '${name}' will be removed in a future release`;
8020 msg += alternative ? `, use '${alternative}' instead.` : '.';
8021 warn(msg, 'DeprecationWarning');
8025 var binary_1 = binary;
8026 var floatTime_1 = floatTime;
8027 var intTime_1 = intTime;
8029 var pairs_1 = pairs;
8031 var timestamp_1 = timestamp;
8033 var warnFileDeprecation_1 = warnFileDeprecation;
8034 var warnOptionDeprecation_1 = warnOptionDeprecation;
8035 var warnings39684f17 = {
8037 floatTime: floatTime_1,
8042 timestamp: timestamp_1,
8044 warnFileDeprecation: warnFileDeprecation_1,
8045 warnOptionDeprecation: warnOptionDeprecation_1
8048 function createMap(schema, obj, ctx) {
8049 const map = new resolveSeq4a68b39b.YAMLMap(schema);
8051 if (obj instanceof Map) {
8052 for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx));
8053 } else if (obj && typeof obj === 'object') {
8054 for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx));
8057 if (typeof schema.sortMapEntries === 'function') {
8058 map.items.sort(schema.sortMapEntries);
8065 createNode: createMap,
8067 nodeClass: resolveSeq4a68b39b.YAMLMap,
8068 tag: 'tag:yaml.org,2002:map',
8069 resolve: resolveSeq4a68b39b.resolveMap
8072 function createSeq(schema, obj, ctx) {
8073 const seq = new resolveSeq4a68b39b.YAMLSeq(schema);
8075 if (obj && obj[Symbol.iterator]) {
8076 for (const it of obj) {
8077 const v = schema.createNode(it, ctx.wrapScalars, null, ctx);
8086 createNode: createSeq,
8088 nodeClass: resolveSeq4a68b39b.YAMLSeq,
8089 tag: 'tag:yaml.org,2002:seq',
8090 resolve: resolveSeq4a68b39b.resolveSeq
8093 identify: value => typeof value === 'string',
8095 tag: 'tag:yaml.org,2002:str',
8096 resolve: resolveSeq4a68b39b.resolveString,
8098 stringify(item, ctx, onComment, onChompKeep) {
8099 ctx = Object.assign({
8102 return resolveSeq4a68b39b.stringifyString(item, ctx, onComment, onChompKeep);
8105 options: resolveSeq4a68b39b.strOptions
8107 const failsafe = [map, seq, string];
8110 const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value);
8112 const intResolve = (src, part, radix) => resolveSeq4a68b39b.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix);
8114 function intStringify(node, radix, prefix) {
8118 if (intIdentify(value) && value >= 0) return prefix + value.toString(radix);
8119 return resolveSeq4a68b39b.stringifyNumber(node);
8123 identify: value => value == null,
8124 createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq4a68b39b.Scalar(null) : null,
8126 tag: 'tag:yaml.org,2002:null',
8127 test: /^(?:~|[Nn]ull|NULL)?$/,
8128 resolve: () => null,
8129 options: resolveSeq4a68b39b.nullOptions,
8130 stringify: () => resolveSeq4a68b39b.nullOptions.nullStr
8133 identify: value => typeof value === 'boolean',
8135 tag: 'tag:yaml.org,2002:bool',
8136 test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
8137 resolve: str => str[0] === 't' || str[0] === 'T',
8138 options: resolveSeq4a68b39b.boolOptions,
8141 }) => value ? resolveSeq4a68b39b.boolOptions.trueStr : resolveSeq4a68b39b.boolOptions.falseStr
8144 identify: value => intIdentify(value) && value >= 0,
8146 tag: 'tag:yaml.org,2002:int',
8148 test: /^0o([0-7]+)$/,
8149 resolve: (str, oct) => intResolve(str, oct, 8),
8150 options: resolveSeq4a68b39b.intOptions,
8151 stringify: node => intStringify(node, 8, '0o')
8154 identify: intIdentify,
8156 tag: 'tag:yaml.org,2002:int',
8157 test: /^[-+]?[0-9]+$/,
8158 resolve: str => intResolve(str, str, 10),
8159 options: resolveSeq4a68b39b.intOptions,
8160 stringify: resolveSeq4a68b39b.stringifyNumber
8163 identify: value => intIdentify(value) && value >= 0,
8165 tag: 'tag:yaml.org,2002:int',
8167 test: /^0x([0-9a-fA-F]+)$/,
8168 resolve: (str, hex) => intResolve(str, hex, 16),
8169 options: resolveSeq4a68b39b.intOptions,
8170 stringify: node => intStringify(node, 16, '0x')
8173 identify: value => typeof value === 'number',
8175 tag: 'tag:yaml.org,2002:float',
8176 test: /^(?:[-+]?\.inf|(\.nan))$/i,
8177 resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
8178 stringify: resolveSeq4a68b39b.stringifyNumber
8181 identify: value => typeof value === 'number',
8183 tag: 'tag:yaml.org,2002:float',
8185 test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
8186 resolve: str => parseFloat(str),
8189 }) => Number(value).toExponential()
8192 identify: value => typeof value === 'number',
8194 tag: 'tag:yaml.org,2002:float',
8195 test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,
8197 resolve(str, frac1, frac2) {
8198 const frac = frac1 || frac2;
8199 const node = new resolveSeq4a68b39b.Scalar(parseFloat(str));
8200 if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length;
8204 stringify: resolveSeq4a68b39b.stringifyNumber
8206 const core = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]);
8209 const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value);
8211 const stringifyJSON = ({
8213 }) => JSON.stringify(value);
8215 const json = [map, seq, {
8216 identify: value => typeof value === 'string',
8218 tag: 'tag:yaml.org,2002:str',
8219 resolve: resolveSeq4a68b39b.resolveString,
8220 stringify: stringifyJSON
8222 identify: value => value == null,
8223 createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq4a68b39b.Scalar(null) : null,
8225 tag: 'tag:yaml.org,2002:null',
8227 resolve: () => null,
8228 stringify: stringifyJSON
8230 identify: value => typeof value === 'boolean',
8232 tag: 'tag:yaml.org,2002:bool',
8233 test: /^true|false$/,
8234 resolve: str => str === 'true',
8235 stringify: stringifyJSON
8237 identify: intIdentify$1,
8239 tag: 'tag:yaml.org,2002:int',
8240 test: /^-?(?:0|[1-9][0-9]*)$/,
8241 resolve: str => resolveSeq4a68b39b.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10),
8244 }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value)
8246 identify: value => typeof value === 'number',
8248 tag: 'tag:yaml.org,2002:float',
8249 test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
8250 resolve: str => parseFloat(str),
8251 stringify: stringifyJSON
8254 json.scalarFallback = str => {
8255 throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`);
8260 const boolStringify = ({
8262 }) => value ? resolveSeq4a68b39b.boolOptions.trueStr : resolveSeq4a68b39b.boolOptions.falseStr;
8264 const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value);
8266 function intResolve$1(sign, src, radix) {
8267 let str = src.replace(/_/g, '');
8269 if (resolveSeq4a68b39b.intOptions.asBigInt) {
8284 const n = BigInt(str);
8285 return sign === '-' ? BigInt(-1) * n : n;
8288 const n = parseInt(str, radix);
8289 return sign === '-' ? -1 * n : n;
8292 function intStringify$1(node, radix, prefix) {
8297 if (intIdentify$2(value)) {
8298 const str = value.toString(radix);
8299 return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
8302 return resolveSeq4a68b39b.stringifyNumber(node);
8305 const yaml11 = failsafe.concat([{
8306 identify: value => value == null,
8307 createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq4a68b39b.Scalar(null) : null,
8309 tag: 'tag:yaml.org,2002:null',
8310 test: /^(?:~|[Nn]ull|NULL)?$/,
8311 resolve: () => null,
8312 options: resolveSeq4a68b39b.nullOptions,
8313 stringify: () => resolveSeq4a68b39b.nullOptions.nullStr
8315 identify: value => typeof value === 'boolean',
8317 tag: 'tag:yaml.org,2002:bool',
8318 test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
8319 resolve: () => true,
8320 options: resolveSeq4a68b39b.boolOptions,
8321 stringify: boolStringify
8323 identify: value => typeof value === 'boolean',
8325 tag: 'tag:yaml.org,2002:bool',
8326 test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,
8327 resolve: () => false,
8328 options: resolveSeq4a68b39b.boolOptions,
8329 stringify: boolStringify
8331 identify: intIdentify$2,
8333 tag: 'tag:yaml.org,2002:int',
8335 test: /^([-+]?)0b([0-1_]+)$/,
8336 resolve: (str, sign, bin) => intResolve$1(sign, bin, 2),
8337 stringify: node => intStringify$1(node, 2, '0b')
8339 identify: intIdentify$2,
8341 tag: 'tag:yaml.org,2002:int',
8343 test: /^([-+]?)0([0-7_]+)$/,
8344 resolve: (str, sign, oct) => intResolve$1(sign, oct, 8),
8345 stringify: node => intStringify$1(node, 8, '0')
8347 identify: intIdentify$2,
8349 tag: 'tag:yaml.org,2002:int',
8350 test: /^([-+]?)([0-9][0-9_]*)$/,
8351 resolve: (str, sign, abs) => intResolve$1(sign, abs, 10),
8352 stringify: resolveSeq4a68b39b.stringifyNumber
8354 identify: intIdentify$2,
8356 tag: 'tag:yaml.org,2002:int',
8358 test: /^([-+]?)0x([0-9a-fA-F_]+)$/,
8359 resolve: (str, sign, hex) => intResolve$1(sign, hex, 16),
8360 stringify: node => intStringify$1(node, 16, '0x')
8362 identify: value => typeof value === 'number',
8364 tag: 'tag:yaml.org,2002:float',
8365 test: /^(?:[-+]?\.inf|(\.nan))$/i,
8366 resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
8367 stringify: resolveSeq4a68b39b.stringifyNumber
8369 identify: value => typeof value === 'number',
8371 tag: 'tag:yaml.org,2002:float',
8373 test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,
8374 resolve: str => parseFloat(str.replace(/_/g, '')),
8377 }) => Number(value).toExponential()
8379 identify: value => typeof value === 'number',
8381 tag: 'tag:yaml.org,2002:float',
8382 test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,
8384 resolve(str, frac) {
8385 const node = new resolveSeq4a68b39b.Scalar(parseFloat(str.replace(/_/g, '')));
8388 const f = frac.replace(/_/g, '');
8389 if (f[f.length - 1] === '0') node.minFractionDigits = f.length;
8395 stringify: resolveSeq4a68b39b.stringifyNumber
8396 }], warnings39684f17.binary, warnings39684f17.omap, warnings39684f17.pairs, warnings39684f17.set, warnings39684f17.intTime, warnings39684f17.floatTime, warnings39684f17.timestamp);
8404 binary: warnings39684f17.binary,
8409 floatTime: warnings39684f17.floatTime,
8413 intTime: warnings39684f17.intTime,
8416 omap: warnings39684f17.omap,
8417 pairs: warnings39684f17.pairs,
8419 set: warnings39684f17.set,
8420 timestamp: warnings39684f17.timestamp
8423 function findTagObject(value, tagName, tags) {
8425 const match = tags.filter(t => t.tag === tagName);
8426 const tagObj = match.find(t => !t.format) || match[0];
8427 if (!tagObj) throw new Error(`Tag ${tagName} not found`);
8429 } // TODO: deprecate/remove class check
8432 return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format);
8435 function createNode(value, tagName, ctx) {
8436 if (value instanceof resolveSeq4a68b39b.Node) return value;
8444 if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2);
8445 let tagObj = findTagObject(value, tagName, schema.tags);
8448 if (typeof value.toJSON === 'function') value = value.toJSON();
8449 if (typeof value !== 'object') return wrapScalars ? new resolveSeq4a68b39b.Scalar(value) : value;
8450 tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map;
8455 delete ctx.onTagObj;
8456 } // Detect duplicate references to the same object & use Alias nodes for all
8457 // after first. The `obj` wrapper allows for circular references to resolve.
8462 if (value && typeof value === 'object' && prevObjects) {
8463 const prev = prevObjects.get(value);
8466 const alias = new resolveSeq4a68b39b.Alias(prev); // leaves source dirty; must be cleaned by caller
8468 ctx.aliasNodes.push(alias); // defined along with prevObjects
8474 prevObjects.set(value, obj);
8477 obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq4a68b39b.Scalar(value) : value;
8478 if (tagName && obj.node instanceof resolveSeq4a68b39b.Node) obj.node.tag = tagName;
8482 function getSchemaTags(schemas, knownTags, customTags, schemaId) {
8483 let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11'
8486 const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', ');
8487 throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`);
8490 if (Array.isArray(customTags)) {
8491 for (const tag of customTags) tags = tags.concat(tag);
8492 } else if (typeof customTags === 'function') {
8493 tags = customTags(tags.slice());
8496 for (let i = 0; i < tags.length; ++i) {
8497 const tag = tags[i];
8499 if (typeof tag === 'string') {
8500 const tagObj = knownTags[tag];
8503 const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', ');
8504 throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
8514 const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
8517 // TODO: remove in v2
8518 // TODO: remove in v2
8524 tags: deprecatedCustomTags
8526 this.merge = !!merge;
8528 this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null;
8529 if (!customTags && deprecatedCustomTags) warnings39684f17.warnOptionDeprecation('tags', 'customTags');
8530 this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema);
8533 createNode(value, wrapScalars, tagName, ctx) {
8535 defaultPrefix: Schema.defaultPrefix,
8539 const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx;
8540 return createNode(value, tagName, createCtx);
8543 createPair(key, value, ctx) {
8547 const k = this.createNode(key, ctx.wrapScalars, null, ctx);
8548 const v = this.createNode(value, ctx.wrapScalars, null, ctx);
8549 return new resolveSeq4a68b39b.Pair(k, v);
8554 PlainValueEc8e588e._defineProperty(Schema, "defaultPrefix", PlainValueEc8e588e.defaultTagPrefix);
8556 PlainValueEc8e588e._defineProperty(Schema, "defaultTags", PlainValueEc8e588e.defaultTags);
8558 var Schema_1 = Schema;
8559 var Schema42e9705c = {
8563 const defaultOptions = {
8568 keepCstNodes: false,
8569 keepNodeTypes: true,
8570 keepBlobsInJSON: true,
8573 prettyErrors: false,
8574 // TODO Set true in v2
8578 const scalarOptions = {
8580 return resolveSeq4a68b39b.binaryOptions;
8584 Object.assign(resolveSeq4a68b39b.binaryOptions, opt);
8588 return resolveSeq4a68b39b.boolOptions;
8592 Object.assign(resolveSeq4a68b39b.boolOptions, opt);
8596 return resolveSeq4a68b39b.intOptions;
8600 Object.assign(resolveSeq4a68b39b.intOptions, opt);
8604 return resolveSeq4a68b39b.nullOptions;
8608 Object.assign(resolveSeq4a68b39b.nullOptions, opt);
8612 return resolveSeq4a68b39b.strOptions;
8616 Object.assign(resolveSeq4a68b39b.strOptions, opt);
8620 const documentOptions = {
8626 prefix: PlainValueEc8e588e.defaultTagPrefix
8629 prefix: 'tag:private.yaml.org,2002:'
8640 prefix: PlainValueEc8e588e.defaultTagPrefix
8651 prefix: PlainValueEc8e588e.defaultTagPrefix
8656 function stringifyTag(doc, tag) {
8657 if ((doc.version || doc.options.version) === '1.0') {
8658 const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);
8659 if (priv) return '!' + priv[1];
8660 const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);
8661 return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`;
8664 let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0);
8667 const dtp = doc.getDefaults().tagPrefixes;
8668 p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0);
8671 if (!p) return tag[0] === '!' ? tag : `!<${tag}>`;
8672 const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({
8680 return p.handle + suffix;
8683 function getTagObject(tags, item) {
8684 if (item instanceof resolveSeq4a68b39b.Alias) return resolveSeq4a68b39b.Alias;
8687 const match = tags.filter(t => t.tag === item.tag);
8688 if (match.length > 0) return match.find(t => t.format === item.format) || match[0];
8693 if (item instanceof resolveSeq4a68b39b.Scalar) {
8694 obj = item.value; // TODO: deprecate/remove class check
8696 const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class);
8697 tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format);
8700 tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
8704 const name = obj && obj.constructor ? obj.constructor.name : typeof obj;
8705 throw new Error(`Tag not resolved for ${name} value`);
8709 } // needs to be called before value stringifier to allow for circular anchor refs
8712 function stringifyProps(node, tagObj, {
8717 const anchor = doc.anchors.getName(node);
8720 anchors[anchor] = node;
8721 props.push(`&${anchor}`);
8725 props.push(stringifyTag(doc, node.tag));
8726 } else if (!tagObj.default) {
8727 props.push(stringifyTag(doc, tagObj.tag));
8730 return props.join(' ');
8733 function stringify(item, ctx, onComment, onChompKeep) {
8740 if (!(item instanceof resolveSeq4a68b39b.Node)) {
8743 onTagObj: o => tagObj = o,
8744 prevObjects: new Map()
8746 item = schema.createNode(item, true, null, createCtx);
8748 for (const alias of createCtx.aliasNodes) {
8749 alias.source = alias.source.node;
8750 let name = anchors.getName(alias.source);
8753 name = anchors.newName();
8754 anchors.map[name] = alias.source;
8759 if (item instanceof resolveSeq4a68b39b.Pair) return item.toString(ctx, onComment, onChompKeep);
8760 if (!tagObj) tagObj = getTagObject(schema.tags, item);
8761 const props = stringifyProps(item, tagObj, ctx);
8762 if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1;
8763 const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq4a68b39b.Scalar ? resolveSeq4a68b39b.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep);
8764 if (!props) return str;
8765 return item instanceof resolveSeq4a68b39b.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`;
8769 static validAnchorNode(node) {
8770 return node instanceof resolveSeq4a68b39b.Scalar || node instanceof resolveSeq4a68b39b.YAMLSeq || node instanceof resolveSeq4a68b39b.YAMLMap;
8773 constructor(prefix) {
8774 PlainValueEc8e588e._defineProperty(this, "map", {});
8776 this.prefix = prefix;
8779 createAlias(node, name) {
8780 this.setAnchor(node, name);
8781 return new resolveSeq4a68b39b.Alias(node);
8784 createMergePair(...sources) {
8785 const merge = new resolveSeq4a68b39b.Merge();
8786 merge.value.items = sources.map(s => {
8787 if (s instanceof resolveSeq4a68b39b.Alias) {
8788 if (s.source instanceof resolveSeq4a68b39b.YAMLMap) return s;
8789 } else if (s instanceof resolveSeq4a68b39b.YAMLMap) {
8790 return this.createAlias(s);
8793 throw new Error('Merge sources must be Map nodes or their Aliases');
8802 return Object.keys(map).find(a => map[a] === node);
8806 return Object.keys(this.map);
8810 return this.map[name];
8814 if (!prefix) prefix = this.prefix;
8815 const names = Object.keys(this.map);
8817 for (let i = 1; true; ++i) {
8818 const name = `${prefix}${i}`;
8819 if (!names.includes(name)) return name;
8821 } // During parsing, map & aliases contain CST nodes
8829 Object.keys(map).forEach(a => {
8830 map[a] = map[a].resolved;
8833 _cstAliases.forEach(a => {
8834 a.source = a.source.resolved;
8837 delete this._cstAliases;
8840 setAnchor(node, name) {
8841 if (node != null && !Anchors.validAnchorNode(node)) {
8842 throw new Error('Anchors may only be set for Scalar, Seq and Map nodes');
8845 if (name && /[\x00-\x19\s,[\]{}]/.test(name)) {
8846 throw new Error('Anchor names must not contain whitespace or control characters');
8852 const prev = node && Object.keys(map).find(a => map[a] === node);
8857 } else if (prev !== name) {
8863 if (!node) return null;
8864 name = this.newName();
8875 const visit = (node, tags) => {
8876 if (node && typeof node === 'object') {
8881 if (node instanceof resolveSeq4a68b39b.Collection) {
8882 if (tag) tags[tag] = true;
8883 node.items.forEach(n => visit(n, tags));
8884 } else if (node instanceof resolveSeq4a68b39b.Pair) {
8885 visit(node.key, tags);
8886 visit(node.value, tags);
8887 } else if (node instanceof resolveSeq4a68b39b.Scalar) {
8888 if (tag) tags[tag] = true;
8895 const listTagNames = node => Object.keys(visit(node, {}));
8897 function parseContents(doc, contents) {
8902 let body = undefined;
8903 let spaceBefore = false;
8905 for (const node of contents) {
8906 if (node.valueRange) {
8907 if (body !== undefined) {
8908 const msg = 'Document contains trailing content not separated by a ... or --- line';
8909 doc.errors.push(new PlainValueEc8e588e.YAMLSyntaxError(node, msg));
8913 const res = resolveSeq4a68b39b.resolveNode(doc, node);
8916 res.spaceBefore = true;
8917 spaceBefore = false;
8921 } else if (node.comment !== null) {
8922 const cc = body === undefined ? comments.before : comments.after;
8923 cc.push(node.comment);
8924 } else if (node.type === PlainValueEc8e588e.Type.BLANK_LINE) {
8927 if (body === undefined && comments.before.length > 0 && !doc.commentBefore) {
8928 // space-separated comments at start are parsed as document comments
8929 doc.commentBefore = comments.before.join('\n');
8930 comments.before = [];
8935 doc.contents = body || null;
8938 doc.comment = comments.before.concat(comments.after).join('\n') || null;
8940 const cb = comments.before.join('\n');
8943 const cbNode = body instanceof resolveSeq4a68b39b.Collection && body.items[0] ? body.items[0] : body;
8944 cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb;
8947 doc.comment = comments.after.join('\n') || null;
8951 function resolveTagDirective({
8954 const [handle, prefix] = directive.parameters;
8956 if (!handle || !prefix) {
8957 const msg = 'Insufficient parameters given for %TAG directive';
8958 throw new PlainValueEc8e588e.YAMLSemanticError(directive, msg);
8961 if (tagPrefixes.some(p => p.handle === handle)) {
8962 const msg = 'The %TAG directive must only be given at most once per handle in the same document.';
8963 throw new PlainValueEc8e588e.YAMLSemanticError(directive, msg);
8972 function resolveYamlDirective(doc, directive) {
8973 let [version] = directive.parameters;
8974 if (directive.name === 'YAML:1.0') version = '1.0';
8977 const msg = 'Insufficient parameters given for %YAML directive';
8978 throw new PlainValueEc8e588e.YAMLSemanticError(directive, msg);
8981 if (!documentOptions[version]) {
8982 const v0 = doc.version || doc.options.version;
8983 const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`;
8984 doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(directive, msg));
8990 function parseDirectives(doc, directives, prevDoc) {
8991 const directiveComments = [];
8992 let hasDirectives = false;
8994 for (const directive of directives) {
9003 doc.tagPrefixes.push(resolveTagDirective(doc, directive));
9005 doc.errors.push(error);
9008 hasDirectives = true;
9014 const msg = 'The %YAML directive must only be given at most once per document.';
9015 doc.errors.push(new PlainValueEc8e588e.YAMLSemanticError(directive, msg));
9019 doc.version = resolveYamlDirective(doc, directive);
9021 doc.errors.push(error);
9024 hasDirectives = true;
9029 const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`;
9030 doc.warnings.push(new PlainValueEc8e588e.YAMLWarning(directive, msg));
9035 if (comment) directiveComments.push(comment);
9038 if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) {
9039 const copyTagPrefix = ({
9047 doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix);
9048 doc.version = prevDoc.version;
9051 doc.commentBefore = directiveComments.join('\n') || null;
9054 function assertCollection(contents) {
9055 if (contents instanceof resolveSeq4a68b39b.Collection) return true;
9056 throw new Error('Expected a YAML collection as document contents');
9060 constructor(options) {
9061 this.anchors = new Anchors(options.anchorPrefix);
9062 this.commentBefore = null;
9063 this.comment = null;
9064 this.contents = null;
9065 this.directivesEndMarker = null;
9067 this.options = options;
9069 this.tagPrefixes = [];
9070 this.version = null;
9075 assertCollection(this.contents);
9076 return this.contents.add(value);
9079 addIn(path, value) {
9080 assertCollection(this.contents);
9081 this.contents.addIn(path, value);
9085 assertCollection(this.contents);
9086 return this.contents.delete(key);
9090 if (resolveSeq4a68b39b.isEmptyPath(path)) {
9091 if (this.contents == null) return false;
9092 this.contents = null;
9096 assertCollection(this.contents);
9097 return this.contents.deleteIn(path);
9101 return Document$1.defaults[this.version] || Document$1.defaults[this.options.version] || {};
9104 get(key, keepScalar) {
9105 return this.contents instanceof resolveSeq4a68b39b.Collection ? this.contents.get(key, keepScalar) : undefined;
9108 getIn(path, keepScalar) {
9109 if (resolveSeq4a68b39b.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq4a68b39b.Scalar ? this.contents.value : this.contents;
9110 return this.contents instanceof resolveSeq4a68b39b.Collection ? this.contents.getIn(path, keepScalar) : undefined;
9114 return this.contents instanceof resolveSeq4a68b39b.Collection ? this.contents.has(key) : false;
9118 if (resolveSeq4a68b39b.isEmptyPath(path)) return this.contents !== undefined;
9119 return this.contents instanceof resolveSeq4a68b39b.Collection ? this.contents.hasIn(path) : false;
9123 assertCollection(this.contents);
9124 this.contents.set(key, value);
9127 setIn(path, value) {
9128 if (resolveSeq4a68b39b.isEmptyPath(path)) this.contents = value;else {
9129 assertCollection(this.contents);
9130 this.contents.setIn(path, value);
9134 setSchema(id, customTags) {
9135 if (!id && !customTags && this.schema) return;
9136 if (typeof id === 'number') id = id.toFixed(1);
9138 if (id === '1.0' || id === '1.1' || id === '1.2') {
9139 if (this.version) this.version = id;else this.options.version = id;
9140 delete this.options.schema;
9141 } else if (id && typeof id === 'string') {
9142 this.options.schema = id;
9145 if (Array.isArray(customTags)) this.options.customTags = customTags;
9146 const opt = Object.assign({}, this.getDefaults(), this.options);
9147 this.schema = new Schema42e9705c.Schema(opt);
9150 parse(node, prevDoc) {
9151 if (this.options.keepCstNodes) this.cstNode = node;
9152 if (this.options.keepNodeTypes) this.type = 'DOCUMENT';
9156 directivesEndMarker,
9162 if (!error.source) error.source = this;
9163 this.errors.push(error);
9166 parseDirectives(this, directives, prevDoc);
9167 if (directivesEndMarker) this.directivesEndMarker = true;
9168 this.range = valueRange ? [valueRange.start, valueRange.end] : null;
9170 this.anchors._cstAliases = [];
9171 parseContents(this, contents);
9172 this.anchors.resolveNodes();
9174 if (this.options.prettyErrors) {
9175 for (const error of this.errors) if (error instanceof PlainValueEc8e588e.YAMLError) error.makePretty();
9177 for (const warn of this.warnings) if (warn instanceof PlainValueEc8e588e.YAMLError) warn.makePretty();
9183 listNonDefaultTags() {
9184 return listTagNames(this.contents).filter(t => t.indexOf(Schema42e9705c.Schema.defaultPrefix) !== 0);
9187 setTagPrefix(handle, prefix) {
9188 if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !');
9191 const prev = this.tagPrefixes.find(p => p.handle === handle);
9192 if (prev) prev.prefix = prefix;else this.tagPrefixes.push({
9197 this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle);
9201 toJSON(arg, onAnchor) {
9207 const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq4a68b39b.Scalar));
9212 mapAsMap: keep && !!mapAsMap,
9214 stringify // Requiring directly in Pair would create circular dependencies
9217 const anchorNames = Object.keys(this.anchors.map);
9218 if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], {
9223 const res = resolveSeq4a68b39b.toJSON(this.contents, arg, ctx);
9224 if (typeof onAnchor === 'function' && ctx.anchors) for (const {
9227 } of ctx.anchors.values()) onAnchor(res, count);
9232 if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified');
9233 const indentSize = this.options.indent;
9235 if (!Number.isInteger(indentSize) || indentSize <= 0) {
9236 const s = JSON.stringify(indentSize);
9237 throw new Error(`"indent" option must be a positive integer, not ${s}`);
9242 let hasDirectives = false;
9245 let vd = '%YAML 1.2';
9247 if (this.schema.name === 'yaml-1.1') {
9248 if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1';
9252 hasDirectives = true;
9255 const tagNames = this.listNonDefaultTags();
9256 this.tagPrefixes.forEach(({
9260 if (tagNames.some(t => t.indexOf(prefix) === 0)) {
9261 lines.push(`%TAG ${handle} ${prefix}`);
9262 hasDirectives = true;
9265 if (hasDirectives || this.directivesEndMarker) lines.push('---');
9267 if (this.commentBefore) {
9268 if (hasDirectives || !this.directivesEndMarker) lines.unshift('');
9269 lines.unshift(this.commentBefore.replace(/^/gm, '#'));
9276 indentStep: ' '.repeat(indentSize),
9277 stringify // Requiring directly in nodes would create circular dependencies
9280 let chompKeep = false;
9281 let contentComment = null;
9283 if (this.contents) {
9284 if (this.contents instanceof resolveSeq4a68b39b.Node) {
9285 if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push('');
9286 if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment
9288 ctx.forceBlockIndent = !!this.comment;
9289 contentComment = this.contents.comment;
9292 const onChompKeep = contentComment ? null : () => chompKeep = true;
9293 const body = stringify(this.contents, ctx, () => contentComment = null, onChompKeep);
9294 lines.push(resolveSeq4a68b39b.addComment(body, '', contentComment));
9295 } else if (this.contents !== undefined) {
9296 lines.push(stringify(this.contents, ctx));
9300 if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push('');
9301 lines.push(this.comment.replace(/^/gm, '#'));
9304 return lines.join('\n') + '\n';
9309 PlainValueEc8e588e._defineProperty(Document$1, "defaults", documentOptions);
9311 var Document_1 = Document$1;
9312 var defaultOptions_1 = defaultOptions;
9313 var scalarOptions_1 = scalarOptions;
9314 var Document2cf6b08c = {
9315 Document: Document_1,
9316 defaultOptions: defaultOptions_1,
9317 scalarOptions: scalarOptions_1
9320 function createNode$1(value, wrapScalars = true, tag) {
9321 if (tag === undefined && typeof wrapScalars === 'string') {
9326 const options = Object.assign({}, Document2cf6b08c.Document.defaults[Document2cf6b08c.defaultOptions.version], Document2cf6b08c.defaultOptions);
9327 const schema = new Schema42e9705c.Schema(options);
9328 return schema.createNode(value, wrapScalars, tag);
9331 class Document$2 extends Document2cf6b08c.Document {
9332 constructor(options) {
9333 super(Object.assign({}, Document2cf6b08c.defaultOptions, options));
9338 function parseAllDocuments(src, options) {
9342 for (const cstDoc of parseCst.parse(src)) {
9343 const doc = new Document$2(options);
9344 doc.parse(cstDoc, prev);
9352 function parseDocument(src, options) {
9353 const cst = parseCst.parse(src);
9354 const doc = new Document$2(options).parse(cst[0]);
9356 if (cst.length > 1) {
9357 const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()';
9358 doc.errors.unshift(new PlainValueEc8e588e.YAMLSemanticError(cst[1], errMsg));
9364 function parse$1(src, options) {
9365 const doc = parseDocument(src, options);
9366 doc.warnings.forEach(warning => warnings39684f17.warn(warning));
9367 if (doc.errors.length > 0) throw doc.errors[0];
9368 return doc.toJSON();
9371 function stringify$1(value, options) {
9372 const doc = new Document$2(options);
9373 doc.contents = value;
9378 createNode: createNode$1,
9379 defaultOptions: Document2cf6b08c.defaultOptions,
9380 Document: Document$2,
9383 parseCST: parseCst.parse,
9385 scalarOptions: Document2cf6b08c.scalarOptions,
9386 stringify: stringify$1
9393 var yaml = dist$1.YAML;
9395 var loaders_1 = createCommonjsModule(function (module, exports) {
9397 Object.defineProperty(exports, "__esModule", {
9400 exports.loaders = void 0;
9401 /* eslint-disable @typescript-eslint/no-require-imports */
9405 const loadJs = function loadJs(filepath) {
9406 if (importFresh$1 === undefined) {
9407 importFresh$1 = importFresh;
9410 const result = importFresh$1(filepath);
9416 const loadJson = function loadJson(filepath, content) {
9417 if (parseJson === undefined) {
9418 parseJson = parseJson$1;
9422 const result = parseJson(content);
9425 error.message = `JSON Error in ${filepath}:\n${error.message}`;
9432 const loadYaml = function loadYaml(filepath, content) {
9433 if (yaml$1 === undefined) {
9438 const result = yaml$1.parse(content, {
9443 error.message = `YAML Error in ${filepath}:\n${error.message}`;
9453 exports.loaders = loaders;
9456 var getPropertyByPath_1 = createCommonjsModule(function (module, exports) {
9458 Object.defineProperty(exports, "__esModule", {
9461 exports.getPropertyByPath = getPropertyByPath; // Resolves property names or property paths defined with period-delimited
9462 // strings or arrays of strings. Property names that are found on the source
9463 // object are used directly (even if they include a period).
9464 // Nested property names that include periods, within a path, are only
9465 // understood in array paths.
9467 function getPropertyByPath(source, path) {
9468 if (typeof path === 'string' && Object.prototype.hasOwnProperty.call(source, path)) {
9469 return source[path];
9472 const parsedPath = typeof path === 'string' ? path.split('.') : path; // eslint-disable-next-line @typescript-eslint/no-explicit-any
9474 return parsedPath.reduce((previous, key) => {
9475 if (previous === undefined) {
9479 return previous[key];
9484 var ExplorerBase_1 = createCommonjsModule(function (module, exports) {
9486 Object.defineProperty(exports, "__esModule", {
9489 exports.getExtensionDescription = getExtensionDescription;
9490 exports.ExplorerBase = void 0;
9492 var _path = _interopRequireDefault(path__default['default']);
9494 function _interopRequireDefault(obj) {
9495 return obj && obj.__esModule ? obj : {
9500 class ExplorerBase {
9501 constructor(options) {
9502 if (options.cache === true) {
9503 this.loadCache = new Map();
9504 this.searchCache = new Map();
9507 this.config = options;
9508 this.validateConfig();
9512 if (this.loadCache) {
9513 this.loadCache.clear();
9517 clearSearchCache() {
9518 if (this.searchCache) {
9519 this.searchCache.clear();
9524 this.clearLoadCache();
9525 this.clearSearchCache();
9529 const config = this.config;
9530 config.searchPlaces.forEach(place => {
9531 const loaderKey = _path.default.extname(place) || 'noExt';
9532 const loader = config.loaders[loaderKey];
9535 throw new Error(`No loader specified for ${getExtensionDescription(place)}, so searchPlaces item "${place}" is invalid`);
9538 if (typeof loader !== 'function') {
9539 throw new Error(`loader for ${getExtensionDescription(place)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
9544 shouldSearchStopWithResult(result) {
9545 if (result === null) return false;
9546 if (result.isEmpty && this.config.ignoreEmptySearchPlaces) return false;
9550 nextDirectoryToSearch(currentDir, currentResult) {
9551 if (this.shouldSearchStopWithResult(currentResult)) {
9555 const nextDir = nextDirUp(currentDir);
9557 if (nextDir === currentDir || currentDir === this.config.stopDir) {
9564 loadPackageProp(filepath, content) {
9565 const parsedContent = loaders_1.loaders.loadJson(filepath, content);
9567 const packagePropValue = (0, getPropertyByPath_1.getPropertyByPath)(parsedContent, this.config.packageProp);
9568 return packagePropValue || null;
9571 getLoaderEntryForFile(filepath) {
9572 if (_path.default.basename(filepath) === 'package.json') {
9573 const loader = this.loadPackageProp.bind(this);
9577 const loaderKey = _path.default.extname(filepath) || 'noExt';
9578 const loader = this.config.loaders[loaderKey];
9581 throw new Error(`No loader specified for ${getExtensionDescription(filepath)}`);
9587 loadedContentToCosmiconfigResult(filepath, loadedContent) {
9588 if (loadedContent === null) {
9592 if (loadedContent === undefined) {
9601 config: loadedContent,
9606 validateFilePath(filepath) {
9608 throw new Error('load must pass a non-empty string');
9614 exports.ExplorerBase = ExplorerBase;
9616 function nextDirUp(dir) {
9617 return _path.default.dirname(dir);
9620 function getExtensionDescription(filepath) {
9621 const ext = _path.default.extname(filepath);
9623 return ext ? `extension "${ext}"` : 'files without extensions';
9627 var readFile_1 = createCommonjsModule(function (module, exports) {
9629 Object.defineProperty(exports, "__esModule", {
9632 exports.readFile = readFile;
9633 exports.readFileSync = readFileSync;
9635 var _fs = _interopRequireDefault(fs__default['default']);
9637 function _interopRequireDefault(obj) {
9638 return obj && obj.__esModule ? obj : {
9643 async function fsReadFileAsync(pathname, encoding) {
9644 return new Promise((resolve, reject) => {
9645 _fs.default.readFile(pathname, encoding, (error, contents) => {
9656 async function readFile(filepath, options = {}) {
9657 const throwNotFound = options.throwNotFound === true;
9660 const content = await fsReadFileAsync(filepath, 'utf8');
9663 if (throwNotFound === false && error.code === 'ENOENT') {
9671 function readFileSync(filepath, options = {}) {
9672 const throwNotFound = options.throwNotFound === true;
9675 const content = _fs.default.readFileSync(filepath, 'utf8');
9679 if (throwNotFound === false && error.code === 'ENOENT') {
9688 var cacheWrapper_1 = createCommonjsModule(function (module, exports) {
9690 Object.defineProperty(exports, "__esModule", {
9693 exports.cacheWrapper = cacheWrapper;
9694 exports.cacheWrapperSync = cacheWrapperSync;
9696 async function cacheWrapper(cache, key, fn) {
9697 const cached = cache.get(key);
9699 if (cached !== undefined) {
9703 const result = await fn();
9704 cache.set(key, result);
9708 function cacheWrapperSync(cache, key, fn) {
9709 const cached = cache.get(key);
9711 if (cached !== undefined) {
9715 const result = fn();
9716 cache.set(key, result);
9723 } = util__default['default'];
9725 async function isType(fsStatType, statsMethodName, filePath) {
9726 if (typeof filePath !== 'string') {
9727 throw new TypeError(`Expected a string, got ${typeof filePath}`);
9731 const stats = await promisify(fs__default['default'][fsStatType])(filePath);
9732 return stats[statsMethodName]();
9734 if (error.code === 'ENOENT') {
9742 function isTypeSync(fsStatType, statsMethodName, filePath) {
9743 if (typeof filePath !== 'string') {
9744 throw new TypeError(`Expected a string, got ${typeof filePath}`);
9748 return fs__default['default'][fsStatType](filePath)[statsMethodName]();
9750 if (error.code === 'ENOENT') {
9758 var isFile = isType.bind(null, 'stat', 'isFile');
9759 var isDirectory = isType.bind(null, 'stat', 'isDirectory');
9760 var isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
9761 var isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
9762 var isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
9763 var isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');
9766 isDirectory: isDirectory,
9767 isSymlink: isSymlink,
9768 isFileSync: isFileSync,
9769 isDirectorySync: isDirectorySync,
9770 isSymlinkSync: isSymlinkSync
9773 var getDirectory_1 = createCommonjsModule(function (module, exports) {
9775 Object.defineProperty(exports, "__esModule", {
9778 exports.getDirectory = getDirectory;
9779 exports.getDirectorySync = getDirectorySync;
9781 var _path = _interopRequireDefault(path__default['default']);
9783 function _interopRequireDefault(obj) {
9784 return obj && obj.__esModule ? obj : {
9789 async function getDirectory(filepath) {
9790 const filePathIsDirectory = await (0, pathType.isDirectory)(filepath);
9792 if (filePathIsDirectory === true) {
9796 const directory = _path.default.dirname(filepath);
9801 function getDirectorySync(filepath) {
9802 const filePathIsDirectory = (0, pathType.isDirectorySync)(filepath);
9804 if (filePathIsDirectory === true) {
9808 const directory = _path.default.dirname(filepath);
9814 var Explorer_1 = createCommonjsModule(function (module, exports) {
9816 Object.defineProperty(exports, "__esModule", {
9819 exports.Explorer = void 0;
9821 var _path = _interopRequireDefault(path__default['default']);
9823 function _interopRequireDefault(obj) {
9824 return obj && obj.__esModule ? obj : {
9829 class Explorer extends ExplorerBase_1.ExplorerBase {
9830 constructor(options) {
9834 async search(searchFrom = process.cwd()) {
9835 const startDirectory = await (0, getDirectory_1.getDirectory)(searchFrom);
9836 const result = await this.searchFromDirectory(startDirectory);
9840 async searchFromDirectory(dir) {
9841 const absoluteDir = _path.default.resolve(process.cwd(), dir);
9843 const run = async () => {
9844 const result = await this.searchDirectory(absoluteDir);
9845 const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
9848 return this.searchFromDirectory(nextDir);
9851 const transformResult = await this.config.transform(result);
9852 return transformResult;
9855 if (this.searchCache) {
9856 return (0, cacheWrapper_1.cacheWrapper)(this.searchCache, absoluteDir, run);
9862 async searchDirectory(dir) {
9863 for await (const place of this.config.searchPlaces) {
9864 const placeResult = await this.loadSearchPlace(dir, place);
9866 if (this.shouldSearchStopWithResult(placeResult) === true) {
9869 } // config not found
9875 async loadSearchPlace(dir, place) {
9876 const filepath = _path.default.join(dir, place);
9878 const fileContents = await (0, readFile_1.readFile)(filepath);
9879 const result = await this.createCosmiconfigResult(filepath, fileContents);
9883 async loadFileContent(filepath, content) {
9884 if (content === null) {
9888 if (content.trim() === '') {
9892 const loader = this.getLoaderEntryForFile(filepath);
9893 const loaderResult = await loader(filepath, content);
9894 return loaderResult;
9897 async createCosmiconfigResult(filepath, content) {
9898 const fileContent = await this.loadFileContent(filepath, content);
9899 const result = this.loadedContentToCosmiconfigResult(filepath, fileContent);
9903 async load(filepath) {
9904 this.validateFilePath(filepath);
9906 const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
9908 const runLoad = async () => {
9909 const fileContents = await (0, readFile_1.readFile)(absoluteFilePath, {
9912 const result = await this.createCosmiconfigResult(absoluteFilePath, fileContents);
9913 const transformResult = await this.config.transform(result);
9914 return transformResult;
9917 if (this.loadCache) {
9918 return (0, cacheWrapper_1.cacheWrapper)(this.loadCache, absoluteFilePath, runLoad);
9926 exports.Explorer = Explorer;
9929 var ExplorerSync_1 = createCommonjsModule(function (module, exports) {
9931 Object.defineProperty(exports, "__esModule", {
9934 exports.ExplorerSync = void 0;
9936 var _path = _interopRequireDefault(path__default['default']);
9938 function _interopRequireDefault(obj) {
9939 return obj && obj.__esModule ? obj : {
9944 class ExplorerSync extends ExplorerBase_1.ExplorerBase {
9945 constructor(options) {
9949 searchSync(searchFrom = process.cwd()) {
9950 const startDirectory = (0, getDirectory_1.getDirectorySync)(searchFrom);
9951 const result = this.searchFromDirectorySync(startDirectory);
9955 searchFromDirectorySync(dir) {
9956 const absoluteDir = _path.default.resolve(process.cwd(), dir);
9959 const result = this.searchDirectorySync(absoluteDir);
9960 const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
9963 return this.searchFromDirectorySync(nextDir);
9966 const transformResult = this.config.transform(result);
9967 return transformResult;
9970 if (this.searchCache) {
9971 return (0, cacheWrapper_1.cacheWrapperSync)(this.searchCache, absoluteDir, run);
9977 searchDirectorySync(dir) {
9978 for (const place of this.config.searchPlaces) {
9979 const placeResult = this.loadSearchPlaceSync(dir, place);
9981 if (this.shouldSearchStopWithResult(placeResult) === true) {
9984 } // config not found
9990 loadSearchPlaceSync(dir, place) {
9991 const filepath = _path.default.join(dir, place);
9993 const content = (0, readFile_1.readFileSync)(filepath);
9994 const result = this.createCosmiconfigResultSync(filepath, content);
9998 loadFileContentSync(filepath, content) {
9999 if (content === null) {
10003 if (content.trim() === '') {
10007 const loader = this.getLoaderEntryForFile(filepath);
10008 const loaderResult = loader(filepath, content);
10009 return loaderResult;
10012 createCosmiconfigResultSync(filepath, content) {
10013 const fileContent = this.loadFileContentSync(filepath, content);
10014 const result = this.loadedContentToCosmiconfigResult(filepath, fileContent);
10018 loadSync(filepath) {
10019 this.validateFilePath(filepath);
10021 const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
10023 const runLoadSync = () => {
10024 const content = (0, readFile_1.readFileSync)(absoluteFilePath, {
10025 throwNotFound: true
10027 const cosmiconfigResult = this.createCosmiconfigResultSync(absoluteFilePath, content);
10028 const transformResult = this.config.transform(cosmiconfigResult);
10029 return transformResult;
10032 if (this.loadCache) {
10033 return (0, cacheWrapper_1.cacheWrapperSync)(this.loadCache, absoluteFilePath, runLoadSync);
10036 return runLoadSync();
10041 exports.ExplorerSync = ExplorerSync;
10044 var dist$2 = createCommonjsModule(function (module, exports) {
10046 Object.defineProperty(exports, "__esModule", {
10049 exports.cosmiconfig = cosmiconfig;
10050 exports.cosmiconfigSync = cosmiconfigSync;
10051 exports.defaultLoaders = void 0;
10053 var _os = _interopRequireDefault(os__default['default']);
10055 function _interopRequireDefault(obj) {
10056 return obj && obj.__esModule ? obj : {
10060 /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
10061 // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
10064 function cosmiconfig(moduleName, options = {}) {
10065 const normalizedOptions = normalizeOptions(moduleName, options);
10066 const explorer = new Explorer_1.Explorer(normalizedOptions);
10068 search: explorer.search.bind(explorer),
10069 load: explorer.load.bind(explorer),
10070 clearLoadCache: explorer.clearLoadCache.bind(explorer),
10071 clearSearchCache: explorer.clearSearchCache.bind(explorer),
10072 clearCaches: explorer.clearCaches.bind(explorer)
10074 } // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
10077 function cosmiconfigSync(moduleName, options = {}) {
10078 const normalizedOptions = normalizeOptions(moduleName, options);
10079 const explorerSync = new ExplorerSync_1.ExplorerSync(normalizedOptions);
10081 search: explorerSync.searchSync.bind(explorerSync),
10082 load: explorerSync.loadSync.bind(explorerSync),
10083 clearLoadCache: explorerSync.clearLoadCache.bind(explorerSync),
10084 clearSearchCache: explorerSync.clearSearchCache.bind(explorerSync),
10085 clearCaches: explorerSync.clearCaches.bind(explorerSync)
10087 } // do not allow mutation of default loaders. Make sure it is set inside options
10090 const defaultLoaders = Object.freeze({
10091 '.cjs': loaders_1.loaders.loadJs,
10092 '.js': loaders_1.loaders.loadJs,
10093 '.json': loaders_1.loaders.loadJson,
10094 '.yaml': loaders_1.loaders.loadYaml,
10095 '.yml': loaders_1.loaders.loadYaml,
10096 noExt: loaders_1.loaders.loadYaml
10098 exports.defaultLoaders = defaultLoaders;
10100 const identity = function identity(x) {
10104 function normalizeOptions(moduleName, options) {
10106 packageProp: moduleName,
10107 searchPlaces: ['package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.js`, `.${moduleName}rc.cjs`, `${moduleName}.config.js`, `${moduleName}.config.cjs`],
10108 ignoreEmptySearchPlaces: true,
10109 stopDir: _os.default.homedir(),
10111 transform: identity,
10112 loaders: defaultLoaders
10114 const normalizedOptions = Object.assign({}, defaults, options, {
10115 loaders: Object.assign({}, defaults.loaders, options.loaders)
10117 return normalizedOptions;
10121 var findParentDir = createCommonjsModule(function (module, exports) {
10123 var exists = fs__default['default'].exists || path__default['default'].exists,
10124 existsSync = fs__default['default'].existsSync || path__default['default'].existsSync;
10126 function splitPath(path) {
10127 var parts = path.split(/(\/|\\)/);
10128 if (!parts.length) return parts; // when path starts with a slash, the first part is empty string
10130 return !parts[0].length ? parts.slice(1) : parts;
10133 exports = module.exports = function (currentFullPath, clue, cb) {
10134 function testDir(parts) {
10135 if (parts.length === 0) return cb(null, null);
10136 var p = parts.join('');
10137 exists(path__default['default'].join(p, clue), function (itdoes) {
10138 if (itdoes) return cb(null, p);
10139 testDir(parts.slice(0, -1));
10143 testDir(splitPath(currentFullPath));
10146 exports.sync = function (currentFullPath, clue) {
10147 function testDir(parts) {
10148 if (parts.length === 0) return null;
10149 var p = parts.join('');
10150 var itdoes = existsSync(path__default['default'].join(p, clue));
10151 return itdoes ? p : testDir(parts.slice(0, -1));
10154 return testDir(splitPath(currentFullPath));
10162 var getStdin = async () => {
10169 stdin.setEncoding('utf8');
10171 for await (const chunk of stdin) {
10178 var buffer = async () => {
10183 return Buffer.concat([]);
10186 for await (const chunk of stdin) {
10187 result.push(chunk);
10188 length += chunk.length;
10191 return Buffer.concat(result, length);
10193 getStdin.buffer = buffer;
10198 constant: "APPVEYOR",
10200 pr: "APPVEYOR_PULL_REQUEST_NUMBER"
10203 name: "Azure Pipelines",
10204 constant: "AZURE_PIPELINES",
10205 env: "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI",
10206 pr: "SYSTEM_PULLREQUEST_PULLREQUESTID"
10210 constant: "BAMBOO",
10211 env: "bamboo_planKey"
10214 name: "Bitbucket Pipelines",
10215 constant: "BITBUCKET",
10216 env: "BITBUCKET_COMMIT",
10217 pr: "BITBUCKET_PR_ID"
10221 constant: "BITRISE",
10223 pr: "BITRISE_PULL_REQUEST"
10228 env: "BUDDY_WORKSPACE_ID",
10229 pr: "BUDDY_EXECUTION_PULL_REQUEST_ID"
10233 constant: "BUILDKITE",
10236 env: "BUILDKITE_PULL_REQUEST",
10242 constant: "CIRCLE",
10244 pr: "CIRCLE_PULL_REQUEST"
10248 constant: "CIRRUS",
10253 name: "AWS CodeBuild",
10254 constant: "CODEBUILD",
10255 env: "CODEBUILD_BUILD_ARN"
10259 constant: "CODESHIP",
10261 CI_NAME: "codeship"
10269 DRONE_BUILD_EVENT: "pull_request"
10278 name: "GitHub Actions",
10279 constant: "GITHUB_ACTIONS",
10280 env: "GITHUB_ACTIONS",
10282 GITHUB_EVENT_NAME: "pull_request"
10287 constant: "GITLAB",
10293 env: "GO_PIPELINE_LABEL"
10297 constant: "HUDSON",
10302 constant: "JENKINS",
10316 constant: "ZEIT_NOW",
10321 constant: "MAGNUM",
10325 name: "Netlify CI",
10326 constant: "NETLIFY",
10329 env: "PULL_REQUEST",
10335 constant: "NEVERCODE",
10338 env: "NEVERCODE_PULL_REQUEST",
10344 constant: "RENDER",
10347 IS_PULL_REQUEST: "true"
10354 pr: "SAIL_PULL_REQUEST_NUMBER"
10358 constant: "SEMAPHORE",
10360 pr: "PULL_REQUEST_NUMBER"
10364 constant: "SHIPPABLE",
10367 IS_PULL_REQUEST: "true"
10372 constant: "SOLANO",
10377 name: "Strider CD",
10378 constant: "STRIDER",
10382 name: "TaskCluster",
10383 constant: "TASKCLUSTER",
10391 constant: "TEAMCITY",
10392 env: "TEAMCITY_VERSION"
10396 constant: "TRAVIS",
10399 env: "TRAVIS_PULL_REQUEST",
10405 var ciInfo = createCommonjsModule(function (module, exports) {
10407 var env = process.env; // Used for testing only
10409 Object.defineProperty(exports, '_vendors', {
10410 value: vendors.map(function (v) {
10414 exports.name = null;
10415 exports.isPR = null;
10416 vendors.forEach(function (vendor) {
10417 var envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
10418 var isCI = envs.every(function (obj) {
10419 return checkEnv(obj);
10421 exports[vendor.constant] = isCI;
10424 exports.name = vendor.name;
10426 switch (typeof vendor.pr) {
10428 // "pr": "CIRRUS_PR"
10429 exports.isPR = !!env[vendor.pr];
10433 if ('env' in vendor.pr) {
10434 // "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" }
10435 exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne;
10436 } else if ('any' in vendor.pr) {
10437 // "pr": { "any": ["ghprbPullId", "CHANGE_ID"] }
10438 exports.isPR = vendor.pr.any.some(function (key) {
10442 // "pr": { "DRONE_BUILD_EVENT": "pull_request" }
10443 exports.isPR = checkEnv(vendor.pr);
10449 // PR detection not supported for this vendor
10450 exports.isPR = null;
10454 exports.isCI = !!(env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari
10455 env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
10456 env.BUILD_NUMBER || // Jenkins, TeamCity
10457 env.RUN_ID || // TaskCluster, dsari
10458 exports.name || false);
10460 function checkEnv(obj) {
10461 if (typeof obj === 'string') return !!env[obj];
10462 return Object.keys(obj).every(function (k) {
10463 return env[k] === obj[k];
10469 cosmiconfig: dist$2.cosmiconfig,
10470 cosmiconfigSync: dist$2.cosmiconfigSync,
10471 findParentDir: findParentDir.sync,
10472 getStdin: getStdin,
10473 isCI: () => ciInfo.isCI
10476 module.exports = thirdParty;